diff --git a/pkgs/id/src/web/collab.rs b/pkgs/id/src/web/collab.rs index c7d20f8b2f..0d01176319 100644 --- a/pkgs/id/src/web/collab.rs +++ b/pkgs/id/src/web/collab.rs @@ -273,6 +273,40 @@ impl Document { self.version.load(std::sync::atomic::Ordering::SeqCst) } + /// Atomically accept a batch of steps submitted at `base_version` + /// (#2968). + /// + /// Holds the steps write lock across the version check, the append, + /// and the version bump, so two sockets submitting at the same base + /// version cannot both pass the check: exactly one is accepted and + /// the other observes the winner's bumped version. Returns the new + /// version on success, or the current version on mismatch. Broadcast + /// and Ack stay with the caller, after this lock has been released. + pub async fn try_apply_steps( + &self, + base_version: u64, + steps: &[serde_json::Value], + client_id: u64, + ) -> Result { + let mut doc_steps = self.steps.write().await; + let current_version = self.version(); + if base_version != current_version { + return Err(current_version); + } + for step in steps { + doc_steps.push(( + Step { data: step.clone() }, + serde_json::Value::Number(client_id.into()), + )); + } + let new_version = self + .version + .fetch_add(steps.len() as u64, std::sync::atomic::Ordering::SeqCst) + + steps.len() as u64; + drop(doc_steps); + Ok(new_version) + } + /// Increment client count when a client connects. /// Returns the new count. pub fn client_connected(&self) -> usize { @@ -635,6 +669,11 @@ fn extract_binary(msg: &Message) -> Option> { /// Apply one versioned client step batch, rejecting oversized batches before /// changing document history, version, or broadcasting an update. +/// +/// The version check, the append, and the version bump happen atomically +/// under the document steps lock (#2968), so two sockets submitting at the +/// same base version cannot both be accepted. The broadcast and log happen +/// after that lock has been released. async fn apply_steps( doc: &Document, version: u64, @@ -647,25 +686,12 @@ async fn apply_steps( )); } - let current_version = doc.version(); - if version != current_version { - return Err(format!( - "Version mismatch: expected {current_version}, got {version}" - )); - } - - let mut doc_steps = doc.steps.write().await; - for step in steps { - doc_steps.push(( - Step { data: step.clone() }, - serde_json::Value::Number(client_id.into()), - )); - } - drop(doc_steps); - - use std::sync::atomic::Ordering; - let new_version = - doc.version.fetch_add(steps.len() as u64, Ordering::SeqCst) + steps.len() as u64; + let new_version = doc + .try_apply_steps(version, steps, client_id) + .await + .map_err(|current_version| { + format!("Version mismatch: expected {current_version}, got {version}") + })?; let update = CollabMessage::Update { steps: steps.to_vec(), @@ -1287,6 +1313,72 @@ async fn handle_collab_socket( mod tests { use super::*; + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn test_try_apply_steps_concurrent_same_base_version() { + // #2968: sockets submitting Steps at the same base version must + // not diverge. Exactly one is accepted; every other observes the + // winner's bumped version and is rejected; the stored steps and + // version reflect only the winner. + // + // The test holds the steps write lock while the submitters + // arrive, modelling the production window: steps-lock contention + // (e.g. a join catch-up read) parks a socket between its version + // check and its append, so a check done before acquiring the + // lock is stale for every parked submitter at once. Under the + // pre-fix ordering several submitters pass the stale check and + // are all accepted (Ok(1), Ok(2), ...); with the check inside + // the lock exactly one wins, deterministically. + use std::sync::Arc; + let doc = Arc::new(Document::new()); + let gate = doc.steps.write().await; + let mut handles = Vec::new(); + for client_id in 1..=4u64 { + let doc = Arc::clone(&doc); + handles.push(tokio::spawn(async move { + let steps = vec![serde_json::json!({ + "stepType": "replace", + "marker": client_id, + })]; + (client_id, doc.try_apply_steps(0, &steps, client_id).await) + })); + } + // Let every submitter arrive at the steps lock. + tokio::time::sleep(std::time::Duration::from_millis(500)).await; + drop(gate); + let mut winners: Vec = Vec::new(); + for handle in handles { + let (client_id, result) = handle.await.unwrap(); + match result { + Ok(1) => winners.push(client_id), + Err(1) => {} + other => panic!( + "submitter {client_id} got {other:?}: only Ok(1) for the single winner and Err(1) for every loser are possible" + ), + } + } + assert_eq!(winners.len(), 1, "exactly one submission must be accepted"); + assert_eq!(doc.version(), 1, "version reflects only the winner's step"); + let stored = doc.steps.read().await; + assert_eq!(stored.len(), 1, "only the winner's step is stored"); + assert_eq!(stored[0].0.data["marker"], winners[0]); + assert_eq!(stored[0].1, serde_json::json!(winners[0])); + } + + #[tokio::test] + async fn test_try_apply_steps_sequential_versions() { + // Single-client sequential flow: a submission at the current + // version is accepted and bumps it; a replay at the stale base + // version is rejected; the next submission at the new version + // succeeds. + let doc = Document::new(); + let step = vec![serde_json::json!({ "stepType": "replace" })]; + assert_eq!(doc.try_apply_steps(0, &step, 7).await, Ok(1)); + assert_eq!(doc.try_apply_steps(0, &step, 7).await, Err(1)); + assert_eq!(doc.try_apply_steps(1, &step, 7).await, Ok(2)); + assert_eq!(doc.version(), 2); + assert_eq!(doc.steps.read().await.len(), 2); + } + #[allow(clippy::unwrap_used, clippy::panic)] #[test] fn test_collab_message_init_roundtrip() {