Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-core/tests/atomic_completion_bounds.rs

Raw
//! SMH-SPEC-SPEC0001: exact completion record layout and codec allocation pins.
use smith::error::MutationState;
use smith::id::{EntryId, ToolCallId};
use smith::message::{ContentBlock, Message, Role};
use smith::structured::ToolArguments;
use smith_alloc::{Counting, Scope, measure};
use smith_core::frame::{Frame, ToolCompletionCheckpoint, read_frames};
use smith_core::metadata::{ToolMutationMetadata, encode};
use smith_core::session::{EntryContent, EntryFrame, TOOL_MUTATION_KIND};
use smith_core::tools::{ToolDispatcher, ToolEffectContext, ToolSession};

fn payload_chunk_codec_layout_and_allocations_are_exact() {
    use smith_core::frame::{NestedPayloadChunk, NestedPayloadPhase};
    #[cfg(target_arch = "x86_64")]
    {
        assert_eq!(std::mem::size_of::<NestedPayloadChunk>(), 80);
        assert_eq!(std::mem::size_of::<Frame>(), 120);
    }
    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: NestedPayloadPhase::Output,
            ordinal: 0,
            bytes: vec![b'x'; smith_core::metadata::NESTED_CHUNK_BYTES_MAX],
        }),
    };
    let (bytes, encoding) = measure(Scope::Session, || frame.encode(128 * 1024).unwrap());
    assert_eq!(encoding.allocations, 1);
    let (recovered, decoding) = measure(Scope::Session, || {
        read_frames(&mut bytes.as_slice(), 128 * 1024).unwrap()
    });
    assert_eq!(recovered.frames, vec![frame]);
    assert_eq!(decoding.allocations, 4);
}

fn nested_completion_codec_allocations_are_exact() {
    payload_chunk_codec_layout_and_allocations_are_exact();
    #[cfg(target_arch = "x86_64")]
    {
        assert_eq!(
            std::mem::size_of::<smith_core::metadata::NestedEffectIntent<'_>>(),
            80
        );
        assert_eq!(
            std::mem::size_of::<smith_core::metadata::NestedEffectCompletion>(),
            64
        );
    }
    let detail = encode(&smith_core::metadata::NestedEffectCompletion {
        submission_id: EntryId::from_u128(1),
        call_id: ToolCallId::from_u128(2),
        index: 0,
        ok: true,
        mutation_state: MutationState::Applied,
        output: "written".to_string(),
    })
    .unwrap();
    let frame = Frame::NestedCommit {
        entry: EntryFrame::new(
            Some(EntryId::from_u128(3)),
            &EntryContent::Meta {
                kind: smith_core::metadata::NESTED_COMPLETION_KIND.into(),
                detail,
            },
        )
        .unwrap(),
    };
    let (bytes, encoding) = measure(Scope::Session, || frame.encode(1024).unwrap());
    assert_eq!(encoding.allocations, 3);
    let (recovered, decoding) = measure(Scope::Session, || {
        read_frames(&mut bytes.as_slice(), 1024).unwrap()
    });
    assert_eq!(recovered.frames, vec![frame]);
    assert_eq!(decoding.allocations, 3);
}

struct PureDispatcher;
impl ToolDispatcher for PureDispatcher {
    fn invoke(
        &mut self,
        _: &str,
        _: &ToolArguments,
        _: &mut ToolEffectContext<'_>,
    ) -> smith::error::Result<String> {
        Ok(String::new())
    }
}

#[global_allocator]
static ALLOCATOR: Counting = Counting;

