Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
perf(desktop): reuse an installed Runtime from metadata instead of re-hashing it (#2309)
Maxc297f0515b92
diff --git a/desktop/README.md b/desktop/README.mdindex 4966a1e48..c27a1894b 100644--- a/desktop/README.md+++ b/desktop/README.md@@ -95,9 +95,14 @@ and is not a fallback for this case.The first launch verifies the embedded Runtime archive and installs itatomically below the operating system's application-data directory. Installsare versioned and content-addressed, so application updates never replace files-used by a running Runtime. Later launches re-verify the extracted file tree and-repair one corrupt slot from the immutable archive; a second integrity failure-is rejected. The Controller owns the archive identity that the UI forwards+used by a running Runtime. The extracted tree is hashed before its slot is+published. A later launch reuses it after checking its file set, sizes, and+read permissions from metadata alone, so it does not re-read the whole tree+before the first health probe; the full hash is repeated on a background thread+while the Runtime starts. A slot that fails either check is repaired from the+immutable archive (the metadata check repairs it before this launch, the+background hash before the next one); a second integrity failure is rejected.+The Controller owns the archive identity that the UI forwardsthrough `/ready`; `vibe start` replaces a mismatched desktop-managed Controllerbefore it can reuse the service. After a successor proves that identity, theshell removes superseded private Runtime trees; reopening an older app reinstallsdiff --git a/desktop/runtime-host/src/launcher.rs b/desktop/runtime-host/src/launcher.rsindex 4ad0196ac..b05bbc96b 100644--- a/desktop/runtime-host/src/launcher.rs+++ b/desktop/runtime-host/src/launcher.rs@@ -368,6 +368,14 @@ impl RuntimeLauncher for BundledVibeLauncher {let prepared = self.bundle.prepare();record_runtime_prepare(&self.log, &prepared, started.elapsed());let runtime = prepared.map_err(|_| LaunchError::RuntimeInstall)?;+ if runtime.reused && claim_audit(&runtime.root) {+ let (bundle, root, log) = (self.bundle.clone(), runtime.root.clone(), self.log.clone());+ std::thread::spawn(move || {+ let started = Instant::now();+ let audited = bundle.audit(&root);+ record_runtime_audit(&log, &audited, started.elapsed());+ });+ }let runtime_id = runtime.runtime_id.clone();Ok(Arc::new(ResolvedVibeExecutable {command: RuntimeCommand::private(@@ -821,6 +829,33 @@ fn record_runtime_prepare();}+/// Whether this process has yet to audit `root`.+///+/// Every bootstrap attempt resolves the Runtime again, and one full hash per+/// reused slot per process is enough: a slot it withdraws is not reused again,+/// and one it passes is not rehashed on each retry.+fn claim_audit(root: &Path) -> bool {+ static AUDITED: OnceLock<std::sync::Mutex<std::collections::HashSet<PathBuf>>> = OnceLock::new();+ AUDITED+ .get_or_init(Default::default)+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .insert(root.to_owned())+}++/// A withdrawn slot is the only trace that the next launch will reinstall, so+/// the verdict is recorded next to the prepare that reused it.+fn record_runtime_audit(log: &BootstrapLog, audited: &Result<(), PrivateRuntimeError>, elapsed: Duration) {+ let mut fields = vec![+ ("outcome", if audited.is_ok() { "intact" } else { "failed" }.to_owned()),+ ("ms", elapsed.as_millis().to_string()),+ ];+ if let Err(error) = audited {+ fields.push(("error", format!("{error:?}")));+ }+ log.record("runtime.audit", &fields);+}+fn parse_endpoint_descriptor(bytes: &[u8]) -> Result<LoopbackOrigin, LaunchError> {if bytes.len() > MAX_ENDPOINT_BYTES as usize {return Err(LaunchError::EndpointOutput);@@ -2001,6 +2036,47 @@ mod tests {std::fs::remove_dir_all(&dir).ok();}+ /// A slot withdrawn by the audit is the one reason a later launch+ /// reinstalls without a failure of its own, so the log has to say so.+ #[test]+ fn an_audit_records_whether_the_reused_slot_was_intact() {+ let dir = scratch_dir("audit-record");+ let log = BootstrapLog::at(dir.join("bootstrap.log"));++ record_runtime_audit(&log, &Ok(()), Duration::from_millis(2_400));+ record_runtime_audit(+ &log,+ &Err(PrivateRuntimeError::ArchiveVerification),+ Duration::from_millis(900),+ );++ let written = std::fs::read_to_string(dir.join("bootstrap.log")).expect("the audits are recorded");+ let records: Vec<&str> = written.lines().collect();+ assert_eq!(records.len(), 2, "{written}");+ assert!(+ records[0].contains("runtime.audit") && records[0].contains("outcome=\"intact\""),+ "{}",+ records[0]+ );+ assert!(+ records[1].contains("outcome=\"failed\"") && records[1].contains("ArchiveVerification"),+ "{}",+ records[1]+ );+ std::fs::remove_dir_all(&dir).ok();+ }++ /// Each bootstrap retry resolves the Runtime again; only the first reuse of+ /// a slot in this process pays for its full hash.+ #[test]+ fn a_slot_is_audited_once_per_process() {+ let root = scratch_dir("audit-claim").join("3.1.1/20aa5822aa3595e1");++ assert!(claim_audit(&root));+ assert!(!claim_audit(&root));+ assert!(claim_audit(&root.with_file_name("20aa5822aa3595e1-repair")));+ }+/// The bootstrap loop aborts a doomed wait on this verdict, so it has to be/// right in every direction: a launcher that refused or failed must be/// visible, the ordinary `vibe start` — which exits 0 once the Runtime isdiff --git a/desktop/runtime-host/src/private_runtime.rs b/desktop/runtime-host/src/private_runtime.rsindex 9fe2ba428..2d62929b4 100644--- a/desktop/runtime-host/src/private_runtime.rs+++ b/desktop/runtime-host/src/private_runtime.rs@@ -218,6 +218,44 @@ impl PrivateRuntimeBundle {install_result}+ /// Hashes a reused install slot in full and withdraws it if it no longer+ /// matches the manifest.+ ///+ /// `prepare()` reuses a slot from metadata alone, so a change metadata cannot+ /// see would otherwise be served on every launch. This repeats the check a+ /// launch used to run inline, meant for a background thread while the+ /// Runtime starts. A failing slot loses its marker. The daemon that may be+ /// running from it is untouched, because nothing it executes is removed. The+ /// next `prepare()` then treats the slot as invalid and reinstalls the+ /// verified archive, by the same repair path as a slot rejected inline.+ pub fn audit(&self, root: &Path) -> Result<(), PrivateRuntimeError> {+ let manifest = self.read_manifest()?;+ validate_manifest(&manifest)?;+ let digest_prefix = manifest+ .archive_sha256+ .get(..16)+ .ok_or(PrivateRuntimeError::ManifestInvalid)?;+ let version_dir = self.install_root.join(&manifest.runtime_version);+ if !install_slots(&version_dir, digest_prefix)+ .iter()+ .any(|slot| slot == root)+ {+ return Err(PrivateRuntimeError::Install(io::Error::new(+ io::ErrorKind::InvalidInput,+ "audited Runtime is not an install slot of the bundled manifest",+ )));+ }+ let verified = verify_installed_tree(root, &manifest);+ if verified.is_err() {+ match fs::remove_file(root.join(INSTALL_MARKER_NAME)) {+ Ok(()) => {}+ Err(error) if error.kind() == io::ErrorKind::NotFound => {}+ Err(error) => return Err(PrivateRuntimeError::Install(error)),+ }+ }+ verified+ }+/// Removes private Runtime trees that are no longer used by the active/// desktop-managed daemon.///@@ -575,7 +613,50 @@ fn required_runtime_files(manifest: &RuntimeBundleManifest) -> [(PathBuf, bool);]}+/// Hashes every file of a freshly extracted tree against `tree_sha256`.+///+/// This runs once per install, on the staging directory, before the marker is+/// written and the slot is published, and again by+/// [`PrivateRuntimeBundle::audit`] off the launch path. Reuse itself checks+/// only [`verify_installed_shape`].fn verify_installed_tree(root: &Path, manifest: &RuntimeBundleManifest) -> Result<(), PrivateRuntimeError> {+ let mut files = verify_installed_shape(root, manifest)?;+ files.sort_by(|left, right| left.0.cmp(&right.0));++ let mut hasher = Sha256::new();+ hasher.update(TREE_HASH_DOMAIN);+ for (relative, path, size) in &files {+ update_tree_header(&mut hasher, relative, *size);+ let mut file = File::open(path).map_err(PrivateRuntimeError::Install)?;+ io::copy(&mut file, &mut hasher).map_err(PrivateRuntimeError::Install)?;+ }+ let actual = format!("{:x}", hasher.finalize());+ if actual != manifest.tree_sha256 {+ return Err(PrivateRuntimeError::ArchiveVerification);+ }+ Ok(())+}++/// Checks a tree's file set against the manifest without reading any file.+///+/// A slot is published only by renaming a staging directory whose full hash+/// matched and whose marker was written after that, so a slot carrying the+/// manifest's marker was hashed in full when it was extracted. Re-hashing it on+/// every launch read the whole tree (about 390MB in 17k files) before the first+/// health probe: 3.5s at the median and 12.6s at p90 over 250 recorded launches.+///+/// What commonly reaches an installed tree afterwards is a process writing into+/// it (bytecode, #2273), a file being removed or truncated, or its permissions+/// changing. Each changes the regular-file count, the unpacked size, or a mode+/// this walk already reads, and a link or special file is rejected outright, so+/// none of those trees is reused. What metadata cannot see (a rename, an+/// equal-size rewrite, data lost in a crash before it reached the disk) is left+/// to [`PrivateRuntimeBundle::audit`], which repeats the full hash off the+/// launch path and withdraws a slot that fails it.+fn verify_installed_shape(+ root: &Path,+ manifest: &RuntimeBundleManifest,+) -> Result<Vec<(String, PathBuf, u64)>, PrivateRuntimeError> {let root_metadata = fs::symlink_metadata(root).map_err(PrivateRuntimeError::Install)?;if !root_metadata.file_type().is_dir() {return Err(PrivateRuntimeError::ArchiveInvalid);@@ -583,28 +664,17 @@ fn verify_installed_tree(root: &Path, manifest: &RuntimeBundleManifest) -> Resullet mut files = Vec::new();collect_tree_files(root, root, &mut files)?;- files.sort_by(|left, right| left.0.cmp(&right.0));-- let mut hasher = Sha256::new();- hasher.update(TREE_HASH_DOMAIN);let mut unpacked_size = 0_u64;- for (relative, path, size) in &files {+ for (_, _, size) in &files {unpacked_size = unpacked_size.checked_add(*size).filter(|value| *value <= manifest.unpacked_size).ok_or(PrivateRuntimeError::ArchiveVerification)?;- update_tree_header(&mut hasher, relative, *size);- let mut file = File::open(path).map_err(PrivateRuntimeError::Install)?;- io::copy(&mut file, &mut hasher).map_err(PrivateRuntimeError::Install)?;}if files.len() as u64 != manifest.entry_count || unpacked_size != manifest.unpacked_size {return Err(PrivateRuntimeError::ArchiveVerification);}- let actual = format!("{:x}", hasher.finalize());- if actual != manifest.tree_sha256 {- return Err(PrivateRuntimeError::ArchiveVerification);- }- Ok(())+ Ok(files)}fn collect_tree_files(@@ -627,6 +697,16 @@ fn collect_tree_files(if !file_type.is_file() {return Err(PrivateRuntimeError::ArchiveVerification);}+ // The install hash opened every file as this user, so a file without+ // the owner read bit was changed afterwards and would fail the Runtime+ // that imports it.+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ if metadata.permissions().mode() & 0o400 == 0 {+ return Err(PrivateRuntimeError::ArchiveVerification);+ }+ }let relative_path = path.strip_prefix(root).map_err(|_| PrivateRuntimeError::ArchiveVerification)?;@@ -679,7 +759,10 @@ fn installed_runtime(return Err(PrivateRuntimeError::ArchiveInvalid);}validate_runtime_files(root, manifest)?;- verify_installed_tree(root, manifest)?;+ // Every caller reaches this for a published slot, whose marker proves the+ // full hash already passed: a reused one, one this launch just renamed into+ // place, or one another process won the rename with.+ verify_installed_shape(root, manifest)?;Ok(InstalledPrivateRuntime {root: root.to_owned(),python: root.join(&manifest.python_entrypoint),@@ -855,6 +938,159 @@ mod tests {fs::remove_dir_all(root).ok();}+ /// Any change to an installed tree's file set or sizes keeps it from being+ /// reused, whichever file it touches.+ #[test]+ fn a_changed_file_set_is_never_reused() {+ type Mutation = (&'static str, fn(&Path));+ let mutations: [Mutation; 4] = [+ ("bytecode written by a Runtime process", |root| {+ fs::create_dir_all(root.join("lib/__pycache__")).expect("bytecode directory");+ fs::write(root.join("lib/__pycache__/data.cpython-312.pyc"), b"pyc").expect("bytecode");+ }),+ ("file removed", |root| {+ fs::remove_file(root.join("lib/data.txt")).expect("remove")+ }),+ ("file truncated", |root| {+ fs::write(root.join("lib/data.txt"), b"").expect("truncate")+ }),+ ("file grown", |root| {+ fs::write(root.join("lib/data.txt"), b"runtime+").expect("grow")+ }),+ ];+ for (label, mutate) in mutations {+ let root = scratch("installed-shape");+ let manifest = write_bundle(&root, Some("lib/data.txt"));+ let bundle = PrivateRuntimeBundle::new(root.join("bundle"), root.join("installs"));+ let first = bundle.prepare().expect("first install");+ mutate(&first.root);++ let next = bundle.prepare().expect("repair install");++ assert!(!next.reused, "{label}: the changed tree was reused");+ assert!(+ next.root+ .ends_with(format!("{}-repair", &manifest.archive_sha256[..16])),+ "{label}: the verified archive was not reinstalled into the repair slot"+ );+ assert_eq!(+ fs::read(next.root.join("lib/data.txt")).expect("repaired file"),+ b"runtime"+ );+ fs::remove_dir_all(root).ok();+ }+ }++ /// A file the Runtime can no longer read is visible from its mode, so it is+ /// repaired before the launch rather than failing the Runtime that imports it.+ #[cfg(unix)]+ #[test]+ fn an_unreadable_file_is_repaired_before_reuse() {+ use std::os::unix::fs::PermissionsExt;++ let root = scratch("unreadable");+ let manifest = write_bundle(&root, Some("lib/data.txt"));+ let bundle = PrivateRuntimeBundle::new(root.join("bundle"), root.join("installs"));+ let first = bundle.prepare().expect("first install");+ let data = first.root.join("lib/data.txt");+ fs::set_permissions(&data, fs::Permissions::from_mode(0o000)).expect("make content unreadable");++ let next = bundle.prepare().expect("repair install");++ assert!(!next.reused, "the unreadable tree was reused");+ assert!(next+ .root+ .ends_with(format!("{}-repair", &manifest.archive_sha256[..16])));+ assert_eq!(+ fs::read(next.root.join("lib/data.txt")).expect("repaired file"),+ b"runtime"+ );+ fs::set_permissions(&data, fs::Permissions::from_mode(0o644)).ok();+ fs::remove_dir_all(root).ok();+ }++ /// Reuse reads no file content, so a change that keeps every count and size+ /// is served once; the audit that follows withdraws the slot and the next+ /// launch reinstalls the verified archive.+ #[test]+ fn what_metadata_cannot_see_is_withdrawn_by_the_audit() {+ type Mutation = (&'static str, fn(&Path));+ let mutations: [Mutation; 2] = [+ ("equal-size rewrite", |root| {+ fs::write(root.join("lib/data.txt"), b"RUNTIME").expect("rewrite")+ }),+ ("rename", |root| {+ fs::rename(root.join("lib/data.txt"), root.join("lib/atad.txt")).expect("rename")+ }),+ ];+ for (label, mutate) in mutations {+ let root = scratch("audit");+ let manifest = write_bundle(&root, Some("lib/data.txt"));+ let bundle = PrivateRuntimeBundle::new(root.join("bundle"), root.join("installs"));+ let first = bundle.prepare().expect("first install");+ mutate(&first.root);++ let reused = bundle.prepare().expect("metadata-only reuse");+ assert!(reused.reused, "{label}: reuse must not read file content");+ assert_eq!(reused.root, first.root);++ assert!(+ matches!(+ bundle.audit(&reused.root),+ Err(PrivateRuntimeError::ArchiveVerification)+ ),+ "{label}: the audit accepted a changed tree"+ );+ assert!(+ !first.root.join(INSTALL_MARKER_NAME).exists(),+ "{label}: slot not withdrawn"+ );++ let next = bundle.prepare().expect("repair install");+ assert!(!next.reused, "{label}: the withdrawn slot was reused");+ assert!(+ next.root+ .ends_with(format!("{}-repair", &manifest.archive_sha256[..16])),+ "{label}: the verified archive was not reinstalled into the repair slot"+ );+ assert_eq!(+ fs::read(next.root.join("lib/data.txt")).expect("repaired file"),+ b"runtime"+ );+ fs::remove_dir_all(root).ok();+ }+ }++ #[test]+ fn an_intact_slot_survives_its_audit() {+ let root = scratch("audit-intact");+ write_bundle(&root, Some("lib/data.txt"));+ let bundle = PrivateRuntimeBundle::new(root.join("bundle"), root.join("installs"));+ let first = bundle.prepare().expect("first install");++ bundle.audit(&first.root).expect("an intact slot passes");+ let next = bundle.prepare().expect("reuse");++ assert!(next.reused);+ assert_eq!(next.root, first.root);+ fs::remove_dir_all(root).ok();+ }++ /// The audit deletes a marker, so it acts only on a slot this bundle owns.+ #[test]+ fn the_audit_touches_only_an_install_slot_of_the_bundle() {+ let root = scratch("audit-foreign");+ write_bundle(&root, None);+ let bundle = PrivateRuntimeBundle::new(root.join("bundle"), root.join("installs"));+ let foreign = root.join("elsewhere");+ fs::create_dir_all(&foreign).expect("foreign directory");+ fs::write(foreign.join(INSTALL_MARKER_NAME), b"{}").expect("foreign marker");++ assert!(matches!(bundle.audit(&foreign), Err(PrivateRuntimeError::Install(_))));+ assert!(foreign.join(INSTALL_MARKER_NAME).exists());+ fs::remove_dir_all(root).ok();+ }+#[cfg(unix)]#[test]fn a_runtime_with_a_non_executable_entrypoint_is_repaired() {