//! In-place `.affine` / `.db` SQLite workspace loader with lazy per-document //! CRDT hydration and zero writeback on read-only inspection. use std::{ collections::BTreeMap, path::{Path, PathBuf}, sync::{ Arc, OnceLock, atomic::{AtomicU64, Ordering}, mpsc, }, }; use affine_client::{LinkGraph, WeightedSearchEngine}; use affine_store::{ sqlite::SqliteDocStorage, workspace_db::{WorkspaceDb, WorkspaceDbTableName}, }; use anyhow::{Context as _, Result}; use blocksuite_playground_doc::try_random_client_id; use crate::doc_store::{ DesktopCollection, DesktopDocStore, DesktopWorkspace, LoadedWorkspace, WorkspaceKind, load_workspace, }; type WorkspaceOpenPayload = (String, Vec, Vec<(WorkspaceDbTableName, Vec)>, usize); enum SqliteWorkerReq { OpenWorkspace { path: PathBuf, reply: mpsc::Sender>, }, LoadDoc { path: PathBuf, doc_id: String, opens: Arc, reply: mpsc::Sender>>>, }, /// The last handle of a backing went away: close its read connection. Release { opens: Arc }, } async fn read_workspace_snapshot(storage: &SqliteDocStorage) -> Result { let tables_ok = storage.validate_required_tables().await?; anyhow::ensure!( tables_ok, "SQLite workspace is missing required AFFiNE tables" ); let space_id = storage .get_space_id() .await .context("failed to read SQLite workspace space_id")? .filter(|s| !s.trim().is_empty()) .ok_or_else(|| anyhow::anyhow!("SQLite workspace has no stored space_id"))?; let blobs = storage .list_blobs() .await .context("failed to list SQLite blobs")?; let root_bytes = storage .get_doc_readonly(&space_id) .await .with_context(|| format!("failed to read SQLite workspace root `{space_id}`"))? .map(|rec| rec.bin) .filter(|b| !b.is_empty()) .ok_or_else(|| anyhow::anyhow!("SQLite workspace root document `{space_id}` is missing"))?; let mut db_tables: Vec<(WorkspaceDbTableName, Vec)> = Vec::new(); for table in [ WorkspaceDbTableName::Folders, WorkspaceDbTableName::DocProperties, WorkspaceDbTableName::DocCustomPropertyInfo, ] { let doc_id = table.local_doc_id(); if let Some(rec) = storage .get_doc_readonly(&doc_id) .await .with_context(|| format!("failed to read SQLite workspace table `{doc_id}`"))? && !rec.bin.is_empty() { db_tables.push((table, rec.bin)); } } Ok((space_id, root_bytes, db_tables, blobs.len())) } fn is_readonly_shm_error(err: &anyhow::Error) -> bool { let msg = format!("{err:#}").to_ascii_lowercase(); msg.contains("readonly database") || msg.contains("unable to open database") } /// Identity of an on-disk SQLite file. A replaced or rewritten file gets a new identity. #[derive(Clone, Debug, PartialEq, Eq)] struct FileIdentity { len: u64, modified: Option, #[cfg(unix)] inode: (u64, u64), } impl FileIdentity { fn of(path: &Path) -> Result { let meta = std::fs::metadata(path) .with_context(|| format!("reading SQLite file metadata `{}`", path.display()))?; Ok(Self { len: meta.len(), modified: meta.modified().ok(), #[cfg(unix)] inode: { use std::os::unix::fs::MetadataExt as _; (meta.dev(), meta.ino()) }, }) } } /// Read-only connection pool of the current backing, kept by the worker between requests. /// /// No read transaction outlives a request, so a reused connection still observes new WAL /// commits of a live writer. struct ReadConnection { opens: Arc, path: PathBuf, identity: FileIdentity, storage: SqliteDocStorage, immutable: bool, } impl ReadConnection { /// `true` while the connection still reads the file at `path` with `identity`. fn serves(&self, path: &Path, identity: &FileIdentity) -> bool { self.path == path && &self.identity == identity && !(self.immutable && has_sidecar(path)) } } /// `true` when a `-wal` or `-shm` sidecar exists, which marks a database with a live writer. fn has_sidecar(path: &Path) -> bool { ["-wal", "-shm"].iter().any(|suffix| { let mut sidecar = path.as_os_str().to_owned(); sidecar.push(suffix); Path::new(&sidecar).exists() }) } async fn close_connection(cached: &mut Option) { if let Some(conn) = cached.take() { conn.storage.close().await; } } async fn read_doc(storage: &SqliteDocStorage, doc_id: &str) -> Result>> { storage .get_doc_readonly(doc_id) .await .map(|r| r.map(|rec| rec.bin)) .map_err(anyhow::Error::from) } /// Read one document through the cached read connection of `path`, opening it first when the /// cache holds another file or a stale identity of this one. async fn load_doc( cached: &mut Option, path: &Path, doc_id: &str, opens: &Arc, ) -> Result>> { let canonical = std::fs::canonicalize(path) .with_context(|| format!("canonicalizing SQLite path `{}`", path.display()))?; let identity = FileIdentity::of(&canonical)?; if cached .as_ref() .is_some_and(|c| !Arc::ptr_eq(&c.opens, opens) || !c.serves(&canonical, &identity)) { close_connection(cached).await; } let path_str = canonical.to_string_lossy().into_owned(); let conn = cached.get_or_insert_with(|| { opens.fetch_add(1, Ordering::Relaxed); ReadConnection { opens: opens.clone(), path: canonical.clone(), identity: identity.clone(), storage: SqliteDocStorage::open_read_only(path_str.clone()), immutable: false, } }); match read_doc(&conn.storage, doc_id).await { Ok(bytes) => Ok(bytes), Err(err) if !conn.immutable && is_readonly_shm_error(&err) => { close_connection(cached).await; let storage = SqliteDocStorage::open_backup_immutable(path_str)?; opens.fetch_add(1, Ordering::Relaxed); let conn = cached.insert(ReadConnection { opens: opens.clone(), path: canonical, identity, storage, immutable: true, }); let res = read_doc(&conn.storage, doc_id).await; if res.is_err() { close_connection(cached).await; } res } Err(err) => { close_connection(cached).await; Err(err) } } } static SQLITE_WORKER: OnceLock, String>> = OnceLock::new(); /// Dedicated single-thread background Tokio worker for read-only SQLite access. /// /// Opens workspaces through the single authoritative [`SqliteDocStorage::open_read_only`] /// entry point. Document reads reuse one read-only connection of the current backing and /// reopen it when the backing changes, the file is replaced, or its last handle is released. /// When the parent directory itself is read-only and no `-wal`/`-shm` sidecar exists, falls /// back to [`SqliteDocStorage::open_backup_immutable`] and leaves it as soon as a sidecar appears. fn sqlite_worker() -> Result<&'static mpsc::Sender> { SQLITE_WORKER .get_or_init(|| { let (tx, rx) = mpsc::channel::(); std::thread::Builder::new() .name("affine-desktop-sqlite-ro".into()) .spawn(move || { let Ok(rt) = tokio::runtime::Builder::new_current_thread() .enable_all() .build() else { return; }; let mut cached: Option = None; while let Ok(req) = rx.recv() { match req { SqliteWorkerReq::OpenWorkspace { path, reply } => { let _ = reply.send(rt.block_on(open_workspace(&path))); } SqliteWorkerReq::LoadDoc { path, doc_id, opens, reply, } => { let res = rt.block_on(load_doc(&mut cached, &path, &doc_id, &opens)); let _ = reply.send(res); } SqliteWorkerReq::Release { opens } => { if cached .as_ref() .is_some_and(|c| Arc::ptr_eq(&c.opens, &opens)) { rt.block_on(close_connection(&mut cached)); } } } } }) .map(|_| tx) .map_err(|e| format!("failed to spawn affine-desktop-sqlite-ro worker thread: {e}")) }) .as_ref() .map_err(|e| anyhow::anyhow!("{e}")) } async fn open_workspace(path: &Path) -> Result { let canonical_path = std::fs::canonicalize(path) .with_context(|| format!("canonicalizing SQLite path `{}`", path.display()))?; let path_str = canonical_path.to_string_lossy().into_owned(); let storage = SqliteDocStorage::open_read_only(path_str.clone()); let snapshot_res = read_workspace_snapshot(&storage).await; storage.close().await; match snapshot_res { Ok(ok) => Ok(ok), Err(err) if is_readonly_shm_error(&err) => { let immutable = SqliteDocStorage::open_backup_immutable(path_str).map_err(anyhow::Error::from)?; let fallback = read_workspace_snapshot(&immutable).await; immutable.close().await; fallback } Err(err) => Err(err), } } /// Releases the worker read connection of a backing once its last handle is dropped. #[derive(Debug)] struct BackingLease { opens: Arc, } impl Drop for BackingLease { fn drop(&mut self) { if let Some(Ok(tx)) = SQLITE_WORKER.get() { let _ = tx.send(SqliteWorkerReq::Release { opens: self.opens.clone(), }); } } } /// Backing handle for on-demand lazy CRDT hydration from an on-disk SQLite workspace file. #[derive(Clone, Debug)] pub struct SqliteLazyBacking { pub path: PathBuf, pub space_id: String, pub blob_count: usize, lease: Arc, } impl SqliteLazyBacking { pub fn new(path: impl Into, space_id: impl Into, blob_count: usize) -> Self { Self { lease: Arc::new(BackingLease { opens: Arc::default(), }), path: path.into(), space_id: space_id.into(), blob_count, } } /// Number of read connections the worker opened for this backing. pub fn read_connection_opens(&self) -> u64 { self.lease.opens.load(Ordering::Relaxed) } /// Read and merge one document's `snapshots` + `updates` from SQLite without writing back. pub fn load_doc_update(&self, doc_id: &str) -> Result>> { let (reply_tx, reply_rx) = mpsc::channel(); sqlite_worker()? .send(SqliteWorkerReq::LoadDoc { path: self.path.clone(), doc_id: doc_id.to_string(), opens: Arc::clone(&self.lease.opens), reply: reply_tx, }) .map_err(|_| anyhow::anyhow!("sqlite read-only worker channel closed"))?; reply_rx .recv() .context("receiving sqlite doc hydration reply")? } } /// Summary metrics produced when opening a real SQLite workspace (strictly privacy-safe counts). #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct SqliteLoadStats { pub total_docs: usize, pub visible_docs: usize, pub trashed_docs: usize, pub journal_docs: usize, pub favorite_docs: usize, pub folder_rows: usize, pub blob_count: usize, pub pending_writebacks: usize, } /// Open an existing 5-step-migrated `.affine` / `.db` SQLite workspace in place /// with zero CRDT writeback and lazy per-document hydration. pub fn open_sqlite_workspace(path: impl AsRef) -> Result<(DesktopDocStore, SqliteLoadStats)> { let path = std::fs::canonicalize(path.as_ref()).with_context(|| { format!( "canonicalizing SQLite workspace path `{}`", path.as_ref().display() ) })?; let (reply_tx, reply_rx) = mpsc::channel(); sqlite_worker()? .send(SqliteWorkerReq::OpenWorkspace { path: path.clone(), reply: reply_tx, }) .map_err(|_| anyhow::anyhow!("sqlite read-only worker channel closed"))?; let (space_id, root_bytes, db_tables, blob_count) = reply_rx .recv() .context("receiving sqlite workspace open reply")??; let client_id = try_random_client_id().context("failed to generate CSPRNG client_id for SQLite open")?; let mut db = if !root_bytes.is_empty() { WorkspaceDb::from_root_update_v1( space_id.clone(), "local-user", client_id, &root_bytes, &[], ) .with_context(|| { format!("failed to decode SQLite snapshots/updates for workspace root `{space_id}`") })? } else { WorkspaceDb::new(space_id.clone(), "local-user", client_id) }; for (table, bytes) in &db_tables { db.load_db_table(*table, bytes).with_context(|| { format!( "failed to decode SQLite workspace table `{}`", table.local_doc_id() ) })?; } let pending_writebacks = db.pending_updates().len(); let LoadedWorkspace { directory, docs, folder_rows, } = load_workspace(db, client_id)?; let mut store = DesktopDocStore { workspaces: vec![DesktopWorkspace { id: space_id.clone(), name: "Local SQLite Workspace".to_string(), kind: WorkspaceKind::Local, synced: true, }], active_workspace_idx: 0, default_full_width: false, directory, docs, folder_rows, folder_cache: Default::default(), collections: vec![DesktopCollection { id: "col-edgeless".into(), name: "Whiteboards".into(), rules: vec![affine_client::domain::CollectionRule::ModeIs( "edgeless".into(), )], }], tag_colors: BTreeMap::new(), link_graph: LinkGraph::default(), search_engine: WeightedSearchEngine::default(), next_seq: 1000, env_rev: 1, workspace_buckets: BTreeMap::new(), derived: crate::doc_store::DerivedCache::default(), writer: None, sqlite_backing: Some(SqliteLazyBacking::new(path, space_id, blob_count)), }; store.reindex_all(); let stats = SqliteLoadStats { total_docs: store.docs.len(), visible_docs: store.visible_docs().len(), trashed_docs: store.trashed_docs().len(), journal_docs: store.journal_docs().len(), favorite_docs: store.favorite_docs().len(), folder_rows: store.folder_rows.len(), blob_count, pending_writebacks, }; Ok((store, stats)) } #[cfg(test)] mod tests { use affine_store::{ directory::DocMode, workspace_db::{DocPropertiesRow, FolderRow, PageIdSource}, }; use blocksuite_playground_doc::{ random_client_id, read::BlockContent, schema::{BlockSpec, ParagraphType}, session::PageDocSession, }; use super::*; fn sha256_file(path: &Path) -> Option { let bytes = std::fs::read(path).ok()?; Some( crate::draft_store::ContentHash::of_bytes(&bytes) .as_str() .to_string(), ) } #[test] fn reopen_observes_external_wal_writes_with_zero_loader_writeback() { let temp_dir = std::env::temp_dir().join("affine-desktop-sqlite-wal-reopen-test"); let _ = std::fs::remove_dir_all(&temp_dir); std::fs::create_dir_all(&temp_dir).unwrap(); let db_path = temp_dir.join("live-wal.affine"); let db_str = db_path.to_string_lossy().into_owned(); let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap(); // 1. Seed initial workspace with doc-1, checkpoint, and close so no -wal remains. let mut ws_db = WorkspaceDb::new("ws-wal-test", "local-user", random_client_id()); ws_db.initialize_meta().unwrap(); ws_db .create_page( PageIdSource::Explicit("doc-1"), "Initial Doc", 1_764_360_000, ) .unwrap(); let mut doc1 = PageDocSession::new("doc-1", random_client_id()).unwrap(); doc1.add_block( "root-1", BlockSpec::Page { title: "Initial Doc".into(), }, None, None, 1, ) .unwrap(); doc1.add_block( "n1", BlockSpec::Note { xywh: None }, Some("root-1"), None, 2, ) .unwrap(); doc1.add_block( "p1", BlockSpec::Paragraph { paragraph_type: ParagraphType::Text, text: "v1".into(), }, Some("n1"), None, 3, ) .unwrap(); rt.block_on(async { let writer = SqliteDocStorage::new(db_str.clone()); writer.connect().await.unwrap(); writer.set_space_id("ws-wal-test").await.unwrap(); writer .push_update( "ws-wal-test", ws_db.root().encode_update_v1().unwrap(), 1_764_360_000, ) .await .unwrap(); writer .push_update("doc-1", doc1.encode_update_v1().unwrap(), 1_764_360_001) .await .unwrap(); writer.checkpoint().await.unwrap(); writer.close().await; }); // 2. First desktop read-only open (before external WAL write). let (store1, stats1) = open_sqlite_workspace(&db_path).unwrap(); assert_eq!(stats1.pending_writebacks, 0); assert!(store1.get_doc("doc-1").is_some()); assert!(store1.get_doc("doc-2").is_none()); assert_readonly_editor_and_header(store1); // 3. External writer opens the same file in WAL mode and writes doc-2 WITHOUT checkpointing. ws_db .create_page( PageIdSource::Explicit("doc-2"), "WAL Fresh Doc", 1_764_360_500, ) .unwrap(); let mut doc2 = PageDocSession::new("doc-2", random_client_id()).unwrap(); doc2.add_block( "root-2", BlockSpec::Page { title: "WAL Fresh Doc".into(), }, None, None, 4, ) .unwrap(); doc2.add_block( "n2", BlockSpec::Note { xywh: None }, Some("root-2"), None, 5, ) .unwrap(); doc2.add_block( "p2", BlockSpec::Paragraph { paragraph_type: ParagraphType::Text, text: "written-in-wal".into(), }, Some("n2"), None, 6, ) .unwrap(); let ext_writer = rt.block_on(async { let writer = SqliteDocStorage::new(db_str.clone()); writer .push_update( "ws-wal-test", ws_db.root().encode_update_v1().unwrap(), 1_764_360_500, ) .await .unwrap(); writer .push_update("doc-2", doc2.encode_update_v1().unwrap(), 1_764_360_501) .await .unwrap(); writer }); let wal_path = PathBuf::from(format!("{db_str}-wal")); let db_hash_before = sha256_file(&db_path); let wal_hash_before = sha256_file(&wal_path); // 4. Desktop re-opens the same path — must see doc-2 from live WAL with 0 writeback. let (mut store2, stats2) = open_sqlite_workspace(&db_path).unwrap(); assert_eq!(stats2.pending_writebacks, 0); assert!( store2.get_doc("doc-2").is_some(), "reopen must observe doc-2 written into live WAL" ); assert!(store2.ensure_doc_hydrated("doc-2").unwrap()); let snap2 = &store2.get_doc("doc-2").unwrap().snapshot; let p2_text = match &snap2.block("p2").unwrap().content { BlockContent::Paragraph { text, .. } => text.plain.as_str(), other => panic!("expected paragraph, got {other:?}"), }; assert_eq!(p2_text, "written-in-wal"); assert_eq!( sha256_file(&db_path), db_hash_before, "read-only desktop loader must not mutate main .affine file" ); assert_eq!( sha256_file(&wal_path), wal_hash_before, "read-only desktop loader must not mutate -wal file" ); rt.block_on(async { ext_writer.close().await; }); let _ = std::fs::remove_dir_all(&temp_dir); } fn assert_readonly_editor_and_header(store: DesktopDocStore) { use ui_tokens::ThemeMode; let state = crate::DesktopAppState::from_doc_store_in_memory(store, ThemeMode::Light, "2026-12-02"); let (platform, app, handle, window) = crate::editor_host::tests::open_test_shell(state, 1280, 800); window.request_frame(); platform.run_until_parked(); app.update(|app| { handle .update(app, |shell, _, cx| { assert!(shell.state.store.is_readonly_sqlite()); let pane = shell.state.split.active(); let editor = shell.editor_host().pane_entity(pane.id).unwrap(); assert!(editor.read(cx).page_readonly()); assert!(editor.read(cx).edgeless_readonly()); }) .unwrap(); }); let click = |id: &str| { let at = app.update(|app| { handle .update(app, |_, window, _| { let bounds = window.frame_snapshot().elements[id].bounds; ui::point( ui::px(bounds.x + bounds.width / 2.0), ui::px(bounds.y + bounds.height / 2.0), ) }) .unwrap() }); window.simulate_click(at); window.request_frame(); platform.run_until_parked(); }; click("desktop.topbar.more"); app.update(|app| { handle .update(app, |_, window, _| { for id in ["rename", "switch_mode", "duplicate", "trash", "favorite"] { let row = &window.frame_snapshot().elements[&format!("desktop.header.menu.{id}")]; assert!(!row.interactive, "{id}"); } }) .unwrap(); }); click("desktop.header.menu.doc_info"); app.update(|app| { handle .update(app, |shell, window, _| { let doc = shell .state .split .active() .active_route() .doc_id() .unwrap() .to_owned(); let frame = window.frame_snapshot(); for width in ["standard", "full"] { assert!( !frame.elements[&format!("desktop.header.info.page_width.{width}")] .interactive ); } assert!( !shell .state .store .set_doc_page_width(&doc, crate::doc_store::PageWidth::Full) ); assert!( !shell .state .store .set_doc_default_mode(&doc, DocMode::Edgeless) ); }) .unwrap(); }); } #[cfg(unix)] #[test] fn readonly_dir_rejects_non_empty_wal_without_shm_and_allows_clean_immutable_read() { use std::os::unix::fs::PermissionsExt as _; let temp_dir = std::env::temp_dir().join("affine-desktop-sqlite-ro-wal-test"); if temp_dir.exists() { let _ = std::fs::set_permissions(&temp_dir, std::fs::Permissions::from_mode(0o755)); for sub in ["ro-with-wal", "ro-clean"] { let p = temp_dir.join(sub); if p.exists() { let _ = std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)); } } let _ = std::fs::remove_dir_all(&temp_dir); } std::fs::create_dir_all(&temp_dir).unwrap(); let src_db = temp_dir.join("src.affine"); let src_str = src_db.to_string_lossy().into_owned(); let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap(); // 1. Create checkpointed base DB containing doc-1. let mut ws_db = WorkspaceDb::new("ws-ro-wal", "local-user", random_client_id()); ws_db.initialize_meta().unwrap(); ws_db .create_page(PageIdSource::Explicit("doc-1"), "Base Doc", 1_764_361_000) .unwrap(); let mut doc1 = PageDocSession::new("doc-1", random_client_id()).unwrap(); doc1.add_block( "root-1", BlockSpec::Page { title: "Base Doc".into(), }, None, None, 1, ) .unwrap(); rt.block_on(async { let writer = SqliteDocStorage::new(src_str.clone()); writer.connect().await.unwrap(); writer.set_space_id("ws-ro-wal").await.unwrap(); writer .push_update( "ws-ro-wal", ws_db.root().encode_update_v1().unwrap(), 1_764_361_000, ) .await .unwrap(); writer .push_update("doc-1", doc1.encode_update_v1().unwrap(), 1_764_361_001) .await .unwrap(); writer.checkpoint().await.unwrap(); writer.close().await; }); // 2. Copy clean checkpointed DB (no -wal) into a read-only directory (0o555) // and point a symlink from a writable directory to it. let ro_clean_dir = temp_dir.join("ro-clean"); std::fs::create_dir_all(&ro_clean_dir).unwrap(); let ro_clean_db = ro_clean_dir.join("clean.affine"); std::fs::copy(&src_db, &ro_clean_db).unwrap(); let ro_clean_symlink = temp_dir.join("shortcut-clean.affine"); std::os::unix::fs::symlink(&ro_clean_db, &ro_clean_symlink).unwrap(); std::fs::set_permissions(&ro_clean_dir, std::fs::Permissions::from_mode(0o555)).unwrap(); for target in [&ro_clean_db, &ro_clean_symlink] { let (clean_store, clean_stats) = open_sqlite_workspace(target).unwrap(); assert_eq!(clean_stats.pending_writebacks, 0); assert!( clean_store.get_doc("doc-1").is_some(), "read-only dir with no -wal must safely open via immutable=1 fallback ({})", target.display() ); } // 3. Write doc-2 into live WAL without checkpointing, verify writable-dir symlink sees // both doc-1 and doc-2, then copy DB + non-empty -wal (without -shm) into a read-only // directory (0o555) and verify both direct path and symlink return Err. ws_db .create_page( PageIdSource::Explicit("doc-2"), "Uncheckpointed WAL Doc", 1_764_361_500, ) .unwrap(); let mut doc2 = PageDocSession::new("doc-2", random_client_id()).unwrap(); doc2.add_block( "root-2", BlockSpec::Page { title: "Uncheckpointed WAL Doc".into(), }, None, None, 2, ) .unwrap(); let live_writer = rt.block_on(async { let writer = SqliteDocStorage::new(src_str.clone()); writer .push_update( "ws-ro-wal", ws_db.root().encode_update_v1().unwrap(), 1_764_361_500, ) .await .unwrap(); writer .push_update("doc-2", doc2.encode_update_v1().unwrap(), 1_764_361_501) .await .unwrap(); writer }); let rw_symlink = temp_dir.join("shortcut-rw-wal.affine"); std::os::unix::fs::symlink(&src_db, &rw_symlink).unwrap(); let (mut rw_sym_store, rw_sym_stats) = open_sqlite_workspace(&rw_symlink).unwrap(); assert_eq!(rw_sym_stats.pending_writebacks, 0); assert!(rw_sym_store.get_doc("doc-1").is_some()); assert!( rw_sym_store.get_doc("doc-2").is_some(), "writable-dir symlink must read doc-2 from target's live WAL" ); assert!(rw_sym_store.ensure_doc_hydrated("doc-2").unwrap()); let ro_wal_dir = temp_dir.join("ro-with-wal"); std::fs::create_dir_all(&ro_wal_dir).unwrap(); let ro_wal_db = ro_wal_dir.join("with-wal.affine"); let ro_wal_sidecar = ro_wal_dir.join("with-wal.affine-wal"); std::fs::copy(&src_db, &ro_wal_db).unwrap(); std::fs::copy(format!("{src_str}-wal"), &ro_wal_sidecar).unwrap(); assert!( std::fs::metadata(&ro_wal_sidecar).unwrap().len() > 0, "copied WAL sidecar must be non-empty" ); let ro_wal_symlink = temp_dir.join("shortcut-ro-wal.affine"); std::os::unix::fs::symlink(&ro_wal_db, &ro_wal_symlink).unwrap(); std::fs::set_permissions(&ro_wal_dir, std::fs::Permissions::from_mode(0o555)).unwrap(); for target in [&ro_wal_db, &ro_wal_symlink] { let res = open_sqlite_workspace(target); assert!( res.is_err(), "read-only dir with non-empty -wal and no -shm must return Err instead of silently dropping doc-2 via immutable=1 ({})", target.display() ); } let _ = std::fs::set_permissions(&ro_clean_dir, std::fs::Permissions::from_mode(0o755)); let _ = std::fs::set_permissions(&ro_wal_dir, std::fs::Permissions::from_mode(0o755)); rt.block_on(async { live_writer.close().await; }); let _ = std::fs::remove_dir_all(&temp_dir); } #[test] fn open_sqlite_reads_db_prefixed_folders_and_doc_properties() { let temp_dir = std::env::temp_dir().join("affine-desktop-sqlite-db-tables-test"); let _ = std::fs::remove_dir_all(&temp_dir); std::fs::create_dir_all(&temp_dir).unwrap(); let db_path = temp_dir.join("db-tables.affine"); let db_str = db_path.to_string_lossy().into_owned(); let mut ws_db = WorkspaceDb::new("ws-db-tables", "local-user", random_client_id()); ws_db.initialize_meta().unwrap(); ws_db .create_page( PageIdSource::Explicit("doc-edgeless-journal"), "Daily Board", 1_764_362_000, ) .unwrap(); ws_db .upsert_db_row( WorkspaceDbTableName::Folders, &FolderRow { id: "folder-1".into(), parent_id: None, data: "Synthetic Folder".into(), folder_type: "folder".into(), index: "a0".into(), }, ) .unwrap(); ws_db .upsert_db_row( WorkspaceDbTableName::DocProperties, &DocPropertiesRow { id: "doc-edgeless-journal".into(), primary_mode: Some("edgeless".into()), edgeless_color_theme: None, journal: Some("2026-11-28".into()), page_width: Some("fullWidth".into()), is_template: None, integration_type: None, created_by: None, updated_by: None, custom_fields: BTreeMap::new(), }, ) .unwrap(); let pending = ws_db.drain_pending_updates(); assert!( pending .iter() .any(|u| u.doc_id == WorkspaceDbTableName::Folders.local_doc_id()), "Folders table update must be stored under db$folders" ); assert!( pending .iter() .any(|u| u.doc_id == WorkspaceDbTableName::DocProperties.local_doc_id()), "DocProperties table update must be stored under db$docProperties" ); let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap(); rt.block_on(async { let writer = SqliteDocStorage::new(db_str.clone()); writer.connect().await.unwrap(); writer.set_space_id("ws-db-tables").await.unwrap(); for (idx, upd) in pending.into_iter().enumerate() { writer .push_update(&upd.doc_id, upd.update, 1_764_362_000 + idx as i64) .await .unwrap(); } writer.checkpoint().await.unwrap(); writer.close().await; }); let (store, stats) = open_sqlite_workspace(&db_path).unwrap(); assert_eq!(stats.pending_writebacks, 0); assert_eq!( stats.folder_rows, 1, "open_sqlite_workspace must load db$folders rows" ); assert_eq!( stats.journal_docs, 1, "open_sqlite_workspace must load journal flags from db$docProperties" ); let doc = store.get_doc("doc-edgeless-journal").unwrap(); assert_eq!(doc.meta.default_mode, DocMode::Edgeless); assert_eq!(doc.meta.page_width, Some(crate::doc_store::PageWidth::Full)); assert_eq!(doc.meta.journal_date.as_deref(), Some("2026-11-28")); let _ = std::fs::remove_dir_all(&temp_dir); } #[test] fn open_sqlite_fails_with_table_name_when_doc_properties_corrupted() { let temp_dir = std::env::temp_dir().join("affine-desktop-sqlite-corrupt-props-test"); let _ = std::fs::remove_dir_all(&temp_dir); std::fs::create_dir_all(&temp_dir).unwrap(); let db_path = temp_dir.join("corrupt-props.affine"); let db_str = db_path.to_string_lossy().into_owned(); let mut ws_db = WorkspaceDb::new("ws-corrupt-props", "local-user", random_client_id()); ws_db.initialize_meta().unwrap(); ws_db .create_page( PageIdSource::Explicit("doc-valid"), "Valid Page", 1_764_363_000, ) .unwrap(); ws_db .upsert_db_row( WorkspaceDbTableName::Folders, &FolderRow { id: "folder-valid".into(), parent_id: None, data: "Valid Folder".into(), folder_type: "folder".into(), index: "a0".into(), }, ) .unwrap(); ws_db .upsert_db_row( WorkspaceDbTableName::DocProperties, &DocPropertiesRow { id: "doc-valid".into(), primary_mode: Some("page".into()), edgeless_color_theme: None, journal: Some("2026-11-28".into()), page_width: None, is_template: None, integration_type: None, created_by: None, updated_by: None, custom_fields: BTreeMap::new(), }, ) .unwrap(); let pending = ws_db.drain_pending_updates(); let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap(); rt.block_on(async { let writer = SqliteDocStorage::new(db_str.clone()); writer.connect().await.unwrap(); writer.set_space_id("ws-corrupt-props").await.unwrap(); for (idx, upd) in pending.into_iter().enumerate() { writer .push_update(&upd.doc_id, upd.update, 1_764_363_000 + idx as i64) .await .unwrap(); } writer.checkpoint().await.unwrap(); writer.close().await; }); // Baseline valid workspace opens cleanly with 1 page, 1 folder, 1 journal. let (_, ok_stats) = open_sqlite_workspace(&db_path).unwrap(); assert_eq!(ok_stats.total_docs, 1); assert_eq!(ok_stats.folder_rows, 1); assert_eq!(ok_stats.journal_docs, 1); // Corrupt `db$docProperties` bytes; opening must return Err naming `db$docProperties` // rather than swallowing the decode failure and falling back to an empty workspace. let props_doc_id = WorkspaceDbTableName::DocProperties.local_doc_id(); rt.block_on(async { let writer = SqliteDocStorage::new(db_str.clone()); writer .push_update( &props_doc_id, vec![0xFF, 0xFF, 0x00, 0xFE, 0xCA, 0xBE], 1_764_363_999, ) .await .unwrap(); writer.checkpoint().await.unwrap(); writer.close().await; }); let err = match open_sqlite_workspace(&db_path) { Ok((_, stats)) => { panic!("corrupted db$docProperties must return Err, not Ok with stats {stats:?}") } Err(err) => err, }; let msg = format!("{err:#}"); assert!( msg.contains("db$docProperties"), "error message must identify corrupted table `db$docProperties`, got: {msg}" ); let _ = std::fs::remove_dir_all(&temp_dir); } #[test] fn open_sqlite_preserves_valid_empty_root_workspace_id_with_zero_pages() { let temp_dir = std::env::temp_dir().join("affine-desktop-sqlite-empty-root-test"); let _ = std::fs::remove_dir_all(&temp_dir); std::fs::create_dir_all(&temp_dir).unwrap(); let db_path = temp_dir.join("empty-root.affine"); let db_str = db_path.to_string_lossy().into_owned(); let mut ws_db = WorkspaceDb::new("ws-empty-root-id", "local-user", random_client_id()); ws_db.initialize_meta().unwrap(); let root_update = ws_db.root().encode_update_v1().unwrap(); let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap(); rt.block_on(async { let writer = SqliteDocStorage::new(db_str.clone()); writer.connect().await.unwrap(); writer.set_space_id("ws-empty-root-id").await.unwrap(); writer .push_update("ws-empty-root-id", root_update, 1_764_364_000) .await .unwrap(); writer.checkpoint().await.unwrap(); writer.close().await; }); let (store, stats) = open_sqlite_workspace(&db_path).unwrap(); assert_eq!( store.active_workspace().id, "ws-empty-root-id", "valid 0-page empty root must preserve its workspace id" ); assert_eq!( stats.total_docs, 0, "empty root workspace must have 0 pages" ); assert!(store.visible_docs().is_empty()); assert!( store.get_doc("ws-empty-root-id").is_none(), "workspace root doc must never leak into ordinary document list" ); assert_eq!(stats.pending_writebacks, 0); let _ = std::fs::remove_dir_all(&temp_dir); } #[test] fn open_sqlite_fails_with_doc_id_when_compacted_root_snapshot_is_truncated() { let temp_dir = std::env::temp_dir().join("affine-desktop-sqlite-trunc-root-test"); let _ = std::fs::remove_dir_all(&temp_dir); std::fs::create_dir_all(&temp_dir).unwrap(); let db_path = temp_dir.join("trunc-root.affine"); let db_str = db_path.to_string_lossy().into_owned(); let mut ws_db = WorkspaceDb::new("ws-trunc-root", "local-user", random_client_id()); ws_db.initialize_meta().unwrap(); ws_db .create_page( PageIdSource::Explicit("doc-keep"), "Surviving Page", 1_764_365_000, ) .unwrap(); let valid_root_bytes = ws_db.root().encode_update_v1().unwrap(); let mut doc_keep = PageDocSession::new("doc-keep", random_client_id()).unwrap(); doc_keep .add_block( "rk", BlockSpec::Page { title: "Surviving Page".into(), }, None, None, 1, ) .unwrap(); let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build() .unwrap(); rt.block_on(async { let writer = SqliteDocStorage::new(db_str.clone()); writer.connect().await.unwrap(); writer.set_space_id("ws-trunc-root").await.unwrap(); writer .push_update("ws-trunc-root", valid_root_bytes.clone(), 1_764_365_000) .await .unwrap(); writer .push_update( "doc-keep", doc_keep.encode_update_v1().unwrap(), 1_764_365_001, ) .await .unwrap(); // Compact `ws-trunc-root` from `updates` into `snapshots`, then truncate its snapshot. let compacted = writer.get_doc("ws-trunc-root").await.unwrap().unwrap(); let truncated = valid_root_bytes[..valid_root_bytes.len().min(3)].to_vec(); assert!( writer .set_doc_snapshot(&affine_store::sqlite::DocRecord { doc_id: "ws-trunc-root".to_string(), bin: truncated, timestamp: compacted.timestamp, }) .await .unwrap() ); writer.checkpoint().await.unwrap(); writer.close().await; }); let err = match open_sqlite_workspace(&db_path) { Ok((store, stats)) => panic!( "truncated root snapshot must return Err, not Ok (ws={}, total_docs={})", store.active_workspace().id, stats.total_docs ), Err(err) => err, }; let msg = format!("{err:#}"); assert!( msg.contains("ws-trunc-root"), "error message must name corrupted candidate doc_id `ws-trunc-root`, got: {msg}" ); assert!( msg.contains("snapshots"), "error message must name SQLite snapshots/updates source, got: {msg}" ); let _ = std::fs::remove_dir_all(&temp_dir); } }