#[test]
fn completion_codec_allocations_and_layout_are_exact() {
    let submission_id = EntryId::new();
    let call_id = ToolCallId::new();
    let result = EntryFrame::new(
        Some(submission_id),
        &EntryContent::ToolResult {
            call_id,
            ok: true,
            output: "written".into(),
        },
    )
    .unwrap();
    let evidence = EntryFrame::new(
        Some(result.id),
        &EntryContent::Meta {
            kind: TOOL_MUTATION_KIND.into(),
            detail: encode(&ToolMutationMetadata::new(call_id, MutationState::Applied)).unwrap(),
        },
    )
    .unwrap();
    let mut message = Message::new(Role::Tool);
    message.add_block(ContentBlock::tool_result(call_id, true, "written"));
    let conversation = EntryFrame::new(Some(evidence.id), &EntryContent::Message(message)).unwrap();
    let frame = Frame::Commit {
        checkpoint: ToolCompletionCheckpoint {
            submission_id,
            call_id,
        },
        entries: Box::new([result, evidence, conversation]),
    };
    let (bytes, encoding) = measure(Scope::Session, || frame.encode(1024).unwrap());
    assert_eq!(encoding.allocations, 7);
    let (recovered, decoding) = measure(Scope::Session, || {
        read_frames(&mut bytes.as_slice(), 1024).unwrap()
    });
    assert_eq!(recovered.frames, vec![frame]);
    assert_eq!(decoding.allocations, 6);
    assert_eq!(std::mem::size_of::<ToolCompletionCheckpoint>(), 32);
    #[cfg(target_arch = "x86_64")]
    assert_eq!(std::mem::size_of::<Frame>(), 120);
    #[cfg(all(target_arch = "x86_64", target_os = "linux"))]
    assert_eq!(std::mem::size_of::<ToolEffectContext<'_>>(), 48);

    let mut tools = ToolSession::new(std::env::temp_dir());
    let submission = tools
        .session
        .append(&EntryContent::Message(Message::with_text(
            Role::User,
            "input",
        )))
        .unwrap()
        .id;
    tools.register(smith::tool::ToolMetadata::new("fixture", "Pure test tool"));
    tools.set_dispatcher(Box::new(PureDispatcher));
    let mut tools = tools.with_completion_boundary(submission, |frame| {
        assert!(matches!(frame, Frame::Commit { .. }));
        Ok(())
    });
    let arguments = ToolArguments::empty_object();
    let (outcome, completion) = measure(Scope::Session, || {
        tools.invoke("fixture", &arguments).unwrap()
    });
    assert!(outcome.ok);
    assert_eq!(completion.allocations, 24);
    assert_eq!(tools.session.active_branch().entries().len(), 5);
    nested_completion_codec_allocations_are_exact();
    causal_completion_layout_and_codec_allocations_are_exact();
}

fn causal_completion_layout_and_codec_allocations_are_exact() {
    use smith_core::metadata::{CausalRecord, NestedCausality, NestedEffectCompletion};
    assert_eq!(std::mem::size_of::<NestedCausality>(), 34);
    let detail = encode(&CausalRecord {
        causal: NestedCausality {
            effect_id: EntryId::from_u128(3),
            parent: Some(EntryId::from_u128(4)),
            invocation: true,
        },
        record: NestedEffectCompletion {
            submission_id: EntryId::from_u128(1),
            call_id: ToolCallId::from_u128(2),
            index: 0,
            ok: true,
            mutation_state: MutationState::NotApplied,
            output: "child",
        },
    })
    .unwrap();
    let frame = Frame::NestedCommit {
        entry: EntryFrame::new(
            Some(EntryId::from_u128(5)),
            &EntryContent::Meta {
                kind: smith_core::metadata::NESTED_COMPLETION_KIND.into(),
                detail,
            },
        )
        .unwrap(),
    };
    let (bytes, encoding) = measure(Scope::Session, || frame.encode(1024).unwrap());
    assert_eq!(encoding.allocations, 3);
    let (decoded, decoding) = measure(Scope::Session, || {
        read_frames(&mut bytes.as_slice(), 1024).unwrap()
    });
    assert_eq!(decoding.allocations, 3);
    assert_eq!(decoded.frames, vec![frame]);
}