Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions pkgs/id/src/world_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -449,10 +449,31 @@ pub struct ForkSpec {
}

/// Read a journal's entries without opening it for append.
///
/// A torn final fragment — a last chunk with no terminating newline, left by
/// a crash mid-append — is excluded with a warning, mirroring
/// [`FileJournal::open`]: that entry was never acknowledged, and a world its
/// own open repairs must stay forkable (#1523). A newline-terminated line
/// that does not parse was fully written, so it stays fatal corruption in
/// any position, including the last line.
fn read_journal_entries(path: &Path) -> Result<Vec<JournalEntry>> {
let bytes = std::fs::read(path).with_context(|| format!("read {}", path.display()))?;
let mut lines: Vec<&[u8]> = bytes.split(|byte| *byte == b'\n').collect();
if bytes.last() != Some(&b'\n') {
// The split's final chunk is an unterminated fragment (or the empty
// tail of an empty file); it is not a complete entry.
if let Some(fragment) = lines.pop() {
if !fragment.is_empty() {
tracing::warn!(
"world journal {}: dropping torn final entry at byte {}",
path.display(),
bytes.len() - fragment.len()
);
}
}
}
let mut entries = Vec::new();
for line in bytes.split(|byte| *byte == b'\n') {
for line in lines {
if line.is_empty() {
continue;
}
Expand Down Expand Up @@ -1562,9 +1583,7 @@ mod tests {
}
));
journal
.append(&JournalEntry::ExecutionProfile {
profile,
})
.append(&JournalEntry::ExecutionProfile { profile })
.unwrap();
}
let entries = journal_entries(dir.path());
Expand Down
101 changes: 101 additions & 0 deletions pkgs/id/tests/world_fork.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,104 @@ fn a_fork_from_a_different_world_is_refused() {

std::fs::remove_dir_all(&root).ok();
}

/// Append raw bytes to a journal file, simulating a writer that crashed
/// mid-append (or wrote a fully-terminated corrupt line).
fn append_raw(dir: &std::path::Path, bytes: &[u8]) {
use std::io::Write;
let mut file = std::fs::OpenOptions::new()
.append(true)
.open(dir.join("journal.jsonl"))
.unwrap();
file.write_all(bytes).unwrap();
}

fn make_source(root: &std::path::Path) -> std::path::PathBuf {
let src = root.join("src");
std::fs::create_dir_all(&src).unwrap();
let modules = ModuleDir::new(src.join("modules"));
let hash = modules.save(b"wasm-bytes").unwrap();
let (mut journal, _) = FileJournal::open(&src.join("journal.jsonl"), "src-world").unwrap();
journal
.append(&JournalEntry::Committed {
event: WorldEvent {
sequence: 1,
participant_id: 0,
kind: WorldEventKind::ProgramInstalled {
module_hash: hash,
seed: 7,
provenance: None,
},
},
})
.unwrap();
drop(journal);
src
}

#[test]
fn a_fork_tolerates_a_crash_torn_journal_tail() {
let root = std::env::temp_dir().join(format!("id-fork-torn-{}", std::process::id()));
let src = make_source(&root);
let dst = root.join("dst");

// A crash mid-append: the final entry is an unterminated fragment. The
// world's own open would drop and truncate it (#1523), so the fork must
// replay to the last complete entry instead of refusing the world.
append_raw(&src, b"{\"entry\":\"committed\",\"partic");

fork_world(
&src,
&dst,
&ForkSpec {
from_world_id: "src-world".to_owned(),
to_world_id: "dst-world".to_owned(),
template: false,
},
)
.unwrap();

// The fork replays to the last complete entry: header rewritten, the
// parent's install copied, provenance recorded, and no trace of the
// torn fragment (read_entries unwraps every line it parses).
let entries = read_entries(&dst);
assert!(matches!(
&entries[0],
JournalEntry::Created { world_id, .. } if world_id == "dst-world"
));
assert!(entries.iter().any(|entry| matches!(
entry,
JournalEntry::Committed { event } if matches!(&event.kind, WorldEventKind::ProgramInstalled { seed, .. } if *seed == 7)
)));
assert!(entries.iter().any(|entry| matches!(
entry,
JournalEntry::Forked { from_world_id, .. } if from_world_id == "src-world"
)));

std::fs::remove_dir_all(&root).ok();
}

#[test]
fn a_fork_refuses_a_corrupt_but_complete_final_line() {
let root = std::env::temp_dir().join(format!("id-fork-corrupt-{}", std::process::id()));
let src = make_source(&root);
let dst = root.join("dst");

// Newline-terminated, so it was fully written: corruption, never a torn
// append. It must stay fatal even in final position.
append_raw(&src, b"this is not a journal entry\n");

let error = fork_world(
&src,
&dst,
&ForkSpec {
from_world_id: "src-world".to_owned(),
to_world_id: "dst-world".to_owned(),
template: false,
},
)
.unwrap_err();
assert!(error.to_string().contains("corrupt"), "{error}");

std::fs::remove_dir_all(&root).ok();
}