//! Same-ledger immutable nested payload chunks (`SMH-SPEC-SPEC0001`). //! Wire: root/call/effect (16 bytes each), effect index (u16), phase (u8), //! ordinal (u16), then 1..=64 KiB bytes; integers are little endian. //! Each phase is contiguous: full chunks followed by at most one short chunk. //! Logical length comes from its publishing marker; count derives by ceiling division. use super::{FRAME_PREFIX_LEN, Frame, fault, schema, seal}; use crate::metadata::{NESTED_CHUNK_BYTES_MAX, NESTED_CHUNKS_MAX}; use smith::error::{FrameFault, Result}; use smith::id::{EntryId, ToolCallId}; const CHUNK_HEADER_LEN: usize = 3 * 16 + 2 + 1 + 2; /// Which canonical value the chunks precede. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum NestedPayloadPhase { /// Must become durable before the intent acknowledgement and effect dispatch. Input, /// Must become durable before the atomic completion acknowledgement. Output, } /// One CRC-protected immutable chunk; never a conversation/history member. /// Owned for one frame only, not copied into the resident session arena. #[derive(Clone, Debug, PartialEq, Eq)] pub struct NestedPayloadChunk { /// Admitted root. pub submission_id: EntryId, /// Outer call. pub call_id: ToolCallId, /// Stable nested intent entry identity, shared by both phases. pub effect_id: EntryId, /// Nested effect ordinal. pub index: u16, /// Canonical value being stored. pub phase: NestedPayloadPhase, /// Zero-based contiguous chunk ordinal. pub ordinal: u16, /// Exact bytes, possibly split within a UTF-8 scalar. pub bytes: Vec, } impl NestedPayloadChunk { pub(crate) fn validate(&self) -> std::result::Result<(), FrameFault> { if self.submission_id.as_u128() == 0 || self.call_id.as_u128() == 0 || self.effect_id.as_u128() == 0 || self.index >= crate::metadata::NESTED_EFFECTS_MAX || usize::from(self.ordinal) >= NESTED_CHUNKS_MAX || self.bytes.is_empty() || self.bytes.len() > NESTED_CHUNK_BYTES_MAX { return Err(schema("invalid nested payload chunk")); } Ok(()) } } pub(super) fn encode(chunk: &NestedPayloadChunk, limit: usize) -> Result> { chunk.validate().map_err(fault)?; let mut out = Vec::with_capacity(FRAME_PREFIX_LEN + CHUNK_HEADER_LEN + chunk.bytes.len() + 4); out.resize(FRAME_PREFIX_LEN, 0); out.extend_from_slice(&chunk.submission_id.as_u128().to_le_bytes()); out.extend_from_slice(&chunk.call_id.as_u128().to_le_bytes()); out.extend_from_slice(&chunk.effect_id.as_u128().to_le_bytes()); out.extend_from_slice(&chunk.index.to_le_bytes()); out.push(match chunk.phase { NestedPayloadPhase::Input => 0, NestedPayloadPhase::Output => 1, }); out.extend_from_slice(&chunk.ordinal.to_le_bytes()); out.extend_from_slice(&chunk.bytes); seal(super::KIND_NESTED_PAYLOAD, 1, out, limit) } pub(super) fn decode(payload: &[u8]) -> std::result::Result { if payload.len() <= CHUNK_HEADER_LEN || payload.len() > CHUNK_HEADER_LEN + NESTED_CHUNK_BYTES_MAX { return Err(schema("invalid nested chunk length")); } let chunk = NestedPayloadChunk { submission_id: EntryId::from_u128(u128::from_le_bytes( payload[..16].try_into().map_err(|_| schema("chunk root"))?, )), call_id: ToolCallId::from_u128(u128::from_le_bytes( payload[16..32] .try_into() .map_err(|_| schema("chunk call"))?, )), effect_id: EntryId::from_u128(u128::from_le_bytes( payload[32..48] .try_into() .map_err(|_| schema("chunk effect"))?, )), index: u16::from_le_bytes([payload[48], payload[49]]), phase: match payload[50] { 0 => NestedPayloadPhase::Input, 1 => NestedPayloadPhase::Output, _ => return Err(schema("chunk phase")), }, ordinal: u16::from_le_bytes([payload[51], payload[52]]), bytes: payload[CHUNK_HEADER_LEN..].to_vec(), }; chunk.validate()?; Ok(Frame::NestedPayload { chunk: Box::new(chunk), }) } #[cfg(test)] mod tests { use super::*; use proptest::prelude::*; proptest! { #[test] fn chunk_codec_roundtrips_exact_bytes(bytes in prop::collection::vec(any::(), 1..=4096), ordinal in 0u16..512, output in any::()) { let frame = Frame::NestedPayload { chunk: Box::new(NestedPayloadChunk { submission_id: EntryId::from_u128(1), call_id: ToolCallId::from_u128(2), effect_id: EntryId::from_u128(3), index: 0, phase: if output { NestedPayloadPhase::Output } else { NestedPayloadPhase::Input }, ordinal, bytes, }) }; let encoded = frame.encode(8192).unwrap(); prop_assert_eq!(super::super::read_frames(&mut encoded.as_slice(), 8192).unwrap().frames, vec![frame]); } } }