Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-core/src/store/lifecycle_tests.rs

Raw
//! SMH-SPEC-PLUG0001, SMH-SPEC-SPEC0001: lifecycle evidence shares writer/reopen/memory ownership laws.
use super::*;
use crate::metadata::encode;
use crate::metadata::lifecycle as evidence;
use crate::session::{EntryContent, Session};
use smith::message::{Message, Role};

fn component() -> crate::tools::ToolComponentProvenance {
    crate::tools::ToolComponentProvenance {
        source_id: "example:lifecycle".into(),
        manifest_sha256: "0".repeat(64),
        component_sha256: "1".repeat(64),
    }
}
fn record(id: EntryId, kind: &str, detail: smith::structured::StructuredData) -> Frame {
    let mut entry = EntryFrame::new(
        None,
        &EntryContent::Meta {
            kind: kind.into(),
            detail,
        },
    )
    .unwrap();
    entry.id = id;
    Frame::Known { entry }
}
fn invocation(root: EntryId, id: EntryId) -> Frame {
    let mut frame = record(
        id,
        evidence::INVOCATION_INTENT,
        encode(&evidence::InvocationIntent {
            root_entry_id: root,
            invocation_id: id,
            boundary: smith::lifecycle::Boundary::PreSettlement,
            round_index: 0,
            handler: "fixture",
            component: &component(),
        })
        .unwrap(),
    );
    if let Frame::Known { entry } = &mut frame {
        entry.parent = Some(root);
    }
    frame
}
fn effect(root: EntryId, parent: EntryId, id: EntryId, ordinal: u16) -> Frame {
    record(
        id,
        evidence::EFFECT_INTENT,
        encode(&evidence::EffectIntent {
            root_entry_id: root,
            invocation_id: parent,
            effect_id: id,
            ordinal,
            operation: "http",
            input: "{}",
        })
        .unwrap(),
    )
}
fn completion(root: EntryId, parent: EntryId, id: EntryId, ordinal: u16) -> Frame {
    record(
        EntryId::new(),
        evidence::EFFECT_COMPLETION,
        encode(&evidence::EffectCompletion {
            root_entry_id: root,
            invocation_id: parent,
            effect_id: id,
            ordinal,
            ok: true,
            mutation_state: smith::error::MutationState::Applied,
            output: "ok",
        })
        .unwrap(),
    )
}
#[test]
fn metadata_routing_never_bypasses_payload_validation() {
    let path = std::env::temp_dir().join(format!("metadata-routing-{}.smh", SessionId::new()));
    let mut opened =
        create_session(&path, &Session::new(), smith::Config::default_valid()).unwrap();
    let before = std::fs::read(&path).unwrap();
    let content = EntryContent::Meta {
        kind: "ordinary".into(),
        detail: encode(&[1u8, 2, 3]).unwrap(),
    };
    // Both append boundaries reject a valid name with a truncated structured payload.
    let mut session = Session::new();
    let entry = *session.append(&content).unwrap();
    let mut bytes = session.bytes(&entry).to_vec();
    bytes.pop();
    assert!(opened.writer.append_entry(&entry, &bytes).is_err());
    let mut frame_entry = EntryFrame::new(None, &content).unwrap();
    frame_entry.content.pop();
    assert!(
        opened
            .writer
            .append_frame(&Frame::Known { entry: frame_entry })
            .is_err()
    );
    assert_eq!(std::fs::read(&path).unwrap(), before);
    std::fs::remove_file(path).unwrap();
}

