Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-core/src/frame/nested.rs

Raw
//! SMH-SPEC-SPEC0001: atomic nested completion and root progress.
use super::{
    EntryFrame, FRAME_PREFIX_LEN, Frame, KIND_NESTED_COMMIT, encode_entry_fields, fault, schema,
    seal,
};
use crate::content_codec::EntryContentView;
use crate::metadata::{NESTED_COMPLETION_KIND, nested_causality, nested_identity};
use smith::error::{FrameFault, Result};

pub(super) fn is_causal_intent(content: &[u8]) -> bool {
    if !crate::content_codec::metadata_name(content)
        .is_ok_and(|name| name == Some(crate::metadata::NESTED_INTENT_KIND))
    {
        return false;
    }
    matches!(EntryContentView::decode(content),
        Ok(EntryContentView::Meta { kind: crate::metadata::NESTED_INTENT_KIND, detail })
            if nested_causality(detail).is_ok_and(|causal| causal.is_some()))
}

pub(super) fn decode_intent(payload: &[u8]) -> std::result::Result<Frame, FrameFault> {
    let entry = super::decode_entry(payload)?;
    if !matches!(entry.kind, crate::session::EntryKind::Meta { .. })
        || !is_causal_intent(&entry.content)
    {
        return Err(schema("causal intent requires explicit typed identity"));
    }
    Ok(Frame::Known { entry })
}

pub fn validate(entry: &EntryFrame) -> std::result::Result<(), FrameFault> {
    let content = EntryContentView::decode(&entry.content)
        .map_err(|_| schema("invalid nested completion content"))?;
    if entry.id.as_u128() == 0 || entry.parent.is_none() || content.kind() != entry.kind {
        return Err(schema("invalid nested completion identity"));
    }
    let EntryContentView::Meta {
        kind: NESTED_COMPLETION_KIND,
        detail,
    } = content
    else {
        return Err(schema("nested commit requires typed completion checkpoint"));
    };
    crate::metadata::validate(NESTED_COMPLETION_KIND, detail)
        .map_err(|_| schema("invalid nested completion schema"))?;
    nested_identity(detail).map_err(|_| schema("invalid nested checkpoint"))?;
    Ok(())
}

fn causal(entry: &EntryFrame) -> std::result::Result<bool, FrameFault> {
    let EntryContentView::Meta { detail, .. } =
        EntryContentView::decode(&entry.content).map_err(|_| schema("invalid nested content"))?
    else {
        return Err(schema("nested content requires metadata"));
    };
    nested_causality(detail)
        .map(|causal| causal.is_some())
        .map_err(|_| schema("invalid nested causality"))
}

pub(super) fn encode(entry: &EntryFrame, limit: usize) -> Result<Vec<u8>> {
    validate(entry).map_err(fault)?;
    let member = encode_entry_fields(
        entry.id,
        entry.parent,
        entry.timestamp_ms,
        entry.kind,
        &entry.content,
        limit,
    )?;
    let mut out = Vec::with_capacity(FRAME_PREFIX_LEN + member.len() + 4);
    out.resize(FRAME_PREFIX_LEN, 0);
    out.extend(member);
    seal(
        KIND_NESTED_COMMIT,
        if causal(entry).map_err(fault)? { 2 } else { 1 },
        out,
        limit,
    )
}

