From 2b5214431152b54ec38b7eeb82134eb67bd98a30 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Wed, 21 Oct 2026 14:38:46 +0200 Subject: [PATCH] fix(history): make restore_page and restore_graph atomic Both run inside Graph::transaction so a failure halfway rolls every change back. Adds a fault-injection hook and a regression test. Co-Authored-By: Claude Sonnet 5.5 --- crates/synapse-history/src/history.rs | 8 ++ crates/synapse-history/src/restore.rs | 144 +++++++++++++++--------- crates/synapse-history/tests/history.rs | 44 ++++++++ 3 files changed, 145 insertions(+), 51 deletions(-) diff --git a/crates/synapse-history/src/history.rs b/crates/synapse-history/src/history.rs index 741437f..0ca919e 100644 --- a/crates/synapse-history/src/history.rs +++ b/crates/synapse-history/src/history.rs @@ -79,6 +79,7 @@ pub struct History { opts: HistoryOptions, /// `(last seen graph seq, time we saw it change)` for idle detection. observed: Option<(i64, i64)>, + pub(crate) fault: std::cell::Cell>, } impl History { @@ -95,9 +96,16 @@ impl History { dir, opts, observed: None, + fault: Default::default(), }) } + /// Test hook: make the next restore fail after `n` block writes/deletes. + #[doc(hidden)] + pub fn inject_restore_fault(&self, n: Option) { + self.fault.set(n); + } + pub fn dir(&self) -> &Path { &self.dir } diff --git a/crates/synapse-history/src/restore.rs b/crates/synapse-history/src/restore.rs index 5b15fb2..a75183e 100644 --- a/crates/synapse-history/src/restore.rs +++ b/crates/synapse-history/src/restore.rs @@ -5,6 +5,7 @@ use crate::Result; use crate::export; use crate::history::{History, SnapshotInfo}; use crate::parse::{ParsedPage, parse_page}; +use std::cell::Cell; use std::collections::{HashMap, HashSet}; use synapse_core::position::between; use synapse_core::{Block, BlockId, Graph, NewPage, Page, new_id}; @@ -19,6 +20,36 @@ pub struct RestoreReport { pub safety_snapshot: Option, } +/// Test hook: fail after this many block writes/deletes. +type Fault<'a> = &'a Cell>; + +fn tick(fault: Fault) -> Result<()> { + if let Some(n) = fault.get() { + if n == 0 { + return Err(crate::Error::NotFound("injected fault".into())); + } + fault.set(Some(n - 1)); + } + Ok(()) +} + +/// Runs `f` in one graph transaction: any error rolls every change back. +fn atomic(graph: &Graph, f: impl FnOnce() -> Result) -> Result { + let mut failure = None; + let out = graph.transaction(|_| match f() { + Ok(v) => Ok(v), + Err(e) => { + failure = Some(e); + Err(synapse_core::Error::Invalid("restore aborted".into())) + } + }); + match (out, failure) { + (Ok(v), _) => Ok(v), + (Err(_), Some(e)) => Err(e), + (Err(e), None) => Err(e.into()), + } +} + struct Plan { blocks: Vec, delete: Vec, @@ -130,8 +161,9 @@ fn same(a: &Block, b: &Block) -> bool { && a.collapsed == b.collapsed } -fn apply_deletes(graph: &Graph, plan: &Plan) -> Result<()> { +fn apply_deletes(graph: &Graph, plan: &Plan, fault: Fault) -> Result<()> { for id in &plan.delete { + tick(fault)?; // Deleting a parent already removed its subtree. if graph.get_block(*id)?.is_some() { graph.delete_block(*id)?; @@ -141,12 +173,13 @@ fn apply_deletes(graph: &Graph, plan: &Plan) -> Result<()> { } /// Writes changed blocks; returns whether anything was written. -fn apply_puts(graph: &Graph, plan: &Plan) -> Result { +fn apply_puts(graph: &Graph, plan: &Plan, fault: Fault) -> Result { let mut wrote = false; for b in &plan.blocks { if graph.get_block(b.id)?.is_some_and(|cur| same(&cur, b)) { continue; } + tick(fault)?; graph.put_block(b)?; wrote = true; } @@ -189,22 +222,26 @@ impl History { safety_snapshot: safety, ..Default::default() }; - match text { - Some(text) => { - let p = plan(graph, title, &parse_page(&text), false)?; - apply_deletes(graph, &p)?; - apply_puts(graph, &p)?; - report.restored = 1; - } - None => { - let page = graph - .page_by_title(title)? - .ok_or_else(|| Self::not_found(title))?; - if clear_or_delete(graph, &page)? { - report.removed = 1; + let fault = &self.fault; + atomic(graph, || { + match text { + Some(text) => { + let p = plan(graph, title, &parse_page(&text), false)?; + apply_deletes(graph, &p, fault)?; + apply_puts(graph, &p, fault)?; + report.restored = 1; + } + None => { + let page = graph + .page_by_title(title)? + .ok_or_else(|| Self::not_found(title))?; + if clear_or_delete(graph, &page)? { + report.removed = 1; + } } } - } + Ok(()) + })?; Ok(report) } @@ -221,44 +258,49 @@ impl History { safety_snapshot: safety, ..Default::default() }; - let mut plans = Vec::new(); - let mut wanted: HashSet = HashSet::new(); - for (path, oid) in &files { - let Some(title) = export::title_from_path(path) else { - continue; - }; - wanted.insert(synapse_core::title_key(&title)); - let text = self.read_blob(*oid)?; - plans.push(plan(graph, &title, &parse_page(&text), true)?); - } - // Delete first so blocks moved between pages can be re-created where they belong. - for p in &plans { - apply_deletes(graph, p)?; - } - for p in &plans { - if apply_puts(graph, p)? { - report.restored += 1; + let fault = &self.fault; + let this = &*self; + atomic(graph, || { + let mut plans = Vec::new(); + let mut wanted: HashSet = HashSet::new(); + for (path, oid) in &files { + let Some(title) = export::title_from_path(path) else { + continue; + }; + wanted.insert(synapse_core::title_key(&title)); + let text = this.read_blob(*oid)?; + plans.push(plan(graph, &title, &parse_page(&text), true)?); } - } - let mut offset = 0; - let mut extra = Vec::new(); - loop { - let batch = graph.list_pages(true, 500, offset)?; - if batch.is_empty() { - break; + // Delete first so blocks moved between pages can be re-created where they belong. + for p in &plans { + apply_deletes(graph, p, fault)?; } - offset += batch.len() as u32; - extra.extend( - batch - .into_iter() - .filter(|p| !wanted.contains(&synapse_core::title_key(&p.title))), - ); - } - for page in extra { - if clear_or_delete(graph, &page)? { - report.removed += 1; + for p in &plans { + if apply_puts(graph, p, fault)? { + report.restored += 1; + } } - } + let mut offset = 0; + let mut extra = Vec::new(); + loop { + let batch = graph.list_pages(true, 500, offset)?; + if batch.is_empty() { + break; + } + offset += batch.len() as u32; + extra.extend( + batch + .into_iter() + .filter(|p| !wanted.contains(&synapse_core::title_key(&p.title))), + ); + } + for page in extra { + if clear_or_delete(graph, &page)? { + report.removed += 1; + } + } + Ok(()) + })?; Ok(report) } } diff --git a/crates/synapse-history/tests/history.rs b/crates/synapse-history/tests/history.rs index 54e66f7..e6cf2c2 100644 --- a/crates/synapse-history/tests/history.rs +++ b/crates/synapse-history/tests/history.rs @@ -297,3 +297,47 @@ fn journals_and_assets() { assert!(files.contains(&asset.hash) && files.contains("image/png")); let _ = NewPage::default(); } + +fn dump(g: &Graph) -> Vec<(String, Vec)> { + let mut out = Vec::new(); + for p in g.list_pages(true, 1000, 0).unwrap() { + let blocks = g + .page_tree(p.id) + .unwrap() + .into_iter() + .map(|(d, b)| format!("{d}:{}:{}", b.id, b.content)) + .collect(); + out.push((p.title, blocks)); + } + out.sort(); + out +} + +#[test] +fn failed_restore_leaves_graph_unchanged() { + let (_d, g, mut h) = setup(); + let a = add(&g, "Doc", &["one", "two", "three"]); + add(&g, "Gone", &["bye", "bye2"]); + let s1 = h.snapshot(&g, T0).unwrap().unwrap(); + at(&g, T0 + 1000); + let b = g.page_tree(a.id).unwrap()[1].1.id; + g.update_block(b, "edited").unwrap(); + g.delete_page(g.page_by_title("Gone").unwrap().unwrap().id) + .unwrap(); + add(&g, "Fresh", &["new"]); + h.snapshot(&g, T0 + 2000).unwrap(); + let before = dump(&g); + let seq = g.last_seq().unwrap(); + + for n in [0, 1, 3] { + h.inject_restore_fault(Some(n)); + assert!(h.restore_graph(&g, &s1.id, T0 + 3000).is_err()); + assert_eq!(dump(&g), before, "graph restore, fault after {n}"); + assert_eq!(g.last_seq().unwrap(), seq, "no ops leaked"); + assert!(h.restore_page(&g, "Doc", &s1.id, T0 + 3000).is_err() || n == 3); + assert_eq!(dump(&g), before, "page restore, fault after {n}"); + } + h.inject_restore_fault(None); + h.restore_graph(&g, &s1.id, T0 + 4000).unwrap(); + assert!(g.page_by_title("Gone").unwrap().is_some()); +}