#[test]
fn lifecycle_wrong_root_parent_duplicates_and_premature_completion_reject_before_write() {
    let path = std::env::temp_dir().join(format!("lifecycle-ledger-{}.smh", SessionId::new()));
    let mut opened =
        create_session(&path, &Session::new(), smith::Config::default_valid()).unwrap();
    let user = EntryFrame::new(
        None,
        &EntryContent::Message(Message::with_text(Role::User, "root")),
    )
    .unwrap();
    let root = user.id;
    opened
        .writer
        .append_frame(&Frame::Known { entry: user })
        .unwrap();
    let parent = EntryId::new();
    assert!(
        opened
            .writer
            .append_frame(&invocation(EntryId::new(), parent))
            .is_err()
    );
    opened
        .writer
        .append_frame(&invocation(root, parent))
        .unwrap();
    assert!(
        opened
            .writer
            .append_frame(&invocation(root, parent))
            .is_err()
    );
    let primitive = EntryId::new();
    assert!(
        opened
            .writer
            .append_frame(&effect(root, EntryId::new(), primitive, 0))
            .is_err()
    );
    assert!(
        opened
            .writer
            .append_frame(&completion(root, parent, primitive, 0))
            .is_err()
    );
    opened
        .writer
        .append_frame(&effect(root, parent, primitive, 0))
        .unwrap();
    assert!(
        opened
            .writer
            .append_frame(&effect(root, parent, primitive, 0))
            .is_err()
    );
    let handler_done = || {
        record(
            EntryId::new(),
            evidence::INVOCATION_COMPLETION,
            encode(&evidence::InvocationCompletion {
                root_entry_id: root,
                invocation_id: parent,
                ok: true,
                output: "[]",
            })
            .unwrap(),
        )
    };
    assert!(opened.writer.append_frame(&handler_done()).is_err());
    let ledger = SessionReader::open(&path)
        .unwrap()
        .work_ledger(opened.writer.config.frame_bytes_max, None)
        .unwrap();
    assert!(
        ledger.unresolved(),
        "reopen retains unknown incomplete effect, never retries"
    );
    assert_eq!(ledger.lifecycle_effect, Some(primitive));
    let mut visible = Vec::new();
    crate::trace::replay(&SessionReader::open(&path).unwrap(), opened.writer.config.frame_bytes_max, |record| {
        if matches!(record.kind, crate::trace::TraceKind::LifecycleEffectStarted
            | crate::trace::TraceKind::LifecycleEffectIncomplete
            | crate::trace::TraceKind::LifecycleInvocationIncomplete) {
            visible.push(serde_json::json!({
                "kind": record.kind,
                "event_ref": record.event_ref.replace(&root.to_string(), "<root>")
                    .replace(&parent.to_string(), "<handler>").replace(&primitive.to_string(), "<effect>"),
            }));
        }
        Ok(())
    }).unwrap();
    insta::assert_snapshot!(serde_json::to_string_pretty(&visible).unwrap(), @r#"
    [
      {
        "kind": "LifecycleEffectStarted",
        "event_ref": "root:<root>:invocation:<handler>:effect:<effect>:entry:<effect>"
      },
      {
        "kind": "LifecycleEffectIncomplete",
        "event_ref": "root:<root>:invocation:<handler>:effect:<effect>:mutation:unknown"
      },
      {
        "kind": "LifecycleInvocationIncomplete",
        "event_ref": "root:<root>:invocation:<handler>:outcome:unknown"
      }
    ]
    "#);

    opened
        .writer
        .append_frame(&completion(root, parent, primitive, 0))
        .unwrap();
    assert!(
        opened
            .writer
            .append_frame(&completion(root, parent, primitive, 0))
            .is_err()
    );
    opened.writer.append_frame(&handler_done()).unwrap();
    let reader = SessionReader::open(&path).unwrap();
    reader
        .validate_work(opened.writer.config.frame_bytes_max)
        .unwrap();
    assert!(
        !reader
            .work_ledger(opened.writer.config.frame_bytes_max, None)
            .unwrap()
            .unresolved()
    );
    drop(opened);
    std::fs::remove_file(path).unwrap();
}
#[test]
fn lifecycle_open_invocation_prevents_root_settlement_and_memory_publication() {
    let root = EntryId::new();
    let parent = EntryId::new();
    let mut ledger = WorkLedger {
        lifecycle_root: Some(root),
        live: vec![(root, WorkStatus::Running)],
        ..Default::default()
    };
    ledger.apply(&invocation(root, parent), None).unwrap();
    assert!(
        ledger
            .apply(
                &Frame::Settlement {
                    submission_id: root,
                    reason: Some(smith::StopReason::EndTurn),
                    output: None
                },
                None
            )
            .is_err()
    );
    let primitive = EntryId::new();
    ledger
        .apply(&effect(root, parent, primitive, 0), None)
        .unwrap();
    assert!(
        ledger
            .apply(&completion(root, EntryId::new(), primitive, 0), None)
            .is_err()
    );
    assert!(
        ledger
            .apply(&completion(root, parent, primitive, 1), None)
            .is_err()
    );
}

#[test]
fn lifecycle_simple_root_remains_the_original_durable_user_after_steering() {
    let user = EntryFrame::new(
        None,
        &EntryContent::Message(Message::with_text(Role::User, "root")),
    )
    .unwrap();
    let root = user.id;
    let steering = EntryFrame::new(
        Some(root),
        &EntryContent::Message(Message::with_text(Role::User, "steering")),
    )
    .unwrap();
    let mut intent = invocation(root, EntryId::new());
    if let Frame::Known { entry } = &mut intent {
        entry.parent = Some(steering.id);
    }
    let frames = [
        Frame::Known { entry: user },
        Frame::Known { entry: steering },
        intent,
    ];
    validate_memory_work(&frames).unwrap();
}

#[test]
fn automatic_checkpoint_defers_open_lifecycle_evidence_until_invocation_completion() {
    fn append_entry(writer: &mut SessionWriter, frames: &mut Vec<Frame>, frame: Frame) {
        let Frame::Known { entry } = &frame else {
            panic!("fixture entry frame");
        };
        writer
            .append_entry(
                &Entry {
                    id: entry.id,
                    parent: entry.parent,
                    timestamp_ms: entry.timestamp_ms,
                    kind: entry.kind,
                    content: crate::session::Span { offset: 0, len: 0 },
                },
                &entry.content,
            )
            .unwrap();
        frames.push(frame);
    }

    for filler_end in 60..=64 {
        let mut frames = Vec::new();
        let path =
            std::env::temp_dir().join(format!("lifecycle-checkpoint-{}.smh", SessionId::new()));
        let mut opened =
            create_session(&path, &Session::new(), smith::Config::default_valid()).unwrap();
        let root_frame = EntryFrame::new(
            None,
            &EntryContent::Message(Message::with_text(Role::User, "root")),
        )
        .unwrap();
        let root = root_frame.id;
        append_entry(
            &mut opened.writer,
            &mut frames,
            Frame::Known { entry: root_frame },
        );
        for _ in 1..filler_end {
            let entry = EntryFrame::new(
                None,
                &EntryContent::Message(Message::with_text(Role::User, "filler")),
            )
            .unwrap();
            append_entry(&mut opened.writer, &mut frames, Frame::Known { entry });
        }

        let invocation_id = EntryId::new();
        append_entry(
            &mut opened.writer,
            &mut frames,
            invocation(root, invocation_id),
        );
        let effect_id = EntryId::new();
        append_entry(
            &mut opened.writer,
            &mut frames,
            effect(root, invocation_id, effect_id, 0),
        );
        append_entry(
            &mut opened.writer,
            &mut frames,
            completion(root, invocation_id, effect_id, 0),
        );
        append_entry(
            &mut opened.writer,
            &mut frames,
            record(
                EntryId::new(),
                evidence::INVOCATION_COMPLETION,
                encode(&evidence::InvocationCompletion {
                    root_entry_id: root,
                    invocation_id,
                    ok: true,
                    output: "[]",
                })
                .unwrap(),
            ),
        );

        validate_memory_work(&frames).unwrap();
        drop(opened);
        let reader = SessionReader::open(&path).unwrap();
        reader
            .validate_work(smith::Config::default_valid().frame_bytes_max)
            .unwrap();
        drop(reader);
        drop(open_session(&path, smith::Config::default_valid()).unwrap());
        std::fs::remove_file(path).unwrap();
    }
}