diff --git a/packages/common/store/src/sqlite/doc.rs b/packages/common/store/src/sqlite/doc.rs index 4de1acd50b..0fd8e1922c 100644 --- a/packages/common/store/src/sqlite/doc.rs +++ b/packages/common/store/src/sqlite/doc.rs @@ -4,7 +4,10 @@ use y_octo::{ diff_update_v1, encode_state_vector_from_update_v1, merge_updates_v1, validate_update_v1, }; -use super::{DocClock, DocDiff, DocRecord, DocUpdate, SqliteDocStorage, millis_to_naive_utc}; +use super::{ + DocClock, DocDiff, DocRecord, DocUpdate, SqliteDocStorage, millis_to_naive_utc, + pushed_clock::CommittedRow, +}; use crate::error::{StoreError, StoreResult}; pub(super) fn is_empty_update(bin: &[u8]) -> bool { @@ -181,6 +184,7 @@ impl SqliteDocStorage { now_ms, ) .await + .map(|commit| commit.committed_row_count()) } /// List durable remote-delete tombstones persisted in `peer_clocks` that have not yet been @@ -236,14 +240,21 @@ impl SqliteDocStorage { let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?; let committed = Self::apply_updates_on_tx(&mut tx, &stamped, create_for_peer).await?; tx.commit().await?; - Ok(committed) + Ok(committed + .into_iter() + .flatten() + .map(|row| (row.doc_id, row.timestamp)) + .collect()) } + /// Write each `(doc_id, update, event_ms)` item as an update row. SQLite is the only clock + /// writer: a row takes `event_ms` or 1 ms after the document clock, whichever is later. + /// Returns the slot of each item, or `None` for an item of a deleted document. pub(super) async fn apply_updates_on_tx( tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, items: &[(&str, &[u8], i64)], create_for_peer: Option<&str>, - ) -> StoreResult> { + ) -> StoreResult>> { enum TxDocState { Tombstoned, Active(Option), @@ -256,7 +267,10 @@ impl SqliteDocStorage { for &(doc_id, update, item_ms) in items { let base_ts = millis_to_naive_utc(item_ms); let existing_clock = match doc_states.get(doc_id) { - Some(TxDocState::Tombstoned) => continue, + Some(TxDocState::Tombstoned) => { + committed.push(None); + continue; + } Some(TxDocState::Active(clock)) => *clock, None => { let is_tombstoned: bool = sqlx::query( @@ -270,6 +284,7 @@ impl SqliteDocStorage { .try_get(0)?; if is_tombstoned { doc_states.insert(doc_id, TxDocState::Tombstoned); + committed.push(None); continue; } let clock: Option = @@ -326,7 +341,11 @@ impl SqliteDocStorage { } doc_states.insert(doc_id, TxDocState::Active(Some(effective_ts))); - committed.push((doc_id.to_string(), effective_ts)); + committed.push(Some(CommittedRow { + doc_id: doc_id.to_string(), + prev_clock: existing_clock, + timestamp: effective_ts, + })); } Ok(committed) @@ -669,6 +688,26 @@ impl SqliteDocStorage { }) .transpose() } + + /// The IDs of `doc_ids` that have a clock row, in chunks of 500 bound parameters. + pub async fn existing_doc_ids( + &self, + doc_ids: &[String], + ) -> StoreResult> { + let mut found = std::collections::HashSet::new(); + for chunk in doc_ids.chunks(500) { + let mut qb = QueryBuilder::new("SELECT doc_id FROM clocks WHERE doc_id IN ("); + let mut separated = qb.separated(", "); + for doc_id in chunk { + separated.push_bind(doc_id); + } + qb.push(")"); + for row in qb.build().fetch_all(&self.pool).await? { + found.insert(row.try_get("doc_id")?); + } + } + Ok(found) + } } #[cfg(test)] @@ -791,6 +830,11 @@ mod tests { .unwrap(); tx.commit().await.unwrap(); + let committed: Vec<(String, NaiveDateTime)> = committed + .into_iter() + .flatten() + .map(|row| (row.doc_id, row.timestamp)) + .collect(); assert_eq!( committed, vec![ diff --git a/packages/common/store/src/sqlite/mod.rs b/packages/common/store/src/sqlite/mod.rs index 05767c0b5c..8ec12faeca 100644 --- a/packages/common/store/src/sqlite/mod.rs +++ b/packages/common/store/src/sqlite/mod.rs @@ -2,6 +2,7 @@ pub mod blob; pub mod doc; pub mod migrations; pub mod paths; +pub mod pushed_clock; pub mod session_mutations; pub mod storage; pub mod sync; @@ -16,6 +17,7 @@ pub use migrations::{FROZEN_SCHEMA_VERSION, MIGRATIONS, get_migrator}; pub use paths::{ resolve_allowlisted_workspace_paths, resolve_workspace_db_path, sanitize_peer_name, }; +pub use pushed_clock::{CheckedAdvance, CommittedRow, PeerProof, SessionCommit, UpdateStamp}; pub use storage::{SqliteDocStorage, SqliteImmediateWriteLock}; /// Convert Unix epoch milliseconds to a UTC `NaiveDateTime`. diff --git a/packages/common/store/src/sqlite/pushed_clock.rs b/packages/common/store/src/sqlite/pushed_clock.rs new file mode 100644 index 0000000000..50b61bd0e1 --- /dev/null +++ b/packages/common/store/src/sqlite/pushed_clock.rs @@ -0,0 +1,393 @@ +//! `peer_clocks.pushed_clock` advance. SQLite is the only clock writer: each update row takes +//! the event time or 1 ms after the document clock, whichever is later. A flush advances +//! `pushed_clock` inside its write transaction from row metadata alone. Content checks for gaps +//! of other writers run in a separate deferred transaction. + +use std::collections::{BTreeMap, HashSet}; + +use chrono::{DateTime, NaiveDateTime}; +use sqlx::Row; +use y_octo::{Doc, DocOptions, StateVector, encode_state_vector_from_update_v1}; + +use super::{SqliteDocStorage, doc::is_empty_update}; +use crate::error::{StoreError, StoreResult}; + +/// Event time and peer proof of one update row that a session flush writes. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct UpdateStamp { + /// Event time in Unix ms. `None` uses the flush time. + pub event_ms: Option, + /// True when the sync peer holds the row content: content that came from the peer, or a + /// local push that the peer acknowledged. + pub held_by_peer: bool, +} + +/// Clock slot of one committed update row: the document clock was `prev_clock` before the +/// write, and the row took `timestamp`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct CommittedRow { + pub doc_id: String, + pub prev_clock: Option, + pub timestamp: NaiveDateTime, +} + +/// Sync peer side of a session flush. +#[derive(Clone, Copy, Debug)] +pub struct PeerProof<'a> { + pub peer: &'a str, + /// Rows of earlier flushes that the peer now holds. + pub held_rows: &'a [CommittedRow], + /// Documents whose whole in-memory state the peer holds. + pub held_doc_ids: &'a [String], +} + +/// Result of a session flush. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct SessionCommit { + /// One entry for each input update: its committed slot, or `None` when the update is empty + /// or its document is deleted. + pub rows: Vec>, + /// `pushed_clock` after the commit for each document with a peer-held row or in + /// `PeerProof::held_doc_ids`. + pub pushed_clocks: BTreeMap>, + /// Documents of `pushed_clocks` that still have rows newer than `pushed_clock`. + pub behind_doc_ids: Vec, +} + +impl SessionCommit { + pub fn committed_row_count(&self) -> usize { + self.rows.iter().flatten().count() + } +} + +/// Outcome of a content-checked `pushed_clock` advance. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum CheckedAdvance { + Advanced(NaiveDateTime), + /// The oldest row newer than `pushed_clock` has a change outside the given state. + Unchanged, + /// Another connection wrote first. Nothing changed, so the caller tries again later. + Busy, +} + +/// The frozen schema stores a missing `pushed_clock` as integer `0`, which reads as the epoch. +fn pushed_or_none(clock: Option) -> Option { + clock.filter(|ts| *ts != DateTime::UNIX_EPOCH.naive_utc()) +} + +fn is_busy(err: &sqlx::Error) -> bool { + matches!(err, sqlx::Error::Database(db) if db + .code() + .and_then(|code| code.parse::().ok()) + .is_some_and(|code| code & 0xFF == 5)) +} + +async fn read_pushed_clock( + conn: &mut sqlx::SqliteConnection, + peer: &str, + doc_id: &str, +) -> StoreResult> { + let clock: Option = + sqlx::query("SELECT pushed_clock FROM peer_clocks WHERE peer = $1 AND doc_id = $2") + .bind(peer) + .bind(doc_id) + .fetch_optional(&mut *conn) + .await? + .map(|row| row.try_get(0)) + .transpose()?; + Ok(pushed_or_none(clock)) +} + +const UPSERT_PUSHED_CLOCK: &str = "INSERT INTO peer_clocks (peer, doc_id, pushed_clock) \ + VALUES ($1, $2, $3) ON CONFLICT(peer, doc_id) DO UPDATE SET pushed_clock = excluded.pushed_clock"; + +/// Advance `pushed_clock` of `peer` along `held` rows inside the write transaction of a flush. +/// A row moves `pushed_clock` only when it took the slot right after it, so the row is the only +/// one between the two clocks. Reads one `peer_clocks` and one `clocks` row per document and no +/// row data. +pub(super) async fn advance_on_tx( + tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, + peer: &str, + held: &[&CommittedRow], + held_doc_ids: &[String], + deleted: &HashSet<&str>, +) -> StoreResult<(BTreeMap>, Vec)> { + let mut by_doc: BTreeMap<&str, Vec<&CommittedRow>> = BTreeMap::new(); + for row in held { + by_doc.entry(row.doc_id.as_str()).or_default().push(row); + } + for doc_id in held_doc_ids { + by_doc.entry(doc_id.as_str()).or_default(); + } + let mut pushed_clocks = BTreeMap::new(); + let mut behind = Vec::new(); + for (doc_id, mut rows) in by_doc { + if deleted.contains(doc_id) { + continue; + } + rows.sort_by_key(|row| row.timestamp); + let start = read_pushed_clock(tx, peer, doc_id).await?; + let mut pushed = start; + for row in rows { + if pushed.is_some_and(|clock| row.timestamp <= clock) { + continue; + } + if pushed != row.prev_clock { + break; + } + pushed = Some(row.timestamp); + } + if let Some(clock) = pushed.filter(|_| pushed != start) { + sqlx::query(UPSERT_PUSHED_CLOCK) + .bind(peer) + .bind(doc_id) + .bind(clock) + .execute(&mut **tx) + .await?; + } + let doc_clock: Option = + sqlx::query("SELECT timestamp FROM clocks WHERE doc_id = $1") + .bind(doc_id) + .fetch_optional(&mut **tx) + .await? + .map(|row| row.try_get(0)) + .transpose()?; + if doc_clock.is_some_and(|clock| pushed.is_none_or(|p| p < clock)) { + behind.push(doc_id.to_string()); + } + pushed_clocks.insert(doc_id.to_string(), pushed); + } + Ok((pushed_clocks, behind)) +} + +/// True when `doc` already holds every struct and every deletion of `update`. +fn doc_contains_update(doc: &mut Doc, encoded: &[u8], update: &[u8]) -> bool { + let state = doc.get_state_vector(); + let structs_known = encode_state_vector_from_update_v1(update) + .and_then(StateVector::decode_v1) + .is_ok_and(|sv| sv.iter().all(|(client, clock)| state.get(client) >= *clock)); + structs_known + && doc.apply_update_from_binary_v1(update).is_ok() + && doc.encode_update_v1().is_ok_and(|after| after == encoded) +} + +/// Newest timestamp of the oldest run of rows that `state_v1` contains. Rows that share one +/// timestamp pass or fail together, because `pushed_clock` holds whole timestamps. +fn held_through( + doc_id: &str, + state_v1: &[u8], + rows: &[(NaiveDateTime, Vec)], +) -> Option { + let mut doc = DocOptions::from_identity(1, doc_id.to_string()).build(); + doc.apply_update_from_binary_v1(state_v1).ok()?; + let encoded = doc.encode_update_v1().ok()?; + let mut held = None; + let mut batch_ts = None; + for (ts, data) in rows { + if batch_ts != Some(*ts) { + held = batch_ts; + batch_ts = Some(*ts); + } + if !is_empty_update(data) && !doc_contains_update(&mut doc, &encoded, data) { + return held; + } + } + batch_ts +} + +/// Read the rows of `doc_id` newer than `pushed_clock` of `peer` and return the newest +/// timestamp up to which `state_v1` contains them. +async fn held_on_tx( + tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, + peer: &str, + doc_id: &str, + state_v1: &[u8], +) -> StoreResult> { + let pushed = read_pushed_clock(tx, peer, doc_id).await?; + let rows = sqlx::query( + "SELECT updated_at AS ts, data FROM snapshots WHERE doc_id = $1 \ + UNION ALL SELECT created_at AS ts, data FROM updates WHERE doc_id = $1", + ) + .bind(doc_id) + .fetch_all(&mut **tx) + .await?; + // Compare decoded times in Rust: SQLite orders every INTEGER before every TEXT. + let mut newer = Vec::with_capacity(rows.len()); + for row in &rows { + let ts: NaiveDateTime = row.try_get("ts")?; + if pushed.is_none_or(|clock| ts > clock) { + newer.push((ts, row.try_get::, _>("data")?)); + } + } + newer.sort_by_key(|(ts, _)| *ts); + Ok(held_through(doc_id, state_v1, &newer)) +} + +/// Write `held` as `pushed_clock` in the transaction that read the rows, and commit. +async fn write_checked_advance( + mut tx: sqlx::Transaction<'_, sqlx::Sqlite>, + peer: &str, + doc_id: &str, + held: NaiveDateTime, +) -> StoreResult { + let write = sqlx::query(UPSERT_PUSHED_CLOCK) + .bind(peer) + .bind(doc_id) + .bind(held) + .execute(&mut *tx) + .await; + match write { + Err(err) if is_busy(&err) => return Ok(CheckedAdvance::Busy), + other => { + other?; + } + } + match tx.commit().await { + Err(err) if is_busy(&err) => Ok(CheckedAdvance::Busy), + other => { + other?; + Ok(CheckedAdvance::Advanced(held)) + } + } +} + +impl SqliteDocStorage { + /// Advance `pushed_clock` of `peer` for `doc_id` over the oldest rows newer than it that + /// `state_v1` contains. One deferred transaction reads the rows and writes the clock, so the + /// write fails with `SQLITE_BUSY_SNAPSHOT` when another connection changed a row after the + /// read. The check runs without the write lock, and a conflict returns + /// [`CheckedAdvance::Busy`] with nothing written. + pub async fn advance_pushed_clock_with_state( + &self, + peer: &str, + doc_id: &str, + state_v1: &[u8], + ) -> StoreResult { + let mut tx = match self.pool.begin().await { + Err(err) if is_busy(&err) => return Ok(CheckedAdvance::Busy), + other => other?, + }; + match held_on_tx(&mut tx, peer, doc_id, state_v1).await { + Ok(Some(held)) => write_checked_advance(tx, peer, doc_id, held).await, + Ok(None) => Ok(CheckedAdvance::Unchanged), + Err(StoreError::Sqlx(err)) if is_busy(&err) => Ok(CheckedAdvance::Busy), + Err(err) => Err(err), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sqlite::{DocRecord, millis_to_naive_utc}; + + /// Returns `(held, outside)`: the peer holds `held`, and `outside` is a concurrent change of + /// another writer that the peer does not hold. + fn held_and_outside_updates() -> (Vec, Vec) { + let doc = DocOptions::from_identity(1, "doc-same-ms".into()).build(); + let mut text = doc.get_or_create_text("content").unwrap(); + text.insert(0, "held").unwrap(); + let other = DocOptions::from_identity(2, "doc-same-ms".into()).build(); + let mut other_text = other.get_or_create_text("content").unwrap(); + other_text.insert(0, "outside").unwrap(); + ( + doc.encode_update_v1().unwrap(), + other.encode_update_v1().unwrap(), + ) + } + + async fn insert_snapshot(storage: &SqliteDocStorage, data: &[u8], at: NaiveDateTime) { + sqlx::query( + "INSERT INTO snapshots (doc_id, data, created_at, updated_at) \ + VALUES ('doc-same-ms', $1, $2, $2)", + ) + .bind(data) + .bind(at) + .execute(&storage.pool) + .await + .unwrap(); + } + + #[tokio::test] + async fn checked_advance_never_passes_an_uncontained_row_of_the_same_millisecond() { + let (held, outside) = held_and_outside_updates(); + let same_ms = millis_to_naive_utc(5_000); + // Each case puts the contained row in one table and the uncontained row in the other, so + // one of the two cases reads the contained row first whatever order SQLite returns. + for (snapshot, update) in [(&held, &outside), (&outside, &held)] { + let storage = SqliteDocStorage::new(":memory:"); + storage.connect().await.unwrap(); + insert_snapshot(&storage, snapshot, same_ms).await; + sqlx::query( + "INSERT INTO updates (doc_id, data, created_at) VALUES ('doc-same-ms', $1, $2)", + ) + .bind(update.as_slice()) + .bind(same_ms) + .execute(&storage.pool) + .await + .unwrap(); + let outcome = storage + .advance_pushed_clock_with_state("server", "doc-same-ms", &held) + .await + .unwrap(); + assert_eq!(outcome, CheckedAdvance::Unchanged); + assert!( + storage + .get_peer_pushed_clock("server", "doc-same-ms") + .await + .unwrap() + .is_none() + ); + } + } + + #[tokio::test] + async fn checked_advance_reports_busy_when_another_connection_rewrites_a_checked_row() { + let dir = std::env::temp_dir().join(format!("checked-advance-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("ws.db").to_string_lossy().into_owned(); + let checker = SqliteDocStorage::new(path.clone()); + checker.connect().await.unwrap(); + let writer = SqliteDocStorage::new(path); + writer.connect().await.unwrap(); + let (held, outside) = held_and_outside_updates(); + let at = millis_to_naive_utc(5_000); + insert_snapshot(&checker, &held, at).await; + + // The checker reads the snapshot that the state contains. Then another connection keeps + // the timestamp and replaces the data before the checker writes. + let mut tx = checker.pool.begin().await.unwrap(); + let checked = held_on_tx(&mut tx, "server", "doc-same-ms", &held) + .await + .unwrap(); + assert_eq!(checked, Some(at)); + let replaced = DocRecord { + doc_id: "doc-same-ms".into(), + bin: outside, + timestamp: at, + }; + assert!(writer.set_doc_snapshot(&replaced).await.unwrap()); + let outcome = write_checked_advance(tx, "server", "doc-same-ms", at) + .await + .unwrap(); + assert_eq!(outcome, CheckedAdvance::Busy); + assert!( + checker + .get_peer_pushed_clock("server", "doc-same-ms") + .await + .unwrap() + .is_none() + ); + + // A new check reads the replaced snapshot and keeps the clock. + let outcome = checker + .advance_pushed_clock_with_state("server", "doc-same-ms", &held) + .await + .unwrap(); + assert_eq!(outcome, CheckedAdvance::Unchanged); + checker.close().await; + writer.close().await; + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/packages/common/store/src/sqlite/session_mutations.rs b/packages/common/store/src/sqlite/session_mutations.rs index ac4200de91..85906b37a8 100644 --- a/packages/common/store/src/sqlite/session_mutations.rs +++ b/packages/common/store/src/sqlite/session_mutations.rs @@ -2,40 +2,24 @@ use std::collections::HashSet; -use chrono::NaiveDateTime; -use sqlx::Row; -use y_octo::{Doc, DocOptions, StateVector, encode_state_vector_from_update_v1}; - use super::{ SqliteDocStorage, doc::{LOCAL_DELETED_DOC_PEER, PENDING_REMOTE_DELETE_PEER, is_empty_update}, + pushed_clock::{CommittedRow, PeerProof, SessionCommit, UpdateStamp, advance_on_tx}, }; use crate::{error::StoreResult, workspace_db::PendingDocUpdate}; -/// True when `doc` already holds every struct and every deletion of `update`. -fn doc_contains_update(doc: &mut Doc, encoded: &[u8], update: &[u8]) -> bool { - let state = doc.get_state_vector(); - let structs_known = encode_state_vector_from_update_v1(update) - .and_then(StateVector::decode_v1) - .is_ok_and(|sv| sv.iter().all(|(client, clock)| state.get(client) >= *clock)); - structs_known - && doc.apply_update_from_binary_v1(update).is_ok() - && doc.encode_update_v1().is_ok_and(|after| after == encoded) -} - impl SqliteDocStorage { /// Atomically delete `deleted_doc_ids`, record durable remote-delete tombstones, clear - /// server-acknowledged tombstones, persist `updates` (with optional per-update timestamps), - /// and advance `peer_clocks.pushed_clock` inside one `BEGIN IMMEDIATE` SQLite transaction. - /// Any update targeting a `doc_id` in `deleted_doc_ids` is filtered out so a deleted document - /// can never be resurrected inside the same batch. Returns the number of committed update - /// rows. + /// server-acknowledged tombstones, persist `updates` stamped by `update_stamps`, and advance + /// `peer_clocks.pushed_clock` inside one `BEGIN IMMEDIATE` SQLite transaction. Any update + /// targeting a `doc_id` in `deleted_doc_ids` is filtered out so a deleted document can never + /// be resurrected inside the same batch. /// - /// `server_held_states` holds, for one peer, the encoded v1 state of each document that the - /// peer holds in whole. `pushed_clock` advances over the oldest rows (snapshot and updates - /// newer than the current `pushed_clock`) that this state contains, and stops before the - /// first timestamp with a row that has a change outside it, so the rows of another writer stay - /// pending. + /// With `peer_proof`, `pushed_clock` of the peer moves along the rows that the peer holds + /// (the rows of this batch stamped `held_by_peer` and `PeerProof::held_rows`) while each row + /// took the slot right after it. This reads no row data. A row of another writer between two + /// held rows stops the advance, and the result lists the document as behind. #[allow(clippy::too_many_arguments)] pub async fn apply_session_mutations_atomic( &self, @@ -43,35 +27,39 @@ impl SqliteDocStorage { tombstone_remote_deletes: &[String], acked_remote_deletes: &[String], updates: &[PendingDocUpdate], - update_timestamps: &[Option], + update_stamps: &[UpdateStamp], create_for_peer: Option<&str>, - server_held_states: Option<(&str, &[(String, Vec)])>, + peer_proof: Option>, now_ms: i64, - ) -> StoreResult { + ) -> StoreResult { let deleted_set: HashSet<&str> = deleted_doc_ids.iter().map(String::as_str).collect(); - let non_empty: Vec<(&str, &[u8], i64)> = updates - .iter() - .enumerate() - .filter(|(_, u)| { - !is_empty_update(&u.update) && !deleted_set.contains(u.doc_id.as_str()) - }) - .map(|(i, u)| { - let ts_ms = update_timestamps - .get(i) - .copied() - .flatten() - .unwrap_or(now_ms); - (u.doc_id.as_str(), u.update.as_slice(), ts_ms) - }) - .collect(); - let held: &[(String, Vec)] = server_held_states.map_or(&[], |(_, states)| states); + let mut kept = Vec::with_capacity(updates.len()); + let mut items: Vec<(&str, &[u8], i64)> = Vec::with_capacity(updates.len()); + for (i, u) in updates.iter().enumerate() { + if is_empty_update(&u.update) || deleted_set.contains(u.doc_id.as_str()) { + continue; + } + let stamp = update_stamps.get(i).copied().unwrap_or_default(); + kept.push((i, stamp.held_by_peer)); + items.push(( + u.doc_id.as_str(), + u.update.as_slice(), + stamp.event_ms.unwrap_or(now_ms), + )); + } + let mut commit = SessionCommit { + rows: vec![None; updates.len()], + ..SessionCommit::default() + }; + let proof_is_empty = peer_proof + .is_none_or(|proof| proof.held_rows.is_empty() && proof.held_doc_ids.is_empty()); if deleted_doc_ids.is_empty() && tombstone_remote_deletes.is_empty() && acked_remote_deletes.is_empty() - && non_empty.is_empty() - && held.is_empty() + && items.is_empty() + && proof_is_empty { - return Ok(0); + return Ok(commit); } let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?; for doc_id in deleted_doc_ids { @@ -112,153 +100,180 @@ impl SqliteDocStorage { .await?; } } - let committed = Self::apply_updates_on_tx(&mut tx, &non_empty, create_for_peer).await?; - if let Some((peer, states)) = server_held_states { - for (doc_id, state) in states { - if deleted_set.contains(doc_id.as_str()) { - continue; - } - let Some(pushed_ts) = - Self::server_held_clock_on_tx(&mut tx, peer, doc_id, state).await? - else { - continue; - }; - sqlx::query( - "INSERT INTO peer_clocks (peer, doc_id, pushed_clock) VALUES ($1, $2, $3) \ - ON CONFLICT(peer, doc_id) DO UPDATE SET pushed_clock = CASE \ - WHEN peer_clocks.pushed_clock IS NULL OR peer_clocks.pushed_clock < excluded.pushed_clock \ - THEN excluded.pushed_clock ELSE peer_clocks.pushed_clock END", - ) - .bind(peer) - .bind(doc_id) - .bind(pushed_ts) - .execute(&mut *tx) - .await?; - } + let committed = Self::apply_updates_on_tx(&mut tx, &items, create_for_peer).await?; + for ((index, _), row) in kept.iter().zip(committed) { + commit.rows[*index] = row; + } + if let Some(proof) = peer_proof { + let held: Vec<&CommittedRow> = proof + .held_rows + .iter() + .chain(kept.iter().filter_map(|&(index, held_by_peer)| { + commit.rows[index].as_ref().filter(|_| held_by_peer) + })) + .collect(); + (commit.pushed_clocks, commit.behind_doc_ids) = + advance_on_tx(&mut tx, proof.peer, &held, proof.held_doc_ids, &deleted_set).await?; } tx.commit().await?; - Ok(committed.len()) - } - - /// Timestamp of the newest row in the oldest run of `doc_id` rows newer than the - /// `pushed_clock` of `peer` whose changes `state_v1` contains, or `None` when a row of the - /// oldest timestamp holds a change outside `state_v1`. The run ends before the first timestamp - /// with any row outside `state_v1`. - async fn server_held_clock_on_tx( - tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, - peer: &str, - doc_id: &str, - state_v1: &[u8], - ) -> StoreResult> { - let rows = sqlx::query( - "WITH pushed AS (SELECT COALESCE((SELECT pushed_clock FROM peer_clocks \ - WHERE peer = $1 AND doc_id = $2), 0) AS clock) \ - SELECT updated_at AS ts, data FROM snapshots, pushed \ - WHERE doc_id = $2 AND updated_at > pushed.clock \ - UNION ALL SELECT created_at AS ts, data FROM updates, pushed \ - WHERE doc_id = $2 AND created_at > pushed.clock \ - ORDER BY ts", - ) - .bind(peer) - .bind(doc_id) - .fetch_all(&mut **tx) - .await?; - if rows.is_empty() { - return Ok(None); - } - let mut doc = DocOptions::from_identity(1, doc_id.to_string()).build(); - if doc.apply_update_from_binary_v1(state_v1).is_err() { - return Ok(None); - } - let Ok(encoded) = doc.encode_update_v1() else { - return Ok(None); - }; - // Rows that share one timestamp pass or fail together: `pushed_clock` can only hold whole - // milliseconds, so it never moves past a row that `state_v1` does not contain. - let mut held = None; - let mut batch_ts = None; - for row in &rows { - let ts: NaiveDateTime = row.try_get("ts")?; - let data: Vec = row.try_get("data")?; - if batch_ts != Some(ts) { - held = batch_ts; - batch_ts = Some(ts); - } - if !is_empty_update(&data) && !doc_contains_update(&mut doc, &encoded, &data) { - return Ok(held); - } - } - Ok(batch_ts) + Ok(commit) } } #[cfg(test)] mod tests { + use chrono::NaiveDateTime; + use super::*; use crate::sqlite::millis_to_naive_utc; - /// Returns `(held, outside)`: the server holds `held`, and `outside` is a concurrent change - /// of another writer that the server does not hold. - fn held_and_outside_updates() -> (Vec, Vec) { - let doc = DocOptions::from_identity(1, "doc-same-ms".into()).build(); - let mut text = doc.get_or_create_text("content").unwrap(); - text.insert(0, "held").unwrap(); - let other = DocOptions::from_identity(2, "doc-same-ms".into()).build(); - let mut other_text = other.get_or_create_text("content").unwrap(); - other_text.insert(0, "outside").unwrap(); - let outside = other.encode_update_v1().unwrap(); - (doc.encode_update_v1().unwrap(), outside) + const PEER: &str = "server"; + + fn update(doc_id: &str) -> PendingDocUpdate { + PendingDocUpdate { + doc_id: doc_id.into(), + update: vec![1, 2, 3], + } + } + + /// Flush one row of `doc_id` at `event_ms` and pass `held_rows` as peer-held rows of + /// earlier flushes. + async fn flush( + storage: &SqliteDocStorage, + doc_id: &str, + event_ms: i64, + held_by_peer: bool, + held_rows: &[CommittedRow], + ) -> SessionCommit { + let stamp = UpdateStamp { + event_ms: Some(event_ms), + held_by_peer, + }; + let proof = PeerProof { + peer: PEER, + held_rows, + held_doc_ids: &[], + }; + storage + .apply_session_mutations_atomic( + &[], + &[], + &[], + &[update(doc_id)], + &[stamp], + None, + Some(proof), + event_ms, + ) + .await + .unwrap() + } + + async fn pushed(storage: &SqliteDocStorage, doc_id: &str) -> Option { + storage + .get_peer_pushed_clock(PEER, doc_id) + .await + .unwrap() + .map(|clock| clock.timestamp) } #[tokio::test] - async fn server_held_clock_never_passes_an_uncontained_row_of_the_same_millisecond() { - let (held, outside) = held_and_outside_updates(); - let same_ms = millis_to_naive_utc(5_000); - // Each case puts the contained row in one table and the uncontained row in the other, so - // one of the two cases reads the contained row first whatever order SQLite returns. - for (snapshot, update) in [(&held, &outside), (&outside, &held)] { - let storage = SqliteDocStorage::new(":memory:"); - storage.connect().await.unwrap(); - sqlx::query( - "INSERT INTO snapshots (doc_id, data, created_at, updated_at) \ - VALUES ('doc-same-ms', $1, $2, $2)", - ) - .bind(snapshot.as_slice()) - .bind(same_ms) - .execute(&storage.pool) - .await - .unwrap(); - sqlx::query( - "INSERT INTO updates (doc_id, data, created_at) VALUES ('doc-same-ms', $1, $2)", - ) - .bind(update.as_slice()) - .bind(same_ms) - .execute(&storage.pool) - .await - .unwrap(); + async fn pushed_clock_moves_only_along_contiguous_peer_held_rows() { + let storage = SqliteDocStorage::new(":memory:"); + storage.connect().await.unwrap(); - let states = [("doc-same-ms".to_string(), held.clone())]; - storage - .apply_session_mutations_atomic( - &[], - &[], - &[], - &[], - &[], - None, - Some(("server", &states)), - 6_000, - ) - .await - .unwrap(); - assert!( - storage - .get_peer_pushed_clock("server", "doc-same-ms") - .await - .unwrap() - .is_none(), - "pushed_clock passed an uncontained row of the same millisecond" - ); - } + // A remote row on a clean document moves `pushed_clock` in the same transaction, also when + // the event time is behind the document clock. + let base = flush(&storage, "doc", 1_000, true, &[]).await; + assert_eq!( + pushed(&storage, "doc").await, + Some(millis_to_naive_utc(1_000)) + ); + assert!(base.behind_doc_ids.is_empty()); + flush(&storage, "doc", 900, true, &[]).await; + assert_eq!( + pushed(&storage, "doc").await, + Some(millis_to_naive_utc(1_001)) + ); + + // Own row A (not yet acknowledged), a row of another writer B, own row C. + let a = flush(&storage, "doc", 2_000, false, &[]).await.rows[0] + .clone() + .unwrap(); + storage.push_update("doc", [7u8, 7], 2_000).await.unwrap(); + let c = flush(&storage, "doc", 2_000, false, &[]).await.rows[0] + .clone() + .unwrap(); + assert_eq!( + (a.timestamp, c.prev_clock, c.timestamp), + ( + millis_to_naive_utc(2_000), + Some(millis_to_naive_utc(2_001)), + millis_to_naive_utc(2_002) + ) + ); + + // The peer acknowledges C and A: the clock stops after A and the document is behind. + let proof = [c.clone(), a.clone()]; + let commit = storage + .apply_session_mutations_atomic( + &[], + &[], + &[], + &[], + &[], + None, + Some(PeerProof { + peer: PEER, + held_rows: &proof, + held_doc_ids: &[], + }), + 3_000, + ) + .await + .unwrap(); + assert_eq!(pushed(&storage, "doc").await, Some(a.timestamp)); + assert_eq!(commit.behind_doc_ids, vec!["doc".to_string()]); + + // A remote row after a blocked row stays blocked, and with the missing row held the + // chain runs through all of them. + let remote = flush(&storage, "doc", 4_000, true, &[]).await; + assert_eq!(pushed(&storage, "doc").await, Some(a.timestamp)); + let remote = remote.rows[0].clone().unwrap(); + let b = CommittedRow { + doc_id: "doc".into(), + prev_clock: Some(a.timestamp), + timestamp: millis_to_naive_utc(2_001), + }; + let commit = flush(&storage, "doc", 5_000, true, &[remote, c, b]).await; + assert_eq!( + pushed(&storage, "doc").await, + Some(millis_to_naive_utc(5_000)) + ); + assert!(commit.behind_doc_ids.is_empty()); + + // A row of a deleted document takes no slot and moves no clock. + let commit = storage + .apply_session_mutations_atomic( + &["doc".to_string()], + &[], + &[], + &[update("doc")], + &[UpdateStamp { + event_ms: Some(6_000), + held_by_peer: true, + }], + None, + Some(PeerProof { + peer: PEER, + held_rows: &[], + held_doc_ids: &[], + }), + 6_000, + ) + .await + .unwrap(); + assert_eq!(commit.rows, vec![None]); + assert!(commit.pushed_clocks.is_empty()); } } diff --git a/packages/frontend/client/src/doc_sync/driver.rs b/packages/frontend/client/src/doc_sync/driver.rs index b3175f0062..46ffdcdb05 100644 --- a/packages/frontend/client/src/doc_sync/driver.rs +++ b/packages/frontend/client/src/doc_sync/driver.rs @@ -11,7 +11,7 @@ use affine_store::{ }; use blocksuite_playground_doc::session::PageDocSession; -use crate::{ClientError, ClientResult, session::WorkspaceSession}; +use crate::{ClientError, ClientResult, session::WorkspaceSession, session_ops::RowStamp}; pub(crate) fn is_non_empty_update(bin: &[u8]) -> bool { !bin.is_empty() && bin != [0, 0] @@ -403,48 +403,26 @@ impl WorkspaceSession { match self.classify_doc(doc_id) { ManagedDocKind::Root => { - let remote_wm = if is_non_empty_update(missing) { - self.apply_remote_update_bytes(doc_id, missing, now_ms)? - } else { - None - }; - return self.reconcile_loaded_doc( - doc_id, - state, - should_reconcile, - remote_wm.is_some(), - now_ms, - ); + let applied = is_non_empty_update(missing) + && self.apply_remote_update_bytes(doc_id, missing, now_ms)?; + return self.reconcile_loaded_doc(doc_id, state, should_reconcile, applied, now_ms); } ManagedDocKind::DbTable(_) => { - let remote_wm = if is_non_empty_update(missing) { - self.apply_remote_db_table_update(doc_id, missing, now_ms)? - } else { - None - }; - return self.reconcile_loaded_doc( - doc_id, - state, - should_reconcile, - remote_wm.is_some(), - now_ms, - ); + let applied = is_non_empty_update(missing) + && self.apply_remote_db_table_update(doc_id, missing, now_ms)?; + return self.reconcile_loaded_doc(doc_id, state, should_reconcile, applied, now_ms); } ManagedDocKind::Page => { if self.doc_exists_locally(doc_id) { - let mut remote_wm = if is_non_empty_update(missing) { - self.apply_remote_update_bytes(doc_id, missing, now_ms)? - } else { - None - }; + let mut applied = is_non_empty_update(missing) + && self.apply_remote_update_bytes(doc_id, missing, now_ms)?; let mut first_staged_err: Option = None; for delta in &staged_deltas { if !is_non_empty_update(delta) { continue; } match self.apply_remote_update_bytes(doc_id, delta, now_ms) { - Ok(Some(wm)) => remote_wm = Some(wm), - Ok(None) => {} + Ok(delta_applied) => applied |= delta_applied, Err(err) => { if first_staged_err.is_none() { first_staged_err = Some(err); @@ -463,7 +441,7 @@ impl WorkspaceSession { doc_id, state, should_reconcile, - remote_wm.is_some(), + applied, now_ms, ); } @@ -476,13 +454,12 @@ impl WorkspaceSession { page.apply_remote_update_v1(missing) .map_err(|e| ClientError::Store(e.to_string()))?; crate::session::rotate_page_client_if_required(&mut page)?; - let mut last_wm = self.doc_sync.next_local_clock_ms(doc_id, now_ms); self.push_stamped_persist_update( PendingDocUpdate { doc_id: doc_id.to_string(), update: missing.to_vec(), }, - Some(last_wm), + RowStamp::remote(Some(now_ms)), ); let mut first_staged_err: Option = None; for delta in staged_deltas { @@ -495,13 +472,12 @@ impl WorkspaceSession { .and_then(|_| crate::session::rotate_page_client_if_required(&mut page)) { Ok(()) => { - last_wm = self.doc_sync.next_local_clock_ms(doc_id, now_ms); self.push_stamped_persist_update( PendingDocUpdate { doc_id: doc_id.to_string(), update: delta, }, - Some(last_wm), + RowStamp::remote(Some(now_ms)), ); } Err(err) => { @@ -570,8 +546,8 @@ impl WorkspaceSession { continue; } match self.apply_remote_update_bytes(doc_id, bin, now_ms) { - Ok(wm) => { - applied |= wm.is_some(); + Ok(update_applied) => { + applied |= update_applied; } Err(err) => { if first_err.is_none() { diff --git a/packages/frontend/client/src/doc_sync/invalidation.rs b/packages/frontend/client/src/doc_sync/invalidation.rs new file mode 100644 index 0000000000..c297b5e389 --- /dev/null +++ b/packages/frontend/client/src/doc_sync/invalidation.rs @@ -0,0 +1,82 @@ +//! Coalesced `space:broadcast-doc-invalidation` repair and the `space:load-doc-timestamps` +//! answer that closes it. + +use std::collections::BTreeMap; + +use super::{DocSyncCoordinator, INVALIDATION_COALESCE_WINDOW_MS}; + +impl DocSyncCoordinator { + /// Record a `space:broadcast-doc-invalidation` signal and schedule a coalesced 50 ms repair + /// window if no repair is currently scheduled or in flight. + pub fn on_doc_invalidated(&mut self, now_ms: i64) { + self.invalidation.pending = true; + self.schedule_invalidation_repair(now_ms); + } + + fn schedule_invalidation_repair(&mut self, now_ms: i64) { + if self.invalidation.scheduled_at_ms.is_some() || self.invalidation.in_flight { + return; + } + self.invalidation.scheduled_at_ms = + Some(now_ms.saturating_add(INVALIDATION_COALESCE_WINDOW_MS)); + } + + /// Check if the 50 ms invalidation window has elapsed and no repair is in flight. + pub fn take_due_invalidation_repair(&mut self, now_ms: i64) -> bool { + if self.invalidation.in_flight { + return false; + } + if self + .invalidation + .scheduled_at_ms + .is_some_and(|at| now_ms >= at) + { + self.invalidation.scheduled_at_ms = None; + self.invalidation.pending = false; + return true; + } + false + } + + pub fn on_invalidation_repair_started(&mut self) { + self.invalidation.in_flight = true; + } + + /// Process `SpaceSyncEvent::DocTimestampsLoaded`, returning document IDs whose server + /// timestamp strictly exceeds the last known `remote_ts`, without creating entries for + /// unmanaged documents. + pub fn on_doc_timestamps_loaded( + &mut self, + timestamps: &BTreeMap, + now_ms: i64, + mut is_managed: impl FnMut(&str) -> bool, + ) -> Vec { + self.invalidation.in_flight = false; + let mut advanced = Vec::new(); + for (doc_id, &server_ts) in timestamps { + let entry = if let Some(existing) = self.entries.get_mut(doc_id.as_str()) { + existing + } else if is_managed(doc_id) { + self.entries.entry(doc_id.clone()).or_default() + } else { + continue; + }; + if entry.remote_ts.is_some_and(|prev| prev >= server_ts) { + continue; + } + entry.remote_ts = Some(server_ts); + advanced.push(doc_id.clone()); + } + if self.invalidation.pending { + self.schedule_invalidation_repair(now_ms); + } + advanced + } + + pub fn on_load_timestamps_failed(&mut self, now_ms: i64) { + self.invalidation.in_flight = false; + if self.invalidation.pending { + self.schedule_invalidation_repair(now_ms); + } + } +} diff --git a/packages/frontend/client/src/doc_sync/mod.rs b/packages/frontend/client/src/doc_sync/mod.rs index c701924503..abdadafb1d 100644 --- a/packages/frontend/client/src/doc_sync/mod.rs +++ b/packages/frontend/client/src/doc_sync/mod.rs @@ -4,6 +4,9 @@ //! Compiles on both native targets and `wasm32-unknown-unknown` with zero system wall-clock calls. pub(crate) mod driver; +mod invalidation; +#[cfg(not(target_family = "wasm"))] +pub(crate) mod receipts; use std::collections::{BTreeMap, VecDeque}; @@ -55,8 +58,12 @@ pub struct DocSyncEntry { pub remote_baseline_known: bool, /// FIFO queue of the sequence numbers of push requests in flight in `SpaceSyncEngine`. pub in_flight_pushes: VecDeque, - /// Highest local clock watermark assigned to writes on this document in this session. - pub last_local_clock_ms: Option, + /// Sequence number of the newest push queued for this document. + pub last_push_seq: Option, + /// Every push of this document up to this sequence number is server-acknowledged. + pub acked_push_seq: Option, + /// Pushes up to this sequence number left the queue without an acknowledgement. + pub abandoned_push_seq: Option, /// True once the server holds the whole in-memory state of this document. The next flush /// advances `peer_clocks.pushed_clock` over the SQLite rows that this state contains. pub server_has_state: bool, @@ -72,6 +79,14 @@ impl DocSyncEntry { pub fn unacked_pushes(&self) -> u32 { self.in_flight_pushes.len() as u32 } + + /// Drop the pushes in flight without an acknowledgement. They never prove a row. + fn abandon_in_flight_pushes(&mut self) { + if !self.in_flight_pushes.is_empty() { + self.abandoned_push_seq = self.last_push_seq; + self.in_flight_pushes.clear(); + } + } } #[derive(Clone, Debug, Default, Eq, PartialEq)] @@ -144,16 +159,21 @@ impl DocSyncCoordinator { .is_some_and(|e| e.needs_reconcile_push) } - /// Allocate a monotonically advancing local clock watermark for `doc_id`, matching SQLite's - /// `+1 ms` tie-breaking rule on equal timestamps. - pub fn next_local_clock_ms(&mut self, doc_id: &str, now_ms: i64) -> i64 { - let entry = self.entry_mut(doc_id); - let next = match entry.last_local_clock_ms { - Some(prev) if prev >= now_ms => prev.saturating_add(1), - _ => now_ms, - }; - entry.last_local_clock_ms = Some(next); - next + /// True when the server acknowledged push `seq` of `doc_id` and every push of the document + /// before it. + pub fn is_push_acked(&self, doc_id: &str, seq: u64) -> bool { + self.entries.get(doc_id).is_some_and(|e| { + e.acked_push_seq.is_some_and(|acked| seq <= acked) + && e.abandoned_push_seq.is_none_or(|abandoned| seq > abandoned) + }) + } + + /// True when push `seq` of `doc_id` left the queue without an acknowledgement. + pub fn is_push_abandoned(&self, doc_id: &str, seq: u64) -> bool { + self.entries.get(doc_id).is_none_or(|e| { + e.abandoned_push_seq + .is_some_and(|abandoned| seq <= abandoned) + }) } pub fn pending_push_doc_ids(&self) -> Vec { @@ -193,7 +213,7 @@ impl DocSyncCoordinator { entry.needs_reconcile_push = false; entry.reconcile_barrier_seq = None; entry.stale_reload_needed = false; - entry.in_flight_pushes.clear(); + entry.abandon_in_flight_pushes(); entry.server_has_state = false; } } @@ -216,27 +236,25 @@ impl DocSyncCoordinator { entry.needs_reconcile_push = false; entry.reconcile_barrier_seq = None; entry.stale_reload_needed = false; - entry.in_flight_pushes.clear(); + entry.abandon_in_flight_pushes(); entry.server_has_state = false; } } - /// Seed locally modified documents recovered from SQLite (`clocks.timestamp > pushed_clock`). - pub fn seed_unpushed_docs(&mut self, doc_clocks: Vec<(String, i64)>) { - for (id, clock_ms) in doc_clocks { + /// Seed documents that SQLite holds with rows the server may lack + /// (`clocks.timestamp > pushed_clock`), for a load and a reconciliation push. + pub fn seed_unpushed_docs(&mut self, doc_ids: impl IntoIterator) { + for id in doc_ids { let entry = self.entry_mut(&id); - if matches!(entry.phase, DocSyncPhase::PendingRemoteDelete { .. }) { - continue; + match entry.phase { + DocSyncPhase::PendingRemoteDelete { .. } => continue, + DocSyncPhase::MissingOnServer => entry.phase = DocSyncPhase::Idle, + _ => {} } entry.needs_push = true; entry.needs_reconcile_push = true; entry.reconcile_barrier_seq = None; entry.server_has_state = false; - entry.last_local_clock_ms = Some( - entry - .last_local_clock_ms - .map_or(clock_ms, |prev| prev.max(clock_ms)), - ); } } @@ -245,18 +263,19 @@ impl DocSyncCoordinator { self.next_push_seq = seq.saturating_add(1); let entry = self.entry_mut(doc_id); entry.in_flight_pushes.push_back(seq); + entry.last_push_seq = Some(seq); entry.server_has_state = false; seq } - /// Record a pushed local mutation on `doc_id`. - pub fn mark_local_write(&mut self, doc_id: &str) { + /// Record a pushed local mutation on `doc_id` and return the sequence number of its push. + pub fn mark_local_write(&mut self, doc_id: &str) -> u64 { let entry = self.entry_mut(doc_id); if matches!(entry.phase, DocSyncPhase::MissingOnServer) { entry.phase = DocSyncPhase::Idle; } entry.needs_push = true; - self.queue_push(doc_id); + self.queue_push(doc_id) } /// Begin remote loading for an absent local document if not already loading or confirmed @@ -424,6 +443,9 @@ impl DocSyncCoordinator { ); entry.remote_baseline_known = true; let popped = entry.in_flight_pushes.pop_front(); + if popped.is_some() && entry.in_flight_pushes.is_empty() { + entry.acked_push_seq = entry.last_push_seq; + } if matches!(entry.phase, DocSyncPhase::PendingRemoteDelete { .. }) || entry.needs_reconcile_push { @@ -441,9 +463,9 @@ impl DocSyncCoordinator { } } - /// Record a dispatched cold-start reconciliation diff or `Create` push. The push resends - /// existing local state, so it never advances `last_local_clock_ms`. Clears - /// `needs_reconcile_push` and holds `reconcile_barrier_seq` until this push is acknowledged. + /// Record a dispatched cold-start reconciliation diff or `Create` push of existing local + /// state. Clears `needs_reconcile_push` and holds `reconcile_barrier_seq` until this push is + /// acknowledged. pub fn record_reconcile_push_dispatched(&mut self, doc_id: &str) { let seq = self.queue_push(doc_id); let entry = self.entry_mut(doc_id); @@ -513,7 +535,7 @@ impl DocSyncCoordinator { entry.needs_reconcile_push = false; entry.reconcile_barrier_seq = None; entry.stale_reload_needed = false; - entry.in_flight_pushes.clear(); + entry.abandon_in_flight_pushes(); entry.server_has_state = false; } @@ -523,7 +545,7 @@ impl DocSyncCoordinator { if let Some(entry) = self.entries.get_mut(doc_id) { entry.load_in_flight = false; entry.stale_reload_needed = false; - entry.in_flight_pushes.clear(); + entry.abandon_in_flight_pushes(); entry.needs_push = false; entry.needs_reconcile_push = false; entry.reconcile_barrier_seq = None; @@ -651,80 +673,6 @@ impl DocSyncCoordinator { } } - /// Record a `space:broadcast-doc-invalidation` signal and schedule a coalesced 50 ms repair - /// window if no repair is currently scheduled or in flight. - pub fn on_doc_invalidated(&mut self, now_ms: i64) { - self.invalidation.pending = true; - self.schedule_invalidation_repair(now_ms); - } - - fn schedule_invalidation_repair(&mut self, now_ms: i64) { - if self.invalidation.scheduled_at_ms.is_some() || self.invalidation.in_flight { - return; - } - self.invalidation.scheduled_at_ms = - Some(now_ms.saturating_add(INVALIDATION_COALESCE_WINDOW_MS)); - } - - /// Check if the 50 ms invalidation window has elapsed and no repair is in flight. - pub fn take_due_invalidation_repair(&mut self, now_ms: i64) -> bool { - if self.invalidation.in_flight { - return false; - } - if self - .invalidation - .scheduled_at_ms - .is_some_and(|at| now_ms >= at) - { - self.invalidation.scheduled_at_ms = None; - self.invalidation.pending = false; - return true; - } - false - } - - pub fn on_invalidation_repair_started(&mut self) { - self.invalidation.in_flight = true; - } - - /// Process `SpaceSyncEvent::DocTimestampsLoaded`, returning document IDs whose server - /// timestamp strictly exceeds the last known `remote_ts`, without creating entries for - /// unmanaged documents. - pub fn on_doc_timestamps_loaded( - &mut self, - timestamps: &BTreeMap, - now_ms: i64, - mut is_managed: impl FnMut(&str) -> bool, - ) -> Vec { - self.invalidation.in_flight = false; - let mut advanced = Vec::new(); - for (doc_id, &server_ts) in timestamps { - let entry = if let Some(existing) = self.entries.get_mut(doc_id.as_str()) { - existing - } else if is_managed(doc_id) { - self.entries.entry(doc_id.clone()).or_default() - } else { - continue; - }; - if entry.remote_ts.is_some_and(|prev| prev >= server_ts) { - continue; - } - entry.remote_ts = Some(server_ts); - advanced.push(doc_id.clone()); - } - if self.invalidation.pending { - self.schedule_invalidation_repair(now_ms); - } - advanced - } - - pub fn on_load_timestamps_failed(&mut self, now_ms: i64) { - self.invalidation.in_flight = false; - if self.invalidation.pending { - self.schedule_invalidation_repair(now_ms); - } - } - /// Reset transient in-flight flags when the transport disconnects or pauses. pub fn on_disconnected(&mut self) { self.invalidation.in_flight = false; diff --git a/packages/frontend/client/src/doc_sync/receipts.rs b/packages/frontend/client/src/doc_sync/receipts.rs new file mode 100644 index 0000000000..c71324430c --- /dev/null +++ b/packages/frontend/client/src/doc_sync/receipts.rs @@ -0,0 +1,110 @@ +//! Committed SQLite rows that can still move `peer_clocks.pushed_clock` once the server holds +//! them. A flush passes the rows the server holds, and SQLite moves `pushed_clock` along them +//! while each row took the slot right after it. + +use std::collections::BTreeMap; + +use affine_store::sqlite::CommittedRow; + +use super::DocSyncCoordinator; + +/// Most rows that a session keeps for `pushed_clock` advances. A row past the limit is not kept, +/// so its document waits for a content check or a reconciliation. +pub(crate) const MAX_CLOCK_RECEIPTS: usize = 4096; + +#[derive(Clone, Debug)] +struct Receipt { + row: CommittedRow, + /// Local push that sent the row content, or `None` for content from the server. + push_seq: Option, + /// True once a flush passed the row as held. + offered: bool, +} + +impl Receipt { + fn is_held(&self, doc_sync: &DocSyncCoordinator) -> bool { + self.push_seq + .is_none_or(|seq| doc_sync.is_push_acked(&self.row.doc_id, seq)) + } +} + +#[derive(Clone, Debug, Default)] +pub(crate) struct ClockReceipts { + docs: BTreeMap>, + len: usize, +} + +impl ClockReceipts { + /// Keep `row`, whose content came from the server (`push_seq` `None`) or went out in local + /// push `push_seq`. `offered` is true when the flush that wrote it passed it as held. + pub(crate) fn record(&mut self, row: CommittedRow, push_seq: Option, offered: bool) { + if self.len < MAX_CLOCK_RECEIPTS { + self.docs + .entry(row.doc_id.clone()) + .or_default() + .push(Receipt { + row, + push_seq, + offered, + }); + self.len += 1; + } + } + + /// The held rows of each document with a row that became held since the last flush. A + /// document whose held rows a flush already passed waits for a new one. + pub(crate) fn held_rows(&self, doc_sync: &DocSyncCoordinator) -> Vec { + self.docs + .values() + .filter(|receipts| { + receipts + .iter() + .any(|receipt| !receipt.offered && receipt.is_held(doc_sync)) + }) + .flatten() + .filter(|receipt| receipt.is_held(doc_sync)) + .map(|receipt| receipt.row.clone()) + .collect() + } + + /// Mark the held rows as passed to a committed flush. + pub(crate) fn mark_offered(&mut self, doc_sync: &DocSyncCoordinator) { + for receipt in self.docs.values_mut().flatten() { + receipt.offered |= receipt.is_held(doc_sync); + } + } + + /// Drop the rows of `doc_id` that `pushed_clock` now covers and the rows whose push left + /// without an acknowledgement. When all rows left are held, a row that no receipt can fill + /// stops `pushed_clock` before them, so they are dropped too. + pub(crate) fn settle( + &mut self, + doc_id: &str, + doc_sync: &DocSyncCoordinator, + covered: impl Fn(&CommittedRow) -> bool, + ) { + let Some(receipts) = self.docs.get_mut(doc_id) else { + return; + }; + let before = receipts.len(); + receipts.retain(|receipt| { + !covered(&receipt.row) + && receipt + .push_seq + .is_none_or(|seq| !doc_sync.is_push_abandoned(doc_id, seq)) + }); + if receipts.iter().all(|receipt| receipt.is_held(doc_sync)) { + receipts.clear(); + } + self.len -= before - receipts.len(); + if receipts.is_empty() { + self.docs.remove(doc_id); + } + } + + pub(crate) fn forget(&mut self, doc_id: &str) { + if let Some(receipts) = self.docs.remove(doc_id) { + self.len -= receipts.len(); + } + } +} diff --git a/packages/frontend/client/src/session.rs b/packages/frontend/client/src/session.rs index 26d3c16364..eb80f25d13 100644 --- a/packages/frontend/client/src/session.rs +++ b/packages/frontend/client/src/session.rs @@ -24,6 +24,8 @@ use blocksuite_playground_doc::{ }; use serde::{Deserialize, Serialize}; +#[cfg(not(target_family = "wasm"))] +use crate::doc_sync::receipts::ClockReceipts; use crate::{ ClientError, ClientResult, auth::{AuthController, NativeAuthPlatform}, @@ -34,6 +36,7 @@ use crate::{ doc_directory::StoreBackedDocDirectory, doc_sync::{DocSyncCoordinator, driver::parse_db_table_doc_id}, host::{HostBridge, HostKind, WsHandle}, + session_ops::RowStamp, }; /// High-level sync status surfaced in workspace chrome and accessibility trees. @@ -88,6 +91,9 @@ fn generate_media_replica_seed_hex() -> ClientResult { /// before a flush finds their documents in SQLite. pub(crate) const MAX_UNVERIFIED_REMOTE_DOCS: usize = 64; pub(crate) const MAX_UNVERIFIED_REMOTE_BYTES: usize = 1024 * 1024; +/// Most documents whose staged remote bytes a SQLite-backed session dropped before a flush +/// looked them up in SQLite. +pub(crate) const MAX_EVICTED_REMOTE_DOCS: usize = 1024; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum UnhydratedDeltaOrigin { @@ -119,11 +125,15 @@ pub struct WorkspaceSession { pub(crate) has_sqlite_backing: bool, /// Oldest first, documents with staged remote bytes that no flush found in SQLite yet. pub(crate) unverified_remote_docs: VecDeque<(String, usize)>, + /// Oldest first, documents whose staged remote bytes left memory before a flush found them. + pub(crate) evicted_remote_doc_ids: VecDeque, pub(crate) active_doc_id: Option, blobs: BTreeMap)>, - pub(crate) pending_persist_updates: Vec<(PendingDocUpdate, Option)>, + pub(crate) pending_persist_updates: Vec<(PendingDocUpdate, RowStamp)>, pub(crate) pending_deleted_docs: Vec, pub(crate) doc_sync: DocSyncCoordinator, + #[cfg(not(target_family = "wasm"))] + pub(crate) clock_receipts: ClockReceipts, media_replica_seed: String, next_media_seq: u64, } @@ -182,11 +192,14 @@ impl WorkspaceSession { unhydrated_pending_deltas: BTreeMap::new(), has_sqlite_backing: false, unverified_remote_docs: VecDeque::new(), + evicted_remote_doc_ids: VecDeque::new(), active_doc_id: None, blobs: BTreeMap::new(), pending_persist_updates: Vec::new(), pending_deleted_docs: Vec::new(), doc_sync: DocSyncCoordinator::new(), + #[cfg(not(target_family = "wasm"))] + clock_receipts: ClockReceipts::default(), media_replica_seed, next_media_seq: 1, }) @@ -391,7 +404,7 @@ impl WorkspaceSession { } self.directory.set_now_ms(now_ms); for u in self.directory.drain_pending_updates() { - self.pending_persist_updates.push((u, None)); + self.pending_persist_updates.push((u, RowStamp::UNPROVEN)); } let summary = self .directory @@ -495,7 +508,7 @@ impl WorkspaceSession { doc_id: doc_id.clone(), update: delta.update, }, - delta.timestamp_ms, + RowStamp::remote(delta.timestamp_ms), ); } } @@ -511,14 +524,6 @@ impl WorkspaceSession { self.open_docs.insert(doc_id, page); } - pub(crate) fn push_stamped_persist_update( - &mut self, - update: PendingDocUpdate, - timestamp_ms: Option, - ) { - self.pending_persist_updates.push((update, timestamp_ms)); - } - pub(crate) fn local_doc_update_v1(&self, doc_id: &str) -> Option> { self.open_docs .get(doc_id) @@ -605,26 +610,6 @@ impl WorkspaceSession { .and_then(|p| p.encode_update_v1().ok()) } - /// Number of queued document updates waiting to be flushed to SQLite WAL. - pub fn pending_persist_count(&self) -> usize { - self.directory.lock_directory().db().pending_updates().len() - + self.pending_persist_updates.len() - } - - #[cfg(not(target_family = "wasm"))] - pub(crate) fn drain_stamped_persist_updates(&mut self) -> Vec<(PendingDocUpdate, Option)> { - let mut out: Vec<(PendingDocUpdate, Option)> = self - .directory - .lock_directory() - .db_mut() - .drain_pending_updates() - .into_iter() - .map(|u| (u, None)) - .collect(); - out.append(&mut self.pending_persist_updates); - out - } - /// Query linked documents via [`WorkspaceDocDirectory`] (`@` mention search). pub fn query_linked_docs(&self, req: &DocQueryRequest) -> Result { self.directory.query_linked_docs(req) @@ -678,7 +663,7 @@ impl WorkspaceSession { inserted.blob.key.clone(), (inserted.blob.clone(), input.bytes.clone()), ); - let wm = self.push_local_doc_update( + let push = self.push_local_doc_update( doc_id, inserted.update_v1.clone(), PushDocIntent::Update, @@ -690,7 +675,7 @@ impl WorkspaceSession { doc_id: doc_id.to_string(), update: inserted.update_v1.clone(), }, - Some(wm), + push.stamp(), ); } Ok(inserted) @@ -712,7 +697,7 @@ impl WorkspaceSession { ); } if let Some(c) = commit { - let wm = self.push_local_doc_update( + let push = self.push_local_doc_update( doc_id, c.update.clone(), PushDocIntent::Update, @@ -724,7 +709,7 @@ impl WorkspaceSession { doc_id: doc_id.to_string(), update: c.update.clone(), }, - Some(wm), + push.stamp(), ); } return Ok(Some(c.update)); @@ -748,51 +733,4 @@ impl WorkspaceSession { pub fn blob_bytes(&self, key: &str) -> Option<&[u8]> { self.blobs.get(key).map(|(_, bytes)| bytes.as_slice()) } - - /// Number of unhydrated documents currently holding staged deltas in memory. - pub fn unhydrated_pending_delta_doc_count(&self) -> usize { - self.unhydrated_pending_deltas.len() - } - - /// Total staged delta bytes currently resident for unhydrated documents. - pub fn unhydrated_pending_delta_bytes(&self) -> usize { - self.unhydrated_pending_deltas - .values() - .flat_map(|deltas| deltas.iter()) - .map(|d| d.update.len()) - .sum() - } - - /// Stage a passive remote delta of a document unknown to this SQLite-backed session: another - /// writer can have added it, so the next flush keeps it only if SQLite has the document. - /// Above the limits, the oldest document loses its staged remote deltas and needs a reload. - pub(crate) fn stage_unverified_remote_delta(&mut self, doc_id: &str, update: &[u8]) { - let docs = &mut self.unverified_remote_docs; - match docs.iter_mut().find(|(id, _)| id == doc_id) { - Some((_, bytes)) => *bytes += update.len(), - None => docs.push_back((doc_id.to_string(), update.len())), - } - self.unhydrated_pending_deltas - .entry(doc_id.to_string()) - .or_default() - .push(UnhydratedDelta { - update: update.to_vec(), - timestamp_ms: None, - origin: UnhydratedDeltaOrigin::Remote, - }); - while self.unverified_remote_docs.len() > MAX_UNVERIFIED_REMOTE_DOCS - || self - .unverified_remote_docs - .iter() - .map(|(_, b)| b) - .sum::() - > MAX_UNVERIFIED_REMOTE_BYTES - { - let Some((evicted, _)) = self.unverified_remote_docs.pop_front() else { - break; - }; - self.drop_remote_unhydrated_deltas(&evicted); - self.doc_sync.mark_stale_reload_needed(&evicted); - } - } } diff --git a/packages/frontend/client/src/session_ops/mod.rs b/packages/frontend/client/src/session_ops/mod.rs index 8d0abee27c..61c453d575 100644 --- a/packages/frontend/client/src/session_ops/mod.rs +++ b/packages/frontend/client/src/session_ops/mod.rs @@ -3,6 +3,12 @@ //! placement live in `organize`. mod organize; +mod persist; +mod remote_apply; + +#[cfg(not(target_family = "wasm"))] +pub(crate) use persist::RowProof; +pub(crate) use persist::RowStamp; use affine_store::{ sync::{EngineIoOutput, PushDocIntent, SpaceSyncOutbound, SpaceSyncState}, @@ -13,7 +19,7 @@ use blocksuite_playground_doc::read::BlockContent; use crate::{ ClientError, ClientResult, - doc_sync::driver::{is_non_empty_update, parse_db_table_doc_id}, + doc_sync::driver::is_non_empty_update, host::HostBridge, session::{ UnhydratedDelta, UnhydratedDeltaOrigin, WorkspaceSession, rotate_page_client_if_required, @@ -95,23 +101,9 @@ impl WorkspaceSession { let _ = host.ws_close(handle); } } - pub(crate) fn push_local_doc_update( - &mut self, - doc_id: impl Into, - update: Vec, - intent: PushDocIntent, - now_ms: i64, - ) -> ClientResult { - let doc_id = doc_id.into(); - let watermark_ms = self.doc_sync.next_local_clock_ms(&doc_id, now_ms); - self.sync - .push_doc_update(doc_id.clone(), update, intent, now_ms)?; - self.doc_sync.mark_local_write(&doc_id); - Ok(watermark_ms) - } /// Resend existing local state of `doc_id` for cold-start reconciliation. The push writes no - /// new SQLite row, so it never advances the local clock of the document. + /// new SQLite row. pub(crate) fn push_reconcile_doc_update( &mut self, doc_id: &str, @@ -125,17 +117,6 @@ impl WorkspaceSession { Ok(()) } - pub(crate) fn drain_directory_updates_stamped(&mut self, watermark_ms: i64) { - let updates = self - .directory - .lock_directory() - .db_mut() - .drain_pending_updates(); - for u in updates { - self.pending_persist_updates.push((u, Some(watermark_ms))); - } - } - /// Merge authoritative local Yjs V1 CRDT update bytes (for example produced by an embedded /// `PlaygroundView`) into this session's `PageDocSession`, updating the directory snapshot, /// `SpaceSyncEngine`, and `pending_persist_updates` whenever the encoded CRDT state @@ -161,7 +142,7 @@ impl WorkspaceSession { let Some(page) = page_opt else { // Document is not yet hydrated from SQLite; stage the delta without inserting an // empty PageDocSession into `open_docs` so later hydration merges with the disk base. - let wm = self.push_local_doc_update( + let push = self.push_local_doc_update( doc_id, update_v1.to_vec(), PushDocIntent::Update, @@ -172,7 +153,7 @@ impl WorkspaceSession { .or_default() .push(UnhydratedDelta { update: update_v1.to_vec(), - timestamp_ms: Some(wm), + timestamp_ms: Some(now_ms), origin: UnhydratedDeltaOrigin::Local, }); self.push_stamped_persist_update( @@ -180,7 +161,7 @@ impl WorkspaceSession { doc_id: doc_id.to_string(), update: update_v1.to_vec(), }, - Some(wm), + push.stamp(), ); return Ok(true); }; @@ -231,13 +212,13 @@ impl WorkspaceSession { } }; if let Some(bytes) = root_update { - let root_wm = self.push_local_doc_update( + let root_push = self.push_local_doc_update( self.space_id.clone(), bytes, PushDocIntent::Update, now_ms, )?; - self.drain_directory_updates_stamped(root_wm); + self.drain_directory_updates_stamped(root_push); } } self.directory.upsert_doc_snapshot( @@ -246,13 +227,14 @@ impl WorkspaceSession { page_rev, ); } - let wm = self.push_local_doc_update(doc_id, diff.clone(), PushDocIntent::Update, now_ms)?; + let push = + self.push_local_doc_update(doc_id, diff.clone(), PushDocIntent::Update, now_ms)?; self.push_stamped_persist_update( PendingDocUpdate { doc_id: doc_id.to_string(), update: diff, }, - Some(wm), + push.stamp(), ); Ok(true) } @@ -274,13 +256,13 @@ impl WorkspaceSession { .map_err(|e| ClientError::Store(e.to_string()))? }; if let Some(bytes) = root_update { - let wm = self.push_local_doc_update( + let push = self.push_local_doc_update( self.space_id.clone(), bytes, PushDocIntent::Update, now_ms, )?; - self.drain_directory_updates_stamped(wm); + self.drain_directory_updates_stamped(push); changed = true; } if let Some(page) = self.open_docs.get_mut(doc_id) { @@ -328,7 +310,7 @@ impl WorkspaceSession { std::sync::Arc::new(updated_snap), page_rev, ); - let wm = self.push_local_doc_update( + let push = self.push_local_doc_update( doc_id, diff.clone(), PushDocIntent::Update, @@ -339,7 +321,7 @@ impl WorkspaceSession { doc_id: doc_id.to_string(), update: diff, }, - Some(wm), + push.stamp(), ); changed = true; } @@ -357,13 +339,13 @@ impl WorkspaceSession { .map_err(|e| ClientError::Store(e.to_string()))? }; if let Some(bytes) = root_update { - let wm = self.push_local_doc_update( + let push = self.push_local_doc_update( self.space_id.clone(), bytes, PushDocIntent::Update, now_ms, )?; - self.drain_directory_updates_stamped(wm); + self.drain_directory_updates_stamped(push); return Ok(true); } Ok(false) @@ -378,13 +360,13 @@ impl WorkspaceSession { .map_err(|e| ClientError::Store(e.to_string()))? }; if let Some(bytes) = root_update { - let wm = self.push_local_doc_update( + let push = self.push_local_doc_update( self.space_id.clone(), bytes, PushDocIntent::Update, now_ms, )?; - self.drain_directory_updates_stamped(wm); + self.drain_directory_updates_stamped(push); return Ok(true); } Ok(false) @@ -406,6 +388,9 @@ impl WorkspaceSession { self.disk_baseline_doc_ids.remove(doc_id); self.unhydrated_pending_deltas.remove(doc_id); self.forget_unverified_remote_doc(doc_id); + self.evicted_remote_doc_ids.retain(|id| id != doc_id); + #[cfg(not(target_family = "wasm"))] + self.clock_receipts.forget(doc_id); self.sync.discard_offline_writes_for_doc(doc_id); self.doc_sync.mark_permanently_deleted(doc_id); if self.active_doc_id.as_deref() == Some(doc_id) { @@ -422,13 +407,13 @@ impl WorkspaceSession { self.doc_sync.mark_delete_in_flight(doc_id); } if let Some(bytes) = root_update { - let wm = self.push_local_doc_update( + let push = self.push_local_doc_update( self.space_id.clone(), bytes, PushDocIntent::Update, now_ms, )?; - self.drain_directory_updates_stamped(wm); + self.drain_directory_updates_stamped(push); return Ok(true); } Ok(false) @@ -445,8 +430,8 @@ impl WorkspaceSession { } #[cfg(not(target_family = "wasm"))] - pub(crate) fn seed_unpushed_docs(&mut self, doc_clocks: Vec<(String, i64)>) { - self.doc_sync.seed_unpushed_docs(doc_clocks); + pub(crate) fn seed_unpushed_docs(&mut self, doc_ids: impl IntoIterator) { + self.doc_sync.seed_unpushed_docs(doc_ids); } #[cfg(not(target_family = "wasm"))] @@ -495,298 +480,14 @@ impl WorkspaceSession { self.unopened_unpushed_docs.remove(doc_id) } - #[cfg(not(target_family = "wasm"))] - pub(crate) fn has_unhydrated_pending_deltas(&self, doc_id: &str) -> bool { - self.unhydrated_pending_deltas - .get(doc_id) - .is_some_and(|deltas| !deltas.is_empty()) - } - - #[cfg(not(target_family = "wasm"))] - pub(crate) fn seed_disk_baseline_docs(&mut self, doc_ids: impl IntoIterator) { - for doc_id in doc_ids { - if !self.doc_sync.is_permanently_deleted(&doc_id) - && doc_id != self.space_id - && parse_db_table_doc_id(&doc_id).is_none() - { - self.disk_baseline_doc_ids.insert(doc_id); - } - } - } - - pub(crate) fn has_disk_baseline(&self, doc_id: &str) -> bool { - self.disk_baseline_doc_ids.contains(doc_id) - } - - pub(crate) fn has_local_unhydrated_deltas(&self, doc_id: &str) -> bool { - self.unhydrated_pending_deltas - .get(doc_id) - .is_some_and(|deltas| { - deltas - .iter() - .any(|delta| delta.origin == UnhydratedDeltaOrigin::Local) - }) - } - - #[cfg(not(target_family = "wasm"))] - pub(crate) fn replay_unhydrated_deltas_into( - &self, - doc_id: &str, - page: &mut blocksuite_playground_doc::session::PageDocSession, - ) { - if let Some(deltas) = self.unhydrated_pending_deltas.get(doc_id) { - for delta in deltas { - if is_non_empty_update(&delta.update) - && page.apply_remote_update_v1(&delta.update).is_ok() - { - let _ = rotate_page_client_if_required(page); - } - } - } - } - - pub(crate) fn forget_unverified_remote_doc(&mut self, doc_id: &str) { - self.unverified_remote_docs.retain(|(id, _)| id != doc_id); - } - - /// Drop the staged remote deltas of `doc_id` and keep its staged local deltas. - pub(crate) fn drop_remote_unhydrated_deltas(&mut self, doc_id: &str) { - self.forget_unverified_remote_doc(doc_id); - if let Some(deltas) = self.unhydrated_pending_deltas.get_mut(doc_id) { - deltas.retain(|delta| delta.origin == UnhydratedDeltaOrigin::Local); - if deltas.is_empty() { - self.unhydrated_pending_deltas.remove(doc_id); - } - } - } - pub fn is_permanently_deleted(&self, doc_id: &str) -> bool { self.doc_sync.is_permanently_deleted(doc_id) } - pub(crate) fn apply_remote_update_bytes( - &mut self, - doc_id: &str, - update_v1: &[u8], - now_ms: i64, - ) -> ClientResult> { - if !is_non_empty_update(update_v1) { - return Ok(None); - } - if doc_id == self.space_id { - self.directory - .lock_directory() - .db_mut() - .apply_remote_root_update(update_v1)?; - let wm = self.doc_sync.next_local_clock_ms(doc_id, now_ms); - self.push_stamped_persist_update( - PendingDocUpdate { - doc_id: doc_id.to_string(), - update: update_v1.to_vec(), - }, - Some(wm), - ); - return Ok(Some(wm)); - } - if doc_id.starts_with("db$") { - return self.apply_remote_db_table_update(doc_id, update_v1, now_ms); - } - if self.doc_sync.is_permanently_deleted(doc_id) { - return Ok(None); - } - if let Some(page) = self.open_docs.get_mut(doc_id) { - let wm = self.doc_sync.next_local_clock_ms(doc_id, now_ms); - page.apply_remote_update_v1(update_v1) - .map_err(|e| ClientError::Store(e.to_string()))?; - rotate_page_client_if_required(page)?; - if let Ok(snap) = page.read_page_snapshot() { - self.directory.upsert_doc_snapshot( - &EditorDocId::new(doc_id), - std::sync::Arc::new(snap), - page.revision(), - ); - } - self.push_stamped_persist_update( - PendingDocUpdate { - doc_id: doc_id.to_string(), - update: update_v1.to_vec(), - }, - Some(wm), - ); - Ok(Some(wm)) - } else if let Some(page) = self.unopened_unpushed_docs.get_mut(doc_id) { - let wm = self.doc_sync.next_local_clock_ms(doc_id, now_ms); - page.apply_remote_update_v1(update_v1) - .map_err(|e| ClientError::Store(e.to_string()))?; - rotate_page_client_if_required(page)?; - self.push_stamped_persist_update( - PendingDocUpdate { - doc_id: doc_id.to_string(), - update: update_v1.to_vec(), - }, - Some(wm), - ); - Ok(Some(wm)) - } else if self.has_disk_baseline(doc_id) || self.has_local_unhydrated_deltas(doc_id) { - let wm = self.doc_sync.next_local_clock_ms(doc_id, now_ms); - self.unhydrated_pending_deltas - .entry(doc_id.to_string()) - .or_default() - .push(UnhydratedDelta { - update: update_v1.to_vec(), - timestamp_ms: Some(wm), - origin: UnhydratedDeltaOrigin::Remote, - }); - Ok(Some(wm)) - } else if self.doc_sync.is_load_in_flight(doc_id) { - self.doc_sync.mark_stale_reload_needed(doc_id); - Ok(None) - } else { - // A SQLite-backed session cannot read SQLite here, so the next flush checks whether - // another writer added the document. A session in memory has no other writer. - if self.has_sqlite_backing { - self.stage_unverified_remote_delta(doc_id, update_v1); - } - Ok(None) - } - } - - #[cfg(not(target_family = "wasm"))] - pub(crate) fn unhydrated_delta_doc_ids(&self) -> Vec { - self.unhydrated_pending_deltas - .iter() - .filter(|(_, deltas)| { - deltas - .iter() - .any(|delta| delta.origin == UnhydratedDeltaOrigin::Remote) - }) - .map(|(id, _)| id.clone()) - .collect() - } - - #[cfg(not(target_family = "wasm"))] - pub(crate) fn drain_unhydrated_deltas_for_docs( - &mut self, - doc_ids: &[String], - ) -> Vec<(PendingDocUpdate, Option)> { - let mut out = Vec::new(); - for id in doc_ids { - self.forget_unverified_remote_doc(id); - if let Some(deltas) = self.unhydrated_pending_deltas.get_mut(id) { - let mut local_only = Vec::new(); - for delta in std::mem::take(deltas) { - match delta.origin { - UnhydratedDeltaOrigin::Remote => out.push(( - PendingDocUpdate { - doc_id: id.clone(), - update: delta.update, - }, - delta.timestamp_ms, - )), - UnhydratedDeltaOrigin::Local => local_only.push(delta), - } - } - if local_only.is_empty() { - self.unhydrated_pending_deltas.remove(id); - } else { - *deltas = local_only; - } - } - } - out - } - - #[cfg(not(target_family = "wasm"))] - pub(crate) fn discard_remote_unhydrated_deltas_without_baseline( - &mut self, - missing_doc_ids: &[String], - ) { - for id in missing_doc_ids { - self.disk_baseline_doc_ids.remove(id); - self.drop_remote_unhydrated_deltas(id); - } - } - - /// Restore drained deletion, tombstone-clear, server-held, and update queues after a failed - /// or cancelled atomic SQLite flush so a subsequent retry commits the exact same mutations - /// without loss. - #[cfg(not(target_family = "wasm"))] - pub(crate) fn restore_failed_flush( - &mut self, - mut deleted_docs: Vec, - acked_remote_deletes: Vec, - server_held_docs: Vec, - mut updates: Vec<(PendingDocUpdate, Option)>, - ) { - for existing in std::mem::take(&mut self.pending_deleted_docs) { - if !deleted_docs.iter().any(|d| d == &existing) { - deleted_docs.push(existing); - } - } - self.pending_deleted_docs = deleted_docs; - self.doc_sync - .restore_acked_deletes_after_failed_flush(acked_remote_deletes); - self.doc_sync.restore_server_held_docs(server_held_docs); - let mut tail = std::mem::take(&mut self.pending_persist_updates); - updates.append(&mut tail); - self.pending_persist_updates = updates; - } - - /// Drain document IDs permanently deleted since the last SQLite flush. - pub fn drain_pending_deleted_docs(&mut self) -> Vec { - std::mem::take(&mut self.pending_deleted_docs) - } - #[cfg(not(target_family = "wasm"))] pub(crate) fn drain_acked_remote_deletes_for_flush(&mut self) -> Vec { self.doc_sync.drain_acked_deletes_for_flush() } - - /// Encode the in-memory state of each document that the server holds in whole, for the next - /// flush to advance `peer_clocks.pushed_clock`. A document without in-memory state stays - /// pending, and a later session reconciles it. - #[cfg(not(target_family = "wasm"))] - pub(crate) fn drain_server_held_states_for_flush(&mut self) -> Vec<(String, Vec)> { - self.doc_sync - .drain_server_held_docs() - .into_iter() - .filter_map(|id| { - let state = self.local_doc_state_v1(&id)?; - Some((id, state)) - }) - .collect() - } - - /// Enqueue externally returned `PendingDocUpdate`s so the next - /// `SqliteWorkspaceStore::flush_session_mutations` persists them atomically to SQLite WAL. - pub fn enqueue_pending_persist_updates(&mut self, updates: Vec) { - for u in updates { - self.pending_persist_updates.push((u, None)); - } - } - - pub(crate) fn apply_remote_db_table_update( - &mut self, - doc_id: &str, - update_v1: &[u8], - now_ms: i64, - ) -> ClientResult> { - if let Some(table) = parse_db_table_doc_id(doc_id) { - self.directory - .lock_directory() - .db_mut() - .load_db_table(table, update_v1)?; - } - let wm = self.doc_sync.next_local_clock_ms(doc_id, now_ms); - self.push_stamped_persist_update( - PendingDocUpdate { - doc_id: doc_id.to_string(), - update: update_v1.to_vec(), - }, - Some(wm), - ); - Ok(Some(wm)) - } } #[cfg(test)] diff --git a/packages/frontend/client/src/session_ops/persist.rs b/packages/frontend/client/src/session_ops/persist.rs new file mode 100644 index 0000000000..9d556e292e --- /dev/null +++ b/packages/frontend/client/src/session_ops/persist.rs @@ -0,0 +1,179 @@ +//! Queue of CRDT updates waiting for the next SQLite flush, with the event time and the sync +//! proof of each row. + +use std::hash::{DefaultHasher, Hash, Hasher}; + +use affine_store::{sync::PushDocIntent, workspace_db::PendingDocUpdate}; + +use crate::{ClientResult, session::WorkspaceSession}; + +/// How the server can come to hold the content of a queued row. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum RowProof { + /// Nothing ties the row to a push. Only a content check or a reconciliation settles it. + Unproven, + /// The content came from the server. + Remote, + /// The content went out in the local push with this sequence number. + Pushed(u64), +} + +/// Event time and sync proof of one queued row. SQLite gives the row its clock slot: the event +/// time or 1 ms after the document clock, whichever is later. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct RowStamp { + pub(crate) event_ms: Option, + pub(crate) proof: RowProof, +} + +impl RowStamp { + pub(crate) const UNPROVEN: Self = Self { + event_ms: None, + proof: RowProof::Unproven, + }; + + pub(crate) const fn remote(event_ms: Option) -> Self { + Self { + event_ms, + proof: RowProof::Remote, + } + } +} + +fn update_digest(doc_id: &str, update: &[u8]) -> u64 { + let mut hasher = DefaultHasher::new(); + doc_id.hash(&mut hasher); + update.hash(&mut hasher); + hasher.finish() +} + +/// A local update that the session handed to the sync engine. +#[derive(Clone, Debug)] +pub(crate) struct LocalPush { + event_ms: i64, + seq: u64, + digest: u64, +} + +impl LocalPush { + /// Stamp for a row that holds exactly the pushed update. + pub(crate) fn stamp(&self) -> RowStamp { + RowStamp { + event_ms: Some(self.event_ms), + proof: RowProof::Pushed(self.seq), + } + } + + /// Stamp for `update`: proven by this push only when it is the pushed update. + fn stamp_for(&self, update: &PendingDocUpdate) -> RowStamp { + if update_digest(&update.doc_id, &update.update) == self.digest { + self.stamp() + } else { + RowStamp { + event_ms: Some(self.event_ms), + proof: RowProof::Unproven, + } + } + } +} + +impl WorkspaceSession { + pub(crate) fn push_local_doc_update( + &mut self, + doc_id: impl Into, + update: Vec, + intent: PushDocIntent, + now_ms: i64, + ) -> ClientResult { + let doc_id = doc_id.into(); + let digest = update_digest(&doc_id, &update); + self.sync + .push_doc_update(doc_id.clone(), update, intent, now_ms)?; + let seq = self.doc_sync.mark_local_write(&doc_id); + Ok(LocalPush { + event_ms: now_ms, + seq, + digest, + }) + } + + /// Queue the pending directory updates for SQLite. An update that `push` sent is proven by + /// it, and any other one stays unproven. + pub(crate) fn drain_directory_updates_stamped(&mut self, push: LocalPush) { + let updates = self + .directory + .lock_directory() + .db_mut() + .drain_pending_updates(); + for u in updates { + let stamp = push.stamp_for(&u); + self.pending_persist_updates.push((u, stamp)); + } + } + + pub(crate) fn push_stamped_persist_update( + &mut self, + update: PendingDocUpdate, + stamp: RowStamp, + ) { + self.pending_persist_updates.push((update, stamp)); + } + + /// Number of queued document updates waiting to be flushed to SQLite WAL. + pub fn pending_persist_count(&self) -> usize { + self.directory.lock_directory().db().pending_updates().len() + + self.pending_persist_updates.len() + } + + #[cfg(not(target_family = "wasm"))] + pub(crate) fn drain_stamped_persist_updates(&mut self) -> Vec<(PendingDocUpdate, RowStamp)> { + let mut out: Vec<(PendingDocUpdate, RowStamp)> = self + .directory + .lock_directory() + .db_mut() + .drain_pending_updates() + .into_iter() + .map(|u| (u, RowStamp::UNPROVEN)) + .collect(); + out.append(&mut self.pending_persist_updates); + out + } + + /// Enqueue externally returned `PendingDocUpdate`s so the next + /// `SqliteWorkspaceStore::flush_session_mutations` persists them atomically to SQLite WAL. + pub fn enqueue_pending_persist_updates(&mut self, updates: Vec) { + for u in updates { + self.pending_persist_updates.push((u, RowStamp::UNPROVEN)); + } + } + + /// Restore drained deletion, tombstone-clear, server-held, and update queues after a failed + /// or cancelled atomic SQLite flush so a subsequent retry commits the exact same mutations + /// without loss. + #[cfg(not(target_family = "wasm"))] + pub(crate) fn restore_failed_flush( + &mut self, + mut deleted_docs: Vec, + acked_remote_deletes: Vec, + server_held_docs: Vec, + mut updates: Vec<(PendingDocUpdate, RowStamp)>, + ) { + for existing in std::mem::take(&mut self.pending_deleted_docs) { + if !deleted_docs.iter().any(|d| d == &existing) { + deleted_docs.push(existing); + } + } + self.pending_deleted_docs = deleted_docs; + self.doc_sync + .restore_acked_deletes_after_failed_flush(acked_remote_deletes); + self.doc_sync.restore_server_held_docs(server_held_docs); + let mut tail = std::mem::take(&mut self.pending_persist_updates); + updates.append(&mut tail); + self.pending_persist_updates = updates; + } + + /// Drain document IDs permanently deleted since the last SQLite flush. + pub fn drain_pending_deleted_docs(&mut self) -> Vec { + std::mem::take(&mut self.pending_deleted_docs) + } +} diff --git a/packages/frontend/client/src/session_ops/remote_apply.rs b/packages/frontend/client/src/session_ops/remote_apply.rs new file mode 100644 index 0000000000..e03902640d --- /dev/null +++ b/packages/frontend/client/src/session_ops/remote_apply.rs @@ -0,0 +1,307 @@ +//! Remote CRDT updates on [`WorkspaceSession`], and the deltas that the session stages for +//! documents it has not loaded. + +use affine_store::workspace_db::PendingDocUpdate; +use blocksuite_editor::EditorDocId; + +use super::persist::RowStamp; +use crate::{ + ClientError, ClientResult, + doc_sync::driver::{is_non_empty_update, parse_db_table_doc_id}, + session::{ + MAX_EVICTED_REMOTE_DOCS, MAX_UNVERIFIED_REMOTE_BYTES, MAX_UNVERIFIED_REMOTE_DOCS, + UnhydratedDelta, UnhydratedDeltaOrigin, WorkspaceSession, rotate_page_client_if_required, + }, +}; + +impl WorkspaceSession { + #[cfg(not(target_family = "wasm"))] + pub(crate) fn has_unhydrated_pending_deltas(&self, doc_id: &str) -> bool { + self.unhydrated_pending_deltas + .get(doc_id) + .is_some_and(|deltas| !deltas.is_empty()) + } + + #[cfg(not(target_family = "wasm"))] + pub(crate) fn seed_disk_baseline_docs(&mut self, doc_ids: impl IntoIterator) { + for doc_id in doc_ids { + if !self.doc_sync.is_permanently_deleted(&doc_id) + && doc_id != self.space_id + && parse_db_table_doc_id(&doc_id).is_none() + { + self.disk_baseline_doc_ids.insert(doc_id); + } + } + } + + pub(crate) fn has_disk_baseline(&self, doc_id: &str) -> bool { + self.disk_baseline_doc_ids.contains(doc_id) + } + + pub(crate) fn has_local_unhydrated_deltas(&self, doc_id: &str) -> bool { + self.unhydrated_pending_deltas + .get(doc_id) + .is_some_and(|deltas| { + deltas + .iter() + .any(|delta| delta.origin == UnhydratedDeltaOrigin::Local) + }) + } + + #[cfg(not(target_family = "wasm"))] + pub(crate) fn replay_unhydrated_deltas_into( + &self, + doc_id: &str, + page: &mut blocksuite_playground_doc::session::PageDocSession, + ) { + if let Some(deltas) = self.unhydrated_pending_deltas.get(doc_id) { + for delta in deltas { + if is_non_empty_update(&delta.update) + && page.apply_remote_update_v1(&delta.update).is_ok() + { + let _ = rotate_page_client_if_required(page); + } + } + } + } + + pub(crate) fn forget_unverified_remote_doc(&mut self, doc_id: &str) { + self.unverified_remote_docs.retain(|(id, _)| id != doc_id); + } + + /// Drop the staged remote deltas of `doc_id` and keep its staged local deltas. + pub(crate) fn drop_remote_unhydrated_deltas(&mut self, doc_id: &str) { + self.forget_unverified_remote_doc(doc_id); + if let Some(deltas) = self.unhydrated_pending_deltas.get_mut(doc_id) { + deltas.retain(|delta| delta.origin == UnhydratedDeltaOrigin::Local); + if deltas.is_empty() { + self.unhydrated_pending_deltas.remove(doc_id); + } + } + } + + /// Number of unhydrated documents currently holding staged deltas in memory. + pub fn unhydrated_pending_delta_doc_count(&self) -> usize { + self.unhydrated_pending_deltas.len() + } + + /// Total staged delta bytes currently resident for unhydrated documents. + pub fn unhydrated_pending_delta_bytes(&self) -> usize { + self.unhydrated_pending_deltas + .values() + .flat_map(|deltas| deltas.iter()) + .map(|d| d.update.len()) + .sum() + } + + /// Stage a passive remote delta of a document unknown to this SQLite-backed session: another + /// writer can have added it, so the next flush keeps it only if SQLite has the document. + /// Above the limits, the oldest document loses its staged remote deltas, and the next flush + /// looks it up in SQLite by ID to load it again from the server. + fn stage_unverified_remote_delta(&mut self, doc_id: &str, update: &[u8]) { + let docs = &mut self.unverified_remote_docs; + match docs.iter_mut().find(|(id, _)| id == doc_id) { + Some((_, bytes)) => *bytes += update.len(), + None => docs.push_back((doc_id.to_string(), update.len())), + } + self.unhydrated_pending_deltas + .entry(doc_id.to_string()) + .or_default() + .push(UnhydratedDelta { + update: update.to_vec(), + timestamp_ms: None, + origin: UnhydratedDeltaOrigin::Remote, + }); + while self.unverified_remote_docs.len() > MAX_UNVERIFIED_REMOTE_DOCS + || self + .unverified_remote_docs + .iter() + .map(|(_, b)| b) + .sum::() + > MAX_UNVERIFIED_REMOTE_BYTES + { + let Some((evicted, _)) = self.unverified_remote_docs.pop_front() else { + break; + }; + self.drop_remote_unhydrated_deltas(&evicted); + if !self.evicted_remote_doc_ids.contains(&evicted) { + if self.evicted_remote_doc_ids.len() == MAX_EVICTED_REMOTE_DOCS { + self.evicted_remote_doc_ids.pop_front(); + } + self.evicted_remote_doc_ids.push_back(evicted); + } + } + } + + /// Number of document IDs whose staged remote deltas were dropped before a flush could look + /// them up in SQLite. + pub fn evicted_remote_doc_count(&self) -> usize { + self.evicted_remote_doc_ids.len() + } + + /// Apply or stage remote `update_v1` of `doc_id`. Returns `true` when the update is applied + /// or staged for SQLite. + pub(crate) fn apply_remote_update_bytes( + &mut self, + doc_id: &str, + update_v1: &[u8], + now_ms: i64, + ) -> ClientResult { + if !is_non_empty_update(update_v1) { + return Ok(false); + } + if doc_id == self.space_id { + self.directory + .lock_directory() + .db_mut() + .apply_remote_root_update(update_v1)?; + self.push_remote_persist_update(doc_id, update_v1, now_ms); + return Ok(true); + } + if doc_id.starts_with("db$") { + return self.apply_remote_db_table_update(doc_id, update_v1, now_ms); + } + if self.doc_sync.is_permanently_deleted(doc_id) { + return Ok(false); + } + if let Some(page) = self.open_docs.get_mut(doc_id) { + page.apply_remote_update_v1(update_v1) + .map_err(|e| ClientError::Store(e.to_string()))?; + rotate_page_client_if_required(page)?; + if let Ok(snap) = page.read_page_snapshot() { + self.directory.upsert_doc_snapshot( + &EditorDocId::new(doc_id), + std::sync::Arc::new(snap), + page.revision(), + ); + } + self.push_remote_persist_update(doc_id, update_v1, now_ms); + Ok(true) + } else if let Some(page) = self.unopened_unpushed_docs.get_mut(doc_id) { + page.apply_remote_update_v1(update_v1) + .map_err(|e| ClientError::Store(e.to_string()))?; + rotate_page_client_if_required(page)?; + self.push_remote_persist_update(doc_id, update_v1, now_ms); + Ok(true) + } else if self.has_disk_baseline(doc_id) || self.has_local_unhydrated_deltas(doc_id) { + self.unhydrated_pending_deltas + .entry(doc_id.to_string()) + .or_default() + .push(UnhydratedDelta { + update: update_v1.to_vec(), + timestamp_ms: Some(now_ms), + origin: UnhydratedDeltaOrigin::Remote, + }); + Ok(true) + } else if self.doc_sync.is_load_in_flight(doc_id) { + self.doc_sync.mark_stale_reload_needed(doc_id); + Ok(false) + } else { + // A SQLite-backed session cannot read SQLite here, so the next flush checks whether + // another writer added the document. A session in memory has no other writer. + if self.has_sqlite_backing { + self.stage_unverified_remote_delta(doc_id, update_v1); + } + Ok(false) + } + } + + fn push_remote_persist_update(&mut self, doc_id: &str, update_v1: &[u8], now_ms: i64) { + self.push_stamped_persist_update( + PendingDocUpdate { + doc_id: doc_id.to_string(), + update: update_v1.to_vec(), + }, + RowStamp::remote(Some(now_ms)), + ); + } + + #[cfg(not(target_family = "wasm"))] + pub(crate) fn unhydrated_delta_doc_ids(&self) -> Vec { + self.unhydrated_pending_deltas + .iter() + .filter(|(_, deltas)| { + deltas + .iter() + .any(|delta| delta.origin == UnhydratedDeltaOrigin::Remote) + }) + .map(|(id, _)| id.clone()) + .collect() + } + + #[cfg(not(target_family = "wasm"))] + pub(crate) fn drain_unhydrated_deltas_for_docs( + &mut self, + doc_ids: &[String], + ) -> Vec<(PendingDocUpdate, RowStamp)> { + let mut out = Vec::new(); + for id in doc_ids { + self.forget_unverified_remote_doc(id); + if let Some(deltas) = self.unhydrated_pending_deltas.get_mut(id) { + let mut local_only = Vec::new(); + for delta in std::mem::take(deltas) { + match delta.origin { + UnhydratedDeltaOrigin::Remote => out.push(( + PendingDocUpdate { + doc_id: id.clone(), + update: delta.update, + }, + RowStamp::remote(delta.timestamp_ms), + )), + UnhydratedDeltaOrigin::Local => local_only.push(delta), + } + } + if local_only.is_empty() { + self.unhydrated_pending_deltas.remove(id); + } else { + *deltas = local_only; + } + } + } + out + } + + #[cfg(not(target_family = "wasm"))] + pub(crate) fn discard_remote_unhydrated_deltas_without_baseline( + &mut self, + missing_doc_ids: &[String], + ) { + for id in missing_doc_ids { + self.disk_baseline_doc_ids.remove(id); + self.drop_remote_unhydrated_deltas(id); + } + } + + /// Settle the evicted document IDs after a flush looked them all up in SQLite. A document + /// that SQLite has (another writer added it) becomes a disk document that the session loads + /// and reconciles with the server, so the dropped remote changes come back with that load. + /// The other IDs are dropped. + #[cfg(not(target_family = "wasm"))] + pub(crate) fn settle_evicted_remote_docs( + &mut self, + in_sqlite: &std::collections::HashSet, + ) { + let found: Vec = std::mem::take(&mut self.evicted_remote_doc_ids) + .into_iter() + .filter(|id| in_sqlite.contains(id) && !self.doc_sync.is_permanently_deleted(id)) + .collect(); + self.seed_disk_baseline_docs(found.iter().cloned()); + self.doc_sync.seed_unpushed_docs(found); + } + + pub(crate) fn apply_remote_db_table_update( + &mut self, + doc_id: &str, + update_v1: &[u8], + now_ms: i64, + ) -> ClientResult { + if let Some(table) = parse_db_table_doc_id(doc_id) { + self.directory + .lock_directory() + .db_mut() + .load_db_table(table, update_v1)?; + } + self.push_remote_persist_update(doc_id, update_v1, now_ms); + Ok(true) + } +} diff --git a/packages/frontend/client/src/sqlite_session.rs b/packages/frontend/client/src/sqlite_session.rs index 73c8881226..586ad47d8d 100644 --- a/packages/frontend/client/src/sqlite_session.rs +++ b/packages/frontend/client/src/sqlite_session.rs @@ -7,8 +7,8 @@ use std::path::Path; use affine_store::{ sqlite::{ - BlobRecord, PendingBlobUpload, SetBlob, SqliteDocStorage, millis_to_naive_utc, - naive_utc_to_millis, resolve_workspace_db_path, + BlobRecord, CheckedAdvance, PeerProof, PendingBlobUpload, SetBlob, SqliteDocStorage, + UpdateStamp, millis_to_naive_utc, naive_utc_to_millis, resolve_workspace_db_path, }, sync::SpaceSyncEvent, workspace_db::{PendingDocUpdate, WORKSPACE_DB_TABLE_NAMES, WorkspaceDb, WorkspaceDbTableName}, @@ -20,6 +20,7 @@ use crate::{ blob_ingest::IngestedBlobRecord, host::{HostBridge, HostKind}, session::WorkspaceSession, + session_ops::{RowProof, RowStamp}, }; /// Most unopened subdocs with unpushed local changes that a session holds in memory at once. @@ -191,7 +192,7 @@ impl SqliteWorkspaceStore { }) .collect(); session.seed_persisted_delete_tombstones(pending_remote_deletes); - session.seed_unpushed_docs(unpushed); + session.seed_unpushed_docs(unpushed.into_iter().map(|(doc_id, _)| doc_id)); } session.seed_acked_local_delete_tombstones(all_deleted); session.seed_disk_baseline_docs(disk_docs); @@ -255,7 +256,7 @@ impl SqliteWorkspaceStore { .await? .is_none_or(|pushed| naive_utc_to_millis(pushed.timestamp) < clock_ms) { - session.seed_unpushed_docs(vec![(doc_id.to_string(), clock_ms)]); + session.seed_unpushed_docs([doc_id.to_string()]); } session.register_loaded_doc(doc_id, page); session.ensure_loaded_doc_synced(doc_id, now_ms); @@ -274,8 +275,10 @@ impl SqliteWorkspaceStore { /// Atomically flush all pending CRDT updates, permanent document deletions, durable /// remote-delete tombstones, server-acknowledged tombstone removals, and `pushed_clock` /// advances from `session` inside one `BEGIN IMMEDIATE` SQLite transaction. - /// `pushed_clock` advances only over the SQLite rows that the in-memory state of a document - /// contains while the server holds that whole state, so rows of another writer stay pending. + /// `pushed_clock` moves along the rows that the server holds (remote content and + /// acknowledged local pushes) from row metadata alone. When a row of another writer stops + /// it, a document whose whole in-memory state the server holds gets a content check after + /// the commit, in a separate deferred transaction. /// /// Host contract: while the session is connected, or while it has unsettled sync work or /// unpushed subdocs, the host must call this method periodically even when no new local edit @@ -328,63 +331,75 @@ impl SqliteWorkspaceStore { session: &'a mut WorkspaceSession, deleted: Vec, acked_remote_deletes: Vec, - server_held_states: Vec<(String, Vec)>, - stamped_updates: Vec<(PendingDocUpdate, Option)>, + server_held_docs: Vec, + stamped_updates: Vec<(PendingDocUpdate, RowStamp)>, committed: bool, } impl Drop for FlushRollbackGuard<'_> { fn drop(&mut self) { if !self.committed { - let deleted = std::mem::take(&mut self.deleted); - let acked_remote_deletes = std::mem::take(&mut self.acked_remote_deletes); - let server_held_docs = std::mem::take(&mut self.server_held_states) - .into_iter() - .map(|(id, _)| id) - .collect(); - let stamped_updates = std::mem::take(&mut self.stamped_updates); self.session.restore_failed_flush( - deleted, - acked_remote_deletes, - server_held_docs, - stamped_updates, + std::mem::take(&mut self.deleted), + std::mem::take(&mut self.acked_remote_deletes), + std::mem::take(&mut self.server_held_docs), + std::mem::take(&mut self.stamped_updates), ); } } } - let mut existing_unhydrated = Vec::new(); - let mut missing_unhydrated = Vec::new(); - for doc_id in session.unhydrated_delta_doc_ids() { - if self.storage.get_doc_clock(&doc_id).await?.is_some() { - existing_unhydrated.push(doc_id); - } else { - missing_unhydrated.push(doc_id); - } - } + // Look up the staged and the evicted remote documents in SQLite: another writer can have + // added them after this session started. + let unhydrated = session.unhydrated_delta_doc_ids(); + let lookup: Vec = unhydrated + .iter() + .chain(&session.evicted_remote_doc_ids) + .cloned() + .collect(); + let in_sqlite = if lookup.is_empty() { + Default::default() + } else { + self.storage.existing_doc_ids(&lookup).await? + }; + let (existing_unhydrated, missing_unhydrated): (Vec, Vec) = unhydrated + .into_iter() + .partition(|doc_id| in_sqlite.contains(doc_id)); if !missing_unhydrated.is_empty() { session.discard_remote_unhydrated_deltas_without_baseline(&missing_unhydrated); } + session.settle_evicted_remote_docs(&in_sqlite); let deleted = session.drain_pending_deleted_docs(); let acked_remote_deletes = session.drain_acked_remote_deletes_for_flush(); - let server_held_states = session.drain_server_held_states_for_flush(); let mut stamped_updates = session.drain_stamped_persist_updates(); stamped_updates.extend(session.drain_unhydrated_deltas_for_docs(&existing_unhydrated)); - if deleted.is_empty() - && acked_remote_deletes.is_empty() - && server_held_states.is_empty() - && stamped_updates.is_empty() - { - return Ok(0); - } let sync_peer = peer .map(str::to_string) .unwrap_or_else(|| session.auth().server_id().to_string()); + let has_peer = !sync_peer.trim().is_empty(); + let server_held_docs = if has_peer { + session.doc_sync.drain_server_held_docs() + } else { + Vec::new() + }; + let held_rows = if has_peer { + session.clock_receipts.held_rows(&session.doc_sync) + } else { + Vec::new() + }; + if deleted.is_empty() + && acked_remote_deletes.is_empty() + && server_held_docs.is_empty() + && stamped_updates.is_empty() + && held_rows.is_empty() + { + return Ok(0); + } let mut rollback = FlushRollbackGuard { session, deleted, acked_remote_deletes, - server_held_states, + server_held_docs, stamped_updates, committed: false, }; @@ -404,26 +419,118 @@ impl SqliteWorkspaceStore { .iter() .map(|(u, _)| u.clone()) .collect(); - let update_timestamps: Vec> = - rollback.stamped_updates.iter().map(|(_, ts)| *ts).collect(); - let written = self + let doc_sync = &rollback.session.doc_sync; + let update_stamps: Vec = rollback + .stamped_updates + .iter() + .map(|(u, stamp)| UpdateStamp { + event_ms: stamp.event_ms, + held_by_peer: has_peer + && match stamp.proof { + RowProof::Remote => true, + RowProof::Pushed(seq) => doc_sync.is_push_acked(&u.doc_id, seq), + RowProof::Unproven => false, + }, + }) + .collect(); + let proof = has_peer.then_some(PeerProof { + peer: sync_peer.as_str(), + held_rows: &held_rows, + held_doc_ids: &rollback.server_held_docs, + }); + let commit = self .storage .apply_session_mutations_atomic( &rollback.deleted, &tombstone_remote_deletes, &rollback.acked_remote_deletes, &updates, - &update_timestamps, + &update_stamps, peer, - Some((sync_peer.as_str(), &rollback.server_held_states)), + proof, now_ms, ) .await?; rollback.committed = true; - rollback - .session - .seed_disk_baseline_docs(updates.into_iter().map(|u| u.doc_id)); - Ok(written) + let session = &mut *rollback.session; + if has_peer { + session.clock_receipts.mark_offered(&session.doc_sync); + } + let new_rows = commit + .rows + .iter() + .zip(&rollback.stamped_updates) + .zip(&update_stamps); + for ((row, (_, stamp)), sent) in new_rows { + let push_seq = match stamp.proof { + RowProof::Remote => None, + RowProof::Pushed(seq) => Some(seq), + RowProof::Unproven => continue, + }; + if let Some(row) = row + && has_peer + { + session + .clock_receipts + .record(row.clone(), push_seq, sent.held_by_peer); + } + } + for (doc_id, pushed) in &commit.pushed_clocks { + session + .clock_receipts + .settle(doc_id, &session.doc_sync, |row| { + pushed.is_some_and(|clock| row.timestamp <= clock) + }); + } + session.seed_disk_baseline_docs(updates.into_iter().map(|u| u.doc_id)); + let held_behind: Vec = commit + .behind_doc_ids + .into_iter() + .filter(|doc_id| rollback.server_held_docs.contains(doc_id)) + .collect(); + self.check_held_states(session, &sync_peer, held_behind) + .await?; + Ok(commit.rows.iter().flatten().count()) + } + + /// Move `pushed_clock` of documents that rows of another writer left behind, by checking + /// their rows against the in-memory state that the server holds. Runs after the flush + /// commit, without the write lock. A document whose check meets a concurrent write stays + /// server-held for the next flush. + async fn check_held_states( + &self, + session: &mut WorkspaceSession, + peer: &str, + doc_ids: Vec, + ) -> ClientResult<()> { + let mut remaining = doc_ids.into_iter(); + while let Some(doc_id) = remaining.next() { + let Some(state) = session.local_doc_state_v1(&doc_id) else { + continue; + }; + let outcome = self + .storage + .advance_pushed_clock_with_state(peer, &doc_id, &state) + .await; + match outcome { + Ok(CheckedAdvance::Advanced(clock)) => { + session + .clock_receipts + .settle(&doc_id, &session.doc_sync, |row| row.timestamp <= clock); + } + Ok(CheckedAdvance::Unchanged) => {} + Ok(CheckedAdvance::Busy) => { + session.doc_sync.restore_server_held_docs(vec![doc_id]); + } + Err(err) => { + session.doc_sync.restore_server_held_docs( + std::iter::once(doc_id).chain(remaining).collect(), + ); + return Err(err.into()); + } + } + } + Ok(()) } /// Load the next batch of unopened subdocs whose local changes the server has not @@ -572,12 +679,199 @@ mod tests { ShareIngestRequest, SharePayloadKind, ingest_share_item_into_sqlite, }; + use blocksuite_playground_doc::schema::BlockSpec; + use super::*; use crate::{ blob_ingest::{PickedMediaInput, prepare_ingested_blob}, - session::{MAX_UNVERIFIED_REMOTE_BYTES, MAX_UNVERIFIED_REMOTE_DOCS}, + host::{MemoryHostBridge, WsHandle}, + session::{ + MAX_EVICTED_REMOTE_DOCS, MAX_UNVERIFIED_REMOTE_BYTES, MAX_UNVERIFIED_REMOTE_DOCS, + }, }; + const WS_URL: &str = "wss://app.affine.pro/socket.io/?EIO=4&transport=websocket"; + const SERVER: &str = "affine-cloud"; + const DOC: &str = "page-p"; + + fn encode_base64(input: &[u8]) -> String { + const TABLE: &[u8; 64] = + b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(input.len().div_ceil(3) * 4); + for chunk in input.chunks(3) { + let n = chunk + .iter() + .enumerate() + .fold(0u32, |n, (i, b)| n | (u32::from(*b) << (16 - 8 * i))); + for i in 0..4 { + out.push(if i <= chunk.len() { + TABLE[((n >> (18 - 6 * i)) & 0x3F) as usize] as char + } else { + '=' + }); + } + } + out + } + + fn temp_dir(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!( + "affine-sqlite-session-{}-{tag}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + dir + } + + fn sent_frames(host: &MemoryHostBridge) -> Vec { + (0..16u64) + .filter_map(|h| host.ws_sent(WsHandle(h))) + .flatten() + .cloned() + .collect() + } + + /// Ack ID of the newest frame sent after `from` that contains every needle. + fn ack_id_after(host: &MemoryHostBridge, from: usize, needles: &[&str]) -> Option { + sent_frames(host)[from..].iter().rev().find_map(|f| { + let digits: String = f + .strip_prefix("42")? + .chars() + .take_while(char::is_ascii_digit) + .collect(); + needles + .iter() + .all(|n| f.contains(n)) + .then(|| digits.parse().ok()) + .flatten() + }) + } + + fn reply(session: &mut WorkspaceSession, host: &mut MemoryHostBridge, frame: &str, t: i64) { + session.on_ws_text(host, WS_URL, frame, t).unwrap(); + } + + fn join(session: &mut WorkspaceSession, host: &mut MemoryHostBridge, id: u64, t: i64) { + let ok = format!( + r#"43{id}[{{"data":{{"clientId":"c-1","success":true,"protocolVersion":1}}}}]"# + ); + reply(session, host, &ok, t); + } + + fn connect(session: &mut WorkspaceSession, host: &mut MemoryHostBridge, t: i64) { + let from = sent_frames(host).len(); + session.connect_sync(host, WS_URL, t).unwrap(); + session.on_ws_open(host, WS_URL, t).unwrap(); + let open = r#"0{"sid":"e-1","upgrades":[],"pingInterval":25000,"pingTimeout":20000}"#; + reply(session, host, open, t); + reply(session, host, r#"40{"sid":"s-1"}"#, t); + let id = ack_id_after(host, from, &["space:join-batch"]).unwrap(); + join(session, host, id, t); + } + + /// Tick until `event` for `doc_id` goes out, answering a `space:join-batch` for it on the + /// way, and return the ack ID of the request. + fn next_request( + session: &mut WorkspaceSession, + host: &mut MemoryHostBridge, + event: &str, + doc_id: &str, + t: i64, + ) -> u64 { + let from = sent_frames(host).len(); + session.on_tick(host, WS_URL, t).unwrap(); + if let Some(id) = ack_id_after(host, from, &["space:join-batch", doc_id]) { + join(session, host, id, t); + session.on_tick(host, WS_URL, t).unwrap(); + } + ack_id_after(host, from, &[event, doc_id]).unwrap() + } + + fn loaded(id: u64, missing: &[u8], state: &[u8], timestamp: i64) -> String { + format!( + r#"43{id}[{{"data":{{"missing":"{}","state":"{}","timestamp":{timestamp}}}}}]"#, + encode_base64(missing), + encode_base64(state) + ) + } + + fn broadcast(doc_id: &str, update: &[u8], timestamp: i64) -> String { + format!( + r#"42["space:broadcast-doc-updates",{{"spaceType":"workspace","spaceId":"ws","docId":"{doc_id}","updates":["{}"],"timestamp":{timestamp},"editor":"peer"}}]"#, + encode_base64(update) + ) + } + + async fn pushed_and_doc_clock(store: &SqliteWorkspaceStore, doc_id: &str) -> (i64, i64) { + let pushed = store + .storage() + .get_peer_pushed_clock(SERVER, doc_id) + .await + .unwrap() + .map_or(0, |c| naive_utc_to_millis(c.timestamp)); + let clock = store + .storage() + .get_doc_clock(doc_id) + .await + .unwrap() + .unwrap(); + (pushed, naive_utc_to_millis(clock.timestamp)) + } + + /// Write a page baseline of `DOC` that the server already holds. + async fn seed_pushed_page(store: &SqliteWorkspaceStore) -> PageDocSession { + let mut page = PageDocSession::new(DOC, 7).unwrap(); + let spec = BlockSpec::Page { title: "P".into() }; + page.add_block("root", spec, None, None, 1).unwrap(); + let ts = store + .storage() + .push_update(DOC, page.encode_update_v1().unwrap(), 1_000) + .await + .unwrap(); + store + .storage() + .set_peer_pushed_clock(SERVER, DOC, ts) + .await + .unwrap(); + page + } + + async fn open_session(store: &SqliteWorkspaceStore, client_id: u64) -> WorkspaceSession { + store + .load_workspace_session( + "u-1", + client_id, + HostKind::Native, + SERVER, + "https://app.affine.pro", + 1_000, + ) + .await + .unwrap() + } + + #[tokio::test] + async fn check_held_states_restores_all_docs_when_the_first_check_fails() { + let store = SqliteWorkspaceStore::open_in_memory("ws").await.unwrap(); + let mut session = open_session(&store, 11).await; + for doc_id in ["doc-a", "doc-b", "doc-c"] { + session.register_loaded_doc(doc_id, PageDocSession::new(doc_id, 11).unwrap()); + session.doc_sync.entry_mut(doc_id).server_has_state = true; + assert!(session.local_doc_state_v1(doc_id).is_some()); + } + let doc_ids = session.doc_sync.drain_server_held_docs(); + assert_eq!(doc_ids, ["doc-a", "doc-b", "doc-c"]); + + store.close().await; + assert!( + store + .check_held_states(&mut session, SERVER, doc_ids.clone()) + .await + .is_err() + ); + assert_eq!(session.doc_sync.drain_server_held_docs(), doc_ids); + } + #[tokio::test] async fn persist_ingested_blob_heals_equal_len_corruption_and_tracks_soft_delete_upload_state() { @@ -704,6 +998,7 @@ mod tests { session.unhydrated_pending_delta_bytes() <= MAX_UNVERIFIED_REMOTE_BYTES, "payload {payload_len}" ); + assert!(session.evicted_remote_doc_count() <= MAX_EVICTED_REMOTE_DOCS); } // A peer appends `v2` to `P`, and the session gets the broadcast without opening `P`. @@ -723,6 +1018,7 @@ mod tests { .unwrap(); assert_eq!(session.unhydrated_pending_delta_doc_count(), 0); assert_eq!(session.unhydrated_pending_delta_bytes(), 0); + assert_eq!(session.evicted_remote_doc_count(), 0); for i in 0..200 { let doc_id = format!("unknown-doc-{i}"); assert!( @@ -746,4 +1042,256 @@ mod tests { store_c.close().await; let _ = std::fs::remove_dir_all(&dir); } + + #[tokio::test] + async fn evicted_broadcast_for_a_doc_of_another_writer_reloads_it_from_the_server() { + // (case, caption bytes of the peer edit, broadcasts for other documents after it) + let cases = [ + ("over-byte-limit", 1_048_600usize, 0usize), + ("over-doc-limit", 9, MAX_UNVERIFIED_REMOTE_DOCS), + ]; + for (case, caption_len, other_docs) in cases { + let dir = temp_dir(case); + let store = SqliteWorkspaceStore::open(&dir, "workspace", "local", "ws") + .await + .unwrap(); + let mut session = open_session(&store, 11).await; + let mut host = MemoryHostBridge::new(HostKind::Native, "inst"); + connect(&mut session, &mut host, 10); + + // The page is not on the server yet: the first load ends missing. + assert!( + store + .open_or_hydrate_document(&mut session, DOC, 300) + .await + .is_err() + ); + let load = next_request(&mut session, &mut host, "space:load-doc", DOC, 310); + let not_found = format!( + r#"43{load}[{{"error":{{"status":404,"code":"DOC_NOT_FOUND","name":"DOC_NOT_FOUND","message":"doc not found"}}}}]"# + ); + reply(&mut session, &mut host, ¬_found, 340); + assert!(session.is_remote_doc_missing(DOC), "{case}"); + + // A Share Extension writes the page into the same SQLite file, and a peer edits it. + let db = resolve_workspace_db_path(&dir, "workspace", "local", "ws").unwrap(); + let share = ShareIngestRequest { + share_id: "share-p".into(), + import_attempt_id: "attempt-p".into(), + doc_id: DOC.into(), + kind: SharePayloadKind::Text, + title: "Shared".into(), + text_or_url: "baseline".into(), + secondary_text: String::new(), + tag_ids: Vec::new(), + collection_id: None, + attachments: Vec::new(), + client_id: 22, + now_ms: 1_000, + }; + ingest_share_item_into_sqlite(&db, "ws", &share, &[]) + .await + .unwrap(); + let mut peer = store.load_doc_session(DOC, 33).await.unwrap().unwrap(); + let root_id = peer.read_page_snapshot().unwrap().root.unwrap().id; + let caption = "p".repeat(caption_len); + let delta = peer + .set_block_caption(&root_id, &caption, 1_002) + .unwrap() + .unwrap() + .update; + reply( + &mut session, + &mut host, + &broadcast(DOC, &delta, 1_004), + 1_004, + ); + for i in 0..other_docs { + let frame = broadcast(&format!("other-{i}"), &delta, 1_005); + reply(&mut session, &mut host, &frame, 1_005); + } + assert_eq!(session.evicted_remote_doc_count(), 1, "{case}"); + assert!(session.unhydrated_pending_delta_doc_count() <= MAX_UNVERIFIED_REMOTE_DOCS); + assert!(session.unhydrated_pending_delta_bytes() <= MAX_UNVERIFIED_REMOTE_BYTES); + + // The flush finds the page in SQLite, and the session loads it from the server. + store + .flush_session_mutations(&mut session, None, 1_100) + .await + .unwrap(); + assert_eq!(session.evicted_remote_doc_count(), 0, "{case}"); + let reload = next_request(&mut session, &mut host, "space:load-doc", DOC, 1_200); + let server_state = peer.encode_update_v1().unwrap(); + let server_sv = peer.encode_state_vector_v1().unwrap(); + let frame = loaded(reload, &server_state, &server_sv, 1_300); + reply(&mut session, &mut host, &frame, 1_300); + store + .flush_session_mutations(&mut session, None, 1_400) + .await + .unwrap(); + + let page = store.load_doc_session(DOC, 55).await.unwrap().unwrap(); + let root = page.read_page_snapshot().unwrap().root.unwrap(); + let read = root.props.get("prop:caption").and_then(|v| v.as_str()); + assert_eq!(read, Some(caption.as_str()), "{case}"); + for i in 0..other_docs { + let doc_id = format!("other-{i}"); + assert!( + store + .storage() + .get_doc_clock(&doc_id) + .await + .unwrap() + .is_none() + ); + } + store.close().await; + let _ = std::fs::remove_dir_all(&dir); + } + } + + #[tokio::test] + async fn remote_update_on_a_pushed_unopened_doc_moves_pushed_clock_without_a_load() { + let dir = temp_dir("pushed-unopened"); + let store = SqliteWorkspaceStore::open(&dir, "workspace", "local", "ws") + .await + .unwrap(); + let mut peer = seed_pushed_page(&store).await; + let mut session = open_session(&store, 11).await; + assert!(!session.has_pending_push(DOC)); + let mut host = MemoryHostBridge::new(HostKind::Native, "inst"); + connect(&mut session, &mut host, 10); + + let delta = peer + .set_block_caption("root", "remote", 2_000) + .unwrap() + .unwrap() + .update; + reply( + &mut session, + &mut host, + &broadcast(DOC, &delta, 2_000), + 2_000, + ); + assert!(!session.is_doc_loaded(DOC)); + store + .flush_session_mutations(&mut session, None, 2_100) + .await + .unwrap(); + let (pushed, clock) = pushed_and_doc_clock(&store, DOC).await; + assert_eq!(pushed, clock); + + // A cold start has nothing to load or push for the page. + let mut restarted = open_session(&store, 12).await; + assert!(!restarted.has_pending_push(DOC)); + connect(&mut restarted, &mut host, 3_000); + store + .flush_session_mutations(&mut restarted, None, 3_100) + .await + .unwrap(); + assert_eq!(restarted.unopened_loaded_doc_count(), 0); + store.close().await; + let _ = std::fs::remove_dir_all(&dir); + } + + #[tokio::test] + async fn acked_local_rows_move_pushed_clock_until_a_row_of_another_writer() { + let dir = temp_dir("acked-local"); + let store = SqliteWorkspaceStore::open(&dir, "workspace", "local", "ws") + .await + .unwrap(); + let mut editor = seed_pushed_page(&store).await; + let mut other = store.load_doc_session(DOC, 99).await.unwrap().unwrap(); + let mut session = open_session(&store, 11).await; + let mut host = MemoryHostBridge::new(HostKind::Native, "inst"); + connect(&mut session, &mut host, 10); + assert!( + store + .open_or_hydrate_document(&mut session, DOC, 100) + .await + .is_ok() + ); + let load = next_request(&mut session, &mut host, "space:load-doc", DOC, 110); + let sv = editor.encode_state_vector_v1().unwrap(); + reply( + &mut session, + &mut host, + &loaded(load, &[0, 0], &sv, 120), + 120, + ); + + // Each local edit is pushed, flushed, and acknowledged. The ack can come before or after + // the flush that writes its row. + let mut acked_row_clock = 0; + for (i, ack_before_flush) in [(0i64, false), (1, true)] { + let t = 1_000 + i * 1_000; + let edit = editor.set_block_caption("root", &format!("v{i}"), t as u64); + let update = edit.unwrap().unwrap().update; + assert!(session.merge_local_doc_update(DOC, &update, t).unwrap()); + let push = next_request(&mut session, &mut host, "space:push-doc-update", DOC, t); + let ack = format!(r#"43{push}[{{"data":{{"accepted":true,"timestamp":{t}}}}}]"#); + if ack_before_flush { + reply(&mut session, &mut host, &ack, t + 10); + } + store + .flush_session_mutations(&mut session, None, t + 20) + .await + .unwrap(); + if !ack_before_flush { + reply(&mut session, &mut host, &ack, t + 30); + store + .flush_session_mutations(&mut session, None, t + 40) + .await + .unwrap(); + } + let (pushed, clock) = pushed_and_doc_clock(&store, DOC).await; + assert_eq!(pushed, clock, "edit {i}"); + acked_row_clock = clock; + } + + // Another writer adds a row, then a local edit lands after it. The server holds the + // whole in-memory state, but the content check finds the other row outside it. + let foreign = other + .set_block_caption("root", "other", 5_000) + .unwrap() + .unwrap() + .update; + store + .storage() + .push_update(DOC, &foreign, 5_000) + .await + .unwrap(); + let update = editor + .set_block_caption("root", "v2", 6_000) + .unwrap() + .unwrap() + .update; + assert!(session.merge_local_doc_update(DOC, &update, 6_000).unwrap()); + let push = next_request(&mut session, &mut host, "space:push-doc-update", DOC, 6_000); + let ack = format!(r#"43{push}[{{"data":{{"accepted":true,"timestamp":6000}}}}]"#); + reply(&mut session, &mut host, &ack, 6_010); + store + .flush_session_mutations(&mut session, None, 6_020) + .await + .unwrap(); + let (pushed, clock) = pushed_and_doc_clock(&store, DOC).await; + assert_eq!(pushed, acked_row_clock); + assert!(pushed < clock); + + // Once the server sends the other row back, the in-memory state holds every row. + reply( + &mut session, + &mut host, + &broadcast(DOC, &foreign, 7_000), + 7_000, + ); + store + .flush_session_mutations(&mut session, None, 7_100) + .await + .unwrap(); + let (pushed, clock) = pushed_and_doc_clock(&store, DOC).await; + assert_eq!(pushed, clock); + store.close().await; + let _ = std::fs::remove_dir_all(&dir); + } }