Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(storage): verify transcript generations before mutation

Seraph-xb7736c6ac495
diff --git a/crates/host-core/src/transcripts.rs b/crates/host-core/src/transcripts.rs
index f871d757a..dc6d87c94 100644
--- a/crates/host-core/src/transcripts.rs
+++ b/crates/host-core/src/transcripts.rs
@@ -31,6 +31,9 @@ use anyhow::{anyhow, Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;
+mod binary_integrity;
+#[cfg(test)]
+mod binary_integrity_tests;
mod binary_migration;
pub(crate) mod binary_storage;
#[cfg(test)]
@@ -813,7 +816,8 @@ fn append_line(path: &Path, header: Option<String>, line: String) -> Result<()>
file.write_all(buf.as_bytes())?;
file.flush()?;
file.sync_data()
- .with_context(|| format!("flush {}", path.display()))
+ .with_context(|| format!("flush {}", path.display()))?;
+ binary_integrity::appended(path, file)
}
/// Whether a non-empty file ends in a newline; an empty file counts as
@@ -1127,6 +1131,7 @@ pub fn write_transcript_with_compactions(
writer.get_ref().sync_data()?;
}
swap_into_place(&tmp, &path)?;
+ binary_integrity::invalidate(&path);
layout::invalidate(data_dir, session_id);
Ok(())
}
@@ -1241,6 +1246,7 @@ pub fn update_message(data_dir: &Path, session_id: &str, record: &MessageRecord)
writer.get_ref().sync_data()?;
}
swap_into_place(&tmp, &path)?;
+ binary_integrity::invalidate(&path);
layout::invalidate(data_dir, session_id);
Ok(true)
}
@@ -1534,6 +1540,7 @@ pub fn remove_session_files(data_dir: &Path, session_id: &str) {
inflight.with_extension("json.tmp"),
inflight,
] {
+ binary_integrity::invalidate(&path);
if let Err(error) = fs::remove_file(&path) {
if error.kind() != std::io::ErrorKind::NotFound {
tracing::warn!(path = %path.display(), %error, "transcript cleanup failed");
diff --git a/crates/host-core/src/transcripts/binary_integrity.rs b/crates/host-core/src/transcripts/binary_integrity.rs
new file mode 100644
index 000000000..7d3e2c5cd
--- /dev/null
+++ b/crates/host-core/src/transcripts/binary_integrity.rs
@@ -0,0 +1,153 @@
+//! Decoder-verified generations for transcript mutations. Layout offsets and
+//! their disk sidecars never prove storage integrity. The Host state lock owns
+//! file writes; this mutex only protects the process-local proof registry.
+use super::*;
+use std::{
+ collections::HashMap,
+ sync::{Mutex, MutexGuard, OnceLock},
+ time::SystemTime,
+};
+
+#[derive(Clone, PartialEq, Eq)]
+struct Generation {
+ identity: layout::FileIdentity,
+ length: u64,
+ modified: SystemTime,
+ #[cfg(unix)]
+ changed: (i64, i64),
+ #[cfg(windows)]
+ changed: i64,
+}
+
+impl Generation {
+ fn from_file(file: &File) -> Result<Self> {
+ let metadata = file.metadata()?;
+ Ok(Self {
+ identity: layout::opened_file_identity(file, &metadata),
+ length: metadata.len(),
+ modified: metadata.modified()?,
+ #[cfg(unix)]
+ changed: {
+ use std::os::unix::fs::MetadataExt;
+ (metadata.ctime(), metadata.ctime_nsec())
+ },
+ #[cfg(windows)]
+ changed: change_time(file)?,
+ })
+ }
+
+ fn can_cache(&self) -> bool {
+ matches!(self.identity, layout::FileIdentity::Available { .. })
+ }
+
+ fn ensure_current(&self, file: &File, path: &Path) -> Result<()> {
+ anyhow::ensure!(
+ *self == Self::from_file(file)? && *self == Self::from_file(&File::open(path)?)?,
+ "transcript changed while checking storage integrity: {}",
+ path.display()
+ );
+ Ok(())
+ }
+}
+
+#[cfg(windows)]
+fn change_time(file: &File) -> Result<i64> {
+ use std::{mem::size_of, os::windows::io::AsRawHandle};
+ use windows_sys::Win32::{
+ Foundation::HANDLE,
+ Storage::FileSystem::{FileBasicInfo, GetFileInformationByHandleEx, FILE_BASIC_INFO},
+ };
+ let mut info = FILE_BASIC_INFO::default();
+ let result = unsafe {
+ GetFileInformationByHandleEx(
+ file.as_raw_handle() as HANDLE,
+ FileBasicInfo,
+ (&mut info as *mut FILE_BASIC_INFO).cast(),
+ size_of::<FILE_BASIC_INFO>() as u32,
+ )
+ };
+ if result == 0 {
+ return Err(std::io::Error::last_os_error()).context("read transcript change time");
+ }
+ Ok(info.ChangeTime)
+}
+
+fn proofs() -> MutexGuard<'static, HashMap<PathBuf, Generation>> {
+ static PROOFS: OnceLock<Mutex<HashMap<PathBuf, Generation>>> = OnceLock::new();
+ PROOFS
+ .get_or_init(|| Mutex::new(HashMap::new()))
+ .lock()
+ .expect("transcript storage integrity proof lock poisoned")
+}
+
+pub(super) fn invalidate(path: &Path) {
+ proofs().remove(path);
+}
+
+/// The prefix was verified by prepare and the new line came from tagged().
+/// Close the synced writer before reading its final metadata: Windows may
+/// publish the last-write timestamp only when the write handle closes.
+pub(super) fn appended(path: &Path, file: File) -> Result<()> {
+ let metadata = file.metadata()?;
+ if !metadata.is_file() {
+ return Ok(());
+ }
+ let identity = layout::opened_file_identity(&file, &metadata);
+ drop(file);
+ let generation = Generation::from_file(&File::open(path)?)?;
+ anyhow::ensure!(
+ identity == generation.identity && metadata.len() == generation.length,
+ "transcript changed after append: {}",
+ path.display()
+ );
+ if generation.can_cache() {
+ proofs().insert(path.to_path_buf(), generation);
+ }
+ Ok(())
+}
+
+/// A first mutation after restart or an outside rewrite checks every existing
+/// line. Ordinary mutations reuse only a proof for this exact file generation.
+pub(super) fn verify(path: &Path, reader: &mut BufReader<File>) -> Result<()> {
+ let generation = Generation::from_file(reader.get_ref())?;
+ generation.ensure_current(reader.get_ref(), path)?;
+ let cached = proofs().get(path).cloned();
+ if generation.can_cache() && cached.as_ref() == Some(&generation) {
+ return Ok(());
+ }
+ invalidate(path);
+ reader.seek(SeekFrom::Start(0))?;
+ #[cfg(test)]
+ SCANS.with(|scans| *scans.borrow_mut().entry(path.to_path_buf()).or_default() += 1);
+ let mut raw = Vec::new();
+ let mut line = String::new();
+ loop {
+ let (read, _) = read_line_tolerant(reader, &mut raw, &mut line)?;
+ if read == 0 {
+ break;
+ }
+ if let Err(error) = binary_storage::validate_line(line.trim()) {
+ if binary_storage::is_error(&error) {
+ return Err(error).with_context(|| format!("validate storage {}", path.display()));
+ }
+ }
+ line.clear();
+ }
+ generation.ensure_current(reader.get_ref(), path)?;
+ if generation.can_cache() {
+ proofs().insert(path.to_path_buf(), generation);
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+thread_local! {
+ // Count real full scans so the O(1) owned-append contract is reproducible
+ // without wall-clock thresholds or depending on another test's activity.
+ static SCANS: std::cell::RefCell<HashMap<PathBuf, usize>> = Default::default();
+}
+
+#[cfg(test)]
+pub(super) fn scan_count(path: &Path) -> usize {
+ SCANS.with(|scans| scans.borrow().get(path).copied().unwrap_or_default())
+}
diff --git a/crates/host-core/src/transcripts/binary_integrity_tests.rs b/crates/host-core/src/transcripts/binary_integrity_tests.rs
new file mode 100644
index 000000000..7a3899f0e
--- /dev/null
+++ b/crates/host-core/src/transcripts/binary_integrity_tests.rs
@@ -0,0 +1,263 @@
+use super::*;
+use serde_json::json;
+
+fn image_record() -> MessageRecord {
+ let image = json!({"type":"image", "data":"YWJjLw==", "mimeType":"image/png"});
+ MessageRecord {
+ id: "image-row".into(),
+ role: "tool".into(),
+ tool_name: None,
+ is_error: false,
+ blocks: json!([image.clone(), image]),
+ meta: None,
+ created_at: "2026-10-27T00:00:00Z".into(),
+ }
+}
+
+fn corrupt_line(fault: &str) -> String {
+ let mut value: Value =
+ serde_json::from_str(&tagged("message", &image_record()).unwrap()).unwrap();
+ assert!(value.get("binaryStorage").is_some());
+ match fault {
+ "malformed" => return "{\"type\":\"message\",\"binaryStorage\":{\"version\":1".into(),
+ "typed" => {
+ value.as_object_mut().unwrap().remove("id");
+ }
+ "reference" => value["binaryStorage"]["refs"][0]["image"] = json!(9),
+ _ => panic!("unknown corruption fixture"),
+ }
+ value.to_string()
+}
+
+fn seed_transcript(data_dir: &Path) -> PathBuf {
+ append_message(data_dir, "s", "old", &image_record()).unwrap();
+ transcript_path(data_dir, "s").unwrap()
+}
+
+fn replace_message_line(path: &Path, fault: &str) {
+ let header = fs::read_to_string(path)
+ .unwrap()
+ .lines()
+ .next()
+ .unwrap()
+ .to_owned();
+ fs::write(path, format!("{header}\n{}\n", corrupt_line(fault))).unwrap();
+}
+
+#[test]
+fn malformed_and_structurally_invalid_encoded_rows_block_mutations() {
+ for fault in ["malformed", "typed"] {
+ for update in [false, true] {
+ let dir = tempfile::tempdir().unwrap();
+ let path = seed_transcript(dir.path());
+ replace_message_line(&path, fault);
+ let before = fs::read(&path).unwrap();
+ let result = if update {
+ update_message(dir.path(), "s", &image_record()).map(|_| ())
+ } else {
+ append_message(dir.path(), "s", "old", &image_record())
+ };
+ let error = result.expect_err(&format!("fault={fault}, update={update}"));
+ assert!(binary_storage::is_error(&error), "{error:#}");
+ assert_eq!(fs::read(&path).unwrap(), before);
+ }
+ }
+}
+
+#[test]
+fn replacement_file_cannot_reuse_a_verified_generation() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = seed_transcript(dir.path());
+ let metadata = fs::metadata(&path).unwrap();
+ let replacement = path.with_extension("replacement");
+ fs::copy(&path, &replacement).unwrap();
+ replace_message_line(&replacement, "reference");
+ File::open(&replacement)
+ .unwrap()
+ .set_times(std::fs::FileTimes::new().set_modified(metadata.modified().unwrap()))
+ .unwrap();
+ fs::rename(replacement, &path).unwrap();
+ assert_eq!(fs::metadata(&path).unwrap().len(), metadata.len());
+ let before = fs::read(&path).unwrap();
+ let error = append_message(dir.path(), "s", "old", &image_record()).unwrap_err();
+ assert!(binary_storage::is_error(&error), "{error:#}");
+ assert_eq!(fs::read(path).unwrap(), before);
+}
+
+#[cfg(unix)]
+#[test]
+fn same_size_rewrite_restoring_mtime_cannot_reuse_a_verified_generation() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = seed_transcript(dir.path());
+ let metadata = fs::metadata(&path).unwrap();
+ // Preserve every byte except one index so length and modification time
+ // cannot distinguish the corruption from the previously verified file.
+ let raw = fs::read_to_string(&path).unwrap();
+ let corrupt = raw.replacen("\"image\":0", "\"image\":9", 1);
+ assert_ne!(raw, corrupt);
+ fs::write(&path, &corrupt).unwrap();
+ File::open(&path)
+ .unwrap()
+ .set_times(std::fs::FileTimes::new().set_modified(metadata.modified().unwrap()))
+ .unwrap();
+ assert_eq!(fs::metadata(&path).unwrap().len(), metadata.len());
+ assert_eq!(
+ fs::metadata(&path).unwrap().modified().unwrap(),
+ metadata.modified().unwrap()
+ );
+ let error = append_message(dir.path(), "s", "old", &image_record()).unwrap_err();
+ assert!(binary_storage::is_error(&error), "{error:#}");
+ assert_eq!(fs::read_to_string(path).unwrap(), corrupt);
+}
+
+#[test]
+fn invalid_encoded_revision_blocks_stored_and_live_revision_appends() {
+ for live in [false, true] {
+ let dir = tempfile::tempdir().unwrap();
+ let revision = RevisionRecord {
+ root_user_id: "root".into(),
+ revision_index: 0,
+ created_at: "old".into(),
+ messages: vec![image_record()],
+ turns: Default::default(),
+ };
+ append_revision(dir.path(), "s", &revision).unwrap();
+ let path = revisions_path(dir.path(), "s").unwrap();
+ let raw = fs::read_to_string(&path).unwrap();
+ let corrupt = raw.replacen("\"image\":0", "\"image\":9", 1);
+ assert_ne!(raw, corrupt);
+ fs::write(&path, &corrupt).unwrap();
+ let result = if live {
+ append_live_revision(
+ dir.path(),
+ "s",
+ &LiveRevisionRecord {
+ root_user_id: "root".into(),
+ revision_index: 1,
+ created_at: "old".into(),
+ },
+ )
+ } else {
+ append_revision(dir.path(), "s", &revision)
+ };
+ let error = result.unwrap_err();
+ assert!(binary_storage::is_error(&error), "{error:#}");
+ assert_eq!(fs::read_to_string(path).unwrap(), corrupt);
+ }
+}
+
+#[test]
+fn plain_bad_rows_and_torn_utf8_remain_tolerated_before_append() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = seed_transcript(dir.path());
+ let mut raw = fs::read(&path).unwrap();
+ raw.extend_from_slice(b"{bad plain row}\n{\"type\":\"message\",\"id\":\"torn\xff");
+ fs::write(&path, &raw).unwrap();
+ append_message(dir.path(), "s", "old", &image_record()).unwrap();
+ assert!(fs::read(&path).unwrap().starts_with(&raw));
+ assert_eq!(read_transcript(dir.path(), "s").unwrap().len(), 2);
+}
+
+#[test]
+fn owned_appends_and_tail_updates_reuse_a_single_full_scan() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = seed_transcript(dir.path());
+ // Simulate the first mutation in a new Host process.
+ binary_integrity::invalidate(&path);
+ append_message(dir.path(), "s", "old", &image_record()).unwrap();
+ assert_eq!(binary_integrity::scan_count(&path), 1);
+ for index in 0..4 {
+ let mut record = image_record();
+ record.id = format!("next-{index}");
+ append_message(dir.path(), "s", "old", &record).unwrap();
+ record.meta = Some(json!({"settled":true}));
+ assert!(update_message(dir.path(), "s", &record).unwrap());
+ }
+ assert_eq!(
+ binary_integrity::scan_count(&path),
+ 1,
+ "normal mutations must not decode the growing history again"
+ );
+}
+
+#[test]
+fn an_open_file_from_an_old_generation_cannot_certify_its_replacement() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = seed_transcript(dir.path());
+ let opened = File::open(&path).unwrap();
+ let replacement = path.with_extension("replacement");
+ fs::copy(&path, &replacement).unwrap();
+ replace_message_line(&replacement, "reference");
+ fs::rename(replacement, &path).unwrap();
+ let error = binary_integrity::verify(&path, &mut BufReader::new(opened)).unwrap_err();
+ assert!(
+ error.to_string().contains("transcript changed"),
+ "{error:#}"
+ );
+ let error = append_message(dir.path(), "s", "old", &image_record()).unwrap_err();
+ assert!(binary_storage::is_error(&error), "{error:#}");
+}
+
+#[test]
+fn rewritten_transcripts_are_checked_before_the_next_append() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = seed_transcript(dir.path());
+ write_transcript(dir.path(), "s", "old", &[image_record()]).unwrap();
+ append_message(dir.path(), "s", "old", &image_record()).unwrap();
+ assert_eq!(binary_integrity::scan_count(&path), 1);
+ let mut next = image_record();
+ next.id = "next".into();
+ append_message(dir.path(), "s", "old", &next).unwrap();
+ let mut first = image_record();
+ first.meta = Some(json!({"settled":true}));
+ assert!(update_message(dir.path(), "s", &first).unwrap());
+ append_message(dir.path(), "s", "old", &next).unwrap();
+ assert_eq!(binary_integrity::scan_count(&path), 2);
+}
+
+#[test]
+fn encoded_compaction_and_revision_record_shapes_are_validated() {
+ for tag in ["compaction", "revision", "revision_live"] {
+ let dir = tempfile::tempdir().unwrap();
+ let path = if tag == "compaction" {
+ seed_transcript(dir.path())
+ } else {
+ let path = revisions_path(dir.path(), "s").unwrap();
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
+ fs::write(&path, "{\"type\":\"storage\",\"schema\":2}\n").unwrap();
+ path
+ };
+ let mut value = serde_json::to_value(image_record()).unwrap();
+ value["type"] = json!(tag);
+ // This valid envelope reconstructs the binary fields, but the known
+ // record's required typed fields are missing or mistyped.
+ let encoded = binary_storage::encode(value).unwrap();
+ let mut file = OpenOptions::new().append(true).open(&path).unwrap();
+ writeln!(file, "{encoded}").unwrap();
+ drop(file);
+ let before = fs::read(&path).unwrap();
+ let error =
+ append_line(&path, None, tagged("message", &image_record()).unwrap()).unwrap_err();
+ assert!(binary_storage::is_error(&error), "tag={tag}: {error:#}");
+ assert_eq!(fs::read(path).unwrap(), before);
+ }
+}
+
+#[test]
+fn legacy_conversion_keeps_invalid_plain_image_rows_plain_and_skippable() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = transcript_path(dir.path(), "s").unwrap();
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
+ let mut value = serde_json::to_value(image_record()).unwrap();
+ value["type"] = json!("message");
+ value.as_object_mut().unwrap().remove("role");
+ let bad_row = value.to_string();
+ fs::write(&path, format!("{{\"type\":\"session\",\"schema\":1,\"sessionId\":\"s\",\"createdAt\":\"old\"}}\n{bad_row}\n")).unwrap();
+ assert!(read_transcript(dir.path(), "s").unwrap().is_empty());
+ append_message(dir.path(), "s", "old", &image_record()).unwrap();
+ assert_eq!(
+ fs::read_to_string(&path).unwrap().lines().nth(1),
+ Some(bad_row.as_str())
+ );
+ assert_eq!(read_transcript(dir.path(), "s").unwrap().len(), 1);
+}
diff --git a/crates/host-core/src/transcripts/binary_migration.rs b/crates/host-core/src/transcripts/binary_migration.rs
index e8ffa3835..a8a0e8102 100644
--- a/crates/host-core/src/transcripts/binary_migration.rs
+++ b/crates/host-core/src/transcripts/binary_migration.rs
@@ -48,10 +48,12 @@ pub(super) fn prepare(path: &Path, header: Option<&str>) -> Result<bool> {
let mut has_session_header = false;
if let Ok(value) = serde_json::from_slice::<Value>(&raw) {
if current_header(&value)? {
+ binary_integrity::verify(path, &mut reader)?;
return Ok(false);
}
has_session_header = value["type"] == "session";
}
+ binary_integrity::verify(path, &mut reader)?;
reader.seek(SeekFrom::Start(0))?;
let tmp = path.with_extension("binary.tmp");
let mut writer = BufWriter::new(File::create(&tmp)?);
@@ -80,14 +82,22 @@ pub(super) fn prepare(path: &Path, header: Option<&str>) -> Result<bool> {
replacement = Some(value);
}
Some("message" | "compaction" | "revision") => {
- let decoded = binary_storage::decode(value.clone())?;
- let encoded = binary_storage::encode(decoded.clone())?;
- anyhow::ensure!(
- binary_storage::decode(encoded.clone())? == decoded,
- "lossless transcript conversion verification failed"
- );
- if encoded != value {
- replacement = Some(encoded);
+ // Readers historically skip malformed plain records. Do
+ // not turn one into an encoded row whose typed read must
+ // fail explicitly. Existing encoded rows were validated
+ // before opening the conversion temporary.
+ if value.get("binaryStorage").is_some()
+ || binary_storage::validate_record(value.clone()).is_ok()
+ {
+ let decoded = binary_storage::decode(value.clone())?;
+ let encoded = binary_storage::encode(decoded.clone())?;
+ anyhow::ensure!(
+ binary_storage::decode(encoded.clone())? == decoded,
+ "lossless transcript conversion verification failed"
+ );
+ if encoded != value {
+ replacement = Some(encoded);
+ }
}
}
_ => {}
@@ -112,5 +122,6 @@ pub(super) fn prepare(path: &Path, header: Option<&str>) -> Result<bool> {
writer.get_ref().sync_data()?;
drop(writer);
swap_into_place(&tmp, path)?;
+ binary_integrity::invalidate(path);
Ok(true)
}
diff --git a/crates/host-core/src/transcripts/binary_storage.rs b/crates/host-core/src/transcripts/binary_storage.rs
index 950e3a30a..b06f51c49 100644
--- a/crates/host-core/src/transcripts/binary_storage.rs
+++ b/crates/host-core/src/transcripts/binary_storage.rs
@@ -636,14 +636,18 @@ pub(crate) fn decode(mut value: Value) -> Result<Value> {
Ok(value)
}
-pub(super) fn read<T: serde::de::DeserializeOwned>(text: &str) -> Result<T> {
- let value: Value = serde_json::from_str(text).map_err(|e| {
+fn parse_line(text: &str) -> Result<Value> {
+ serde_json::from_str(text).map_err(|e| {
if text.contains("\"binaryStorage\"") {
invalid(e.to_string())
} else {
anyhow!(e)
}
- })?;
+ })
+}
+
+pub(super) fn read<T: serde::de::DeserializeOwned>(text: &str) -> Result<T> {
+ let value = parse_line(text)?;
let encoded = value.get("binaryStorage").is_some();
let decoded = decode(value)?;
serde_json::from_value(decoded).map_err(|e| {
@@ -655,6 +659,31 @@ pub(super) fn read<T: serde::de::DeserializeOwned>(text: &str) -> Result<T> {
})
}
+/// Validate the storage representation without making historical plain rows
+/// obey newer business schemas. Encoded known rows have the same typed
+/// validation and explicit corruption errors as their normal read paths.
+pub(super) fn validate_line(text: &str) -> Result<()> {
+ let value = parse_line(text)?;
+ let encoded = value.get("binaryStorage").is_some();
+ let value = decode(value)?;
+ if !encoded {
+ return Ok(());
+ }
+ validate_record(value).map_err(|error| invalid(error.to_string()))
+}
+
+pub(super) fn validate_record(value: Value) -> serde_json::Result<()> {
+ match value.get("type").and_then(Value::as_str) {
+ Some("message") => serde_json::from_value::<super::MessageRecord>(value).map(|_| ()),
+ Some("compaction") => serde_json::from_value::<super::CompactionRecord>(value).map(|_| ()),
+ Some("revision") => serde_json::from_value::<super::RevisionRecord>(value).map(|_| ()),
+ Some("revision_live") => {
+ serde_json::from_value::<super::LiveRevisionRecord>(value).map(|_| ())
+ }
+ _ => Ok(()),
+ }
+}
+
/// Relocation changes structured paths. Apply that same intentional change to
/// proven image-result JSON mirrors, preserving every other literal byte. Plain
/// narrative content is never rewritten or guessed to be a machine mirror.
diff --git a/crates/host-core/src/transcripts/layout.rs b/crates/host-core/src/transcripts/layout.rs
index acc415090..7a2dec946 100644
--- a/crates/host-core/src/transcripts/layout.rs
+++ b/crates/host-core/src/transcripts/layout.rs
@@ -569,6 +569,16 @@ fn store_layout_cache(data_dir: &Path, session_id: &str, layout: &TranscriptLayo
#[cfg(unix)]
fn file_identity(_path: &Path, metadata: &fs::Metadata) -> FileIdentity {
+ unix_file_identity(metadata)
+}
+
+#[cfg(unix)]
+pub(super) fn opened_file_identity(_file: &File, metadata: &fs::Metadata) -> FileIdentity {
+ unix_file_identity(metadata)
+}
+
+#[cfg(unix)]
+fn unix_file_identity(metadata: &fs::Metadata) -> FileIdentity {
use std::os::unix::fs::MetadataExt;
let mut file_id = [0u8; 16];
file_id[..8].copy_from_slice(&metadata.ino().to_be_bytes());
@@ -581,15 +591,20 @@ fn file_identity(_path: &Path, metadata: &fs::Metadata) -> FileIdentity {
#[cfg(windows)]
fn file_identity(path: &Path, _metadata: &fs::Metadata) -> FileIdentity {
+ let Ok(file) = File::open(path) else {
+ return FileIdentity::Unavailable;
+ };
+ opened_file_identity(&file, _metadata)
+}
+
+#[cfg(windows)]
+pub(super) fn opened_file_identity(file: &File, _metadata: &fs::Metadata) -> FileIdentity {
use std::{mem::size_of, os::windows::io::AsRawHandle};
use windows_sys::Win32::{
Foundation::HANDLE,
Storage::FileSystem::{FileIdInfo, GetFileInformationByHandleEx, FILE_ID_INFO},
};
- let Ok(file) = File::open(path) else {
- return FileIdentity::Unavailable;
- };
let mut info = FILE_ID_INFO::default();
let result = unsafe {
GetFileInformationByHandleEx(
@@ -614,6 +629,11 @@ fn file_identity(_path: &Path, _metadata: &fs::Metadata) -> FileIdentity {
FileIdentity::Unavailable
}
+#[cfg(not(any(unix, windows)))]
+pub(super) fn opened_file_identity(_file: &File, _metadata: &fs::Metadata) -> FileIdentity {
+ FileIdentity::Unavailable
+}
+
#[cfg(test)]
#[path = "../transcripts_layout_tests.rs"]
mod tests;