From a250ec69eb91a2a89b34e8899e9a6b0114ba46dd Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 10 Sep 2026 00:17:19 +0200 Subject: [PATCH 1/5] Give the media stream records a home that is not one producer's MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four record types described a media stream and nothing about who produced it, while living in odin-core under a `muninn.` prefix. Every field is producer-agnostic; the name was the only coupling, and a second producer would have had to impersonate Muninn or fork the shape. They move to cultnet-rs as `gamecult.media_*`, matching the prefix already used for cross-service contracts like gamecult.runtime_presence_health and gamecult.service_trust_anchor, while cultmesh.* stays reserved for session primitives. Field order and key indices are carried over untouched, including the `default` on missing_video_chunk_keys. The tests pin what a consumer in another language is entitled to rely on: positional layout, the slot each field occupies, and that a record written before that field was appended still decodes. One test is ignored rather than passing. Byte payloads currently serialize as MessagePack arrays of integers because the derive writes its own Serialize and ignores serde attributes; C#, TypeScript and Python all emit bin, which makes Rust the divergent runtime and costs 1.45x on every media byte. Fixing it needs an opt-in hint in cultcache-rs-derive rather than a global change, because signatures are taken over the whole positional serialization and canonical hashes over the same bytes — flipping byte encoding estate-wide would invalidate the live Idunn authority chain. That work is sequenced by the Swarm Migration session; the ignored test un-ignores when the hint lands. Parked on its own branch. The Muninn and Odin ends of this move are not done: odin-core still declares these types, and muninn-daemon still imports them from there. Co-Authored-By: Claude Opus 5 --- packages/cultnet-rs/src/lib.rs | 2 + .../cultnet-rs/src/media_stream_contracts.rs | 194 +++++++++++++++ .../tests/media_stream_contracts.rs | 227 ++++++++++++++++++ 3 files changed, 423 insertions(+) create mode 100644 packages/cultnet-rs/src/media_stream_contracts.rs create mode 100644 packages/cultnet-rs/tests/media_stream_contracts.rs diff --git a/packages/cultnet-rs/src/lib.rs b/packages/cultnet-rs/src/lib.rs index 3e8a3c94..5aa121af 100644 --- a/packages/cultnet-rs/src/lib.rs +++ b/packages/cultnet-rs/src/lib.rs @@ -1,6 +1,7 @@ mod contracts; mod idunn_deployment_brake; mod idunn_lifecycle_brake; +mod media_stream_contracts; mod provider_health_contracts; mod runtime_authority_contracts; mod service_identity; @@ -19,6 +20,7 @@ mod transport; pub use contracts::*; pub use idunn_deployment_brake::*; pub use idunn_lifecycle_brake::*; +pub use media_stream_contracts::*; pub use provider_health_contracts::*; pub use runtime_authority_contracts::*; pub use service_identity::*; diff --git a/packages/cultnet-rs/src/media_stream_contracts.rs b/packages/cultnet-rs/src/media_stream_contracts.rs new file mode 100644 index 00000000..e47b3a28 --- /dev/null +++ b/packages/cultnet-rs/src/media_stream_contracts.rs @@ -0,0 +1,194 @@ +//! CultMesh Media Stream: the typed contract for carrying live audio and video +//! over CultNet. +//! +//! These records describe a media stream and nothing about who produced it. A +//! capture broker, an editor runtime, a recorder, or a synthetic source may all +//! publish them; an OBS bridge, a compositor, a recorder, or a browser lowering +//! may all consume them. Producers advertise their streams through Odin and +//! consumers resolve them there, so neither end needs to name the other. +//! +//! They lived in `odin-core` as `muninn.media_*`, named after the one producer +//! that happened to emit them first. Every field here is producer-agnostic — the +//! name was the only coupling, and a second producer would have had to +//! impersonate Muninn or fork the shape. +//! +//! # Layout is wire contract +//! +//! CultCache encodes these positionally. Field order and `key` indices are the +//! wire format: append new fields with `default` at the next free index, never +//! reorder or renumber. `missing_video_chunk_keys` shows the pattern. +//! +//! # Timebase +//! +//! `pts_ticks`, `duration_ticks` and `deadline_ticks` are expressed in +//! `timebase_num / timebase_den` units, carried per record so a consumer never +//! has to assume a producer's clock. `deadline_ticks` is the presentation +//! deadline past which a late arrival is worth dropping rather than displaying. +//! +//! # Reliability +//! +//! Nothing here specifies a delivery guarantee. Whether a stream rides a +//! reliable or lossy CultNet channel, and whether it carries parity, is a +//! transport decision made per stream — not a property of the payload shape. +//! Video parity shards exist for producers that choose forward error correction; +//! audio currently has no parity record, and a producer emitting audio on a +//! lossy channel needs one. + +use cultcache_rs::DatabaseEntry; + +pub const GAMECULT_MEDIA_VIDEO_ACCESS_UNIT_SCHEMA: &str = "gamecult.media_video_access_unit.v1"; +pub const GAMECULT_MEDIA_VIDEO_PARITY_SHARD_SCHEMA: &str = "gamecult.media_video_parity_shard.v2"; +pub const GAMECULT_MEDIA_AUDIO_PACKET_SCHEMA: &str = "gamecult.media_audio_packet.v1"; +pub const GAMECULT_MEDIA_RECEIVER_FEEDBACK_SCHEMA: &str = "gamecult.media_receiver_feedback.v1"; + +/// One coded video access unit, possibly split across `chunk_count` records +/// sharing a `frame_id`. A consumer reassembles by `(stream_id, session_id, +/// frame_id)` and orders by `chunk_index`. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "gamecult.media_video_access_unit", + schema = "gamecult.media_video_access_unit.v1" +)] +pub struct GameCultMediaVideoAccessUnitRecord { + #[cultcache(key = 0)] + pub stream_id: String, + #[cultcache(key = 1)] + pub session_id: String, + #[cultcache(key = 2)] + pub frame_id: u64, + #[cultcache(key = 3)] + pub codec: String, + #[cultcache(key = 4)] + pub pts_ticks: i64, + #[cultcache(key = 5)] + pub duration_ticks: u32, + #[cultcache(key = 6)] + pub timebase_num: u32, + #[cultcache(key = 7)] + pub timebase_den: u32, + #[cultcache(key = 8)] + pub keyframe: bool, + #[cultcache(key = 9)] + pub dependency_frame_id: Option, + #[cultcache(key = 10)] + pub deadline_ticks: i64, + #[cultcache(key = 11)] + pub chunk_index: u16, + #[cultcache(key = 12)] + pub chunk_count: u16, + #[cultcache(key = 13)] + pub payload: Vec, +} + +/// Forward-error-correction parity for one video access unit. Carries the +/// framing fields of the access unit it protects so a receiver can recover +/// without having seen the original, plus the shard geometry needed to run +/// recovery: `parity_index` within `parity_count`, and the chunk sizes the +/// parity was computed over. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "gamecult.media_video_parity_shard", + schema = "gamecult.media_video_parity_shard.v2" +)] +pub struct GameCultMediaVideoParityShardRecord { + #[cultcache(key = 0)] + pub stream_id: String, + #[cultcache(key = 1)] + pub session_id: String, + #[cultcache(key = 2)] + pub frame_id: u64, + #[cultcache(key = 3)] + pub codec: String, + #[cultcache(key = 4)] + pub pts_ticks: i64, + #[cultcache(key = 5)] + pub duration_ticks: u32, + #[cultcache(key = 6)] + pub timebase_num: u32, + #[cultcache(key = 7)] + pub timebase_den: u32, + #[cultcache(key = 8)] + pub keyframe: bool, + #[cultcache(key = 9)] + pub dependency_frame_id: Option, + #[cultcache(key = 10)] + pub deadline_ticks: i64, + #[cultcache(key = 11)] + pub chunk_count: u16, + #[cultcache(key = 12)] + pub parity_index: u16, + #[cultcache(key = 13)] + pub parity_count: u16, + #[cultcache(key = 14)] + pub chunk_payload_bytes: u32, + #[cultcache(key = 15)] + pub last_chunk_payload_bytes: u32, + #[cultcache(key = 16)] + pub payload: Vec, +} + +/// One coded audio packet. Unlike video these are not chunked: a packet is +/// whole or it is absent, and `payload` carries whatever `codec` names. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "gamecult.media_audio_packet", + schema = "gamecult.media_audio_packet.v1" +)] +pub struct GameCultMediaAudioPacketRecord { + #[cultcache(key = 0)] + pub stream_id: String, + #[cultcache(key = 1)] + pub session_id: String, + #[cultcache(key = 2)] + pub packet_id: u64, + #[cultcache(key = 3)] + pub codec: String, + #[cultcache(key = 4)] + pub pts_ticks: i64, + #[cultcache(key = 5)] + pub duration_ticks: u32, + #[cultcache(key = 6)] + pub timebase_num: u32, + #[cultcache(key = 7)] + pub timebase_den: u32, + #[cultcache(key = 8)] + pub deadline_ticks: i64, + #[cultcache(key = 9)] + pub payload: Vec, +} + +/// What a receiver observed, published back to the producer so it can adapt: +/// what decoded, what is missing, what arrived too late, and how much queue and +/// jitter the receiver is carrying. +/// +/// This is the only record here that flows consumer-to-producer. A producer is +/// free to ignore it; it reports observation, it does not issue commands. +#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] +#[cultcache( + type = "gamecult.media_receiver_feedback", + schema = "gamecult.media_receiver_feedback.v1" +)] +pub struct GameCultMediaReceiverFeedbackRecord { + #[cultcache(key = 0)] + pub stream_id: String, + #[cultcache(key = 1)] + pub session_id: String, + #[cultcache(key = 2)] + pub receiver_id: String, + #[cultcache(key = 3)] + pub highest_decodable_frame_id: Option, + #[cultcache(key = 4)] + pub missing_frame_ids: Vec, + #[cultcache(key = 5)] + pub late_frame_ids: Vec, + #[cultcache(key = 6)] + pub requested_keyframe: bool, + #[cultcache(key = 7)] + pub jitter_us: i64, + #[cultcache(key = 8)] + pub decode_queue_us: i64, + #[cultcache(key = 9)] + pub observed_at: String, + #[cultcache(key = 10, default)] + pub missing_video_chunk_keys: Vec, +} diff --git a/packages/cultnet-rs/tests/media_stream_contracts.rs b/packages/cultnet-rs/tests/media_stream_contracts.rs new file mode 100644 index 00000000..9d2fc664 --- /dev/null +++ b/packages/cultnet-rs/tests/media_stream_contracts.rs @@ -0,0 +1,227 @@ +//! The CultMesh Media Stream records are a wire contract shared by producers and +//! consumers that never link each other. These tests pin the properties a +//! consumer is entitled to rely on: positional layout, declared field order, and +//! tolerance of records written before an appended field existed. + +use cultcache_rs::DatabaseEntry; +use cultnet_rs::{ + GAMECULT_MEDIA_AUDIO_PACKET_SCHEMA, GAMECULT_MEDIA_RECEIVER_FEEDBACK_SCHEMA, + GAMECULT_MEDIA_VIDEO_ACCESS_UNIT_SCHEMA, GAMECULT_MEDIA_VIDEO_PARITY_SHARD_SCHEMA, + GameCultMediaAudioPacketRecord, GameCultMediaReceiverFeedbackRecord, + GameCultMediaVideoAccessUnitRecord, GameCultMediaVideoParityShardRecord, +}; +use rmpv::Value; + +fn access_unit() -> GameCultMediaVideoAccessUnitRecord { + GameCultMediaVideoAccessUnitRecord { + stream_id: "raven-primary-av".to_string(), + session_id: "session-1".to_string(), + frame_id: 4242, + codec: "h264".to_string(), + pts_ticks: 90_000, + duration_ticks: 3_000, + timebase_num: 1, + timebase_den: 90_000, + keyframe: true, + dependency_frame_id: None, + deadline_ticks: 108_000, + chunk_index: 2, + chunk_count: 5, + payload: vec![0xDE, 0xAD, 0xBE, 0xEF], + } +} + +fn audio_packet() -> GameCultMediaAudioPacketRecord { + GameCultMediaAudioPacketRecord { + stream_id: "raven-primary-av".to_string(), + session_id: "session-1".to_string(), + packet_id: 77, + codec: "opus".to_string(), + pts_ticks: 48_000, + duration_ticks: 960, + timebase_num: 1, + timebase_den: 48_000, + deadline_ticks: 96_000, + payload: vec![1, 2, 3], + } +} + +fn decode_as_value(bytes: &[u8]) -> Value { + rmp_serde::from_slice(bytes).expect("records decode as generic MessagePack") +} + +/// The declared `key` indices are the wire layout, not documentation. A consumer +/// in another language reads position 2 for `frame_id` and position 13 for +/// `payload`; reordering the struct would silently break it. +#[test] +fn video_access_unit_encodes_as_a_positional_array() { + let encoded = rmp_serde::to_vec(&access_unit()).expect("encodes"); + let Value::Array(slots) = decode_as_value(&encoded) else { + panic!("access units must encode as a positional array"); + }; + + assert_eq!(slots.len(), 14, "field count is wire contract"); + assert_eq!(slots[0].as_str(), Some("raven-primary-av")); + assert_eq!(slots[2].as_u64(), Some(4242), "slot 2 is frame_id"); + assert_eq!(slots[3].as_str(), Some("h264")); + assert_eq!(slots[8].as_bool(), Some(true), "slot 8 is keyframe"); + assert!(slots[9].is_nil(), "an absent dependency stays nil, not 0"); + assert_eq!(slots[12].as_u64(), Some(5), "slot 12 is chunk_count"); + assert!( + matches!(&slots[13], Value::Binary(_) | Value::Array(_)), + "slot 13 is the payload; see payload_should_encode_as_messagepack_bin \ + for which of the two it ought to be" + ); +} + +/// Ignored until `cultcache-rs-derive` grows a `bytes` hint. +/// +/// The derive writes its own `Serialize` and calls `serialize_element` per slot, +/// so a `Vec` field goes out as a MessagePack array of integers. C#, +/// TypeScript and Python all emit `bin` for byte fields, which makes Rust the +/// divergent runtime and these records unreadable by the reference +/// implementation. `#[serde(with = "serde_bytes")]` cannot fix it — the derive +/// ignores serde attributes. +/// +/// It also costs 1.45x on every media byte: an 848-byte payload encodes to 1234 +/// bytes as an integer array against 851 as `bin`. +/// +/// The fix is not local to this file. Changing byte encoding globally would +/// invalidate every signature in the Idunn authority chain, because signatures +/// are taken over the whole positional serialization and canonical hashes over +/// the same bytes. It needs an opt-in hint so these three media records can +/// adopt `bin` without moving the signature-bearing ones. Owned by the Swarm +/// Migration work; un-ignore this when the hint lands. +#[test] +#[ignore = "blocked on a `bytes` opt-in hint in cultcache-rs-derive"] +fn payload_should_encode_as_messagepack_bin() { + let encoded = rmp_serde::to_vec(&access_unit()).expect("encodes"); + let Value::Array(slots) = decode_as_value(&encoded) else { + panic!("access units must encode as a positional array"); + }; + + assert_eq!( + slots[13].as_slice(), + Some([0xDE, 0xAD, 0xBE, 0xEF].as_slice()), + "payloads belong on the wire as bin, not as an array of integers" + ); +} + +#[test] +fn audio_packets_are_whole_and_carry_their_own_timebase() { + let encoded = rmp_serde::to_vec(&audio_packet()).expect("encodes"); + let Value::Array(slots) = decode_as_value(&encoded) else { + panic!("audio packets must encode as a positional array"); + }; + + assert_eq!(slots.len(), 10, "field count is wire contract"); + assert_eq!(slots[2].as_u64(), Some(77), "slot 2 is packet_id"); + assert_eq!(slots[6].as_u64(), Some(1), "slot 6 is timebase_num"); + assert_eq!(slots[7].as_u64(), Some(48_000), "slot 7 is timebase_den"); + + let decoded: GameCultMediaAudioPacketRecord = + rmp_serde::from_slice(&encoded).expect("round-trips"); + assert_eq!(decoded, audio_packet()); +} + +#[test] +fn parity_shards_carry_the_geometry_recovery_needs() { + let shard = GameCultMediaVideoParityShardRecord { + stream_id: "raven-primary-av".to_string(), + session_id: "session-1".to_string(), + frame_id: 4242, + codec: "h264".to_string(), + pts_ticks: 90_000, + duration_ticks: 3_000, + timebase_num: 1, + timebase_den: 90_000, + keyframe: false, + dependency_frame_id: Some(4241), + deadline_ticks: 108_000, + chunk_count: 5, + parity_index: 1, + parity_count: 2, + chunk_payload_bytes: 1024, + last_chunk_payload_bytes: 512, + payload: vec![9, 9, 9], + }; + + let encoded = rmp_serde::to_vec(&shard).expect("encodes"); + let Value::Array(slots) = decode_as_value(&encoded) else { + panic!("parity shards must encode as a positional array"); + }; + + assert_eq!(slots.len(), 17, "field count is wire contract"); + assert_eq!(slots[12].as_u64(), Some(1), "slot 12 is parity_index"); + assert_eq!(slots[13].as_u64(), Some(2), "slot 13 is parity_count"); + assert_eq!( + slots[15].as_u64(), + Some(512), + "slot 15 is last_chunk_payload_bytes, which recovery needs to size the tail" + ); + + let decoded: GameCultMediaVideoParityShardRecord = + rmp_serde::from_slice(&encoded).expect("round-trips"); + assert_eq!(decoded, shard); +} + +/// `missing_video_chunk_keys` was appended after producers were already writing +/// feedback. A record written without it must still decode, or the append was a +/// breaking change wearing a `default` attribute. +#[test] +fn receiver_feedback_decodes_records_written_before_its_last_field() { + let without_appended_field = Value::Array(vec![ + Value::from("raven-primary-av"), + Value::from("session-1"), + Value::from("starfire-obs"), + Value::from(4200u64), + Value::Array(vec![Value::from(4198u64)]), + Value::Array(vec![Value::from(4199u64)]), + Value::from(true), + Value::from(1_500i64), + Value::from(9_000i64), + Value::from("2026-09-09T00:00:00Z"), + ]); + + let mut bytes = Vec::new(); + rmpv::encode::write_value(&mut bytes, &without_appended_field).expect("writes legacy record"); + + let decoded: GameCultMediaReceiverFeedbackRecord = + rmp_serde::from_slice(&bytes).expect("a pre-append record must still decode"); + + assert_eq!(decoded.receiver_id, "starfire-obs"); + assert_eq!(decoded.highest_decodable_frame_id, Some(4200)); + assert!(decoded.requested_keyframe); + assert!( + decoded.missing_video_chunk_keys.is_empty(), + "the appended field defaults rather than failing the decode" + ); +} + +/// The published constants and the derived type identity must not drift apart; +/// a consumer resolving by schema id and a producer registering by type would +/// then disagree without either failing to compile. +#[test] +fn published_schema_constants_match_the_derived_identity() { + assert_eq!( + GameCultMediaVideoAccessUnitRecord::SCHEMA_NAME, + GAMECULT_MEDIA_VIDEO_ACCESS_UNIT_SCHEMA + ); + assert_eq!( + GameCultMediaVideoParityShardRecord::SCHEMA_NAME, + GAMECULT_MEDIA_VIDEO_PARITY_SHARD_SCHEMA + ); + assert_eq!( + GameCultMediaAudioPacketRecord::SCHEMA_NAME, + GAMECULT_MEDIA_AUDIO_PACKET_SCHEMA + ); + assert_eq!( + GameCultMediaReceiverFeedbackRecord::SCHEMA_NAME, + GAMECULT_MEDIA_RECEIVER_FEEDBACK_SCHEMA + ); + + assert_eq!( + GameCultMediaAudioPacketRecord::TYPE, + "gamecult.media_audio_packet" + ); +} From 2ba404cc0b57a5447f1c93988830c3c1c310080e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 10 Sep 2026 00:31:11 +0200 Subject: [PATCH 2/5] Carry media payloads as bin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The three media payload fields take the derive's `bytes` attribute, so they serialize as MessagePack `bin` instead of an array of integers. An 848-byte payload goes from 1234 bytes on the wire to 851 — 1.45x off every media byte, on the one link measured to be starved. This is a correction to the previous commit's reasoning, not a new capability. That commit claimed the derive could not emit bin and left a test ignored against a hint that needed designing. The hint has existed all along: cultcache-rs-derive parses `bytes` at lib.rs:92, serializes through serde_bytes::Bytes at :135, and decodes through ByteBuf at :154 and :170. What is inert on a DatabaseEntry struct is `#[serde(with = "serde_bytes")]`, because the derive reads only its own attribute namespace — which is a different and much smaller claim than the one that was made. The ignored test is now un-ignored and passing, and the tolerant assertion it was propping up is exact again. Four fields elsewhere are missing `bytes` and are deliberately untouched here: IdunnDeploymentBrakeRecord.signature, IdunnDaemonHealthTrustBindingRecord .signer_public_key, GameCultServiceTrustAnchorRecord.signer_public_key, and IdunnAuthenticatedProviderHealthProjectionRecord.signature. Those carry stored state and signing history — six trust anchors live in the deployment projection on yggdrasil, and the brake store is byte-exact checked — so they need sequencing with a re-sign rather than a flag flip. Owned by the Swarm Migration work. Co-Authored-By: Claude Opus 5 --- .../cultnet-rs/src/media_stream_contracts.rs | 12 +++++-- .../tests/media_stream_contracts.rs | 34 +++++++------------ 2 files changed, 21 insertions(+), 25 deletions(-) diff --git a/packages/cultnet-rs/src/media_stream_contracts.rs b/packages/cultnet-rs/src/media_stream_contracts.rs index e47b3a28..815e3392 100644 --- a/packages/cultnet-rs/src/media_stream_contracts.rs +++ b/packages/cultnet-rs/src/media_stream_contracts.rs @@ -18,6 +18,12 @@ //! wire format: append new fields with `default` at the next free index, never //! reorder or renumber. `missing_video_chunk_keys` shows the pattern. //! +//! Payloads carry `bytes` so they serialize as MessagePack `bin` rather than an +//! array of integers, which is what the C#, TypeScript and Python runtimes +//! expect and what keeps a 848-byte payload at 851 bytes instead of 1234. Note +//! that this is the derive's own attribute — `#[serde(with = "serde_bytes")]` +//! is inert here, because `DatabaseEntry` writes its own `Serialize`. +//! //! # Timebase //! //! `pts_ticks`, `duration_ticks` and `deadline_ticks` are expressed in @@ -76,7 +82,7 @@ pub struct GameCultMediaVideoAccessUnitRecord { pub chunk_index: u16, #[cultcache(key = 12)] pub chunk_count: u16, - #[cultcache(key = 13)] + #[cultcache(key = 13, bytes)] pub payload: Vec, } @@ -123,7 +129,7 @@ pub struct GameCultMediaVideoParityShardRecord { pub chunk_payload_bytes: u32, #[cultcache(key = 15)] pub last_chunk_payload_bytes: u32, - #[cultcache(key = 16)] + #[cultcache(key = 16, bytes)] pub payload: Vec, } @@ -153,7 +159,7 @@ pub struct GameCultMediaAudioPacketRecord { pub timebase_den: u32, #[cultcache(key = 8)] pub deadline_ticks: i64, - #[cultcache(key = 9)] + #[cultcache(key = 9, bytes)] pub payload: Vec, } diff --git a/packages/cultnet-rs/tests/media_stream_contracts.rs b/packages/cultnet-rs/tests/media_stream_contracts.rs index 9d2fc664..963d78a2 100644 --- a/packages/cultnet-rs/tests/media_stream_contracts.rs +++ b/packages/cultnet-rs/tests/media_stream_contracts.rs @@ -67,33 +67,23 @@ fn video_access_unit_encodes_as_a_positional_array() { assert_eq!(slots[8].as_bool(), Some(true), "slot 8 is keyframe"); assert!(slots[9].is_nil(), "an absent dependency stays nil, not 0"); assert_eq!(slots[12].as_u64(), Some(5), "slot 12 is chunk_count"); - assert!( - matches!(&slots[13], Value::Binary(_) | Value::Array(_)), - "slot 13 is the payload; see payload_should_encode_as_messagepack_bin \ - for which of the two it ought to be" + assert_eq!( + slots[13].as_slice(), + Some([0xDE, 0xAD, 0xBE, 0xEF].as_slice()), + "slot 13 is the payload, carried as bin" ); } -/// Ignored until `cultcache-rs-derive` grows a `bytes` hint. +/// Payloads must reach the wire as MessagePack `bin`, not as an array of +/// integers. The C#, TypeScript and Python runtimes all read byte fields as +/// `bin`, so a payload serialized as a sequence is unreadable by the reference +/// implementation, and costs 1.45x besides: 848 bytes encode to 1234 as an +/// integer array against 851 as `bin`. /// -/// The derive writes its own `Serialize` and calls `serialize_element` per slot, -/// so a `Vec` field goes out as a MessagePack array of integers. C#, -/// TypeScript and Python all emit `bin` for byte fields, which makes Rust the -/// divergent runtime and these records unreadable by the reference -/// implementation. `#[serde(with = "serde_bytes")]` cannot fix it — the derive -/// ignores serde attributes. -/// -/// It also costs 1.45x on every media byte: an 848-byte payload encodes to 1234 -/// bytes as an integer array against 851 as `bin`. -/// -/// The fix is not local to this file. Changing byte encoding globally would -/// invalidate every signature in the Idunn authority chain, because signatures -/// are taken over the whole positional serialization and canonical hashes over -/// the same bytes. It needs an opt-in hint so these three media records can -/// adopt `bin` without moving the signature-bearing ones. Owned by the Swarm -/// Migration work; un-ignore this when the hint lands. +/// This is what the derive's `bytes` attribute buys. `#[serde(with = +/// "serde_bytes")]` will not do it — `DatabaseEntry` emits its own `Serialize` +/// and reads only its own `cultcache` attribute namespace. #[test] -#[ignore = "blocked on a `bytes` opt-in hint in cultcache-rs-derive"] fn payload_should_encode_as_messagepack_bin() { let encoded = rmp_serde::to_vec(&access_unit()).expect("encodes"); let Value::Array(slots) = decode_as_value(&encoded) else { From 36f31920ce69a80ad4c340a7bdfb23d63a9273e9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 10 Sep 2026 00:49:32 +0200 Subject: [PATCH 3/5] Let a caller choose what the media channel does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `media` was hardcoded Reliable in two places — the profile builder and the per-channel send options — so no caller could ask for anything else. Measured on Raven through `cultnet-impair`, 848-byte packets at 12 Mbps, which is Muninn's real media shape: profile mode delivered ack bytes clean unreliable 100.00% 43 clean reliable 69.10% 131,322 loss 1% unreliable 98.95% 43 loss 1% reliable 72.00% 135,837 loss 3% unreliable 96.73% 43 loss 3% reliable 73.30% 138,030 A reliable media channel loses 31% of a clean 12 Mbps offer, and its delivery barely moves as loss rises, so loss is not the binding constraint — it cannot carry the rate. An unreliable one holds everything on a clean link and then degrades by about the loss injected. The reverse channel differs by three orders of magnitude. Muninn wanted the unreliable lane and had no way to say so. It signalled the intent the only way the API allowed, by passing no reliable expiry, and its own test has asserted Unreliable and failed since it was written. With this change it passes. Delivery now comes from the advertised profile, resolved by `channel_delivery` alongside the `channel_reliable_expire_after_ms` that already worked this way. That removes the send path's private opinion about reliability, so the profile a peer was shown and the behaviour it gets cannot disagree. The channels whose semantics are fixed by design — schema reliable and ordered, realtime unreliable — are untouched and pinned by a test. `media_delivery: None` means Reliable, so no existing consumer changes behaviour. It is still source-breaking for anyone constructing the three options types with a struct literal rather than `::client(...)`: two sites in cultmesh-rs, four in Muninn, seven across the test suites here, all mechanical. An earlier draft claimed Muninn was unaffected; the compiler disagreed. The `examples/media_delivery_probe.rs` added here is what produced the table, so the claim can be re-run rather than believed. Note its sender-side wire-cost figure is unsound for the reliable case: the sender stops draining after five seconds while retransmission is still in flight, so those byte counts under-report. The delivery percentages are receiver-measured and stand. Co-Authored-By: Claude Opus 5 --- packages/cultmesh-rs/src/lib.rs | 1 + .../cultmesh-rs/tests/rudp_document_server.rs | 1 + .../examples/media_delivery_probe.rs | 177 ++++++++++++++++++ packages/cultnet-rs/src/cultmesh.rs | 2 + packages/cultnet-rs/src/rudp.rs | 43 ++++- packages/cultnet-rs/tests/cultnet.rs | 7 + .../tests/media_channel_delivery.rs | 92 +++++++++ 7 files changed, 321 insertions(+), 2 deletions(-) create mode 100644 packages/cultnet-rs/examples/media_delivery_probe.rs create mode 100644 packages/cultnet-rs/tests/media_channel_delivery.rs diff --git a/packages/cultmesh-rs/src/lib.rs b/packages/cultmesh-rs/src/lib.rs index 7999f18b..135314bb 100644 --- a/packages/cultmesh-rs/src/lib.rs +++ b/packages/cultmesh-rs/src/lib.rs @@ -955,6 +955,7 @@ fn connect_rudp_client( socket.set_read_timeout(Some(poll_interval))?; let mut client = CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { + media_delivery: None, runtime_id: runtime_id.to_string(), socket, mode: cultnet_rs::CultNetRudpSocketMode::Client, diff --git a/packages/cultmesh-rs/tests/rudp_document_server.rs b/packages/cultmesh-rs/tests/rudp_document_server.rs index c0f191b4..df14b4ea 100644 --- a/packages/cultmesh-rs/tests/rudp_document_server.rs +++ b/packages/cultmesh-rs/tests/rudp_document_server.rs @@ -163,6 +163,7 @@ fn client(target: SocketAddr, id: u32) -> Result +//! media_delivery_probe send +//! ``` +//! +//! The sender reports amplification: wire bytes divided by offered payload +//! bytes. At 1.0 nothing was retransmitted. Well above 1.0 under loss is the +//! pathology. + +use std::env; +use std::net::{SocketAddr, UdpSocket}; +use std::time::{Duration, Instant}; + +use anyhow::{Result, anyhow}; +use cultnet_rs::{ + CultNetRudpServerHubOptions, CultNetRudpSocketTransportConnection, + CultNetRudpSocketTransportOptions, CultNetTransportDelivery, +}; + +const CHANNEL: &str = "media"; +const DRAIN: Duration = Duration::from_secs(5); + +fn main() -> Result<()> { + let args: Vec = env::args().collect(); + match args.get(1).map(String::as_str) { + Some("recv") => recv( + args.get(2).ok_or_else(|| anyhow!("bind addr"))?.parse()?, + args.get(3).ok_or_else(|| anyhow!("expect count"))?.parse()?, + ), + Some("send") => send( + args.get(2).ok_or_else(|| anyhow!("endpoint"))?.parse()?, + match args.get(3).map(String::as_str) { + Some("unreliable") => CultNetTransportDelivery::Unreliable, + Some("reliable") => CultNetTransportDelivery::Reliable, + other => return Err(anyhow!("delivery must be reliable|unreliable, got {other:?}")), + }, + args.get(4).ok_or_else(|| anyhow!("payload bytes"))?.parse()?, + args.get(5).ok_or_else(|| anyhow!("count"))?.parse()?, + args.get(6).map(|v| v.parse()).transpose()?.unwrap_or(12.0), + ), + _ => Err(anyhow!( + "usage: media_delivery_probe recv | send " + )), + } +} + +fn recv(bind: SocketAddr, expect: u64) -> Result<()> { + let socket = UdpSocket::bind(bind)?; + socket.set_nonblocking(true)?; + let mut hub = cultnet_rs::CultNetRudpServerHub::new(CultNetRudpServerHubOptions::new( + "probe-recv", + socket, + 0x0BE0_0001, + ))?; + + println!("listening on {bind}, expecting {expect} frames"); + let started = Instant::now(); + let mut frames = 0u64; + let mut payload_bytes = 0u64; + let mut last_progress = Instant::now(); + + loop { + while let Some(event) = hub.receive_event_once()? { + if let cultnet_rs::CultNetRudpServerEvent::Frame { frame, .. } = event + && frame.channel_id == CHANNEL + { + frames += 1; + payload_bytes += frame.payload.len() as u64; + last_progress = Instant::now(); + } + } + if frames >= expect || last_progress.elapsed() > DRAIN { + break; + } + std::thread::sleep(Duration::from_micros(200)); + } + + let stats = hub.stats(); + let elapsed = started.elapsed().as_secs_f64(); + println!("RESULT recv frames={frames} expected={expect} payload_bytes={payload_bytes}"); + println!( + "RESULT recv wire_bytes_in={} wire_bytes_out={} elapsed_s={elapsed:.2} delivered_pct={:.2}", + stats.bytes_received, + stats.bytes_sent, + (frames as f64 / expect as f64) * 100.0 + ); + Ok(()) +} + +fn send( + endpoint: SocketAddr, + delivery: CultNetTransportDelivery, + payload_bytes: usize, + count: u64, + target_mbps: f64, +) -> Result<()> { + let socket = UdpSocket::bind("0.0.0.0:0")?; + socket.set_nonblocking(true)?; + let mut options = + CultNetRudpSocketTransportOptions::client("probe-send", socket, endpoint, 0x0BE0_0001); + options.media_delivery = Some(delivery); + options.media_reliable_expire_after_ms = None; + + let mut transport = CultNetRudpSocketTransportConnection::new(options)?; + transport.connect(b"probe".to_vec())?; + let deadline = Instant::now() + Duration::from_secs(10); + while !transport.connected() { + let _ = transport.receive_once()?; + transport.poll_resends()?; + if Instant::now() >= deadline { + return Err(anyhow!("timed out connecting to {endpoint}")); + } + std::thread::sleep(Duration::from_millis(2)); + } + + // Pace to a realistic media rate. An unpaced blast overruns the receiver's + // socket buffer and manufactures loss that has nothing to do with the link. + let per_packet = Duration::from_secs_f64((payload_bytes as f64 * 8.0) / (target_mbps * 1e6)); + let payload = vec![0xA5u8; payload_bytes]; + let offered = payload_bytes as u64 * count; + let started = Instant::now(); + let mut sent = 0u64; + let mut would_block = 0u64; + + while sent < count { + match transport.send(CHANNEL, payload.clone()) { + Ok(()) => sent += 1, + Err(error) if error.to_string().contains("would block") => { + would_block += 1; + transport.poll_resends()?; + let _ = transport.receive_once()?; + std::thread::sleep(Duration::from_micros(500)); + } + Err(error) => return Err(error), + } + if sent % 64 == 0 { + let _ = transport.receive_once()?; + transport.poll_resends()?; + } + let due = started + per_packet.mul_f64(sent as f64); + if let Some(wait) = due.checked_duration_since(Instant::now()) { + std::thread::sleep(wait); + } + } + let send_elapsed = started.elapsed(); + + // Let retransmission run: this is where a reliable channel spends what an + // unreliable one does not. + let drain_start = Instant::now(); + while drain_start.elapsed() < DRAIN { + let _ = transport.receive_once()?; + transport.poll_resends()?; + std::thread::sleep(Duration::from_millis(1)); + } + + let stats = transport.stats(); + let amplification = stats.bytes_sent as f64 / offered as f64; + println!( + "RESULT send delivery={delivery:?} payload_bytes={payload_bytes} count={count} offered={offered} target_mbps={target_mbps}" + ); + println!( + "RESULT send wire_bytes={} amplification={amplification:.3} send_s={:.2} total_s={:.2} would_block={would_block} reliable_expired={}", + stats.bytes_sent, + send_elapsed.as_secs_f64(), + started.elapsed().as_secs_f64(), + stats.reliable_packets_expired + ); + Ok(()) +} diff --git a/packages/cultnet-rs/src/cultmesh.rs b/packages/cultnet-rs/src/cultmesh.rs index efc8acad..14998396 100644 --- a/packages/cultnet-rs/src/cultmesh.rs +++ b/packages/cultnet-rs/src/cultmesh.rs @@ -319,6 +319,7 @@ impl CultMesh { let socket = bind_rudp_socket(&options)?; CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { media_reliable_expire_after_ms: None, + media_delivery: None, runtime_id: runtime_id.into(), socket, mode: CultNetRudpSocketMode::Server, @@ -343,6 +344,7 @@ impl CultMesh { let socket = bind_rudp_socket(&options)?; CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { media_reliable_expire_after_ms: None, + media_delivery: None, runtime_id: runtime_id.into(), socket, mode: CultNetRudpSocketMode::Client, diff --git a/packages/cultnet-rs/src/rudp.rs b/packages/cultnet-rs/src/rudp.rs index f1fd4ca4..b7019b1b 100644 --- a/packages/cultnet-rs/src/rudp.rs +++ b/packages/cultnet-rs/src/rudp.rs @@ -1210,6 +1210,8 @@ pub struct CultNetRudpSocketTransportOptions { pub max_pending_reliable_packets: Option, pub reconnect_policy: Option, pub media_reliable_expire_after_ms: Option, + /// `None` means the historical default, `Reliable`. + pub media_delivery: Option, } impl CultNetRudpSocketTransportOptions { @@ -1221,6 +1223,7 @@ impl CultNetRudpSocketTransportOptions { ) -> Self { Self { media_reliable_expire_after_ms: Some(DEFAULT_MEDIA_RELIABLE_EXPIRE_AFTER_MS), + media_delivery: None, runtime_id: runtime_id.into(), socket, mode: CultNetRudpSocketMode::Client, @@ -1239,6 +1242,7 @@ impl CultNetRudpSocketTransportOptions { pub fn server(runtime_id: impl Into, socket: UdpSocket, connection_id: u32) -> Self { Self { media_reliable_expire_after_ms: Some(DEFAULT_MEDIA_RELIABLE_EXPIRE_AFTER_MS), + media_delivery: None, runtime_id: runtime_id.into(), socket, mode: CultNetRudpSocketMode::Server, @@ -1280,12 +1284,15 @@ pub struct CultNetRudpServerHubOptions { pub max_pending_reliable_packets: Option, pub max_peers: usize, pub media_reliable_expire_after_ms: Option, + /// `None` means the historical default, `Reliable`. + pub media_delivery: Option, } impl CultNetRudpServerHubOptions { pub fn new(runtime_id: impl Into, socket: UdpSocket, connection_id: u32) -> Self { Self { media_reliable_expire_after_ms: Some(DEFAULT_MEDIA_RELIABLE_EXPIRE_AFTER_MS), + media_delivery: None, runtime_id: runtime_id.into(), socket, connection_id, @@ -1372,6 +1379,7 @@ impl CultNetRudpServerHub { options.runtime_id, RudpTransportProfileOptions { media_reliable_expire_after_ms: options.media_reliable_expire_after_ms, + media_delivery: options.media_delivery, transport_id: options.transport_id, host: Some(local_addr.ip().to_string()), port: Some(local_addr.port()), @@ -1451,6 +1459,7 @@ impl CultNetRudpServerHub { channel_id, now_ms(), channel_reliable_expire_after_ms(&self.profile, channel_id), + channel_delivery(&self.profile, channel_id), ), self.max_fragment_bytes, )? @@ -1671,6 +1680,7 @@ impl CultNetRudpSocketTransportConnection { options.runtime_id, RudpTransportProfileOptions { media_reliable_expire_after_ms: options.media_reliable_expire_after_ms, + media_delivery: options.media_delivery, transport_id: options.transport_id, host: Some(local_addr.ip().to_string()), port: Some(local_addr.port()), @@ -1738,6 +1748,7 @@ impl CultNetRudpSocketTransportConnection { channel_id, now_ms(), channel_reliable_expire_after_ms(&self.profile, channel_id), + channel_delivery(&self.profile, channel_id), ); let packets = self.session @@ -1759,6 +1770,7 @@ impl CultNetRudpSocketTransportConnection { channel_id, now_ms(), channel_reliable_expire_after_ms(&self.profile, channel_id), + channel_delivery(&self.profile, channel_id), ); // This lineage has no reliable-expiry concept, so every reliable channel is // already non-expiring. Restore the expiry half of this guard if one is added. @@ -2073,6 +2085,8 @@ pub struct RudpTransportProfileOptions { pub max_pending_reliable_packets: Option, pub reconnect_policy: Option, pub media_reliable_expire_after_ms: Option, + /// `None` means the historical default, `Reliable`. + pub media_delivery: Option, } pub fn create_rudp_transport_profile( @@ -2125,7 +2139,9 @@ pub fn create_rudp_transport_profile( }, CultNetTransportChannel { channel_id: "media".to_string(), - delivery: CultNetTransportDelivery::Reliable, + delivery: options + .media_delivery + .unwrap_or(CultNetTransportDelivery::Reliable), ordering: CultNetTransportOrdering::Unordered, max_payload_bytes: options.max_payload_bytes, max_fragment_bytes: options.max_fragment_bytes, @@ -2254,10 +2270,30 @@ fn channel_reliable_expire_after_ms( .and_then(|channel| channel.reliable_expire_after_ms) } +/// The advertised profile owns each channel's delivery, for the same reason it +/// owns expiry: a send path that hardcodes reliability can disagree with the +/// profile the peer was shown, and then no one can say what the channel does. +/// +/// Falls back to `Reliable` for a channel the profile does not describe, which +/// is what every channel got before delivery was configurable. +fn channel_delivery( + profile: &CultNetTransportProfile, + channel_id: &str, +) -> CultNetTransportDelivery { + profile + .transports + .iter() + .flat_map(|transport| transport.channels.iter()) + .find(|channel| channel.channel_id == channel_id) + .map(|channel| channel.delivery) + .unwrap_or(CultNetTransportDelivery::Reliable) +} + fn channel_send_options( channel_id: &str, now_ms: u64, reliable_expire_after_ms: Option, + delivery: CultNetTransportDelivery, ) -> CultNetRudpSendOptions { match channel_id { "schema" => CultNetRudpSendOptions { @@ -2274,8 +2310,11 @@ fn channel_send_options( now_ms, reliable_expire_after_ms: None, }, + // The one channel whose delivery a caller chooses. Media that has gone + // stale is worth dropping, not retransmitting: a reliable media channel + // under loss adds load exactly when the link has least to give. "media" => CultNetRudpSendOptions { - reliable: true, + reliable: matches!(delivery, CultNetTransportDelivery::Reliable), ordered: false, sequenced: false, now_ms, diff --git a/packages/cultnet-rs/tests/cultnet.rs b/packages/cultnet-rs/tests/cultnet.rs index 851646cf..7be6ea18 100644 --- a/packages/cultnet-rs/tests/cultnet.rs +++ b/packages/cultnet-rs/tests/cultnet.rs @@ -359,6 +359,7 @@ fn rudp_transport_profile_advertises_state_and_realtime_channels() { let profile = create_rudp_transport_profile( "rust-rudp", cultnet_rs::RudpTransportProfileOptions { + media_delivery: None, transport_id: Some("public-rudp".to_string()), host: Some("127.0.0.1".to_string()), port: Some(7777), @@ -1248,6 +1249,7 @@ fn rudp_socket_transport_handshakes_and_carries_reliable_ordered_schema_frames() let connection_id = 0x1020_3040; let mut server = CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { + media_delivery: None, runtime_id: "rust-rudp-server".to_string(), socket: server_socket, mode: CultNetRudpSocketMode::Server, @@ -1264,6 +1266,7 @@ fn rudp_socket_transport_handshakes_and_carries_reliable_ordered_schema_frames() })?; let mut client = CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { + media_delivery: None, runtime_id: "rust-rudp-client".to_string(), socket: client_socket, mode: CultNetRudpSocketMode::Client, @@ -1340,6 +1343,7 @@ fn rudp_socket_transport_carries_fragmented_reliable_ordered_schema_frames() -> let connection_id = 0x1020_3041; let mut server = CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { + media_delivery: None, runtime_id: "rust-rudp-fragment-server".to_string(), socket: server_socket, mode: CultNetRudpSocketMode::Server, @@ -1356,6 +1360,7 @@ fn rudp_socket_transport_carries_fragmented_reliable_ordered_schema_frames() -> })?; let mut client = CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { + media_delivery: None, runtime_id: "rust-rudp-fragment-client".to_string(), socket: client_socket, mode: CultNetRudpSocketMode::Client, @@ -1470,6 +1475,7 @@ fn rudp_socket_flush_waits_for_large_fragment_delivery() -> Result<()> { let connection_id = 0x1020_3043; let mut server = CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { + media_delivery: None, runtime_id: "rust-rudp-window-server".into(), socket: server_socket, mode: CultNetRudpSocketMode::Server, @@ -1486,6 +1492,7 @@ fn rudp_socket_flush_waits_for_large_fragment_delivery() -> Result<()> { })?; let mut client = CultNetRudpSocketTransportConnection::new(CultNetRudpSocketTransportOptions { + media_delivery: None, runtime_id: "rust-rudp-window-client".into(), socket: client_socket, mode: CultNetRudpSocketMode::Client, diff --git a/packages/cultnet-rs/tests/media_channel_delivery.rs b/packages/cultnet-rs/tests/media_channel_delivery.rs new file mode 100644 index 00000000..499be0d3 --- /dev/null +++ b/packages/cultnet-rs/tests/media_channel_delivery.rs @@ -0,0 +1,92 @@ +//! Media delivery is the caller's choice, and the advertised profile is where +//! that choice lives. +//! +//! Before this, `media` was hardcoded `Reliable` in two places — the profile +//! builder and the per-channel send options — so no caller could say otherwise. +//! A producer asking for an unreliable media lane got a reliable one that +//! retransmits under loss, which adds load exactly when the link has least to +//! give. Muninn asked for that lane by passing no expiry, meaning "unreliable, +//! so expiry is moot", and got reliable-with-no-expiry instead: retransmit +//! forever. +//! +//! The default stays `Reliable` so every existing consumer is untouched. + +use std::net::UdpSocket; + +use cultnet_rs::{ + CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportOptions, + CultNetTransportDelivery, +}; + +fn media_channel_delivery( + media_delivery: Option, +) -> (CultNetTransportDelivery, Option) { + let socket = UdpSocket::bind("127.0.0.1:0").expect("binds"); + let endpoint = "127.0.0.1:5204".parse().expect("parses"); + let mut options = CultNetRudpSocketTransportOptions::client("test-media", socket, endpoint, 7); + options.media_delivery = media_delivery; + options.media_reliable_expire_after_ms = None; + + let transport = CultNetRudpSocketTransportConnection::new(options).expect("opens"); + let channel = transport + .profile + .transports + .first() + .expect("a transport") + .channels + .iter() + .find(|channel| channel.channel_id == "media") + .expect("a media channel"); + (channel.delivery, channel.reliable_expire_after_ms) +} + +#[test] +fn media_defaults_to_reliable_so_existing_consumers_do_not_move() { + let (delivery, _) = media_channel_delivery(None); + assert_eq!(delivery, CultNetTransportDelivery::Reliable); +} + +#[test] +fn a_caller_can_ask_for_an_unreliable_media_lane() { + let (delivery, expiry) = media_channel_delivery(Some(CultNetTransportDelivery::Unreliable)); + assert_eq!(delivery, CultNetTransportDelivery::Unreliable); + assert_eq!( + expiry, None, + "an unreliable channel has nothing to expire; the pairing should stay honest" + ); +} + +#[test] +fn asking_for_reliable_explicitly_matches_the_default() { + let (explicit, _) = media_channel_delivery(Some(CultNetTransportDelivery::Reliable)); + let (defaulted, _) = media_channel_delivery(None); + assert_eq!(explicit, defaulted); +} + +/// The channels whose semantics are fixed by design must not drift with this. +#[test] +fn the_other_channels_keep_their_fixed_delivery() { + let socket = UdpSocket::bind("127.0.0.1:0").expect("binds"); + let endpoint = "127.0.0.1:5204".parse().expect("parses"); + let mut options = CultNetRudpSocketTransportOptions::client("test-media", socket, endpoint, 8); + options.media_delivery = Some(CultNetTransportDelivery::Unreliable); + + let transport = CultNetRudpSocketTransportConnection::new(options).expect("opens"); + let channels = &transport + .profile + .transports + .first() + .expect("a transport") + .channels; + + let delivery_of = |id: &str| { + channels + .iter() + .find(|channel| channel.channel_id == id) + .unwrap_or_else(|| panic!("channel {id}")) + .delivery + }; + + assert_eq!(delivery_of("schema"), CultNetTransportDelivery::Reliable); + assert_eq!(delivery_of("realtime"), CultNetTransportDelivery::Unreliable); +} From a3e6877945f22134af99999a60f85cf7acc16056 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 10 Sep 2026 02:00:19 +0200 Subject: [PATCH 4/5] Move the media wire envelope where both ends can reach it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A media record travels wrapped in cultnet.document_put_raw.v0 with a schema id, a record key and provenance. Both ends have to agree on that exactly, and until now only Muninn had it: the producer was Rust in one repository and the consumer was 6,515 lines of C++ in another, each with its own reading of the same bytes. Ratatoskr could not decode a real stream without it. Two things change in the move rather than after it. The producer namespace is now the caller's. The Muninn implementation hardcoded "muninn-media:" into every message id and "muninn.media" into every tag, so a second producer would have had to label its traffic as Muninn's to be understood. `MediaWireProvenance` carries it instead, and a test asserts the envelope names no producer the caller did not supply. The four hand-written wire payload structs are gone. Each restated a record's entire field list as a positional tuple, in order, kept in step by discipline alone — and existed for one reason: `#[serde(with = "serde_bytes")]` on the payload, which cannot be applied to a DatabaseEntry struct because the derive does not read serde attributes. Now that the records carry `#[cultcache(key = N, bytes)]` the derive emits bin itself, so the records serialize directly. That last part is a wire claim, so it is tested rather than asserted: `the_derive_reproduces_the_hand_written_wire_payload_byte_for_byte` reconstructs the legacy struct and compares output byte for byte. It matches, which makes the deletion a simplification instead of a silent break. Record key shapes move here too. A consumer parses them to tell a chunk from its siblings and a retransmission from a new frame, so they are contract and belong beside the records rather than in whichever producer wrote them first. Muninn's copies are not removed yet; that is the other half of this move. Co-Authored-By: Claude Opus 5 --- packages/cultnet-rs/src/lib.rs | 2 + packages/cultnet-rs/src/media_stream_wire.rs | 185 +++++++++++++++ .../cultnet-rs/tests/media_stream_wire.rs | 217 ++++++++++++++++++ 3 files changed, 404 insertions(+) create mode 100644 packages/cultnet-rs/src/media_stream_wire.rs create mode 100644 packages/cultnet-rs/tests/media_stream_wire.rs diff --git a/packages/cultnet-rs/src/lib.rs b/packages/cultnet-rs/src/lib.rs index 5aa121af..074c2a29 100644 --- a/packages/cultnet-rs/src/lib.rs +++ b/packages/cultnet-rs/src/lib.rs @@ -2,6 +2,7 @@ mod contracts; mod idunn_deployment_brake; mod idunn_lifecycle_brake; mod media_stream_contracts; +mod media_stream_wire; mod provider_health_contracts; mod runtime_authority_contracts; mod service_identity; @@ -21,6 +22,7 @@ pub use contracts::*; pub use idunn_deployment_brake::*; pub use idunn_lifecycle_brake::*; pub use media_stream_contracts::*; +pub use media_stream_wire::*; pub use provider_health_contracts::*; pub use runtime_authority_contracts::*; pub use service_identity::*; diff --git a/packages/cultnet-rs/src/media_stream_wire.rs b/packages/cultnet-rs/src/media_stream_wire.rs new file mode 100644 index 00000000..2959eef8 --- /dev/null +++ b/packages/cultnet-rs/src/media_stream_wire.rs @@ -0,0 +1,185 @@ +//! How a CultMesh Media Stream record travels: the envelope both ends must +//! agree on. +//! +//! The records in `media_stream_contracts` describe media. This describes how +//! one reaches a peer — wrapped in `cultnet.document_put_raw.v0` with a schema +//! id, a record key, and provenance. It lives here because a producer and a +//! consumer that never link each other still have to agree on it exactly, and +//! the last time they did not, one end was Rust and the other was 6,515 lines +//! of C++ that had drifted. +//! +//! # No producer's name belongs in a shared envelope +//! +//! The Muninn implementation this replaces hardcoded `"muninn-media:"` into +//! every message id and `"muninn.media"` into every tag, so a second producer +//! would have had to label its traffic as Muninn's. The producer namespace is a +//! parameter here: see [`MediaWireProvenance`]. +//! +//! # Record keys are addresses, not decoration +//! +//! A key identifies one piece of media within a session, so a consumer can tell +//! a retransmission from a new frame and a chunk from its siblings. The shapes +//! are fixed by this module rather than by each producer, because a consumer +//! parses them. + +use anyhow::{Result, anyhow}; + +use crate::contracts::{ + CultNetMessage, CultNetRawDocumentRecord, CultNetRawPayloadEncoding, CultNetWireContract, + decode_cultnet_message_from_slice, encode_cultnet_message_to_vec, +}; +use crate::media_stream_contracts::{ + GAMECULT_MEDIA_AUDIO_PACKET_SCHEMA, GAMECULT_MEDIA_RECEIVER_FEEDBACK_SCHEMA, + GAMECULT_MEDIA_VIDEO_ACCESS_UNIT_SCHEMA, GAMECULT_MEDIA_VIDEO_PARITY_SHARD_SCHEMA, + GameCultMediaAudioPacketRecord, GameCultMediaReceiverFeedbackRecord, + GameCultMediaVideoAccessUnitRecord, GameCultMediaVideoParityShardRecord, +}; + +/// The CultNet channel media rides. +pub const GAMECULT_MEDIA_CHANNEL: &str = "media"; + +/// One media record on its way somewhere. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum GameCultMediaWireRecord { + Video(GameCultMediaVideoAccessUnitRecord), + VideoParity(GameCultMediaVideoParityShardRecord), + Audio(GameCultMediaAudioPacketRecord), + Feedback(GameCultMediaReceiverFeedbackRecord), +} + +/// Who is sending, and when. `producer` namespaces message ids and tags so a +/// stream can be attributed without the envelope knowing any producer by name. +#[derive(Clone, Copy, Debug)] +pub struct MediaWireProvenance<'a> { + pub stored_at: &'a str, + pub runtime_id: &'a str, + pub role: &'a str, + pub producer: &'a str, +} + +impl MediaWireProvenance<'_> { + fn validate(&self) -> Result<()> { + for (name, value) in [ + ("stored_at", self.stored_at), + ("runtime_id", self.runtime_id), + ("role", self.role), + ("producer", self.producer), + ] { + if value.is_empty() { + return Err(anyhow!("media wire provenance {name} must be non-empty")); + } + } + Ok(()) + } +} + +impl GameCultMediaWireRecord { + pub fn schema_id(&self) -> &'static str { + match self { + Self::Video(_) => GAMECULT_MEDIA_VIDEO_ACCESS_UNIT_SCHEMA, + Self::VideoParity(_) => GAMECULT_MEDIA_VIDEO_PARITY_SHARD_SCHEMA, + Self::Audio(_) => GAMECULT_MEDIA_AUDIO_PACKET_SCHEMA, + Self::Feedback(_) => GAMECULT_MEDIA_RECEIVER_FEEDBACK_SCHEMA, + } + } + + /// Addresses this record within its session. + pub fn record_key(&self) -> String { + match self { + Self::Video(record) => format!( + "{}:{}:video:{}:{}", + record.stream_id, record.session_id, record.frame_id, record.chunk_index + ), + Self::VideoParity(record) => format!( + "{}:{}:video-parity:{}:{}", + record.stream_id, record.session_id, record.frame_id, record.parity_index + ), + Self::Audio(record) => format!( + "{}:{}:audio:{}", + record.stream_id, record.session_id, record.packet_id + ), + Self::Feedback(record) => format!( + "{}:{}:feedback:{}", + record.stream_id, record.session_id, record.receiver_id + ), + } + } + + /// The record's own MessagePack form. + /// + /// Serializing the record directly is only correct because the payload + /// fields carry `#[cultcache(key = N, bytes)]`. Muninn previously mirrored + /// each record into a parallel tuple struct — every field restated, in + /// order, by hand — solely so `#[serde(with = "serde_bytes")]` could be + /// applied to the payload, because the `DatabaseEntry` derive does not read + /// serde attributes. Those shadow structs are gone; the derive emits `bin` + /// itself now. Do not reintroduce one. + fn payload_bytes(&self) -> Result> { + match self { + Self::Video(record) => rmp_serde::to_vec(record), + Self::VideoParity(record) => rmp_serde::to_vec(record), + Self::Audio(record) => rmp_serde::to_vec(record), + Self::Feedback(record) => rmp_serde::to_vec(record), + } + .map_err(Into::into) + } +} + +/// Wraps a media record for the wire. +pub fn encode_media_wire_record( + record: &GameCultMediaWireRecord, + provenance: MediaWireProvenance<'_>, +) -> Result> { + provenance.validate()?; + + let schema_id = record.schema_id(); + let record_key = record.record_key(); + let message = CultNetMessage::DocumentPutRaw { + message_id: format!( + "{}-media:{}:{}", + provenance.producer, + schema_id, + record_key.replace(':', "-") + ), + document: CultNetRawDocumentRecord { + schema_id: schema_id.to_string(), + record_key, + stored_at: provenance.stored_at.to_string(), + payload_encoding: CultNetRawPayloadEncoding::Messagepack, + payload: record.payload_bytes()?, + source_runtime_id: Some(provenance.runtime_id.to_string()), + source_agent_id: None, + source_role: Some(provenance.role.to_string()), + tags: Some(vec![format!("{}.media", provenance.producer)]), + }, + }; + + encode_cultnet_message_to_vec(&message, CultNetWireContract::CultNetSchemaV0).map_err(Into::into) +} + +/// Unwraps a media record from the wire. +pub fn decode_media_wire_record(payload: &[u8]) -> Result { + let message = decode_cultnet_message_from_slice(payload, CultNetWireContract::CultNetSchemaV0)?; + let CultNetMessage::DocumentPutRaw { document, .. } = message else { + return Err(anyhow!("expected cultnet.document_put_raw.v0")); + }; + if document.payload_encoding != CultNetRawPayloadEncoding::Messagepack { + return Err(anyhow!("media document payload must be MessagePack")); + } + + match document.schema_id.as_str() { + GAMECULT_MEDIA_VIDEO_ACCESS_UNIT_SCHEMA => Ok(GameCultMediaWireRecord::Video( + rmp_serde::from_slice(&document.payload)?, + )), + GAMECULT_MEDIA_VIDEO_PARITY_SHARD_SCHEMA => Ok(GameCultMediaWireRecord::VideoParity( + rmp_serde::from_slice(&document.payload)?, + )), + GAMECULT_MEDIA_AUDIO_PACKET_SCHEMA => Ok(GameCultMediaWireRecord::Audio( + rmp_serde::from_slice(&document.payload)?, + )), + GAMECULT_MEDIA_RECEIVER_FEEDBACK_SCHEMA => Ok(GameCultMediaWireRecord::Feedback( + rmp_serde::from_slice(&document.payload)?, + )), + other => Err(anyhow!("unknown media schema {other}")), + } +} diff --git a/packages/cultnet-rs/tests/media_stream_wire.rs b/packages/cultnet-rs/tests/media_stream_wire.rs new file mode 100644 index 00000000..cee31a04 --- /dev/null +++ b/packages/cultnet-rs/tests/media_stream_wire.rs @@ -0,0 +1,217 @@ +//! The envelope, and one proof that removing Muninn's shadow structs changed +//! nothing on the wire. + +use cultnet_rs::{ + GAMECULT_MEDIA_CHANNEL, GameCultMediaAudioPacketRecord, GameCultMediaReceiverFeedbackRecord, + GameCultMediaVideoAccessUnitRecord, GameCultMediaVideoParityShardRecord, + GameCultMediaWireRecord, MediaWireProvenance, decode_media_wire_record, + encode_media_wire_record, +}; +use serde::Serialize; + +fn provenance() -> MediaWireProvenance<'static> { + MediaWireProvenance { + stored_at: "unix:1000", + runtime_id: "raven", + role: "muninn.media", + producer: "muninn", + } +} + +fn access_unit() -> GameCultMediaVideoAccessUnitRecord { + GameCultMediaVideoAccessUnitRecord { + stream_id: "raven-primary-av".to_string(), + session_id: "session-1".to_string(), + frame_id: 4242, + codec: "h264".to_string(), + pts_ticks: 90_000, + duration_ticks: 3_000, + timebase_num: 1, + timebase_den: 90_000, + keyframe: true, + dependency_frame_id: None, + deadline_ticks: 108_000, + chunk_index: 2, + chunk_count: 5, + payload: (0u8..=255).collect(), + } +} + +/// Muninn's `VideoAccessUnitWirePayload`, reproduced exactly as it was. +/// +/// It existed only so `#[serde(with = "serde_bytes")]` could reach the payload, +/// because the `DatabaseEntry` derive ignores serde attributes. Every other +/// field was restated by hand, in order, and had to stay in step with the record +/// by discipline alone. +#[derive(Serialize)] +struct LegacyVideoAccessUnitWirePayload<'a>( + &'a str, + &'a str, + u64, + &'a str, + i64, + u32, + u32, + u32, + bool, + Option, + i64, + u16, + u16, + #[serde(with = "serde_bytes")] &'a [u8], +); + +/// If these differ, deleting the shadow structs was a wire break rather than a +/// simplification, and every existing consumer would need to move in step. +#[test] +fn the_derive_reproduces_the_hand_written_wire_payload_byte_for_byte() { + let record = access_unit(); + let legacy = LegacyVideoAccessUnitWirePayload( + &record.stream_id, + &record.session_id, + record.frame_id, + &record.codec, + record.pts_ticks, + record.duration_ticks, + record.timebase_num, + record.timebase_den, + record.keyframe, + record.dependency_frame_id, + record.deadline_ticks, + record.chunk_index, + record.chunk_count, + &record.payload, + ); + + let from_derive = rmp_serde::to_vec(&record).expect("record encodes"); + let from_shadow = rmp_serde::to_vec(&legacy).expect("shadow struct encodes"); + + assert_eq!( + from_derive, from_shadow, + "the `bytes` attribute must reproduce what serde_bytes produced by hand" + ); +} + +#[test] +fn a_video_record_round_trips_through_the_envelope() { + let record = GameCultMediaWireRecord::Video(access_unit()); + let wire = encode_media_wire_record(&record, provenance()).expect("encodes"); + assert_eq!(decode_media_wire_record(&wire).expect("decodes"), record); +} + +#[test] +fn every_variant_round_trips() { + let variants = vec![ + GameCultMediaWireRecord::Video(access_unit()), + GameCultMediaWireRecord::VideoParity(GameCultMediaVideoParityShardRecord { + stream_id: "s".to_string(), + session_id: "x".to_string(), + frame_id: 1, + codec: "h264".to_string(), + pts_ticks: 0, + duration_ticks: 1, + timebase_num: 1, + timebase_den: 90_000, + keyframe: false, + dependency_frame_id: Some(0), + deadline_ticks: 1, + chunk_count: 4, + parity_index: 1, + parity_count: 2, + chunk_payload_bytes: 848, + last_chunk_payload_bytes: 400, + payload: vec![1, 2, 3], + }), + GameCultMediaWireRecord::Audio(GameCultMediaAudioPacketRecord { + stream_id: "s".to_string(), + session_id: "x".to_string(), + packet_id: 9, + codec: "opus".to_string(), + pts_ticks: 0, + duration_ticks: 960, + timebase_num: 1, + timebase_den: 48_000, + deadline_ticks: 1, + payload: vec![4, 5, 6], + }), + GameCultMediaWireRecord::Feedback(GameCultMediaReceiverFeedbackRecord { + stream_id: "s".to_string(), + session_id: "x".to_string(), + receiver_id: "starfire-obs".to_string(), + highest_decodable_frame_id: Some(41), + missing_frame_ids: vec![42], + late_frame_ids: vec![43], + requested_keyframe: true, + jitter_us: 500, + decode_queue_us: 2_000, + observed_at: "unix:1000".to_string(), + missing_video_chunk_keys: vec!["42:1".to_string()], + }), + ]; + + for record in variants { + let wire = encode_media_wire_record(&record, provenance()).expect("encodes"); + assert_eq!( + decode_media_wire_record(&wire).expect("decodes"), + record, + "variant {} did not survive the envelope", + record.schema_id() + ); + } +} + +/// Record keys address one piece of media within a session. A consumer parses +/// them, so their shape is contract. +#[test] +fn record_keys_distinguish_chunks_parity_and_senders() { + let mut second_chunk = access_unit(); + second_chunk.chunk_index = 3; + + let first = GameCultMediaWireRecord::Video(access_unit()).record_key(); + let second = GameCultMediaWireRecord::Video(second_chunk).record_key(); + assert_ne!(first, second, "chunks of one frame must not share a key"); + assert!(first.contains(":video:"), "got {first}"); +} + +/// A shared envelope must not label another producer's traffic as Muninn's. +#[test] +fn the_producer_namespace_is_the_callers_not_the_envelopes() { + let record = GameCultMediaWireRecord::Video(access_unit()); + let theirs = MediaWireProvenance { + stored_at: "unix:1000", + runtime_id: "nightwing", + role: "brokkr.media", + producer: "brokkr", + }; + + let wire = encode_media_wire_record(&record, theirs).expect("encodes"); + let text = String::from_utf8_lossy(&wire); + assert!(text.contains("brokkr-media:"), "message id names the producer"); + assert!(text.contains("brokkr.media"), "tag names the producer"); + assert!( + !text.contains("muninn"), + "the envelope must not name a producer the caller did not supply" + ); +} + +#[test] +fn provenance_must_be_complete() { + let record = GameCultMediaWireRecord::Video(access_unit()); + for blank in ["stored_at", "runtime_id", "role", "producer"] { + let mut incomplete = provenance(); + match blank { + "stored_at" => incomplete.stored_at = "", + "runtime_id" => incomplete.runtime_id = "", + "role" => incomplete.role = "", + _ => incomplete.producer = "", + } + let error = encode_media_wire_record(&record, incomplete) + .expect_err("empty provenance must be refused"); + assert!(error.to_string().contains(blank), "got {error}"); + } +} + +#[test] +fn the_media_channel_is_named_once() { + assert_eq!(GAMECULT_MEDIA_CHANNEL, "media"); +} From 96138ffcfa7d48fe00d31079d7859baa1f3c9a58 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 10 Sep 2026 02:23:56 +0200 Subject: [PATCH 5/5] Validate on decode, where both ends inherit it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Moving the envelope moved less than it should have. Muninn's decoder validated every record and checked the envelope's key against the key derived from the record's own contents; the version that landed here did neither, so the move was quietly a downgrade. Six of Muninn's tests failed on the switch and said so, which is the only reason this is a paragraph rather than a bug. The four record validators and the video chunk key move here with it. They check the contract, not one producer's use of it: non-empty identifiers, non-zero timebases, sane pressure figures, well-formed chunk keys. Left in Muninn they would have protected the producer and left every consumer to invent its own idea of a well-formed record — which is how a C++ receiver and a Rust sender came to disagree while each looked correct alone. The record-key check is the sharper one. A key is derived from the record it addresses, so a mismatch means envelope and payload disagree about what the thing is. Admitting that would let a consumer address media by a key its producer never meant. VideoChunkKey comes too. Its string form ("42:1") travels in receiver feedback and is parsed at the other end, so it was already contract living in a producer. Co-Authored-By: Claude Opus 5 --- packages/cultnet-rs/src/media_stream_wire.rs | 290 ++++++++++++++++++- 1 file changed, 276 insertions(+), 14 deletions(-) diff --git a/packages/cultnet-rs/src/media_stream_wire.rs b/packages/cultnet-rs/src/media_stream_wire.rs index 2959eef8..7083d927 100644 --- a/packages/cultnet-rs/src/media_stream_wire.rs +++ b/packages/cultnet-rs/src/media_stream_wire.rs @@ -167,19 +167,281 @@ pub fn decode_media_wire_record(payload: &[u8]) -> Result Ok(GameCultMediaWireRecord::Video( - rmp_serde::from_slice(&document.payload)?, - )), - GAMECULT_MEDIA_VIDEO_PARITY_SHARD_SCHEMA => Ok(GameCultMediaWireRecord::VideoParity( - rmp_serde::from_slice(&document.payload)?, - )), - GAMECULT_MEDIA_AUDIO_PACKET_SCHEMA => Ok(GameCultMediaWireRecord::Audio( - rmp_serde::from_slice(&document.payload)?, - )), - GAMECULT_MEDIA_RECEIVER_FEEDBACK_SCHEMA => Ok(GameCultMediaWireRecord::Feedback( - rmp_serde::from_slice(&document.payload)?, - )), - other => Err(anyhow!("unknown media schema {other}")), + let record = match document.schema_id.as_str() { + GAMECULT_MEDIA_VIDEO_ACCESS_UNIT_SCHEMA => { + let record: GameCultMediaVideoAccessUnitRecord = + rmp_serde::from_slice(&document.payload)?; + validate_video_record(&record)?; + GameCultMediaWireRecord::Video(record) + } + GAMECULT_MEDIA_VIDEO_PARITY_SHARD_SCHEMA => { + let record: GameCultMediaVideoParityShardRecord = + rmp_serde::from_slice(&document.payload)?; + validate_video_parity_record(&record)?; + GameCultMediaWireRecord::VideoParity(record) + } + GAMECULT_MEDIA_AUDIO_PACKET_SCHEMA => { + let record: GameCultMediaAudioPacketRecord = + rmp_serde::from_slice(&document.payload)?; + validate_audio_record(&record)?; + GameCultMediaWireRecord::Audio(record) + } + GAMECULT_MEDIA_RECEIVER_FEEDBACK_SCHEMA => { + let record: GameCultMediaReceiverFeedbackRecord = + rmp_serde::from_slice(&document.payload)?; + validate_feedback_record(&record)?; + GameCultMediaWireRecord::Feedback(record) + } + other => return Err(anyhow!("unsupported media schema {other}")), + }; + + // The key is derived from the record's own contents, so a mismatch means the + // envelope and its payload disagree about what this is. Admitting it would + // let a consumer address media by a key its producer never meant. + let expected = record.record_key(); + if document.record_key != expected { + return Err(anyhow!( + "record key mismatch: envelope says {}, record derives {expected}", + document.record_key + )); + } + + Ok(record) +} + +// --------------------------------------------------------------------------- +// Validation +// +// Moved here from Muninn with the envelope. A decoder that does not validate +// leaves each consumer to invent its own idea of a well-formed record, which is +// how the C++ receiver and the Rust sender came to disagree while both looked +// correct in isolation. Muninn's tests for these came too; they now cover the +// contract rather than one producer's copy of it. +// --------------------------------------------------------------------------- + +/// Addresses one chunk of a video frame. The string form appears in receiver +/// feedback and is parsed by consumers, so its shape is contract. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct VideoChunkKey { + pub frame_id: u64, + pub chunk_index: u16, +} + +impl VideoChunkKey { + pub fn new(frame_id: u64, chunk_index: u16) -> Self { + Self { + frame_id, + chunk_index, + } + } + + pub fn parse(value: &str) -> Result { + if value.matches(':').count() != 1 { + return Err(anyhow!( + "video chunk key must contain exactly one ':' separator" + )); + } + let (frame_id, chunk_index) = value + .split_once(':') + .ok_or_else(|| anyhow!("video chunk key must be ':'"))?; + Ok(Self { + frame_id: frame_id + .parse() + .map_err(|_| anyhow!("video chunk key frame_id must be an integer"))?, + chunk_index: chunk_index + .parse() + .map_err(|_| anyhow!("video chunk key chunk_index must be an integer"))?, + }) + } + + pub fn as_feedback_key(&self) -> String { + format!("{}:{}", self.frame_id, self.chunk_index) } } + +pub fn video_chunk_feedback_key(frame_id: u64, chunk_index: u16) -> String { + VideoChunkKey::new(frame_id, chunk_index).as_feedback_key() +} + +pub fn normalize_video_chunk_feedback_keys(keys: Vec) -> Result> { + let mut parsed = keys + .iter() + .map(|key| VideoChunkKey::parse(key)) + .collect::>>()?; + parsed.sort_unstable(); + parsed.dedup(); + Ok(parsed + .into_iter() + .map(|key| key.as_feedback_key()) + .collect()) +} + +pub fn validate_video_record(record: &GameCultMediaVideoAccessUnitRecord) -> Result<()> { + if record.stream_id.is_empty() { + return Err(anyhow!("video media record stream_id must be non-empty")); + } + if record.session_id.is_empty() { + return Err(anyhow!("video media record session_id must be non-empty")); + } + if record.codec.is_empty() { + return Err(anyhow!("video media record codec must be non-empty")); + } + if record.timebase_num == 0 || record.timebase_den == 0 { + return Err(anyhow!("video media record timebase must be non-zero")); + } + if record.duration_ticks == 0 { + return Err(anyhow!( + "video media record duration_ticks must be greater than zero" + )); + } + if record.deadline_ticks < record.pts_ticks { + return Err(anyhow!( + "video media record deadline_ticks must not precede pts_ticks" + )); + } + if record.chunk_count == 0 { + return Err(anyhow!("video media record chunk_count must be non-zero")); + } + if record.chunk_index >= record.chunk_count { + return Err(anyhow!( + "video media record chunk_index {} is outside chunk_count {}", + record.chunk_index, + record.chunk_count + )); + } + if record.payload.is_empty() { + return Err(anyhow!("video media record payload must be non-empty")); + } + Ok(()) +} + +pub fn validate_video_parity_record(record: &GameCultMediaVideoParityShardRecord) -> Result<()> { + if record.stream_id.is_empty() { + return Err(anyhow!( + "video parity media record stream_id must be non-empty" + )); + } + if record.session_id.is_empty() { + return Err(anyhow!( + "video parity media record session_id must be non-empty" + )); + } + if record.codec.is_empty() { + return Err(anyhow!("video parity media record codec must be non-empty")); + } + if record.timebase_num == 0 || record.timebase_den == 0 { + return Err(anyhow!( + "video parity media record timebase must be non-zero" + )); + } + if record.duration_ticks == 0 { + return Err(anyhow!( + "video parity media record duration_ticks must be greater than zero" + )); + } + if record.deadline_ticks < record.pts_ticks { + return Err(anyhow!( + "video parity media record deadline_ticks must not precede pts_ticks" + )); + } + if record.chunk_count == 0 { + return Err(anyhow!( + "video parity media record chunk_count must be non-zero" + )); + } + if record.parity_count == 0 || record.parity_index >= record.parity_count { + return Err(anyhow!( + "video parity media record has invalid parity stripe metadata" + )); + } + if record.parity_count > record.chunk_count { + return Err(anyhow!( + "video parity media record parity_count exceeds chunk_count" + )); + } + if record.chunk_payload_bytes == 0 || record.last_chunk_payload_bytes == 0 { + return Err(anyhow!( + "video parity media record chunk lengths must be non-zero" + )); + } + if record.last_chunk_payload_bytes > record.chunk_payload_bytes { + return Err(anyhow!( + "video parity media record last chunk length exceeds regular chunk length" + )); + } + if record.payload.is_empty() { + return Err(anyhow!( + "video parity media record payload must be non-empty" + )); + } + if record.payload.len() > record.chunk_payload_bytes as usize { + return Err(anyhow!( + "video parity media record payload exceeds declared chunk length" + )); + } + Ok(()) +} + +pub fn validate_audio_record(record: &GameCultMediaAudioPacketRecord) -> Result<()> { + if record.stream_id.is_empty() { + return Err(anyhow!("audio media record stream_id must be non-empty")); + } + if record.session_id.is_empty() { + return Err(anyhow!("audio media record session_id must be non-empty")); + } + if record.codec.is_empty() { + return Err(anyhow!("audio media record codec must be non-empty")); + } + if record.timebase_num == 0 || record.timebase_den == 0 { + return Err(anyhow!("audio media record timebase must be non-zero")); + } + if record.duration_ticks == 0 { + return Err(anyhow!( + "audio media record duration_ticks must be greater than zero" + )); + } + if record.deadline_ticks < record.pts_ticks { + return Err(anyhow!( + "audio media record deadline_ticks must not precede pts_ticks" + )); + } + if record.payload.is_empty() { + return Err(anyhow!("audio media record payload must be non-empty")); + } + Ok(()) +} + +pub fn validate_feedback_record(record: &GameCultMediaReceiverFeedbackRecord) -> Result<()> { + if record.stream_id.is_empty() { + return Err(anyhow!( + "receiver feedback media record stream_id must be non-empty" + )); + } + if record.session_id.is_empty() { + return Err(anyhow!( + "receiver feedback media record session_id must be non-empty" + )); + } + if record.receiver_id.is_empty() { + return Err(anyhow!( + "receiver feedback media record receiver_id must be non-empty" + )); + } + if record.observed_at.is_empty() { + return Err(anyhow!( + "receiver feedback media record observed_at must be non-empty" + )); + } + if record.jitter_us < 0 { + return Err(anyhow!( + "receiver feedback media record jitter_us must be non-negative" + )); + } + if record.decode_queue_us < 0 { + return Err(anyhow!( + "receiver feedback media record decode_queue_us must be non-negative" + )); + } + normalize_video_chunk_feedback_keys(record.missing_video_chunk_keys.clone())?; + Ok(()) +}