pub(super) fn decode(mut payload: &[u8], version: u16) -> std::result::Result<Frame, FrameFault> {
    let entry = super::commit::member(&mut payload)?;
    if !payload.is_empty() {
        return Err(schema("nested commit trailing bytes"));
    }
    validate(&entry)?;
    if causal(&entry)? != (version == 2) {
        return Err(schema("nested causal semantics require version 2"));
    }
    Ok(Frame::NestedCommit { entry })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::metadata::{NESTED_EFFECTS_MAX, NestedEffectCompletion};
    use crate::session::EntryContent;
    use proptest::prelude::*;
    use smith::error::MutationState;
    use smith::id::{EntryId, ToolCallId};

    #[test]
    fn causal_intent_uses_required_envelope_and_rejects_flat_relabelling() {
        let effect_id = EntryId::from_u128(3);
        let causal = crate::metadata::NestedCausality {
            effect_id,
            parent: None,
            invocation: true,
        };
        let detail = crate::metadata::encode_nested(
            crate::metadata::NestedEffectIntent {
                submission_id: EntryId::from_u128(1),
                call_id: ToolCallId::from_u128(2),
                index: 0,
                operation: "write",
                component: None,
                input: "input",
            },
            Some(&causal),
        )
        .unwrap();
        let mut entry = EntryFrame::new(
            Some(EntryId::from_u128(4)),
            &EntryContent::Meta {
                kind: crate::metadata::NESTED_INTENT_KIND.into(),
                detail,
            },
        )
        .unwrap();
        entry.id = effect_id;
        let frame = Frame::Known { entry };
        let mut bytes = frame.encode(8192).unwrap();
        assert_eq!(
            u16::from_le_bytes([bytes[4], bytes[5]]),
            super::super::KIND_CAUSAL_INTENT
        );
        assert_eq!(
            super::super::read_frames(&mut bytes.as_slice(), 8192)
                .unwrap()
                .frames,
            vec![frame.clone()]
        );
        let frames = [
            Frame::Header {
                header: crate::session::Session::new().header(),
            },
            frame,
        ];
        assert!(crate::session::Session::from_frames(&frames).is_err());
        bytes.truncate(bytes.len() - 4);
        let flattened = seal(
            super::super::KIND_ENTRY,
            super::super::VERSION_ENTRY,
            bytes,
            8192,
        )
        .unwrap();
        let recovery = super::super::read_frames(&mut flattened.as_slice(), 8192).unwrap();
        assert!(recovery.frames.is_empty());
        assert_eq!(recovery.damage_count, 1);
    }

    proptest! {
        #[test]
        fn nested_completion_codec_roundtrips(
            index in 0..NESTED_EFFECTS_MAX,
            ok in any::<bool>(),
            explicit in any::<bool>(),
            invocation in any::<bool>(),
            output in ".{0,512}",
        ) {
            let causal = crate::metadata::NestedCausality {
                effect_id: EntryId::from_u128(3),
                parent: Some(EntryId::from_u128(4)),
                invocation,
            };
            let detail = crate::metadata::encode_nested(NestedEffectCompletion {
                submission_id: EntryId::from_u128(1), call_id: ToolCallId::from_u128(2),
                index, ok, mutation_state: if explicit && invocation { MutationState::NotApplied } else { MutationState::Unknown }, output,
            }, explicit.then_some(&causal)).unwrap();
            if explicit {
                let typed: crate::metadata::CausalRecord<NestedEffectCompletion> = detail.deserialize_as().unwrap();
                prop_assert_eq!(typed.causal, causal);
                prop_assert_eq!(typed.record.index, index);
            }
            let entry = EntryFrame::new(Some(EntryId::from_u128(5)), &EntryContent::Meta {
                kind: NESTED_COMPLETION_KIND.into(), detail,
            }).unwrap();
            let frame = Frame::NestedCommit { entry };
            let bytes = frame.encode(8192).unwrap();
            prop_assert_eq!(u16::from_le_bytes([bytes[6], bytes[7]]), if explicit { 2 } else { 1 });
            prop_assert_eq!(super::super::read_frames(&mut bytes.as_slice(), 8192).unwrap().frames, vec![frame]);
            if explicit {
                let mut downgraded = bytes;
                downgraded.truncate(downgraded.len() - 4);
                let downgraded = seal(KIND_NESTED_COMMIT, 1, downgraded, 8192).unwrap();
                prop_assert!(super::super::read_frames(&mut downgraded.as_slice(), 8192).is_err());
            }
        }
    }
}