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
205 changes: 183 additions & 22 deletions pkgs/id/src/world_doctor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -337,10 +337,44 @@ pub fn check_journal(inputs: &DoctorInputs) -> Finding {
let Some(journal) = inputs.journal.as_deref() else {
return ok("journal", "no journal to check");
};
match validate_journal_file(journal) {
Ok((entries, version)) => ok(
match inspect_journal_file(journal) {
Ok(summary) if summary.version > MAX_JOURNAL_VERSION => fail(
"journal",
format!("{entries} entries, format version {version}"),
format!(
"{}: journal format version {} is newer than this binary supports",
journal.display(),
summary.version
),
format!(
"use an id binary that supports journal format version {} before opening this world",
summary.version
),
),
Ok(summary) if summary.version < JOURNAL_VERSION => fail(
"journal",
format!(
"{}: journal format version {} is older than this binary supports",
journal.display(),
summary.version
),
"restore the journal from a backup, or recreate the world",
),
Ok(summary) if summary.torn_tail => warn(
"journal",
format!(
"{}: {} entries, format version {}; an unterminated final entry will be dropped on open",
journal.display(),
summary.entries,
summary.version
),
"opening the world will drop the incomplete final entry and continue",
),
Ok(summary) => ok(
"journal",
format!(
"{} entries, format version {}",
summary.entries, summary.version
),
),
Err(error) => fail(
"journal",
Expand All @@ -350,20 +384,27 @@ pub fn check_journal(inputs: &DoctorInputs) -> Finding {
}
}

/// Parse a journal file and check its format, without opening it for append.
///
/// Returns the entry count and the `Created` version.
///
/// # Errors
///
/// A missing file, a first entry that is not `Created`, a version this binary
/// does not know, or any malformed entry.
pub fn validate_journal_file(path: &Path) -> Result<(usize, u32)> {
struct JournalSummary {
entries: usize,
version: u32,
torn_tail: bool,
}

/// Parse a journal and record an incomplete final append without treating it
/// as corruption. The opener drops that tail before appending again.
fn inspect_journal_file(path: &Path) -> Result<JournalSummary> {
let bytes =
std::fs::read(path).map_err(|error| anyhow::anyhow!("cannot read journal: {error}"))?;
let has_unterminated_tail = !bytes.is_empty() && !bytes.ends_with(b"\n");
let last_line_index = bytes.iter().filter(|byte| **byte == b'\n').count();
let mut entries = 0usize;
let mut version = None;
let mut torn_tail = false;
for (index, line) in bytes.split(|byte| *byte == b'\n').enumerate() {
if index == last_line_index && has_unterminated_tail && !line.is_empty() {
torn_tail = true;
break;
}
if line.is_empty() {
continue;
}
Expand All @@ -379,10 +420,6 @@ pub fn validate_journal_file(path: &Path) -> Result<(usize, u32)> {
"entry {} is `Created`, but it is not the first entry",
index + 1
);
anyhow::ensure!(
(JOURNAL_VERSION..=MAX_JOURNAL_VERSION).contains(created_version),
"journal format version {created_version} is not one this binary supports ({JOURNAL_VERSION}..={MAX_JOURNAL_VERSION})"
);
version = Some(*created_version);
}
_ if entries == 0 => {
Expand All @@ -393,7 +430,30 @@ pub fn validate_journal_file(path: &Path) -> Result<(usize, u32)> {
entries += 1;
}
anyhow::ensure!(entries > 0, "journal is empty");
Ok((entries, version.unwrap_or(JOURNAL_VERSION)))
Ok(JournalSummary {
entries,
version: version.unwrap_or(JOURNAL_VERSION),
torn_tail,
})
}

/// Parse a journal file and check its format, without opening it for append.
///
/// Returns the entry count and the `Created` version.
///
/// # Errors
///
/// A missing file, a first entry that is not `Created`, a version this binary
/// does not know, or any malformed complete entry. An unterminated final
/// append is ignored, matching `FileJournal::open`.
pub fn validate_journal_file(path: &Path) -> Result<(usize, u32)> {
let summary = inspect_journal_file(path)?;
anyhow::ensure!(
(JOURNAL_VERSION..=MAX_JOURNAL_VERSION).contains(&summary.version),
"journal format version {} is not one this binary supports ({JOURNAL_VERSION}..={MAX_JOURNAL_VERSION})",
summary.version
);
Ok((summary.entries, summary.version))
}

/// The clock reads a positive unix time. A zero (or absurd) reading means the
Expand Down Expand Up @@ -553,10 +613,9 @@ mod tests {
}

#[test]
fn a_journal_version_zero_and_blank_lines_match_restore() {
// #1598: restore (world/core.rs) requires version 1..=MAX and reads
// the first *parsed* entry (world_store skips blank lines); doctor
// must agree on both.
fn a_journal_version_and_blank_lines_follow_open_rules() {
// #1598 originally pinned doctor to the restore reader. Triage #2999
// supersedes that for blank lines: all journal readers skip them.
let dir = std::env::temp_dir().join(format!("id-doctor-1598-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("journal.jsonl");
Expand All @@ -572,11 +631,30 @@ mod tests {
std::fs::write(&path, format!("{}\n", created(0))).unwrap();
assert!(validate_journal_file(&path).is_err());

// A leading blank line does not move the header: still valid.
// Leading blank line.
std::fs::write(&path, format!("\n{}\n", created(JOURNAL_VERSION))).unwrap();
let (entries, version) = validate_journal_file(&path).unwrap();
assert_eq!((entries, version), (1, JOURNAL_VERSION));

// A blank line between valid records is ignored.
let revoked = serde_json::json!({
"entry": "revoked",
"participant_id": 1,
"by": null,
});
std::fs::write(
&path,
format!("{}\n\n{}\n", created(JOURNAL_VERSION), revoked),
)
.unwrap();
let (entries, version) = validate_journal_file(&path).unwrap();
assert_eq!((entries, version), (2, JOURNAL_VERSION));

// Trailing blank lines are ignored too.
std::fs::write(&path, format!("{}\n\n", created(JOURNAL_VERSION))).unwrap();
let (entries, version) = validate_journal_file(&path).unwrap();
assert_eq!((entries, version), (1, JOURNAL_VERSION));

// A leading blank line does not hide a missing header either.
let bad = serde_json::json!({"entry": "caps_granted", "granted": []});
std::fs::write(&path, format!("\n{bad}\n")).unwrap();
Expand All @@ -585,6 +663,89 @@ mod tests {
std::fs::remove_dir_all(&dir).ok();
}

#[test]
fn a_torn_final_entry_is_a_recoverable_warning_and_not_rewritten() {
let dir = std::env::temp_dir().join(format!("id-doctor-torn-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("journal.jsonl");
let created = serde_json::json!({
"entry": "created",
"world_id": "w",
"version": JOURNAL_VERSION,
});
let mut bytes = format!("{created}\n").into_bytes();
bytes.extend_from_slice(b"{\"entry\":\"revoked\",\"participant");
std::fs::write(&path, &bytes).unwrap();

let finding = check_journal(&DoctorInputs {
journal: Some(path.clone()),
..inputs()
});
assert_eq!(finding.severity, Severity::Warn, "{finding:#?}");
assert!(
finding.detail.contains("unterminated final entry"),
"{finding:#?}"
);
assert!(finding.fix.contains("drop"), "{finding:#?}");
assert!(!finding.fix.contains("restore"), "{finding:#?}");
assert_eq!(std::fs::read(&path).unwrap(), bytes, "doctor is read-only");

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

#[test]
fn a_future_journal_version_gets_unsupported_binary_advice() {
let dir = std::env::temp_dir().join(format!("id-doctor-future-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("journal.jsonl");
let future = serde_json::json!({
"entry": "created",
"world_id": "w",
"version": MAX_JOURNAL_VERSION + 1,
});
std::fs::write(&path, format!("{future}\n")).unwrap();

let finding = check_journal(&DoctorInputs {
journal: Some(path),
..inputs()
});
assert_eq!(finding.severity, Severity::Fail, "{finding:#?}");
assert!(
finding.fix.contains("supports journal format"),
"{finding:#?}"
);
assert!(!finding.fix.contains("restore"), "{finding:#?}");

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

#[test]
fn mid_file_journal_corruption_remains_a_failure() {
let dir = std::env::temp_dir().join(format!("id-doctor-corrupt-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("journal.jsonl");
let created = serde_json::json!({
"entry": "created",
"world_id": "w",
"version": JOURNAL_VERSION,
});
let revoked = serde_json::json!({
"entry": "revoked",
"participant_id": 1,
"by": null,
});
std::fs::write(&path, format!("{created}\nnot-json\n{revoked}\n")).unwrap();

let finding = check_journal(&DoctorInputs {
journal: Some(path),
..inputs()
});
assert_eq!(finding.severity, Severity::Fail, "{finding:#?}");
assert!(finding.fix.contains("restore"), "{finding:#?}");

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

#[test]
fn a_warn_only_report_does_not_fail_the_exit_result() {
// Healthy inputs, except the resolved compiler differs from the
Expand Down
30 changes: 30 additions & 0 deletions pkgs/id/src/world_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@ impl FileJournal {
break;
}
let complete = line.last() == Some(&b'\n');
if line == b"\n" {
// Empty lines carry no entry. Preserve their bytes so a
// later torn-tail repair cannot truncate past them.
good_len += read as u64;
continue;
}
match serde_json::from_slice::<JournalEntry>(&line) {
Ok(entry) if complete => {
entries.push(entry);
Expand Down Expand Up @@ -1083,6 +1089,30 @@ mod tests {
assert!(err.to_string().contains("corrupt"), "{err:#}");
}

#[test]
fn blank_lines_before_between_and_after_entries_are_skipped() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("journal.jsonl");
drop(FileJournal::open(&path, "w").unwrap());
let created = std::fs::read(&path).unwrap();
let revoked = serde_json::to_vec(&JournalEntry::Revoked {
participant_id: 1,
by: None,
})
.unwrap();

let mut with_blanks = b"\n".to_vec();
with_blanks.extend_from_slice(&created);
with_blanks.extend_from_slice(b"\n");
with_blanks.extend_from_slice(&revoked);
with_blanks.extend_from_slice(b"\n\n");
std::fs::write(&path, &with_blanks).unwrap();

let (_, entries) = FileJournal::open(&path, "w").unwrap();
assert_eq!(entries.len(), 2);
assert_eq!(std::fs::read(&path).unwrap(), with_blanks);
}

#[test]
fn a_terminated_entry_this_binary_cannot_read_is_refused_not_dropped() {
let dir = TempDir::new().unwrap();
Expand Down
Loading