Merge branch 'refs/heads/claude/history-785c80' into feat/integration

This commit is contained in:
dasemu committed 2026-10-21 14:43:53 +02:00
commit a85316d470
3 files changed
+145 -51

No files matched your search

+8
View File
@@ -79,6 +79,7 @@ pub struct History {
opts: HistoryOptions, opts: HistoryOptions,
/// `(last seen graph seq, time we saw it change)` for idle detection. /// `(last seen graph seq, time we saw it change)` for idle detection.
observed: Option<(i64, i64)>, observed: Option<(i64, i64)>,
pub(crate) fault: std::cell::Cell<Option<usize>>,
} }
impl History { impl History {
@@ -95,9 +96,16 @@ impl History {
dir, dir,
opts, opts,
observed: None, 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<usize>) {
self.fault.set(n);
}
pub fn dir(&self) -> &Path { pub fn dir(&self) -> &Path {
&self.dir &self.dir
} }
+93 -51
View File
@@ -5,6 +5,7 @@ use crate::Result;
use crate::export; use crate::export;
use crate::history::{History, SnapshotInfo}; use crate::history::{History, SnapshotInfo};
use crate::parse::{ParsedPage, parse_page}; use crate::parse::{ParsedPage, parse_page};
use std::cell::Cell;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use synapse_core::position::between; use synapse_core::position::between;
use synapse_core::{Block, BlockId, Graph, NewPage, Page, new_id}; use synapse_core::{Block, BlockId, Graph, NewPage, Page, new_id};
@@ -19,6 +20,36 @@ pub struct RestoreReport {
pub safety_snapshot: Option<SnapshotInfo>, pub safety_snapshot: Option<SnapshotInfo>,
} }
/// Test hook: fail after this many block writes/deletes.
type Fault<'a> = &'a Cell<Option<usize>>;
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<T>(graph: &Graph, f: impl FnOnce() -> Result<T>) -> Result<T> {
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 { struct Plan {
blocks: Vec<Block>, blocks: Vec<Block>,
delete: Vec<BlockId>, delete: Vec<BlockId>,
@@ -130,8 +161,9 @@ fn same(a: &Block, b: &Block) -> bool {
&& a.collapsed == b.collapsed && 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 { for id in &plan.delete {
tick(fault)?;
// Deleting a parent already removed its subtree. // Deleting a parent already removed its subtree.
if graph.get_block(*id)?.is_some() { if graph.get_block(*id)?.is_some() {
graph.delete_block(*id)?; graph.delete_block(*id)?;
@@ -141,12 +173,13 @@ fn apply_deletes(graph: &Graph, plan: &Plan) -> Result<()> {
} }
/// Writes changed blocks; returns whether anything was written. /// Writes changed blocks; returns whether anything was written.
fn apply_puts(graph: &Graph, plan: &Plan) -> Result<bool> { fn apply_puts(graph: &Graph, plan: &Plan, fault: Fault) -> Result<bool> {
let mut wrote = false; let mut wrote = false;
for b in &plan.blocks { for b in &plan.blocks {
if graph.get_block(b.id)?.is_some_and(|cur| same(&cur, b)) { if graph.get_block(b.id)?.is_some_and(|cur| same(&cur, b)) {
continue; continue;
} }
tick(fault)?;
graph.put_block(b)?; graph.put_block(b)?;
wrote = true; wrote = true;
} }
@@ -189,22 +222,26 @@ impl History {
safety_snapshot: safety, safety_snapshot: safety,
..Default::default() ..Default::default()
}; };
match text { let fault = &self.fault;
Some(text) => { atomic(graph, || {
let p = plan(graph, title, &parse_page(&text), false)?; match text {
apply_deletes(graph, &p)?; Some(text) => {
apply_puts(graph, &p)?; let p = plan(graph, title, &parse_page(&text), false)?;
report.restored = 1; apply_deletes(graph, &p, fault)?;
} apply_puts(graph, &p, fault)?;
None => { report.restored = 1;
let page = graph }
.page_by_title(title)? None => {
.ok_or_else(|| Self::not_found(title))?; let page = graph
if clear_or_delete(graph, &page)? { .page_by_title(title)?
report.removed = 1; .ok_or_else(|| Self::not_found(title))?;
if clear_or_delete(graph, &page)? {
report.removed = 1;
}
} }
} }
} Ok(())
})?;
Ok(report) Ok(report)
} }
@@ -221,44 +258,49 @@ impl History {
safety_snapshot: safety, safety_snapshot: safety,
..Default::default() ..Default::default()
}; };
let mut plans = Vec::new(); let fault = &self.fault;
let mut wanted: HashSet<String> = HashSet::new(); let this = &*self;
for (path, oid) in &files { atomic(graph, || {
let Some(title) = export::title_from_path(path) else { let mut plans = Vec::new();
continue; let mut wanted: HashSet<String> = HashSet::new();
}; for (path, oid) in &files {
wanted.insert(synapse_core::title_key(&title)); let Some(title) = export::title_from_path(path) else {
let text = self.read_blob(*oid)?; continue;
plans.push(plan(graph, &title, &parse_page(&text), true)?); };
} wanted.insert(synapse_core::title_key(&title));
// Delete first so blocks moved between pages can be re-created where they belong. let text = this.read_blob(*oid)?;
for p in &plans { plans.push(plan(graph, &title, &parse_page(&text), true)?);
apply_deletes(graph, p)?;
}
for p in &plans {
if apply_puts(graph, p)? {
report.restored += 1;
} }
} // Delete first so blocks moved between pages can be re-created where they belong.
let mut offset = 0; for p in &plans {
let mut extra = Vec::new(); apply_deletes(graph, p, fault)?;
loop {
let batch = graph.list_pages(true, 500, offset)?;
if batch.is_empty() {
break;
} }
offset += batch.len() as u32; for p in &plans {
extra.extend( if apply_puts(graph, p, fault)? {
batch report.restored += 1;
.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;
} }
} 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) Ok(report)
} }
} }
+44
View File
@@ -297,3 +297,47 @@ fn journals_and_assets() {
assert!(files.contains(&asset.hash) && files.contains("image/png")); assert!(files.contains(&asset.hash) && files.contains("image/png"));
let _ = NewPage::default(); let _ = NewPage::default();
} }
fn dump(g: &Graph) -> Vec<(String, Vec<String>)> {
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());
}