reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
Documentation
#![cfg(test)]

use super::Event;

#[test]
fn event_preserves_kind_and_payload_presence() {
    let absent = Event::new("idle".into(), None);
    assert_eq!(absent.kind(), "idle");
    assert_eq!(absent.payload(), None);

    let empty = Event::new("empty".into(), Some(Vec::new().into_boxed_slice()));
    assert_eq!(empty.payload(), Some([].as_slice()));

    let bytes = vec![0, 0xff, b'{'];
    let event = Event::new("provider.fact".into(), Some(bytes.into_boxed_slice()));
    assert_eq!(event.payload(), Some([0, 0xff, b'{'].as_slice()));
}

#[test]
fn clone_and_owned_parts_are_independent() {
    let event = Event::new(
        "usage".into(),
        Some(Vec::from(&b"{\"tokens\":2}"[..]).into_boxed_slice()),
    );
    let cloned = event.clone();
    let (kind, mut payload) = event.into_parts();
    payload.as_mut().expect("present payload")[0] = b'[';

    assert_eq!(kind, "usage");
    assert_eq!(cloned.kind(), "usage");
    assert_eq!(cloned.payload(), Some(&b"{\"tokens\":2}"[..]));
}

/// `Debug` names the kind and preserves every payload presence, and prints no
/// payload byte in any of the three states.
mod debug_format {
    use super::Event;
    use crate::redact_tests::{SECRET, assert_redacted};

    /// `None`, `Some(<0 bytes>)` and `Some(<N bytes>)` stay three renderings.
    ///
    /// This is the same "absent versus present-empty" fact the serde form keeps
    /// apart, so a `Debug` that collapsed them would make an operator's view of a
    /// value disagree with the wire form of the very same value.
    #[test]
    fn debug_keeps_absent_present_empty_and_present_sized_apart() {
        let absent = Event::new("idle".into(), None);
        assert_eq!(
            format!("{absent:?}"),
            r#"Event { kind: "idle", payload: None }"#
        );

        let empty = Event::new("empty".into(), Some(Vec::new().into_boxed_slice()));
        assert_eq!(
            format!("{empty:?}"),
            r#"Event { kind: "empty", payload: Some(<0 bytes>) }"#
        );

        let sized = Event::new("usage".into(), Some(vec![1, 2].into_boxed_slice()));
        assert_eq!(
            format!("{sized:?}"),
            r#"Event { kind: "usage", payload: Some(<2 bytes>) }"#
        );
        assert_ne!(format!("{absent:?}"), format!("{empty:?}"));
    }

    /// The payload bytes are the crate sentinel, so a leak would print them.
    #[test]
    fn debug_sizes_the_payload_and_never_prints_a_byte_of_it() {
        let event = Event::new("secret".into(), Some(Box::from(SECRET.as_bytes())));
        // Neither `{:?}` nor `{:#?}` may contain the sentinel, and the redaction
        // tokens must be identical under both flags (ADR-018's no-escape-hatch
        // rule).
        assert_redacted(&event);
        // Pin the whole rendering rather than grepping for one decimal byte.
        // The derive this replaced printed the payload as `Some([115, 107, …])`,
        // so any surviving byte would change this string; a substring probe for
        // a single byte value (e.g. `"115"`) could pass by coincidence against a
        // rendering that still leaked others.
        assert_eq!(
            format!("{event:?}"),
            r#"Event { kind: "secret", payload: Some(<21 bytes>) }"#
        );
    }
}

/// What the `serde` feature adds to this module, and what it refuses.
#[cfg(feature = "serde")]
mod serde_format {
    use super::Event;
    use crate::wire::wire_tests::{assert_expecting, assert_refusal, encode, round_trip};

    /// Absent and present-empty are two different facts about a producer.
    #[test]
    fn an_audit_payload_keeps_its_presence_apart_from_its_emptiness() {
        let absent = Event::new("idle".into(), None);
        let empty = Event::new("idle".into(), Some(Vec::new().into_boxed_slice()));
        assert_eq!(encode(&absent), r#"{"kind":"idle","payload":null}"#);
        assert_eq!(encode(&empty), r#"{"kind":"idle","payload":[]}"#);
        assert_ne!(encode(&absent), encode(&empty));
        assert_eq!(round_trip(&absent), absent);
        assert_eq!(round_trip(&empty), empty);
    }

    #[test]
    fn an_audit_event_reads_from_both_the_map_and_the_sequence_form() {
        let event = Event::new("usage".into(), Some(vec![1, 2].into_boxed_slice()));
        assert_eq!(round_trip(&event), event);
        assert_eq!(
            serde_json::from_str::<Event>(r#"["usage",[1,2]]"#)
                .expect("a compact format writes a struct as its fields in order"),
            event
        );
        assert_eq!(
            serde_json::from_str::<Event>(r#"["idle",null]"#)
                .expect("an absent payload survives the sequence form"),
            Event::new("idle".into(), None)
        );
    }

    #[test]
    fn an_audit_event_refuses_an_unknown_repeated_missing_or_mistyped_document() {
        assert_refusal(
            serde_json::from_str::<Event>(r#"{"kind":"k","payload":null,"extra":1}"#),
            "unknown field `extra`",
        );
        assert_refusal(
            serde_json::from_str::<Event>(r#"{"kind":"k","kind":"k","payload":null}"#),
            "duplicate field `kind`",
        );
        assert_refusal(
            serde_json::from_str::<Event>(r#"{"kind":"k"}"#),
            "missing field `payload`",
        );
        assert_refusal(
            serde_json::from_str::<Event>(r#"["k"]"#),
            "every struct field",
        );
        assert_expecting::<Event>("an audit event");
    }
}