use super::tree::{SessionNode, StoredStateTransition};
use super::*;
use rho_providers::model::{AssistantMessage, ModelIdentity, ProviderContextBlock};
use serde_json::json;
use std::fs::OpenOptions;
const PRE_TREE_SESSIONS: [(u32, &str, &str); 3] = [
(
1,
"11111111-1111-4111-8111-111111111111",
include_str!("session/fixtures/session-v1.jsonl"),
),
(
2,
"22222222-2222-4222-8222-222222222222",
include_str!("session/fixtures/session-v2.jsonl"),
),
(
3,
"33333333-3333-4333-8333-333333333333",
include_str!("session/fixtures/session-v3.jsonl"),
),
];
const SESSION_V4: &str = include_str!("session/fixtures/session-v4.jsonl");
const SESSION_V5: &str = include_str!("session/fixtures/session-v5.jsonl");
const DISPLAY_FIXTURE_ID: &str = "44444444-4444-4444-8444-444444444444";
#[test]
fn every_supported_application_session_fixture_restores_as_a_snapshot() {
let cases = [
(
4,
DISPLAY_FIXTURE_ID,
SESSION_V4,
3,
0,
0,
"rho:display-fixture",
3,
4,
),
(
5,
DISPLAY_FIXTURE_ID,
SESSION_V5,
3,
0,
0,
"rho:display-fixture",
3,
4,
),
];
for (version, id, fixture, revision, compactions, removed, cache_key, model_len, display_len) in
cases
{
let (root, cwd, session) = session_from_fixture(id, fixture);
let first: serde_json::Value =
serde_json::from_str(fixture.lines().next().unwrap()).unwrap();
assert_eq!(first["version"], version);
let snapshot = session
.snapshot_for_resume(
ModelIdentity::new("target", "fixture-api", "fixture-model"),
"rho:migrated-v1".into(),
)
.unwrap();
let tree = tree::SessionTree::load(session.path()).unwrap();
let history = persistence::history_from_tree(&tree).unwrap();
let display = persistence::active_display_from_tree(&tree).unwrap();
assert_eq!(
snapshot.schema_version(),
rho_sdk::SESSION_SNAPSHOT_SCHEMA_VERSION
);
assert_eq!(snapshot.session_id().as_str(), id);
assert_eq!(snapshot.revision(), Revision::from_u64(revision));
assert_eq!(snapshot.compaction().completed_compactions(), compactions);
assert_eq!(snapshot.compaction().removed_messages(), removed);
assert_eq!(snapshot.prompt_cache_key(), Some(cache_key));
assert_eq!(snapshot.history(), history);
assert_eq!(history.len(), model_len);
assert_eq!(display.len(), display_len);
drop((root, cwd));
}
}
#[test]
fn display_row_references_restore_the_same_transcript_as_full_rows() {
let restore = |fixture: &str| {
let (_root, _cwd, session) = session_from_fixture(DISPLAY_FIXTURE_ID, fixture);
let tree = tree::SessionTree::load(session.path()).unwrap();
let display = tree
.projected_display(tree.active_leaf_id().unwrap())
.unwrap();
let mut extractor = search_evidence::Extractor::default();
let evidence = fixture
.lines()
.flat_map(|line| extractor.extract(&serde_json::from_str(line).unwrap(), 0))
.map(|evidence| (evidence.role, evidence.text))
.collect::<Vec<_>>();
(serde_json::to_value(display).unwrap(), evidence)
};
let (v4_display, v4_evidence) = restore(SESSION_V4);
let (v5_display, v5_evidence) = restore(SESSION_V5);
pretty_assertions::assert_eq!(v5_display, v4_display);
pretty_assertions::assert_eq!(v5_evidence, v4_evidence);
pretty_assertions::assert_eq!(
v5_evidence,
[
("user".to_owned(), "typed prompt".to_owned()),
("assistant".to_owned(), "fixture answer".to_owned()),
(
"assistant".to_owned(),
"follow-up after a full snapshot".to_owned(),
),
]
);
}
#[test]
fn saves_follow_the_display_row_format_of_the_file_header() {
use display_rows::{DisplayRowFormat, StoredDisplayRow};
for (id, fixture, format) in [
(DISPLAY_FIXTURE_ID, SESSION_V4, DisplayRowFormat::Inline),
(DISPLAY_FIXTURE_ID, SESSION_V5, DisplayRowFormat::ModelRefs),
] {
let (_root, _cwd, session) = session_from_fixture(id, fixture);
let restored = session
.snapshot_for_resume(
ModelIdentity::new("fixture-provider", "fixture-api", "fixture-model"),
"rho:fallback".into(),
)
.unwrap();
let mut history = restored.history().to_vec();
history.push(Message::assistant_text("next"));
let next = SessionSnapshot::new(
restored.session_id().clone(),
restored.revision().checked_next().unwrap(),
history,
restored.provider().clone(),
restored.compaction().clone(),
)
.with_prompt_cache_key(restored.prompt_cache_key().unwrap());
session
.save_snapshot(&next, &[Message::assistant_text("next")])
.unwrap();
let Some(SessionEntry::Node { node }) = read_entries(session.path()).unwrap().pop() else {
panic!("save appends a node");
};
let expected = match format {
DisplayRowFormat::Inline => StoredDisplayRow::Inline {
timestamp: Some(node.timestamp.clone()),
message: Message::assistant_text("next"),
},
DisplayRowFormat::ModelRefs => StoredDisplayRow::Model(0),
};
pretty_assertions::assert_eq!(node.display_messages, vec![expected], "{id} {format:?}");
}
}
#[test]
fn rejects_sessions_from_unsupported_or_malformed_versions() {
for (name, contents, expected) in [
(
"future-version",
format!(
"{{\"type\":\"session\",\"version\":{},\"id\":\"future-version\",\"timestamp\":\"1\",\"cwd\":\"/tmp\"}}\n",
SESSION_VERSION + 1
),
"unsupported session version",
),
(
"pre-version",
"{\"type\":\"session\",\"version\":0,\"id\":\"pre-version\",\"timestamp\":\"1\",\"cwd\":\"/tmp\"}\n".into(),
"unsupported session version",
),
(
"malformed",
"{\"type\":\"session\",\"version\":5,\"id\":\"malformed\",\"timestamp\":\"1\",\"cwd\":\"/tmp\"}\n{\"type\":\"node\",\"timestamp\":\"2\"}\n".into(),
"missing field",
),
] {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join(format!("1_{name}.jsonl"));
fs::write(&path, contents).unwrap();
let error = summarize_session_file(&path, directory.path()).unwrap_err();
assert!(error.to_string().contains(expected), "{error:#}");
}
}
#[test]
fn pre_tree_sessions_fail_to_open_with_the_release_that_opens_them() {
for (version, id, fixture) in PRE_TREE_SESSIONS {
let root = tempfile::tempdir().unwrap();
let cwd = tempfile::tempdir().unwrap();
let dir = session_dir_in_root(root.path(), cwd.path());
fs::create_dir_all(&dir).unwrap();
let mut lines = fixture.lines();
let mut header: serde_json::Value = serde_json::from_str(lines.next().unwrap()).unwrap();
header["cwd"] = cwd.path().to_string_lossy().into_owned().into();
let transcript = std::iter::once(header.to_string())
.chain(lines.map(str::to_owned))
.collect::<Vec<_>>()
.join("\n");
fs::write(
dir.join(format!("100_{id}.jsonl")),
format!("{transcript}\n"),
)
.unwrap();
let listed = Session::list_in_root(root.path(), cwd.path(), SessionListing::Everything)
.unwrap()
.into_iter()
.map(|summary| (summary.id.clone(), summary.has_messages()))
.collect::<Vec<_>>();
pretty_assertions::assert_eq!(listed, [(id.to_owned(), false)], "v{version}");
pretty_assertions::assert_eq!(
persistence::SessionStore::workspace_of(root.path(), id).unwrap(),
Some(cwd.path().to_path_buf()),
"v{version}"
);
let error = Session::open_by_id_in_root(root.path(), cwd.path(), &id[..8]).unwrap_err();
pretty_assertions::assert_eq!(
error
.downcast_ref::<persistence::PreTreeSession>()
.map(|error| error.version),
Some(version),
"{error:#}"
);
}
}
#[test]
fn rejects_snapshot_delta_without_matching_base_revision() {
let corrupted = SESSION_V4.replacen("\"base_revision\":1", "\"base_revision\":0", 1);
let (_root, _cwd, session) = session_from_fixture(DISPLAY_FIXTURE_ID, &corrupted);
let error = session
.snapshot_for_resume(
ModelIdentity::new("target", "api", "model"),
"rho:fallback".into(),
)
.unwrap_err();
assert!(error.to_string().contains("base revision"), "{error:#}");
}
#[test]
fn consecutive_snapshot_saves_append_only_new_history() {
let root = tempfile::tempdir().unwrap();
let cwd = tempfile::tempdir().unwrap();
let session = Session::create_in_root(root.path(), cwd.path()).unwrap();
let identity = ModelIdentity::new("provider", "api", "model");
let id = SessionId::from_string(session.id().to_owned()).unwrap();
let first = SessionSnapshot::new(
id.clone(),
Revision::from_u64(1),
vec![Message::user_text("history only in base")],
identity.clone(),
CompactionState::default(),
)
.with_prompt_cache_key("rho:fallback");
let second = SessionSnapshot::new(
id,
Revision::from_u64(2),
vec![
Message::user_text("history only in base"),
Message::assistant_text("new delta message"),
],
identity.clone(),
CompactionState::default(),
)
.with_prompt_cache_key("rho:fallback");
session.save_snapshot(&first, first.history()).unwrap();
session
.save_snapshot(&second, &second.history()[1..])
.unwrap();
let entries = read_entries(session.path()).unwrap();
assert!(matches!(
entries[1],
SessionEntry::Node {
node: SessionNode {
transition: StoredStateTransition::Snapshot { .. },
..
}
}
));
assert!(matches!(
entries[2],
SessionEntry::Node {
node: SessionNode {
transition: StoredStateTransition::SnapshotDelta { .. },
..
}
}
));
let last_record = fs::read_to_string(session.path())
.unwrap()
.lines()
.last()
.unwrap()
.to_string();
assert!(!last_record.contains("history only in base"));
assert!(last_record.contains("new delta message"));
let restored = session
.snapshot_for_resume(identity, "rho:fallback".into())
.unwrap();
assert_eq!(restored, second);
let display: Vec<_> =
persistence::active_display_from_tree(&tree::SessionTree::load(session.path()).unwrap())
.unwrap()
.into_iter()
.map(|row| row.message)
.collect();
assert_eq!(display, second.history());
}
#[test]
fn history_replacement_writes_a_new_complete_snapshot_base() {
let root = tempfile::tempdir().unwrap();
let cwd = tempfile::tempdir().unwrap();
let session = Session::create_in_root(root.path(), cwd.path()).unwrap();
let identity = ModelIdentity::new("provider", "api", "model");
let id = SessionId::from_string(session.id().to_owned()).unwrap();
let first = SessionSnapshot::new(
id.clone(),
Revision::from_u64(2),
vec![
Message::user_text("old"),
Message::assistant_text("history"),
],
identity.clone(),
CompactionState::default(),
)
.with_prompt_cache_key("rho:fallback");
let compacted = SessionSnapshot::new(
id,
Revision::from_u64(3),
vec![Message::user_text("compact summary")],
identity.clone(),
CompactionState::default(),
)
.with_prompt_cache_key("rho:fallback");
session.save_snapshot(&first, &[]).unwrap();
session.save_snapshot(&compacted, &[]).unwrap();
assert!(matches!(
read_entries(session.path()).unwrap().last(),
Some(SessionEntry::Node {
node: SessionNode {
transition: StoredStateTransition::Snapshot { .. },
..
}
})
));
assert_eq!(
session
.snapshot_for_resume(identity, "rho:fallback".into())
.unwrap(),
compacted
);
}
#[test]
fn failed_snapshot_save_retains_the_previous_complete_revision() {
let root = tempfile::tempdir().unwrap();
let cwd = tempfile::tempdir().unwrap();
let session = Session::create_in_root(root.path(), cwd.path()).unwrap();
let identity = ModelIdentity::new("provider", "api", "model");
let first = SessionSnapshot::new(
SessionId::from_string(session.id().to_owned()).unwrap(),
Revision::from_u64(1),
vec![Message::user_text("durable")],
identity.clone(),
CompactionState::default(),
)
.with_prompt_cache_key("rho:durable");
session
.save_snapshot(&first, &[Message::user_text("display durable")])
.unwrap();
let before = fs::read(session.path()).unwrap();
let wrong_id = SessionSnapshot::new(
SessionId::from_string("different-session").unwrap(),
Revision::from_u64(2),
vec![Message::user_text("must not commit")],
identity.clone(),
CompactionState::default(),
);
assert!(session.save_snapshot(&wrong_id, &[]).is_err());
assert_eq!(fs::read(session.path()).unwrap(), before);
OpenOptions::new()
.append(true)
.open(session.path())
.unwrap()
.write_all(b"{\"type\":\"node\"")
.unwrap();
let restored = session
.snapshot_for_resume(identity.clone(), "rho:fallback".into())
.unwrap();
assert_eq!(restored.revision(), first.revision());
assert_eq!(restored.history(), first.history());
session.save_snapshot(&first, &[]).unwrap();
let restored_after_repair = session
.snapshot_for_resume(identity, "rho:fallback".into())
.unwrap();
assert_eq!(restored_after_repair, first);
}
#[test]
fn resumed_snapshot_reports_and_filters_incompatible_provider_context() {
let root = tempfile::tempdir().unwrap();
let cwd = tempfile::tempdir().unwrap();
let session = Session::create_in_root(root.path(), cwd.path()).unwrap();
let source = ModelIdentity::new("source", "source-api", "source-model");
let target = ModelIdentity::new("target", "target-api", "target-model");
let snapshot = SessionSnapshot::new(
SessionId::from_string(session.id().to_owned()).unwrap(),
Revision::from_u64(1),
vec![Message::assistant(AssistantMessage {
content: vec![ContentBlock::Text("portable answer".into())],
provider_context: vec![ProviderContextBlock {
identity: source.clone(),
kind: "source_native_context".into(),
position: None,
data: json!({"opaque": true}),
replay: rho_sdk::model::ReplayScope::ExactModel,
}],
..AssistantMessage::default()
})],
source,
CompactionState::default(),
);
session
.save_snapshot(&snapshot, snapshot.history())
.unwrap();
let resumed = session
.snapshot_for_resume(target.clone(), "rho:resume".into())
.unwrap();
let report = resumed.provider_context_omissions(&target);
let Message::EnrichedAssistant(message) = resumed.history()[0].clone() else {
panic!("expected enriched assistant");
};
let prepared =
rho_sdk::model::handoff::prepare_assistant(Arc::unwrap_or_clone(message), &target);
assert_eq!(report.omitted_provider_context, 1);
assert_eq!(report.omitted_kinds, ["source_native_context"]);
assert!(prepared.replay_context.is_empty());
}
fn session_from_fixture(
id: &str,
fixture: &str,
) -> (tempfile::TempDir, tempfile::TempDir, Session) {
let root = tempfile::tempdir().unwrap();
let cwd = tempfile::tempdir().unwrap();
let dir = session_dir_in_root(root.path(), cwd.path());
fs::create_dir_all(&dir).unwrap();
let path = dir.join(format!("100_{id}.jsonl"));
fs::write(&path, fixture).unwrap();
let session = Session::from_parts(root.path(), cwd.path(), id.into(), path).unwrap();
(root, cwd, session)
}