From 06c440a8688bc2c3f188cd0f68437ac11597e0c9 Mon Sep 17 00:00:00 2001 From: mdbase release automation Date: Sat, 28 Nov 2026 22:08:02 +1100 Subject: [PATCH 1/4] Preserve refused disk edits and share identical text in sealed entries (Refs #1952) --- changelog.d/1952.md | 4 + .../crates/daemon/src/runtime/event_loop.rs | 3 + runtime/crates/daemon/src/runtime/notices.rs | 77 +- .../crates/daemon/tests/fixtures/sync_pair.rs | 49 +- .../daemon/tests/store_format_upgrade.rs | 1 + runtime/crates/daemon/tests/web_replica.rs | 1 + runtime/crates/replica/src/conformance.rs | 1 + runtime/crates/replica/src/fake.rs | 20 + runtime/crates/replica/src/mem.rs | 1 + runtime/crates/replica/src/replica/append.rs | 120 +- runtime/crates/replica/src/replica/apply.rs | 10 + .../replica/src/replica/attachment_upload.rs | 13 +- .../replica/collection_setup/publication.rs | 1 + runtime/crates/replica/src/replica/disk.rs | 92 +- .../crates/replica/src/replica/local/tests.rs | 2 + runtime/crates/replica/src/replica/mod.rs | 11 + runtime/crates/replica/src/replica/refused.rs | 676 +++++++++++ runtime/crates/replica/src/replica/submit.rs | 1 + .../src/replica/unindexed_capture_runtime.rs | 17 +- .../replica/src/replica/unindexed_move.rs | 1 + .../src/replica/unindexed_reverse_capture.rs | 1 + runtime/crates/replica/src/store.rs | 39 +- .../crates/replica/src/tests/apply_results.rs | 4 + .../replica/src/tests/attachment_ingest.rs | 36 + .../tests/attachment_ingest/binary_holds.rs | 1 + runtime/crates/replica/src/tests/disk.rs | 1007 +++++++++++++++++ runtime/crates/replica/src/tests/engine.rs | 47 + runtime/crates/replica/src/tests/hosted.rs | 4 + runtime/crates/replica/tests/interfaces.rs | 20 + runtime/docs/contracts/log-entry.md | 7 +- 30 files changed, 2215 insertions(+), 52 deletions(-) create mode 100644 changelog.d/1952.md create mode 100644 runtime/crates/replica/src/replica/refused.rs diff --git a/changelog.d/1952.md b/changelog.d/1952.md new file mode 100644 index 000000000..742ce7a1e --- /dev/null +++ b/changelog.d/1952.md @@ -0,0 +1,4 @@ +## Fixed + +- Keep local edits when their sync entry is too large, and show the affected file in daemon status and logs. +- Large disk edits store one copy of the new document when it matches the applied result, so more Private edits fit within the sealed entry limit. diff --git a/runtime/crates/daemon/src/runtime/event_loop.rs b/runtime/crates/daemon/src/runtime/event_loop.rs index 2dbf0f086..94c56294a 100644 --- a/runtime/crates/daemon/src/runtime/event_loop.rs +++ b/runtime/crates/daemon/src/runtime/event_loop.rs @@ -26,6 +26,9 @@ pub(super) fn run( mut lock: mdbn_local_host::HostLock, ) { let GrantSignals { grants, changes } = signals; + rep.set_oversized_file_warning(|path| { + tracing::warn!(path = ?path, code = "too_large", "file change refused by sync"); + }); let mut ingest = VecDeque::new(); let mut active_log = None; let mut last_heartbeat = std::time::Instant::now(); diff --git a/runtime/crates/daemon/src/runtime/notices.rs b/runtime/crates/daemon/src/runtime/notices.rs index d21b92d21..ce3235dee 100644 --- a/runtime/crates/daemon/src/runtime/notices.rs +++ b/runtime/crates/daemon/src/runtime/notices.rs @@ -8,6 +8,7 @@ pub(super) fn file_notices(rep: &Replica) -> Vec use mdbn_wire::client::HoldReason; let unsupported = &rep.store().inner().stats.unsupported_paths; let failures = rep.attachment_ingest_failures(); + let edits = rep.refused_files(); let (mut holds, error) = match rep.store().holds() { Ok(holds) => (holds, None), Err(_) => ( @@ -20,7 +21,11 @@ pub(super) fn file_notices(rep: &Replica) -> Vec ), }; holds.sort_by_key(|hold| hold.reason != HoldReason::UnknownProvenance); - let total = unsupported.len() + failures.len() + holds.len() + usize::from(error.is_some()); + let total = unsupported.len() + + failures.len() + + edits.len() + + holds.len() + + usize::from(error.is_some()); let skipped = unsupported .iter() .map(|(path, reason)| crate::control::Notice { @@ -36,6 +41,7 @@ pub(super) fn file_notices(rep: &Replica) -> Vec .unwrap_or_else(|| problem.code.clone()), message: problem.message.clone(), }); + let edits = edits.map(|(path, problem, deleted)| edit_refused_notice(path, problem, deleted)); let held = holds.into_iter().map(|hold| { let collision = rep .store() @@ -62,7 +68,7 @@ pub(super) fn file_notices(rep: &Replica) -> Vec match hold.reason { HoldReason::Conflict => "Changed here and elsewhere; file held.", HoldReason::UnknownProvenance => { - "mdbase could not tell which version this file was based on; file held on this computer." + "Changed by a program mdbase does not recognise; file held." } HoldReason::DeletedElsewhere => "Deleted on another device; file held.", HoldReason::ReadOnly => "Changed while read-only; file held.", @@ -78,11 +84,46 @@ pub(super) fn file_notices(rep: &Replica) -> Vec } }); limited_file_notices( - error.into_iter().chain(skipped).chain(refused).chain(held), + error + .into_iter() + .chain(skipped) + .chain(refused) + .chain(edits) + .chain(held), total, ) } +/// A file whose change was rejected; the disk keeps what was written there. +fn edit_refused_notice( + path: &str, + problem: &mdbn_wire::client::Problem, + deleted: bool, +) -> crate::control::Notice { + let why = match (problem.code.as_str(), problem.reason.as_deref()) { + (_, Some("refs")) => "it refers to too many files", + (_, Some("attachment_objects_missing")) => "a file it attaches could not be uploaded", + ("too_large", _) => "it is too large", + _ => "it is not a valid change", + }; + let message = if deleted { + format!( + "This deletion could not be synced ({why}). The file is deleted on this \ + device only and still exists elsewhere. Put the file back to sync it again." + ) + } else { + format!( + "This change could not be synced ({why}). The content is kept in the file. \ + Edit the file to try again." + ) + }; + crate::control::Notice { + path: Some(path.into()), + code: "edit_refused".into(), + message, + } +} + fn limited_file_notices( notices: impl Iterator, total: usize, @@ -112,6 +153,36 @@ fn limited_file_notices( #[cfg(test)] mod tests { + #[test] + fn a_refused_edit_is_noticed_on_its_file() { + let problem = mdbn_replica::api::ErrorCode::TooLarge + .problem_with_reason("item_bytes", "the log refused this change"); + let notice = super::edit_refused_notice("notes/big.md", &problem, false); + assert_eq!(notice.path.as_deref(), Some("notes/big.md")); + assert_eq!(notice.code, "edit_refused"); + assert_eq!( + notice.message, + "This change could not be synced (it is too large). The content is kept in \ + the file. Edit the file to try again." + ); + let missing = mdbn_replica::api::ErrorCode::NotFound + .problem_with_reason("attachment_objects_missing", "upload it again"); + let notice = super::edit_refused_notice("media/a.png", &missing, false); + assert!( + notice + .message + .contains("(a file it attaches could not be uploaded)") + ); + let invalid = mdbn_replica::api::ErrorCode::InvalidRequest.problem("refused"); + let notice = super::edit_refused_notice("notes/gone.md", &invalid, true); + assert_eq!( + notice.message, + "This deletion could not be synced (it is not a valid change). The file is \ + deleted on this device only and still exists elsewhere. Put the file back to \ + sync it again." + ); + } + #[test] fn file_notices_bound_work_and_bytes_without_hiding_the_omitted_count() { let mapped = std::cell::Cell::new(0); diff --git a/runtime/crates/daemon/tests/fixtures/sync_pair.rs b/runtime/crates/daemon/tests/fixtures/sync_pair.rs index c2738b79b..77e1e7d86 100644 --- a/runtime/crates/daemon/tests/fixtures/sync_pair.rs +++ b/runtime/crates/daemon/tests/fixtures/sync_pair.rs @@ -600,14 +600,47 @@ pub async fn run_private_approval(log: &str, dir: &Path) { assert!( matches!(approval(&ra, Op::Pending(sa)).await, Ok(Reply::Pending(list)) if list.is_empty()) ); - std::fs::write(dir.join(b.label).join("from-b.md"), "private on B\n").unwrap(); - converge( - &dir.join(a.label).join("from-b.md"), - "private on B\n", - Duration::from_secs(60), - ) - .await; - println!("PASS: B keyed by A; notes open both ways"); + // A real file watcher, two Private replicas, and the sealed log limit. + let path = "from-b.md"; + let local = dir.join(b.label).join(path); + let peer = dir.join(a.label).join(path); + let original = format!("{}\n", "x".repeat(99)).repeat(3450); + let edited = format!("{original}{}\n", "y".repeat(99)); + let wait = Duration::from_secs(60); + for doc in [&original, &edited] { + std::fs::write(&local, doc).unwrap(); + converge_bytes(&peer, doc.as_bytes(), wait).await; + } + + let oversized = format!("{edited}{}", "z".repeat(400_000)); + std::fs::write(&local, &oversized).unwrap(); + tokio::time::timeout(wait, async { + loop { + let (_, notices) = rb.telemetry().await.unwrap(); + if notices + .iter() + .any(|n| n.code == "edit_refused" && n.path.as_deref() == Some(path)) + { + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + }) + .await + .expect("the refused Private edit must be visible in daemon status"); + assert!(std::fs::read(&local).unwrap() == oversized.as_bytes()); + assert!(std::fs::read(&peer).unwrap() == edited.as_bytes()); + + std::fs::write(&local, "corrected on B\n").unwrap(); + converge_bytes(&peer, b"corrected on B\n", wait).await; + assert!( + !rb.telemetry() + .await + .unwrap() + .1 + .iter() + .any(|n| n.code == "edit_refused" && n.path.as_deref() == Some(path)) + ); ra.stop().await; rb.stop().await; } diff --git a/runtime/crates/daemon/tests/store_format_upgrade.rs b/runtime/crates/daemon/tests/store_format_upgrade.rs index 37ed7db08..c41472ff2 100644 --- a/runtime/crates/daemon/tests/store_format_upgrade.rs +++ b/runtime/crates/daemon/tests/store_format_upgrade.rs @@ -158,6 +158,7 @@ fn pending() -> PendingRow { grant: None, uploads: Vec::new(), refs: Vec::new(), + submitted: false, } } diff --git a/runtime/crates/daemon/tests/web_replica.rs b/runtime/crates/daemon/tests/web_replica.rs index a00e309cb..d5628a26a 100644 --- a/runtime/crates/daemon/tests/web_replica.rs +++ b/runtime/crates/daemon/tests/web_replica.rs @@ -1207,6 +1207,7 @@ fn dormant_local_capture_is_rejected_on_ordinary_host_reopen() { grant: Some(owner), uploads: Vec::new(), refs: Vec::new(), + submitted: true, }], ..Tx::default() }) diff --git a/runtime/crates/replica/src/conformance.rs b/runtime/crates/replica/src/conformance.rs index 86ba51d12..62175ddb4 100644 --- a/runtime/crates/replica/src/conformance.rs +++ b/runtime/crates/replica/src/conformance.rs @@ -500,6 +500,7 @@ pub fn pending_row(order: u64, m: u64) -> PendingRow { grant: None, uploads: Vec::new(), refs: Vec::new(), + submitted: false, } } diff --git a/runtime/crates/replica/src/fake.rs b/runtime/crates/replica/src/fake.rs index 806ef46da..9a2a3ec6b 100644 --- a/runtime/crates/replica/src/fake.rs +++ b/runtime/crates/replica/src/fake.rs @@ -623,6 +623,11 @@ pub struct Faults { /// Fault (lost objects): the next this-many appends are refused /// `refs_missing`, without being performed. pub refs_missing_appends: u32, + /// Appends carrying an item larger than this are refused `too_large` / + /// `item_bytes`, as the service does, without being performed. + pub item_bytes_limit: Option, + /// The next appends fail with these errors in order, without being performed. + pub fail_appends: Vec, /// Every `put_object` fails with this error, without being performed. pub put_object_error: Option, /// Every `put_snapshot` fails with this error, without being performed. @@ -691,6 +696,21 @@ impl LogClient for FakeLog { missing: vec![mdbn_wire::common::B32([0xee; 32])], }); } + if let LogRequest::Append(p) = &request { + if !self.faults.fail_appends.is_empty() { + return Err(self.faults.fail_appends.remove(0)); + } + if let Some(limit) = self.faults.item_bytes_limit + && p.items.iter().any(|i| i.0.len() > limit) + { + return Err(LogError::Service { + code: LogErrorCode::TooLarge, + reason: Some("item_bytes".into()), + retry_after_ms: None, + missing: Vec::new(), + }); + } + } let lie = self.faults.lie_behind > 0 && matches!(&request, LogRequest::Read(p) if p.kinds.is_none()); let mut reply = self.service.handle(&self.client, request); diff --git a/runtime/crates/replica/src/mem.rs b/runtime/crates/replica/src/mem.rs index 144ee2d33..f950ca78f 100644 --- a/runtime/crates/replica/src/mem.rs +++ b/runtime/crates/replica/src/mem.rs @@ -1530,6 +1530,7 @@ mod retained_boundary_tests { grant: None, uploads: Vec::new(), refs: Vec::new(), + submitted: false, } } diff --git a/runtime/crates/replica/src/replica/append.rs b/runtime/crates/replica/src/replica/append.rs index d4be08de3..076970e40 100644 --- a/runtime/crates/replica/src/replica/append.rs +++ b/runtime/crates/replica/src/replica/append.rs @@ -330,7 +330,12 @@ impl Replica { if self.adopt_step() { return Ok(()); } - let rows = self.store.pending(None, self.tuning.max_items.min(64))?; + let limit = if std::mem::take(&mut self.append_probe) { + 1 + } else { + self.tuning.max_items.min(64) + }; + let rows = self.store.pending(None, limit)?; if rows.is_empty() { return Ok(()); } @@ -1185,15 +1190,39 @@ impl Replica { } /// Rejected at head: resolve the receipt, drop from pending, rebuild the view. + /// The files the rejected rows touched keep their bytes (`refused.rs`). pub(crate) fn resolve_rejected( &mut self, rejected: Vec<(Uuid, Option, mdbn_wire::client::Problem)>, + ) -> Result<(), StoreError> { + let refused = self.refused_rows(&rejected)?; + self.resolve_rejected_fencing(rejected, refused) + } + + /// [`Self::resolve_rejected`] with the files to fence, in the same commit. + pub(crate) fn resolve_rejected_fencing( + &mut self, + rejected: Vec<(Uuid, Option, mdbn_wire::client::Problem)>, + refused: Vec, ) -> Result<(), StoreError> { if rejected.is_empty() { return Ok(()); } let now = self.now(); let mut tx = Tx::default(); + let warnings = self.warn_oversized_file.map(|warn| { + let paths: Vec<_> = refused + .iter() + .filter(|file| file.problem.code == "too_large") + .map(|file| file.path.clone()) + .collect(); + (warn, paths) + }); + let mut fence = self.refused.clone(); + if !refused.is_empty() { + fence.add(refused); + tx.meta.push(fence.meta()); + } let mut resolved = Vec::new(); let mut forget = Vec::new(); for (id, grant, problem) in rejected { @@ -1246,6 +1275,12 @@ impl Replica { )); } self.store.commit(tx)?; + self.refused = fence; + if let Some((warn, paths)) = warnings { + for path in paths { + warn(&path); + } + } for id in forget { self.resurrected.remove(&id); } @@ -1440,9 +1475,9 @@ impl Replica { } Err(LogError::Service { code, + reason, retry_after_ms, missing, - .. }) => match code { LogErrorCode::Unavailable | LogErrorCode::RateLimited @@ -1479,10 +1514,31 @@ impl Replica { self.incident(IncidentKind::UpgradeRequired, None); self.append = AppendState::Stopped; } - LogErrorCode::TooLarge if sent.mutations.len() > 1 => { - self.tuning.max_items = 1; + LogErrorCode::TooLarge if sent.params.items.len() > 1 => { + // The batch, or one of its items: send the head row alone + // next, so an item's refusal can be pinned on it. + self.append_probe = true; self.append = AppendState::Idle; } + LogErrorCode::TooLarge + if sent.mutations.len() == 1 + && item_refusal(reason.as_deref()) + && self.rejects_log_refusal(sent.mutations[0]) => + { + // The log measured this one change too large: reject it + // (its files keep their bytes, `refused.rs`) instead of + // stopping the whole collection behind it. + match self.reject_refused(sent.mutations[0], reason.as_deref()) { + Ok(()) => self.append = AppendState::Idle, + Err(e) => { + self.incident( + IncidentKind::Integrity, + Some(mdbn_wire::common::Value::Text(format!("store: {e}"))), + ); + self.append = AppendState::Stopped; + } + } + } LogErrorCode::RefsMissing => { // An uploaded attachment whose objects the log no longer has // fails terminally (typed); anything else (blob parts being @@ -1504,8 +1560,9 @@ impl Replica { } } _ => { - // invalid / not_found / too_large on one item: a bug or a stale - // replica. Re-read and stop until something changes. + // invalid / not_found / too_large for anything but the item + // itself: a bug or a stale replica, not one change. Re-read + // and stop until something changes. self.incident( IncidentKind::Integrity, Some(mdbn_wire::common::Value::Text(format!( @@ -1521,6 +1578,32 @@ impl Replica { } } + /// Whether the log's refusal of pending row `id` rejects it + /// ([`super::refused::rejects_log_refusal`]); otherwise the append stops. + fn rejects_log_refusal(&self, id: Uuid) -> bool { + self.store + .pending_get(&id) + .ok() + .flatten() + .is_some_and(|row| { + super::refused::rejects_log_refusal(row.mutation.source, self.store.has_files()) + }) + } + + /// Reject the one change the log measured too large (`item_refusal`), + /// with the log's reason as its problem's. + fn reject_refused(&mut self, id: Uuid, reason: Option<&str>) -> Result<(), StoreError> { + let Some(row) = self.store.pending_get(&id)? else { + return Ok(()); + }; + let reason = reason.unwrap_or_default(); + let problem = crate::api::ErrorCode::TooLarge.problem_with_reason( + reason, + format!("the log refused this change: too_large ({reason})"), + ); + self.resolve_rejected(vec![(id, row.grant, problem)]) + } + fn on_read_reply( &mut self, reply: LogReply, @@ -2010,6 +2093,12 @@ fn _other() -> Inflight { Inflight::Other } +/// Whether a `too_large` refusal measured the item itself (`log-service-api.md` +/// §10), not the batch. Every other refusal of an append stops it. +fn item_refusal(reason: Option<&str>) -> bool { + matches!(reason, Some("item_bytes" | "refs")) +} + /// The canonical payload of a legacy row: exactly the legacy codec, whose /// operations and effects are all legacy (anything else is a typed rejection). fn legacy_entry_plain( @@ -2038,7 +2127,7 @@ fn legacy_entry_plain( .map_err(|e| crate::api::ApiError::from(super::unencodable_result(&e)))?, ) }; - let payload = EntryPayload { + let mut payload = EntryPayload { resurrect, sem: mdbn_wire::common::Version { major: planned.sem.major, @@ -2055,6 +2144,23 @@ fn legacy_entry_plain( }, texts: None, }; + // A disk edit carries both the observed document and the applied result. + // Share a whole literal only when they agree; history can read it directly. + if let ([Op::Document(edit)], [mdbn_wire::entry::Effect::PutRecord(put)]) = ( + payload.mutation.ops.as_mut_slice(), + payload.effects.as_mut_slice(), + ) && put.id == edit.id + && let Some(new) = &mut edit.new + && let Text::Inline(text) = &mut new.doc + && text.len() >= 1024 + && matches!(&put.doc, Text::Inline(result) if result == text) + { + payload.texts = Some(vec![mdbn_wire::entry::TextDef::Literal(std::mem::take( + text, + ))]); + new.doc = Text::Index(0); + put.doc = Text::Index(0); + } payload .to_bytes() .map_err(|_| crate::api::ErrorCode::InvalidRequest.err("result does not encode")) diff --git a/runtime/crates/replica/src/replica/apply.rs b/runtime/crates/replica/src/replica/apply.rs index 655645473..edf39be0b 100644 --- a/runtime/crates/replica/src/replica/apply.rs +++ b/runtime/crates/replica/src/replica/apply.rs @@ -135,6 +135,7 @@ struct ChangeStage { legacy_effects: Vec, attachment_files: Vec, holds_changed: bool, + refused: Option, } impl Replica { @@ -2008,6 +2009,10 @@ impl Replica { if own_match && payload.mutation.origin == self.cfg.replica_id { self.prepare_conflict_holds(&payload.mutation, conflicts, tx, &t)?; } + // A confirmed change of a record whose refused bytes the disk keeps. + let own_write = (own_match && payload.mutation.origin == self.cfg.replica_id) + .then_some(&payload.mutation); + let refused = self.prepare_refused_holds(own_write, &legacy_effects, tx)?; let holds_changed = !tx.holds_put.is_empty() || self.store.holds()?.iter().any(|hold| { hold.reason == mdbn_wire::client::HoldReason::ReadOnly @@ -2019,6 +2024,7 @@ impl Replica { legacy_effects, attachment_files, holds_changed, + refused, }) } @@ -2055,6 +2061,7 @@ impl Replica { legacy_effects, attachment_files, holds_changed, + refused, } = changes; for (key, shown) in before { self.before.entry(key).or_insert(shown); @@ -2108,6 +2115,9 @@ impl Replica { return Ok(Outcome::Applied); } self.query_context = query_context; + if let Some(rest) = refused { + self.refused_applied(rest); + } self.log_time = log_time; self.sem_ratchet_set(ratchet); // The entry is committed: a later typed abort cannot certify that the diff --git a/runtime/crates/replica/src/replica/attachment_upload.rs b/runtime/crates/replica/src/replica/attachment_upload.rs index 74d80afb3..b0b55e33d 100644 --- a/runtime/crates/replica/src/replica/attachment_upload.rs +++ b/runtime/crates/replica/src/replica/attachment_upload.rs @@ -1794,9 +1794,13 @@ impl Replica { grant, uploads: Vec::new(), refs: f.refs.clone(), + submitted: !up.origin.external && self.store.has_files(), }; check_row_refs(&row)?; - let committed = self.store.commit(Tx { + // A disk edit ends the fence of a refused one there (`refused.rs`). + let mutation = row.mutation.clone(); + let submitted = row.submitted; + let mut tx = Tx { pending_put: vec![row], meta: std::iter::once(( meta_keys::COUNTERS.into(), @@ -1813,7 +1817,11 @@ impl Replica { .collect(), ack_observations: up.origin.acks.clone(), ..Tx::default() - }); + }; + let refused = self + .release_refused(&mutation, submitted, &mut tx) + .map_err(store_problem)?; + let committed = self.store.commit(tx); if let Err(error) = committed { if up.origin.delegated.is_some() { if matches!(error, crate::store::StoreError::CommitAborted(_)) { @@ -1826,6 +1834,7 @@ impl Replica { } return Err(store_problem(error)); } + self.refused_released(refused); self.touch.add(order, &touches); self.pending_keys.insert(order, touches); self.status_dirty = true; diff --git a/runtime/crates/replica/src/replica/collection_setup/publication.rs b/runtime/crates/replica/src/replica/collection_setup/publication.rs index 4864cb011..f900f50a9 100644 --- a/runtime/crates/replica/src/replica/collection_setup/publication.rs +++ b/runtime/crates/replica/src/replica/collection_setup/publication.rs @@ -151,6 +151,7 @@ impl Replica { grant: Some(grant), uploads: vec![], refs: plan.source_refs().to_vec(), + submitted: self.store.has_files(), }; // Certified abort is retryable only through a new explicit review. An // uncertain commit permanently fences this actor; never replay its MID. diff --git a/runtime/crates/replica/src/replica/disk.rs b/runtime/crates/replica/src/replica/disk.rs index 2af87829c..b8dfdd24d 100644 --- a/runtime/crates/replica/src/replica/disk.rs +++ b/runtime/crates/replica/src/replica/disk.rs @@ -162,6 +162,14 @@ impl Replica { settled.push((key, PublishState::NotPublished)); continue; } + // A refused change: the file keeps the user's bytes (`refused.rs`). + if self + .refused + .fenced(id, &[path, was.as_ref().map(|w| w.path.as_str())]) + { + settled.push((key, PublishState::NotPublished)); + continue; + } let publish = match (was, now) { (None, None) => None, (None, Some((path, doc))) => Some(Publish::Write { @@ -480,7 +488,10 @@ impl Replica { // interrupted move or delete. let mut stray = Vec::new(); for (path, rev) in &known { - if wanted.contains_key(path) || held.contains(path) { + if wanted.contains_key(path) + || held.contains(path) + || self.refused.fenced(None, &[Some(path)]) + { continue; } // Stored file identity owns this path, including native Markdown and @@ -1162,7 +1173,21 @@ impl Replica { } // Which record is this? let from = o.moved_from.clone().unwrap_or_else(|| o.path.clone()); - let id = self.holder_at(&from).or_else(|| self.holder_at(&o.path)); + // A refused disk edit here (`refused.rs`): the disk kept its bytes, and + // a refused move or create names the record it was for. + let paths = [Some(o.path.as_str()), o.moved_from.as_deref()]; + let refused = |id| { + self.refused + .get(id, &paths) + .filter(|f| f.mine.is_some()) + .cloned() + }; + let fence = refused(None); + let id = self + .holder_at(&from) + .or_else(|| self.holder_at(&o.path)) + .or_else(|| fence.as_ref().and_then(|f| f.id)); + let fence = refused(id).or(fence); // A held record collects saves. if let Some(i) = id && let Some(mut h) = self.store.hold(&i)? @@ -1187,9 +1212,17 @@ impl Replica { && *p == o.path && d == t { - return self.ack(o.token); + return self.ack_releasing(o.token, id, &o.path); + } + if let (Some(f), Some(i)) = (&fence, id) + && self.hold_moved_refused(i, f, &o.path, text.as_deref(), o.token)? + { + return Ok(()); } let base = match (&shown, o.base) { + // The new edit continues the refused one: plan it from what that + // was based on, so anything confirmed since conflicts. + _ if fence.is_some() => fence.as_ref().and_then(|f| f.base.clone()), (Some((p, d)), Some(b)) if rev(d) == b => Some(DocVersion { path: p.clone(), doc: Text::Inline(d.clone()), @@ -1217,10 +1250,11 @@ impl Replica { && *p == o.path && d == t { - return self.ack(o.token); + return self.ack_releasing(o.token, id, &o.path); } - if id.is_none() && text.is_none() { - return self.ack(o.token); + // Gone, and nothing here to delete (a refused create, removed). + if shown.is_none() && text.is_none() { + return self.ack_releasing(o.token, id, &o.path); } let id = match id { Some(i) => i, @@ -1267,7 +1301,7 @@ impl Replica { // A deleted resource file: ingested as a resource delete. let shown = self.local_view_doc(&DiskKey::Resource(o.path.clone())); if shown.is_none() { - return self.ack(o.token); + return self.ack_releasing(o.token, None, &o.path); } self.before.insert(DiskKey::Resource(o.path.clone()), None); return self.capture_resource( @@ -1282,7 +1316,7 @@ impl Replica { .local_view_doc(&DiskKey::Resource(o.path.clone())) .is_some_and(|(_, d)| d == doc) { - return self.ack(o.token); + return self.ack_releasing(o.token, None, &o.path); } self.before.insert( DiskKey::Resource(o.path.clone()), @@ -1479,10 +1513,21 @@ impl Replica { // An external edit is never rejected by contract; a planner refusal // here is a bug or a resource write that is invalid. Keep the user's // bytes (nothing is published) and report. + let problem = super::submit::rejection_problem(&rej); + if !retain_on_refusal + && super::refused::fences(m.source, &problem, self.store.has_files()) + { + // A disk edit: a durable rejection, and its files fenced with a + // per-file notice (`refused.rs`). + self.before.clear(); + let fence = self.refused_targets(&m.clone().into(), false, &[], &problem)?; + self.resolve_rejected_fencing(vec![(m.id, None, problem.clone())], fence)?; + self.ack_all(tokens)?; + return Ok(rejected_receipt(m.id, problem)); + } if !retain_on_refusal { self.ack_all(tokens)?; } - let problem = super::submit::rejection_problem(&rej); self.incident( mdbn_wire::client::IncidentKind::Integrity, Some(mdbn_wire::common::Value::Text(format!( @@ -1551,21 +1596,26 @@ impl Replica { let order = self.next_order; self.next_order += 1; let id = m.id; - self.store.commit(Tx { - pending_put: vec![PendingRow { - order, - mutation: m.into(), - effects: effects.clone(), - touches: touches.clone(), - grant: None, - uploads: Vec::new(), - refs: Vec::new(), - }], + let mutation = m.into(); + let mut tx = Tx { ack_observations: tokens, holds_del, meta: vec![(meta_keys::COUNTERS.into(), i64_meta(self.clock_floor))], ..Tx::default() - })?; + }; + let refused = self.release_refused(&mutation, false, &mut tx)?; + tx.pending_put.push(PendingRow { + order, + mutation, + effects: effects.clone(), + touches: touches.clone(), + grant: None, + uploads: Vec::new(), + refs: Vec::new(), + submitted: false, + }); + self.store.commit(tx)?; + self.refused_released(refused); { let view = StoreView::new(&self.store, self.catalog.clone()); for e in &planned.effects { @@ -1717,7 +1767,7 @@ impl Replica { id: B16, path: Option<&str>, ) -> Result { - if self.store.hold(&id)?.is_some() { + if self.store.hold(&id)?.is_some() || self.refused.fenced(Some(id), &[path]) { return Ok(true); } if let Some(path) = path diff --git a/runtime/crates/replica/src/replica/local/tests.rs b/runtime/crates/replica/src/replica/local/tests.rs index 7866e94e7..a3d493f4c 100644 --- a/runtime/crates/replica/src/replica/local/tests.rs +++ b/runtime/crates/replica/src/replica/local/tests.rs @@ -180,6 +180,7 @@ fn pending(r: &mut Replica, granted: bool) -> Uuid { grant: granted.then_some(GRANT), uploads: vec![], refs: Vec::new(), + submitted: false, }], ..Tx::default() }) @@ -644,6 +645,7 @@ fn existing_local_backlog_drains_all_pages_in_one_pump() { grant: None, uploads: vec![], refs: Vec::new(), + submitted: false, }); } r.store_mut() diff --git a/runtime/crates/replica/src/replica/mod.rs b/runtime/crates/replica/src/replica/mod.rs index afe9d4ad1..44d911fb6 100644 --- a/runtime/crates/replica/src/replica/mod.rs +++ b/runtime/crates/replica/src/replica/mod.rs @@ -136,6 +136,7 @@ mod query_index; mod query_profile; mod record_admission; pub(crate) mod ref_index; +mod refused; mod repair; pub(crate) mod snapshot; mod snapshot_text; @@ -464,6 +465,9 @@ pub struct Replica { pub(crate) repair_stats: lost_tail::RepairStats, /// Own acknowledged mutations being resurrected: mutation ID → earlier seq. pub(crate) resurrected: std::collections::BTreeMap, + /// Files whose rejected change the disk keeps (`refused.rs`). + pub(crate) refused: refused::Refused, + warn_oversized_file: Option, /// The revocation latch. pub(crate) latch: latch::Latch, /// When `log_regressed` was last raised (cleared after 24 hours). @@ -529,6 +533,8 @@ pub struct Replica { pub(crate) reading: bool, pub(crate) caught_up: bool, pub(crate) moved_streak: u32, + /// Send only the head row next: a batch was refused for one of its items. + pub(crate) append_probe: bool, pub(crate) stalled: Option<(IncidentKind, u64)>, stall_read: stall_read::ReadBackoff, /// Control read-ahead while waiting for a key (`join_ahead.rs`). @@ -852,6 +858,8 @@ impl Replica { let resurrected = lost_tail::decode_resurrected(store.meta(meta_keys::RESURRECT)?.as_deref()) .map_err(|e| OpenError::Corrupt(format!("resurrect set: {e}")))?; + let refused = refused::decode(store.meta(meta_keys::REFUSED)?.as_deref()) + .map_err(|e| OpenError::Corrupt(format!("refused files: {e}")))?; let latch = match store.meta(meta_keys::LATCH)? { Some(b) => latch::Latch::from_bytes(&b) .map_err(|e| OpenError::Corrupt(format!("revocation latch: {e}")))?, @@ -890,6 +898,8 @@ impl Replica { store_generation: 0, repair_stats: lost_tail::RepairStats::default(), resurrected, + refused, + warn_oversized_file: None, latch, regressed_at: None, orphans: orphan_rows, @@ -933,6 +943,7 @@ impl Replica { reading: false, caught_up: false, moved_streak: 0, + append_probe: false, stalled: None, stall_read: Default::default(), join_ahead: None, diff --git a/runtime/crates/replica/src/replica/refused.rs b/runtime/crates/replica/src/replica/refused.rs new file mode 100644 index 000000000..de878a1d8 --- /dev/null +++ b/runtime/crates/replica/src/replica/refused.rs @@ -0,0 +1,676 @@ +//! Refused files: the disk keeps the bytes of a rejected change ([`fences`]). +//! +//! Rejecting a pending change un-layers it, so the local view goes back to the +//! confirmed version. Publishing that would overwrite (or recreate, or delete) +//! what the user just wrote. Instead every record, file and resource a +//! rejected change targets is fenced: [`Replica::materialize`] and attachment fetch +//! publish nothing there, restart reconciliation leaves it alone, and the host +//! shows a per-file notice ([`Replica::refused_files`]). +//! +//! A fence ends when the user's next disk edit there is captured, in the +//! capture's own commit; a record edit is then planned from the version the +//! refused change was based on. A confirmed change of a fenced record from +//! elsewhere becomes an ordinary conflict hold (mine: what the disk shows; +//! theirs: the new confirmed version): at apply, or, when a snapshot or a +//! rollback installed it, at the user's next edit there. Persisted in +//! [`meta_keys::REFUSED`]. + +use std::collections::BTreeMap; + +use mdbn_wire::attachment_runtime_v1 as rt; +use mdbn_wire::cbor::{self, Cbor}; +use mdbn_wire::client::{Hold, HoldReason, Problem}; +use mdbn_wire::common::{B16, Text, Uuid}; +use mdbn_wire::entry::Effect; +use mdbn_wire::intent::{Create, Delete, DocVersion, Op, Rename, Source, Update}; +use mdbn_wire::schema::Wire; +use mdbn_wire::snapshot::TextOrBlob; + +use super::Replica; +use super::disk::{DiskKey, Shown}; +use crate::store::{MetaPut, Store, StoreError, Tx, meta_keys}; + +/// Whether a rejected row's files keep their bytes on disk (fenced) rather +/// than going back to the confirmed version: the user's own disk edits, and +/// on a store with files an app's write refused for the change itself (too +/// large, invalid, unencodable, a stale setup review), whose typed content the +/// app may not keep. Access and revocation rejections, and conflicts, revert. +pub(crate) fn fences(source: Source, problem: &Problem, has_files: bool) -> bool { + let item = matches!( + problem.code.as_str(), + "too_large" | "invalid_request" | "invalid_record" + ) || problem.reason.as_deref() == Some("setup_changed"); + source == Source::External || has_files && item +} + +/// Whether the log's refusal of one change (`too_large`) rejects it. An app's +/// write on a store without files stays pending and the append stops instead, +/// so its content is not lost: these wait on the SDK keeping the app's draft +/// on a late rejection. +pub(crate) fn rejects_log_refusal(source: Source, has_files: bool) -> bool { + source == Source::External || has_files +} + +/// One fenced file. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct RefusedFile { + /// The record or file whose change was refused. + pub(crate) id: Option, + /// Where the disk keeps the refused bytes. + pub(crate) path: String, + /// Why the change was refused. + pub(crate) problem: Problem, + /// When (host clock). + pub(crate) at: i64, + /// A record's text as the disk shows it (empty: deleted), for a conflict + /// hold. `None` for files, which stay fenced instead. + pub(crate) mine: Option, + /// The record version the refused edit was based on (none: a create). + pub(crate) base: Option, + /// The refused change deleted the file. + pub(crate) deleted: bool, + /// The bytes are an app's submission, not the user's disk edit: only then + /// may this replica's later app write replace them (absent in older meta: + /// a disk edit). + pub(crate) from_app: bool, +} + +/// The fenced files, by path key. +#[derive(Debug, Clone, Default, PartialEq)] +pub(crate) struct Refused(BTreeMap); + +fn key(path: &str) -> String { + mdbn_core::paths::path_key(path) +} + +impl Refused { + /// Whether `id` or any of `paths` is fenced. + pub(crate) fn fenced(&self, id: Option, paths: &[Option<&str>]) -> bool { + self.get(id, paths).is_some() + } + + /// The entry for `id`, else for the first fenced of `paths`. + pub(crate) fn get(&self, id: Option, paths: &[Option<&str>]) -> Option<&RefusedFile> { + id.and_then(|i| self.0.values().find(|f| f.id == Some(i))) + .or_else(|| paths.iter().flatten().find_map(|p| self.0.get(&key(p)))) + } + + /// Fence `files`, replacing earlier entries at the same paths, except + /// that an app's refused write never replaces a fence over the user's + /// refused disk edit: the disk still holds the user's bytes, and that + /// fence is what keeps them. + pub(crate) fn add(&mut self, files: Vec) { + for f in files { + let k = key(&f.path); + if f.from_app && self.0.get(&k).is_some_and(|old| !old.from_app) { + continue; + } + self.0.insert(k, f); + } + } + + /// Drop the entries for any of `ids` or `paths`. Returns whether any was. + fn remove(&mut self, ids: &[Option], paths: &[&str]) -> bool { + let n = self.0.len(); + self.0.retain(|k, f| { + let named = paths.iter().any(|p| key(p) == *k); + !(named || f.id.is_some() && ids.contains(&f.id)) + }); + self.0.len() != n + } + + pub(crate) fn meta(&self) -> MetaPut { + ( + meta_keys::REFUSED.into(), + (!self.0.is_empty()).then(|| encode(self)), + ) + } +} + +fn encode(refused: &Refused) -> Vec { + let entries = refused + .0 + .values() + .map(|f| { + Cbor::Array(vec![ + Cbor::Text(f.path.clone()), + f.id.map_or(Cbor::Null, |i| Cbor::Bytes(i.0.to_vec())), + f.problem.to_cbor(), + Cbor::int(f.at), + f.mine.clone().map_or(Cbor::Null, Cbor::Text), + f.base.as_ref().map_or(Cbor::Null, Wire::to_cbor), + Cbor::Bool(f.deleted), + Cbor::Bool(f.from_app), + ]) + }) + .collect(); + cbor::encode(&Cbor::Array(entries)).unwrap_or_default() +} + +/// The persisted fence (absent: empty). +pub(crate) fn decode(bytes: Option<&[u8]>) -> Result { + let mut out = Refused::default(); + let Some(bytes) = bytes else { + return Ok(out); + }; + let Ok(Cbor::Array(entries)) = cbor::decode(bytes) else { + return Err("not an array"); + }; + for e in entries { + let Cbor::Array(e) = e else { + return Err("entry"); + }; + let (e, from_app) = match e.as_slice() { + [rest @ .., Cbor::Bool(from_app)] if rest.len() == 7 => (rest, *from_app), + e => (e, false), + }; + let [ + Cbor::Text(path), + id, + problem, + at, + mine, + base, + Cbor::Bool(deleted), + ] = e + else { + return Err("entry"); + }; + let id = match id { + Cbor::Null => None, + Cbor::Bytes(b) => Some(B16(b.as_slice().try_into().map_err(|_| "id")?)), + _ => return Err("id"), + }; + let at = match at { + Cbor::Uint(v) => i64::try_from(*v).map_err(|_| "at")?, + Cbor::Nint(v) => -1 - i64::try_from(*v).map_err(|_| "at")?, + _ => return Err("at"), + }; + let mine = match mine { + Cbor::Null => None, + Cbor::Text(t) => Some(t.clone()), + _ => return Err("mine"), + }; + let base = match base { + Cbor::Null => None, + b => Some(DocVersion::from_cbor(b).map_err(|_| "base")?), + }; + out.add(vec![RefusedFile { + id, + path: path.clone(), + problem: Problem::from_cbor(problem).map_err(|_| "problem")?, + at, + mine, + base, + deleted: *deleted, + from_app, + }]); + } + Ok(out) +} + +/// The fence an apply keeps, and what the disk shows for the fences this +/// replica's own write ended. +pub(crate) type RefusedApply = (Refused, Vec<(DiskKey, Option)>); + +/// One record, file or resource (no ID) a change targets. +struct Target { + id: Option, + path: String, + mine: Option, + base: Option, + deleted: bool, +} + +fn inline(t: &Text) -> Option { + match t { + Text::Inline(s) => Some(s.clone()), + Text::Index(_) => None, + } +} + +impl Replica { + /// Send the host a collection-relative path when a file change is rejected + /// as too large and its bytes are kept on disk. + pub fn set_oversized_file_warning(&mut self, warn: fn(&str)) { + self.warn_oversized_file = Some(warn); + } + + /// Files whose change was rejected, kept as the user left them, with + /// why and whether the edit was a delete. Each clears when the user's next + /// change there is captured. + pub fn refused_files(&self) -> impl ExactSizeIterator { + self.refused + .0 + .values() + .map(|f| (f.path.as_str(), &f.problem, f.deleted)) + } + + /// The fence entries for rejected pending rows ([`fences`]). + pub(crate) fn refused_rows( + &self, + rejected: &[(Uuid, Option, Problem)], + ) -> Result, StoreError> { + let mut out = Vec::new(); + if !self.store.has_files() && !self.store.materializes_attachments() { + return Ok(out); + } + for (id, _, problem) in rejected { + let Some(row) = self.store.pending_get(id)? else { + continue; + }; + if fences(row.mutation.source, problem, self.store.has_files()) { + out.extend(self.refused_targets( + &row.mutation, + row.submitted, + &row.effects, + problem, + )?); + } + } + Ok(out) + } + + /// What a change targets, from its operations alone (never files a + /// planner rewrote along with it). An app's record write is found in its + /// planned `effects`, based on the confirmed record. + fn targets(&self, m: &rt::Mutation, effects: &[Effect]) -> Result, StoreError> { + let at = |id: Option, path: &str| Target { + id, + path: path.to_string(), + mine: None, + base: None, + deleted: false, + }; + let file = |id: Uuid, path: &str| at(Some(id), path); + let mut out = Vec::new(); + for op in &m.ops { + match op { + rt::Op::Legacy(Op::Document(d)) => { + let Some(v) = d.new.as_ref().or(d.base.as_ref()) else { + continue; + }; + out.push(Target { + mine: match &d.new { + Some(n) => inline(&n.doc), + None => Some(String::new()), + }, + base: d.base.clone(), + deleted: d.new.is_none(), + ..file(d.id, &v.path) + }); + } + rt::Op::Legacy( + Op::Create(Create { id, .. }) + | Op::Update(Update { id, .. }) + | Op::Delete(Delete { id, .. }) + | Op::Rename(Rename { id, .. }), + ) => { + let Some((path, mine, deleted)) = effects.iter().rev().find_map(|e| match e { + Effect::PutRecord(p) if p.id == *id => { + Some((&p.path, inline(&p.doc), false)) + } + Effect::RemoveRecord(r) if r.id == *id => { + Some((&r.path, Some(String::new()), true)) + } + _ => None, + }) else { + continue; + }; + out.push(Target { + mine, + base: self.store.record(id)?.map(|r| DocVersion { + path: r.path, + doc: Text::Inline(r.doc), + }), + deleted, + ..file(*id, path) + }); + } + rt::Op::Legacy(Op::FilePut(f)) => out.push(file(f.id, &f.path)), + rt::Op::Legacy(Op::FileMove(f)) => out.push(file(f.id, &f.to)), + rt::Op::Legacy(Op::FileDelete(f)) => { + if let Some(row) = self.store.file(&f.id)? { + out.push(Target { + deleted: true, + ..file(f.id, &row.path) + }); + } + } + rt::Op::FileAttach(f) => out.push(file(f.id, &f.path)), + rt::Op::OrdinaryAttachmentContinuation(f) => out.push(file(f.id, &f.path)), + rt::Op::UnindexedMarkdownPut(f) => out.push(file(f.id, &f.path)), + rt::Op::RecordToUnindexedMarkdown(f) => out.push(file(f.id, &f.path)), + rt::Op::UnindexedMarkdownToRecord(f) => out.push(file(f.id, &f.path)), + rt::Op::OrdinaryFileToRecord(f) => out.push(file(f.id, &f.path)), + rt::Op::Legacy(Op::ResourcePut(r)) => out.push(Target { + mine: inline(&r.doc), + ..at(None, &r.path) + }), + rt::Op::Legacy(Op::ResourceDelete(r)) => out.push(Target { + mine: Some(String::new()), + deleted: true, + ..at(None, &r.path) + }), + // Settings are not fenced. + rt::Op::Legacy(_) => {} + } + } + Ok(out) + } + + /// The fence entries for a refused change. + /// `submitted`: the change is an app's submission + /// ([`crate::store::PendingRow::submitted`]), + /// not a capture from disk or a hold resolution. + pub(crate) fn refused_targets( + &self, + m: &rt::Mutation, + submitted: bool, + effects: &[Effect], + problem: &Problem, + ) -> Result, StoreError> { + // `source` alone cannot tell: resource edits from disk are `api` writes. + let from_app = m.source != Source::External && submitted; + Ok(self + .targets(m, effects)? + .into_iter() + .map(|t| RefusedFile { + id: t.id, + path: t.path, + problem: problem.clone(), + at: self.now(), + mine: t.mine, + base: t.base, + deleted: t.deleted, + from_app, + }) + .collect()) + } + + /// A captured disk edit, or a hold resolution (the user chose), ends the + /// fence of what it targets, in the capture's commit. Returns the fence to + /// keep once `tx` commits. `submitted` marks an app's submission + /// ([`crate::store::PendingRow::submitted`]), which ends no fence here + /// (apply ends an app's own, [`Self::prepare_refused_holds`]). + pub(crate) fn release_refused( + &self, + m: &rt::Mutation, + submitted: bool, + tx: &mut Tx, + ) -> Result, StoreError> { + // A resource edit from disk is a captured `api` write; an app's resource + // write (e.g. a collection setup) must not end a fence over the user's + // refused disk edit. + let resources = !submitted + && m.ops.iter().all(|op| { + matches!( + op, + rt::Op::Legacy(Op::ResourcePut(_) | Op::ResourceDelete(_)) + ) + }); + let resolves_hold = !tx.holds_del.is_empty(); + if m.source != Source::External && !resources && !resolves_hold || self.refused.0.is_empty() + { + return Ok(None); + } + let mut ids = Vec::new(); + let mut paths = Vec::new(); + for op in &m.ops { + if let rt::Op::Legacy(Op::Document(d)) = op { + // A move or delete names the record's other path as its base. + if let Some(b) = &d.base { + paths.push(b.path.clone()); + } + } + } + for t in self.targets(m, &[])? { + ids.push(t.id); + paths.push(t.path); + } + let paths: Vec<&str> = paths.iter().map(String::as_str).collect(); + let mut rest = self.refused.clone(); + if !rest.remove(&ids, &paths) { + return Ok(None); + } + tx.meta.push(rest.meta()); + Ok(Some(rest)) + } + + /// Keep the fence `release_refused` left, once its transaction committed. + pub(crate) fn refused_released(&mut self, rest: Option) { + if let Some(rest) = rest { + self.refused = rest; + self.status_dirty = true; + } + } + + /// Keep the fence `rest` an apply left, and record what the disk shows + /// where this replica's own write ended a fence: the refused bytes, not + /// the view the write was layered over, so materialize publishes over them. + pub(crate) fn refused_applied(&mut self, (rest, shown): RefusedApply) { + self.before.extend(shown); + self.refused = rest; + self.status_dirty = true; + } + + /// The user's file kept the local view after all (a revert): its fence + /// ends with the acknowledgement. + pub(crate) fn ack_releasing( + &mut self, + token: crate::store::ObservationId, + id: Option, + path: &str, + ) -> Result<(), StoreError> { + let mut rest = self.refused.clone(); + let mut tx = Tx { + ack_observations: vec![token], + ..Tx::default() + }; + let released = rest.remove(&[id], &[path]); + if released { + tx.meta.push(rest.meta()); + } + self.store.commit(tx)?; + self.refused_released(released.then_some(rest)); + Ok(()) + } + + /// A disk edit of a fenced record whose confirmed version is no longer the + /// refused change's base (installed by a snapshot or a rollback; apply + /// makes its own holds): held as a conflict, as apply would (mine: the + /// disk's bytes), instead of planned. The fence ends and `token` is + /// acknowledged in the hold's commit. Returns whether it held. + pub(crate) fn hold_moved_refused( + &mut self, + id: Uuid, + fence: &RefusedFile, + path: &str, + text: Option<&str>, + token: crate::store::ObservationId, + ) -> Result { + let confirmed = self.store.record(&id)?; + let moved = match (&fence.base, &confirmed) { + (Some(b), Some(r)) => { + b.path != r.path || inline(&b.doc).as_deref() != Some(r.doc.as_str()) + } + (None, None) => false, + _ => true, + }; + if !moved { + return Ok(false); + } + let mut rest = self.refused.clone(); + rest.remove(&[Some(id)], &[path]); + let hold = Hold { + id, + path: path.to_string(), + reason: HoldReason::Conflict, + since: self.now(), + base: fence + .base + .as_ref() + .and_then(|b| inline(&b.doc)) + .map(TextOrBlob::Text), + mine: TextOrBlob::Text(text.unwrap_or_default().to_string()), + theirs: confirmed.map(|r| TextOrBlob::Text(r.doc)), + saves: 1, + }; + self.store.commit(Tx { + holds_put: vec![hold], + ack_observations: vec![token], + meta: vec![rest.meta()], + ..Tx::default() + })?; + self.refused = rest; + self.status_dirty = true; + self.push_holds(); + Ok(true) + } + + /// Apply of a confirmed entry touching fenced records, in its transaction. + /// This replica's `own` write, whatever its source, ends the fences of an + /// app's refused bytes it targets ([`Self::targets`]: not its planner + /// rewrites), which then materialize normally. Any other change of a + /// fenced record, including over a user's refused disk edit, becomes a + /// conflict hold so the user's bytes are never published over, matched by + /// record ID only; files and resources stay fenced. Returns the fence to + /// keep after commit and what the disk shows ([`Self::refused_applied`]). + pub(crate) fn prepare_refused_holds( + &self, + own: Option<&rt::Mutation>, + effects: &[Effect], + tx: &mut Tx, + ) -> Result, StoreError> { + let mut rest = self.refused.clone(); + let mut shown = Vec::new(); + if let Some(m) = own + && !rest.0.is_empty() + { + let targets = self.targets(m, effects)?; + rest.0.retain(|k, f| { + !(f.from_app + && targets + .iter() + .any(|t| key(&t.path) == *k || f.id.is_some() && t.id == f.id)) + }); + for (k, f) in &self.refused.0 { + let Some(mine) = f.mine.as_deref().filter(|_| !rest.0.contains_key(k)) else { + continue; + }; + // The bytes belong to the target that is the fenced record, or + // else to the one now written at its path (a new record there). + let owner = targets + .iter() + .find(|t| f.id.is_some() && t.id == f.id) + .or_else(|| targets.iter().find(|t| t.path == f.path)) + .map_or(f.id, |t| t.id); + let key = match owner { + Some(id) => DiskKey::Record(id), + None => DiskKey::Resource(f.path.clone()), + }; + let at = (!f.deleted).then(|| Shown { + path: f.path.clone(), + rev: mdbn_wire::hash::sha256(mine.as_bytes()), + }); + shown.push((key, at)); + } + } + for e in effects { + let id = match e { + Effect::PutRecord(p) => p.id, + Effect::RemoveRecord(p) => p.id, + _ => continue, + }; + let Some(f) = rest.0.values().find(|f| f.id == Some(id)).cloned() else { + continue; + }; + let Some(mine) = f.mine.clone() else { + continue; + }; + rest.remove(&[f.id], &[]); + if self.store.hold(&id)?.is_some() || tx.holds_put.iter().any(|h| h.id == id) { + continue; + } + let theirs = if let Some(r) = tx.records_put.iter().rev().find(|r| r.id == id) { + Some(TextOrBlob::Text(r.doc.clone())) + } else if tx.records_del.contains(&id) { + None + } else { + self.store.record(&id)?.map(|r| TextOrBlob::Text(r.doc)) + }; + tx.holds_put.push(Hold { + id, + path: f.path.clone(), + reason: HoldReason::Conflict, + since: self.now(), + base: self.store.record(&id)?.map(|r| TextOrBlob::Text(r.doc)), + mine: TextOrBlob::Text(mine), + theirs, + saves: 1, + }); + } + if rest == self.refused { + return Ok(None); + } + tx.meta.push(rest.meta()); + Ok(Some((rest, shown))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::api::ErrorCode; + + /// Who keeps a rejected change's bytes: a disk edit always; an app's write + /// only on a store with files and only for the change itself. + #[test] + fn which_rejections_are_fenced() { + let mut revoked = ErrorCode::Forbidden.problem("revoked"); + revoked.reason = Some("revoked_after_loss".into()); + let too_large = ErrorCode::TooLarge.problem_with_reason("item_bytes", "too large"); + let setup = ErrorCode::Conflict.problem_with_reason("setup_changed", "review again"); + for (source, problem, files, fenced) in [ + (Source::External, &revoked, true, true), + (Source::External, &too_large, true, true), + (Source::Api, &too_large, true, true), + ( + Source::Api, + &ErrorCode::InvalidRequest.problem("bad"), + true, + true, + ), + (Source::Api, &setup, true, true), + (Source::Api, &too_large, false, false), + (Source::Api, &revoked, true, false), + ( + Source::Api, + &ErrorCode::Unauthenticated.problem("no session"), + true, + false, + ), + ( + Source::Api, + &ErrorCode::Forbidden.problem("no capability"), + true, + false, + ), + ( + Source::Api, + &ErrorCode::Conflict.problem("path taken"), + true, + false, + ), + ] { + assert_eq!( + fences(source, problem, files), + fenced, + "{source:?} {problem:?} {files}" + ); + } + assert!(rejects_log_refusal(Source::External, false)); + assert!(rejects_log_refusal(Source::Api, true)); + assert!(!rejects_log_refusal(Source::Api, false)); + } +} diff --git a/runtime/crates/replica/src/replica/submit.rs b/runtime/crates/replica/src/replica/submit.rs index a8682b0a6..d8648babb 100644 --- a/runtime/crates/replica/src/replica/submit.rs +++ b/runtime/crates/replica/src/replica/submit.rs @@ -569,6 +569,7 @@ impl Replica { grant, uploads: Vec::new(), refs: Vec::new(), + submitted: self.store.has_files(), }; if local_owner.is_some() { self.session(session)?; diff --git a/runtime/crates/replica/src/replica/unindexed_capture_runtime.rs b/runtime/crates/replica/src/replica/unindexed_capture_runtime.rs index 99ede020f..0d945573b 100644 --- a/runtime/crates/replica/src/replica/unindexed_capture_runtime.rs +++ b/runtime/crates/replica/src/replica/unindexed_capture_runtime.rs @@ -42,11 +42,23 @@ impl Replica { } pub(super) fn commit_native_capture_tx( &mut self, - tx: Tx, + mut tx: Tx, unknown_reason: &str, ) -> StoreResult<()> { + // A disk edit ends the fence of a refused one there (`refused.rs`). + let refused = match tx + .pending_put + .first() + .map(|r| (r.mutation.clone(), r.submitted)) + { + Some((m, submitted)) => self.release_refused(&m, submitted, &mut tx)?, + None => None, + }; match self.store.commit(tx) { - Ok(_) => Ok(()), + Ok(_) => { + self.refused_released(refused); + Ok(()) + } Err(e) => { if !matches!(e, StoreError::CommitAborted(_)) { self.terminal_store_fault(unknown_reason); @@ -141,6 +153,7 @@ impl Replica { grant: None, uploads: Vec::new(), refs: refs.clone(), + submitted: token.is_none() && self.store.has_files(), }; // Reuse the append row checker; complete closure came only from the // opaque uploader, never from caller-declared refs. diff --git a/runtime/crates/replica/src/replica/unindexed_move.rs b/runtime/crates/replica/src/replica/unindexed_move.rs index ecae54173..1edad352f 100644 --- a/runtime/crates/replica/src/replica/unindexed_move.rs +++ b/runtime/crates/replica/src/replica/unindexed_move.rs @@ -381,6 +381,7 @@ impl Replica { grant: None, uploads: vec![], refs, + submitted: false, }], meta: fence_meta, ..Tx::default() diff --git a/runtime/crates/replica/src/replica/unindexed_reverse_capture.rs b/runtime/crates/replica/src/replica/unindexed_reverse_capture.rs index b8be14ba1..03a265b09 100644 --- a/runtime/crates/replica/src/replica/unindexed_reverse_capture.rs +++ b/runtime/crates/replica/src/replica/unindexed_reverse_capture.rs @@ -106,6 +106,7 @@ impl Replica { grant: None, uploads: vec![p.source], refs: p.refs, + submitted: observation.is_none() && self.store.has_files(), }; // The pending inline text is data for Core replanning; only wire emission // externalizes it. Preflight includes BOTH op/result references and GC refs. diff --git a/runtime/crates/replica/src/store.rs b/runtime/crates/replica/src/store.rs index 556e0ef3c..5f81f2aed 100644 --- a/runtime/crates/replica/src/store.rs +++ b/runtime/crates/replica/src/store.rs @@ -334,6 +334,15 @@ pub struct PendingRow { /// distinct ciphertext chunk and manifest Item hashes of an uploaded /// attachment (`log-entry.md` §2.1). Empty for every other row. pub refs: Vec, + /// An app's submission (a client `submit`, an app attachment upload, a + /// collection setup, an API unindexed capture), not a capture from disk, a + /// hold resolution or a native move. Device-local provenance for + /// refused-change fences (`refused.rs`), which `validated_at` cannot give + /// since a write may set its own level; never on the wire. Set only on + /// stores with files (the only ones that fence an app's write), so rows of + /// other stores (browser, hosted) keep their earlier bytes for a rollback. + /// Rows written before it read as captured. + pub submitted: bool, } impl PendingRow { @@ -350,9 +359,17 @@ impl PendingRow { }, self.uploads.to_cbor(), ]; - // Rows without refs keep their earlier six-element bytes. - if !self.refs.is_empty() { - fields.push(self.refs.to_cbor()); + // Captured rows without refs keep their earlier six-element bytes; a + // submitted row appends `true` after its refs (null when empty). + if !self.refs.is_empty() || self.submitted { + fields.push(if self.refs.is_empty() { + Cbor::Null + } else { + self.refs.to_cbor() + }); + } + if self.submitted { + fields.push(Cbor::Bool(true)); } let c = Cbor::Array(fields); // Encoding a well-formed value cannot fail; the codec only rejects @@ -364,9 +381,15 @@ impl PendingRow { pub fn from_bytes(bytes: &[u8]) -> Result { let c = cbor::decode(bytes)?; let a = mdbn_wire::schema::array(&c, "PendingRow")?; - let (order, m, e, t, g, u, refs) = match a { - [order, m, e, t, g, u] => (order, m, e, t, g, u, None), - [order, m, e, t, g, u, refs] => (order, m, e, t, g, u, Some(refs)), + let (order, m, e, t, g, u, refs, submitted) = match a { + [order, m, e, t, g, u] => (order, m, e, t, g, u, None, false), + [order, m, e, t, g, u, refs] => (order, m, e, t, g, u, Some(refs), false), + [order, m, e, t, g, u, Cbor::Null, Cbor::Bool(true)] => { + (order, m, e, t, g, u, None, true) + } + [order, m, e, t, g, u, refs, Cbor::Bool(true)] => { + (order, m, e, t, g, u, Some(refs), true) + } _ => { return Err(SchemaError::Invalid { ty: "PendingRow", @@ -399,6 +422,7 @@ impl PendingRow { }, uploads: Vec::::from_cbor(u)?, refs, + submitted, }) } } @@ -1491,6 +1515,9 @@ pub mod meta_keys { /// Lost-tail orphans: other authors' lost entries, and own writes lost after /// revocation (49-byte records). pub const ORPHANS: &str = "replica.orphans"; + /// Files whose change was rejected and whose disk bytes nothing may + /// overwrite until the user edits them again (`refused.rs`). Device-local. + pub const REFUSED: &str = "replica.refused"; /// Device materialization policy. pub const MATERIALIZATION: &str = "replica.materialization"; /// Local-only grants (collections without a log, policy.md preamble). diff --git a/runtime/crates/replica/src/tests/apply_results.rs b/runtime/crates/replica/src/tests/apply_results.rs index 1e11dfcf9..ec6c78676 100644 --- a/runtime/crates/replica/src/tests/apply_results.rs +++ b/runtime/crates/replica/src/tests/apply_results.rs @@ -751,6 +751,7 @@ fn conflicts_aliases_and_dismissals_are_stored_with_the_entry() { grant: None, uploads: Vec::new(), refs: Vec::new(), + submitted: false, }], ..Tx::default() }, @@ -855,6 +856,7 @@ fn own_conflicted_attachment_is_held_and_stops_its_fetch() { grant: None, uploads: Vec::new(), refs: Vec::new(), + submitted: false, }], ..Tx::default() }, @@ -883,6 +885,7 @@ fn own_pending_mutation_is_confirmed() { grant: None, uploads: Vec::new(), refs: Vec::new(), + submitted: false, }; seed( &mut n.r, @@ -1132,6 +1135,7 @@ fn busy_setup(n: &mut Node) -> Case { grant: None, uploads: Vec::new(), refs: Vec::new(), + submitted: false, }], ..Tx::default() }, diff --git a/runtime/crates/replica/src/tests/attachment_ingest.rs b/runtime/crates/replica/src/tests/attachment_ingest.rs index f19e141f0..d01bbcac5 100644 --- a/runtime/crates/replica/src/tests/attachment_ingest.rs +++ b/runtime/crates/replica/src/tests/attachment_ingest.rs @@ -212,6 +212,42 @@ fn a_delete_removes_the_file_everywhere() { assert!(a.r.store().att_disk().outstanding.is_empty()); } +/// A rejected delete of an attachment file (`refused.rs`) keeps the file +/// deleted here: it is not fetched back, now or after a restart. +#[test] +fn a_refused_attachment_delete_is_not_fetched_back() { + use crate::log::{LogError, LogErrorCode}; + let svc = FakeLogService::new(); + let (mut a, data_rc) = ingest_node(&svc, 1); + user(&mut a, |d| d.user_write(PATH, &data(2 * CHUNK + 10))); + let id = file_at(&a, PATH).unwrap().id; + a.log.faults.fail_appends = vec![LogError::Service { + code: LogErrorCode::TooLarge, + reason: Some("item_bytes".into()), + retry_after_ms: None, + missing: Vec::new(), + }]; + user(&mut a, |d| d.user_remove(PATH)); + assert!( + a.r.store().file(&id).unwrap().is_some(), + "the delete was rejected" + ); + let refused: Vec<_> = + a.r.refused_files() + .map(|(p, _, deleted)| (p.to_string(), deleted)) + .collect(); + assert_eq!(refused, vec![(PATH.to_string(), true)]); + assert!(!a.r.store().att_disk().files.contains_key(PATH)); + assert_eq!(a.r.attachment_chunks_fetched(), 0); + drop(a); + let mut a = attach_node_with(&svc, 1, MemStore::shared(data_rc)); + a.r.observe(None).unwrap(); + sync(&mut a); + assert_eq!(a.r.refused_files().len(), 1); + assert!(!a.r.store().att_disk().files.contains_key(PATH)); + assert_eq!(a.r.attachment_chunks_fetched(), 0); +} + #[test] fn an_interrupted_upload_resumes_from_its_checkpoint_after_a_restart() { let svc = FakeLogService::new(); diff --git a/runtime/crates/replica/src/tests/attachment_ingest/binary_holds.rs b/runtime/crates/replica/src/tests/attachment_ingest/binary_holds.rs index cde80ece5..8600c97fa 100644 --- a/runtime/crates/replica/src/tests/attachment_ingest/binary_holds.rs +++ b/runtime/crates/replica/src/tests/attachment_ingest/binary_holds.rs @@ -169,6 +169,7 @@ fn replanned_file_collision_fences_the_original_operation_path() { grant: None, uploads: Vec::new(), refs: Vec::new(), + submitted: false, }], ..Tx::default() }) diff --git a/runtime/crates/replica/src/tests/disk.rs b/runtime/crates/replica/src/tests/disk.rs index 8d2f10357..47a075b9b 100644 --- a/runtime/crates/replica/src/tests/disk.rs +++ b/runtime/crates/replica/src/tests/disk.rs @@ -969,6 +969,112 @@ fn settle(ns: &mut [&mut Node]) { } } +#[test] +fn a_private_disk_edit_over_the_sealed_entry_limit_keeps_its_bytes() { + use crate::seal::KeyringSealer; + use mdbn_wire::client::{ReceiptState, SyncMode}; + use mdbn_wire::policy::CState; + + static WARNINGS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + + let svc = FakeLogService::new(); + let device_id = B16([101; 16]); + let (sign_sk, kem_sk) = ([0x31; 32], [0x32; 32]); + crate::testkit::TestControlPlane::signed(COL).genesis_with_keys( + &svc, + CState::E2e, + device_id, + &sign_sk, + &kem_sk, + ); + let disk = Rc::new(RefCell::new(Disk::default())); + let clock = Rc::new(Cell::new(1_700_000_000_000)); + let mut replica = Replica::open( + ReplicaConfig { + collection: COL, + replica_id: B16([1; 16]), + device_id, + mode: SyncMode::Synced, + log_endpoint: EndpointId(1), + verify: true, + runtime_version: "test".into(), + trusted_roots: vec![crate::testkit::signed_root()], + e2e: true, + trusted_signers: vec![], + user_enabled_cloud_copy: false, + chosen_state: Some(CState::E2e), + key_grants_only: false, + expected_genesis: None, + policy_pins: None, + }, + DiskStore { + inner: MemStore::new(), + disk: disk.clone(), + barrier_fails: false, + }, + Box::new(crate::plan::CorePlanner), + Box::new(KeyringSealer::new(COL, device_id, &sign_sk, &kem_sk)), + Host { + clock: Box::new(TestClock(clock)), + entropy: Box::new(crate::crypto::TestEntropy::new(1)), + zones: Box::new(UtcOnly), + }, + DeviceSecrets { sign_sk, kem_sk }, + ) + .unwrap(); + replica.set_oversized_file_warning(|path| WARNINGS.lock().unwrap().push(path.into())); + let mut log = svc.client(device_id); + pump(&mut replica, &mut log, 100); + assert_eq!(replica.sealer.current_epoch(), Some(1)); + + let path = "journal.md"; + let original = format!("{}\n", "x".repeat(99)).repeat(3450); + let edited = format!("{original}{}\n", "y".repeat(99)); + disk.borrow_mut().keep_committed = true; + let mut save = |replica: &mut Replica, text: &str| { + disk.borrow_mut().user_write(path, Some(text)); + replica.observe(None).unwrap(); + pump(replica, &mut log, 100); + let receipts: Vec<_> = disk + .borrow_mut() + .committed + .drain(..) + .flat_map(|tx| tx.local_receipts_put) + .collect(); + let [receipt]: [LocalReceipt; 1] = receipts.try_into().unwrap(); + receipt + }; + + let receipt = save(&mut replica, &original); + assert_eq!(receipt.state, ReceiptState::Confirmed); + let receipt = save(&mut replica, &edited); + assert_eq!(receipt.state, ReceiptState::Confirmed); + assert!(disk.borrow().files[path] == edited); + let confirmed_head = replica.head(); + + // Even with the new document shared, old + new now exceed the sealed bound. + let oversized = format!("{edited}{}", "z".repeat(400_000)); + let receipt = save(&mut replica, &oversized); + assert_eq!(receipt.state, ReceiptState::Rejected); + let problem = receipt.problem.unwrap(); + assert_eq!(problem.code, "too_large"); + assert_eq!(problem.message, "the entry exceeds 1 MiB"); + assert_eq!(replica.head(), confirmed_head); + assert_eq!(replica.store().pending_count().unwrap(), 0); + assert!( + disk.borrow().files[path] == oversized, + "the confirmed version overwrote the rejected edit ({} bytes on disk, expected {})", + disk.borrow().files[path].len(), + oversized.len(), + ); + let notices: Vec<_> = replica + .refused_files() + .map(|(path, problem, deleted)| (path, problem.code.as_str(), deleted)) + .collect(); + assert_eq!(notices, [(path, "too_large", false)]); + assert_eq!(WARNINGS.lock().unwrap().as_slice(), [path]); +} + fn create(n: &mut Node, id: u8, path: &str, doc: &str) -> mdbn_wire::client::Receipt { n.r.submit( n.s, @@ -2765,6 +2871,7 @@ fn local_only_grants_come_from_the_host() { grant: Some(gid), uploads: Vec::new(), refs: Vec::new(), + submitted: false, }], ..Tx::default() }) @@ -3775,3 +3882,903 @@ fn synced_read_only_volume_applies_remote_entries_and_refuses_local_writes() { assert_eq!(err.problem().reason.as_deref(), Some("read_only_volume")); assert_eq!(b.r.sync_status().pending, 0); } + +// ------------------------------------------------- refused edits (`refused.rs`) + +/// More than the fake log takes in one item (see [`item_limited`]). +fn big() -> String { + "x".repeat(8192) +} + +/// A node whose log refuses items over 4 KiB `too_large`/`item_bytes`, as the +/// service does, with record 1 confirmed at `a.md`. +fn item_limited(svc: &FakeLogService, n: u8) -> Node { + let mut a = node(svc, n); + create(&mut a, 1, "a.md", "original"); + settle(&mut [&mut a]); + a.log.faults.item_bytes_limit = Some(4096); + a +} + +/// Save `text` at `path` on disk and ingest it; the captured mutation's ID. +fn save(n: &mut Node, path: &str, text: Option<&str>) -> Uuid { + n.disk.borrow_mut().user_write(path, text); + n.r.observe(None).unwrap(); + let rows = n.r.store().pending(None, 64).unwrap(); + rows.last().unwrap().mutation.id +} + +fn refused(n: &Node) -> Vec<(String, Option)> { + n.r.refused_files() + .map(|(p, problem, _)| (p.to_string(), problem.reason.clone())) + .collect() +} + +fn integrity(n: &Node) -> bool { + n.r.sync_status() + .incidents + .iter() + .any(|i| i.kind == mdbn_wire::client::IncidentKind::Integrity) +} + +fn rejected_with(n: &Node, m: &Uuid, reason: &str) { + let r = n.r.store().local_receipt(m).unwrap().unwrap(); + assert_eq!(r.state, mdbn_wire::client::ReceiptState::Rejected); + let p = r.problem.unwrap(); + assert_eq!(p.code, "too_large"); + assert_eq!(p.reason.as_deref(), Some(reason)); +} + +/// Exchange calls as `settle` does; the item count of every append sent. +fn settle_counting_appends(n: &mut Node) -> Vec { + use crate::log::{LogClient, LogPort}; + let mut sizes = Vec::new(); + for _ in 0..100 { + n.r.observe(None).unwrap(); + for call in n.r.take_log_calls() { + if let crate::log::LogRequest::Append(p) = &call.request { + sizes.push(p.items.len()); + } + let reply = n.log.call(call.request); + n.r.on_log_reply(call.id, reply); + } + n.r.tick(); + } + sizes +} + +/// (a) The log refuses one edit for its size: the edit is rejected, the file +/// keeps the user's bytes and says why, and the collection keeps syncing. +#[test] +fn a_refused_edit_is_rejected_and_keeps_the_user_bytes() { + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + let m = save(&mut a, "a.md", Some(&big())); + settle(&mut [&mut a]); + rejected_with(&a, &m, "item_bytes"); + assert_eq!(a.file("a.md"), Some(big()), "the user's bytes are kept"); + assert_eq!( + a.r.store().record(&B16([1; 16])).unwrap().unwrap().doc, + "original" + ); + assert_eq!( + refused(&a), + vec![("a.md".into(), Some("item_bytes".into()))] + ); + assert!(a.r.list_holds(a.s).unwrap().is_empty()); + assert!(!integrity(&a)); + assert_ne!(a.r.append, crate::replica::append::AppendState::Stopped); + // Other files keep syncing. + a.disk.borrow_mut().user_write("b.md", Some("fine")); + settle(&mut [&mut a]); + assert_eq!(a.r.store().pending_count().unwrap(), 0); + assert_eq!(a.r.store().record_count().unwrap(), 2); + assert_eq!(a.file("a.md"), Some(big())); +} + +/// (b) Editing the refused file again syncs the new bytes from the local view: +/// no hold, and the fence is gone. +#[test] +fn editing_a_refused_file_again_syncs_it() { + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + save(&mut a, "a.md", Some(&big())); + settle(&mut [&mut a]); + assert_eq!(refused(&a).len(), 1); + let m = save(&mut a, "a.md", Some("smaller")); + settle(&mut [&mut a]); + assert!(a.r.list_holds(a.s).unwrap().is_empty()); + assert_eq!( + a.r.store().local_receipt(&m).unwrap().unwrap().state, + mdbn_wire::client::ReceiptState::Confirmed + ); + assert_eq!( + a.r.store().record(&B16([1; 16])).unwrap().unwrap().doc, + "smaller" + ); + assert_eq!(a.file("a.md").as_deref(), Some("smaller")); + assert!(refused(&a).is_empty()); +} + +/// (b) A refused move edited again at its new path moves the same record: +/// the old path is not recreated, now or after a restart. +#[test] +fn editing_a_refused_move_again_moves_the_record() { + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + move_file(&mut a, "a.md", "b.md", &big()); + settle(&mut [&mut a]); + assert_eq!( + refused(&a), + vec![("b.md".into(), Some("item_bytes".into()))] + ); + assert!(a.file("a.md").is_none(), "the move is not undone"); + assert_eq!(a.file("b.md"), Some(big())); + save(&mut a, "b.md", Some("moved")); + settle(&mut [&mut a]); + assert!(a.r.list_holds(a.s).unwrap().is_empty()); + assert!(refused(&a).is_empty()); + let row = a.r.store().record(&B16([1; 16])).unwrap().unwrap(); + assert_eq!((row.path.as_str(), row.doc.as_str()), ("b.md", "moved")); + assert_eq!(a.r.store().record_count().unwrap(), 1); + let Node { r, log, disk, .. } = a; + let mut a = reopen(&svc, 1, r.into_store(), log, disk); + settle(&mut [&mut a]); + assert!(a.file("a.md").is_none()); + assert_eq!(a.file("b.md").as_deref(), Some("moved")); +} + +/// (c) A refused delete is not undone: the file is not recreated, now or +/// after a restart. +#[test] +fn a_refused_delete_is_not_recreated() { + use crate::log::{LogError, LogErrorCode}; + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + a.log.faults.fail_appends = vec![LogError::Service { + code: LogErrorCode::TooLarge, + reason: Some("item_bytes".into()), + retry_after_ms: None, + missing: Vec::new(), + }]; + let m = save(&mut a, "a.md", None); + settle(&mut [&mut a]); + rejected_with(&a, &m, "item_bytes"); + assert!(a.file("a.md").is_none()); + assert!(a.r.store().record(&B16([1; 16])).unwrap().is_some()); + assert_eq!( + refused(&a), + vec![("a.md".into(), Some("item_bytes".into()))] + ); + let Node { r, log, disk, .. } = a; + let mut a = reopen(&svc, 1, r.into_store(), log, disk); + settle(&mut [&mut a]); + assert!(a.file("a.md").is_none(), "not recreated at open"); + assert_eq!(refused(&a).len(), 1); +} + +/// (d) The fence and its notice survive a restart; nothing is re-sent and the +/// file is untouched. +#[test] +fn a_refused_edit_stays_refused_after_a_restart() { + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + let m = save(&mut a, "a.md", Some(&big())); + settle(&mut [&mut a]); + let head = svc.head(&COL); + let Node { r, log, disk, .. } = a; + let mut a = reopen(&svc, 1, r.into_store(), log, disk); + let appends = settle_counting_appends(&mut a); + assert!(appends.is_empty(), "{appends:?}"); + assert_eq!(svc.head(&COL), head); + rejected_with(&a, &m, "item_bytes"); + assert_eq!( + refused(&a), + vec![("a.md".into(), Some("item_bytes".into()))] + ); + assert_eq!(a.file("a.md"), Some(big())); + assert_eq!(a.r.store().pending_count().unwrap(), 0); + assert!(a.r.list_holds(a.s).unwrap().is_empty()); +} + +/// (e) An edit shrunk but still too large is refused again, its notice still +/// shown; the real fix then syncs. No circuit breaker stops the loop. +#[test] +fn a_still_too_large_edit_is_refused_again_then_a_fix_syncs() { + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + let first = save(&mut a, "a.md", Some(&big())); + settle(&mut [&mut a]); + rejected_with(&a, &first, "item_bytes"); + let smaller = "x".repeat(6000); + let second = save(&mut a, "a.md", Some(&smaller)); + settle(&mut [&mut a]); + rejected_with(&a, &second, "item_bytes"); + assert_eq!( + refused(&a), + vec![("a.md".into(), Some("item_bytes".into()))] + ); + assert_eq!(a.file("a.md"), Some(smaller)); + assert!(!integrity(&a)); + let fixed = save(&mut a, "a.md", Some("fixed")); + settle(&mut [&mut a]); + assert_eq!( + a.r.store().local_receipt(&fixed).unwrap().unwrap().state, + mdbn_wire::client::ReceiptState::Confirmed + ); + assert_eq!( + a.r.store().record(&B16([1; 16])).unwrap().unwrap().doc, + "fixed" + ); + assert!(refused(&a).is_empty()); + assert!(a.r.list_holds(a.s).unwrap().is_empty()); +} + +/// (e) Two oversized autosaves of one file in one batch are both rejected; the +/// loop does not stop. +#[test] +fn two_oversized_autosaves_in_one_batch_are_both_rejected() { + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + let first = save(&mut a, "a.md", Some(&big())); + let later = "y".repeat(8192); + let second = save(&mut a, "a.md", Some(&later)); + assert_ne!(first, second); + settle(&mut [&mut a]); + for m in [first, second] { + assert_eq!( + a.r.store().local_receipt(&m).unwrap().unwrap().state, + mdbn_wire::client::ReceiptState::Rejected + ); + } + assert_eq!(a.file("a.md"), Some(later)); + assert_eq!(refused(&a).len(), 1); + assert_eq!(a.r.store().pending_count().unwrap(), 0); + assert!(!integrity(&a)); + assert_ne!(a.r.append, crate::replica::append::AppendState::Stopped); +} + +/// (e) Two different oversized files are both rejected; the loop does not stop. +#[test] +fn two_different_oversized_files_are_both_rejected() { + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + let one = save(&mut a, "a.md", Some(&big())); + settle(&mut [&mut a]); + let two = save(&mut a, "b.md", Some(&big())); + settle(&mut [&mut a]); + rejected_with(&a, &one, "item_bytes"); + rejected_with(&a, &two, "item_bytes"); + assert_eq!(refused(&a).len(), 2); + assert_eq!(a.file("b.md"), Some(big())); + assert!(!integrity(&a)); + assert_ne!(a.r.append, crate::replica::append::AppendState::Stopped); +} + +/// (f) A refused batch is probed one row at a time: only the guilty edit is +/// rejected; the others confirm. +#[test] +fn a_refused_batch_rejects_only_the_guilty_item() { + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + { + let mut d = a.disk.borrow_mut(); + d.user_write("one.md", Some("1")); + d.user_write("big.md", Some(&big())); + d.user_write("two.md", Some("2")); + } + let appends = settle_counting_appends(&mut a); + assert!( + appends.windows(2).any(|w| w[0] > 1 && w[1] == 1), + "a multi-item refusal sends the head alone: {appends:?}" + ); + assert_eq!(a.r.store().pending_count().unwrap(), 0); + assert_eq!(a.r.store().record_count().unwrap(), 3); + assert_eq!( + refused(&a), + vec![("big.md".into(), Some("item_bytes".into()))] + ); + assert_eq!(a.file("big.md"), Some(big())); + assert!(!integrity(&a)); + assert_ne!(a.r.append, crate::replica::append::AppendState::Stopped); + // The probe is one-shot: later batches carry several items again. + { + let mut d = a.disk.borrow_mut(); + d.user_write("three.md", Some("3")); + d.user_write("four.md", Some("4")); + } + let appends = settle_counting_appends(&mut a); + assert_eq!(appends, vec![2]); +} + +/// (g) Refusals that are not about one change still stop the loop with an +/// integrity incident, and nothing is rejected or published. +#[test] +fn chain_signature_epoch_and_not_found_refusals_still_stop() { + use crate::log::{LogError, LogErrorCode}; + for (code, reason) in [ + (LogErrorCode::Invalid, Some("kind")), + (LogErrorCode::Invalid, Some("shape")), + (LogErrorCode::Invalid, Some("chain")), + (LogErrorCode::Invalid, Some("signature")), + (LogErrorCode::Invalid, Some("epoch")), + (LogErrorCode::NotFound, None), + ] { + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + a.log.faults.fail_appends = vec![LogError::Service { + code, + reason: reason.map(String::from), + retry_after_ms: None, + missing: Vec::new(), + }]; + let m = save(&mut a, "a.md", Some("edited")); + settle(&mut [&mut a]); + assert!(integrity(&a), "{reason:?}"); + assert_eq!(a.r.append, crate::replica::append::AppendState::Stopped); + assert!(a.r.store().pending_get(&m).unwrap().is_some()); + assert!(a.r.store().local_receipt(&m).unwrap().is_none()); + assert!(refused(&a).is_empty()); + assert_eq!(a.file("a.md").as_deref(), Some("edited")); + } +} + +/// (h) A disk edit rejected while planning its append (over 1 MiB sealed, with +/// the real planner) keeps the user's bytes, and the store knows those bytes, +/// so nothing overwrites them, now or after a restart. +#[test] +fn a_disk_edit_too_large_to_append_keeps_its_bytes() { + let svc = FakeLogService::new(); + let mut a = node(&svc, 1); + a.r.planner = Box::new(crate::plan::CorePlanner); + a.disk.borrow_mut().user_write("a.md", Some("original")); + settle(&mut [&mut a]); + assert_eq!(a.r.store().record_count().unwrap(), 1); + let doc = "y".repeat(1_000_000); + a.disk.borrow_mut().user_write("a.md", Some(&doc)); + settle(&mut [&mut a]); + assert_eq!(a.r.store().pending_count().unwrap(), 0); + let id = crate::Store::record_at(a.r.store(), &mdbn_core::paths::path_key("a.md")) + .unwrap() + .unwrap(); + assert_eq!(a.r.store().record(&id).unwrap().unwrap().doc, "original"); + let problems: Vec<_> = + a.r.refused_files() + .map(|(p, problem, _)| (p.to_string(), problem.code.clone())) + .collect(); + assert_eq!(problems, vec![("a.md".into(), "too_large".into())]); + assert_eq!(a.file("a.md").as_deref(), Some(doc.as_str())); + assert_eq!(a.disk.borrow().known.get("a.md"), Some(&h(&doc))); + assert!(!integrity(&a)); + let Node { r, log, disk, .. } = a; + let mut a = reopen(&svc, 1, r.into_store(), log, disk); + a.r.planner = Box::new(crate::plan::CorePlanner); + settle(&mut [&mut a]); + assert_eq!(a.file("a.md").as_deref(), Some(doc.as_str())); + assert_eq!(a.disk.borrow().known.get("a.md"), Some(&h(&doc))); + assert_eq!(refused(&a).len(), 1); +} + +/// (h) An app's write too large to append keeps the bytes its records left on +/// disk (a store with files). +#[test] +fn an_app_write_too_large_to_append_keeps_its_files() { + let svc = FakeLogService::new(); + let mut a = node(&svc, 1); + settle(&mut [&mut a]); + let doc = "y".repeat(300_000); + let paths = ["h1.md", "h2.md", "h3.md", "h4.md"]; + let r = + a.r.submit( + a.s, + SubmitParams { + ops: paths + .iter() + .enumerate() + .map(|(i, p)| { + Op::Create(Create { + id: B16([40 + i as u8; 16]), + path: Some((*p).into()), + type_name: None, + frontmatter: None, + body: None, + document: Some(Text::Inline(doc.clone())), + }) + }) + .collect(), + mutation_id: None, + conflict_mode: None, + timezone: None, + allow_partial: None, + mutation_ids: None, + dry_run: None, + include: None, + wait: None, + validation: None, + }, + ) + .unwrap() + .remove(0); + settle(&mut [&mut a]); + let receipt = a.r.store().local_receipt(&r.mutation).unwrap().unwrap(); + assert_eq!(receipt.state, mdbn_wire::client::ReceiptState::Rejected); + assert_eq!(receipt.problem.unwrap().code, "too_large"); + for p in paths { + assert_eq!(a.file(p).as_deref(), Some(doc.as_str()), "{p}"); + } + assert_eq!(refused(&a).len(), paths.len()); + assert_eq!(a.r.store().record_count().unwrap(), 0); + assert!(!integrity(&a)); +} + +/// (i) A confirmed change elsewhere to a refused file becomes a conflict hold +/// (mine: the bytes on disk; theirs: the new version), never published over. +#[test] +fn a_remote_change_to_a_refused_file_is_held_as_a_conflict() { + use mdbn_wire::snapshot::TextOrBlob; + let svc = FakeLogService::new(); + let mut a = node(&svc, 1); + let mut b = node(&svc, 2); + create(&mut a, 1, "a.md", "original"); + settle(&mut [&mut a, &mut b]); + a.log.faults.item_bytes_limit = Some(4096); + save(&mut a, "a.md", Some(&big())); + settle(&mut [&mut a]); + assert_eq!(refused(&a).len(), 1); + b.disk.borrow_mut().user_write("a.md", Some("theirs")); + settle(&mut [&mut a, &mut b]); + assert_eq!(a.file("a.md"), Some(big()), "the disk is untouched"); + let holds = a.r.list_holds(a.s).unwrap(); + assert_eq!(holds.len(), 1); + assert_eq!(holds[0].reason, mdbn_wire::client::HoldReason::Conflict); + assert_eq!(holds[0].path, "a.md"); + assert_eq!(holds[0].mine, TextOrBlob::Text(big())); + assert_eq!(holds[0].theirs, Some(TextOrBlob::Text("theirs".into()))); + assert!(refused(&a).is_empty(), "the hold replaces the fence"); + assert!(!integrity(&a)); + assert_eq!(b.file("a.md").as_deref(), Some("theirs")); +} + +/// An app's write the log refuses for its size, on a store with files: its +/// bytes stay on disk with a notice, and a later edit of the file syncs. +#[test] +fn an_app_write_refused_for_its_size_keeps_its_bytes_until_edited() { + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + let m = create(&mut a, 2, "app.md", &big()).mutation; + settle(&mut [&mut a]); + rejected_with(&a, &m, "item_bytes"); + assert_eq!(a.file("app.md"), Some(big())); + assert_eq!( + refused(&a), + vec![("app.md".into(), Some("item_bytes".into()))] + ); + assert!(!integrity(&a)); + let edit = save(&mut a, "app.md", Some("typed")); + settle(&mut [&mut a]); + assert_eq!( + a.r.store().local_receipt(&edit).unwrap().unwrap().state, + mdbn_wire::client::ReceiptState::Confirmed + ); + let row = a.r.store().record(&B16([2; 16])).unwrap().unwrap(); + assert_eq!((row.path.as_str(), row.doc.as_str()), ("app.md", "typed")); + assert!(refused(&a).is_empty()); +} + +/// An app's write rejected for anything but the change itself (here a +/// conflict) reverts as before: no fence, no notice. +#[test] +fn an_app_write_rejected_for_a_conflict_reverts() { + let svc = FakeLogService::new(); + let mut a = node(&svc, 1); + let mut b = node(&svc, 2); + settle(&mut [&mut a, &mut b]); + let m = create(&mut a, 2, "same.md", "app").mutation; + a.r.observe(None).unwrap(); + create(&mut b, 3, "same.md", "theirs"); + settle(&mut [&mut b]); + settle(&mut [&mut a, &mut b]); + let r = a.r.store().local_receipt(&m).unwrap().unwrap(); + assert_eq!(r.state, mdbn_wire::client::ReceiptState::Rejected); + assert_eq!(r.problem.unwrap().code, "conflict"); + assert!(refused(&a).is_empty()); + assert_eq!(a.file("same.md").as_deref(), Some("theirs")); +} + +/// A refused move whose new path another device then takes with a different +/// record: the fence (matched by record) survives, the old path is not +/// recreated, and the new path keeps the user's bytes. +#[test] +fn a_refused_move_keeps_its_fence_when_another_record_takes_its_path() { + let svc = FakeLogService::new(); + let mut a = node(&svc, 1); + let mut b = node(&svc, 2); + create(&mut a, 1, "a.md", "original"); + settle(&mut [&mut a, &mut b]); + a.log.faults.item_bytes_limit = Some(4096); + move_file(&mut a, "a.md", "b.md", &big()); + settle(&mut [&mut a]); + assert_eq!(refused(&a).len(), 1); + create(&mut b, 2, "b.md", "another"); + settle(&mut [&mut a, &mut b]); + assert_eq!( + a.r.store().record(&B16([2; 16])).unwrap().unwrap().path, + "b.md" + ); + assert_eq!( + refused(&a), + vec![("b.md".into(), Some("item_bytes".into()))] + ); + assert!(a.r.list_holds(a.s).unwrap().is_empty()); + assert!(a.file("a.md").is_none(), "not recreated"); + assert_eq!(a.file("b.md"), Some(big())); +} + +/// A snapshot install does not publish over a fenced record, and the next +/// edit there, its base no longer the confirmed version, is a conflict hold +/// (mine: the disk's bytes) as apply would make: the disk keeps the user's +/// bytes in every state, through a restart too. +#[test] +fn a_snapshot_under_a_refused_file_then_an_edit_is_held() { + use mdbn_wire::snapshot::TextOrBlob; + let svc = FakeLogService::new(); + let mut a = node(&svc, 1); + let mut b = node(&svc, 2); + create(&mut a, 1, "a.md", "original"); + settle(&mut [&mut a, &mut b]); + b.log.faults.item_bytes_limit = Some(4096); + save(&mut b, "a.md", Some(&big())); + settle(&mut [&mut b]); + assert_eq!(refused(&b).len(), 1); + assert_eq!(b.file("a.md"), Some(big())); + save(&mut a, "a.md", Some("theirs")); + settle(&mut [&mut a]); + let seq = a.r.head().seq; + a.r.build_snapshot_now().unwrap(); + settle(&mut [&mut a]); + svc.compact(&COL, seq); + // B missed the entries: it finds them compacted and installs the snapshot. + let _ = crate::log::LogClient::poll_pushes(&mut b.log); + crate::log::LogPort::on_log_push(&mut b.r, crate::log::LogPush::Reconnected); + settle(&mut [&mut b]); + assert_eq!(b.r.stats.snapshots_installed, 1); + assert_eq!( + b.r.store().record(&B16([1; 16])).unwrap().unwrap().doc, + "theirs" + ); + assert_eq!(b.file("a.md"), Some(big()), "the disk is untouched"); + b.disk.borrow_mut().user_write("a.md", Some("mine again")); + settle(&mut [&mut a, &mut b]); + assert_eq!(b.file("a.md").as_deref(), Some("mine again")); + let holds = b.r.list_holds(b.s).unwrap(); + assert_eq!(holds.len(), 1, "{holds:?}"); + assert_eq!(holds[0].reason, mdbn_wire::client::HoldReason::Conflict); + assert_eq!(holds[0].path, "a.md"); + assert_eq!(holds[0].mine, TextOrBlob::Text("mine again".into())); + assert_eq!(holds[0].theirs, Some(TextOrBlob::Text("theirs".into()))); + assert!(b.r.store().conflicts(None).unwrap().is_empty()); + assert_eq!(b.r.store().pending_count().unwrap(), 0); + assert!(refused(&b).is_empty(), "the hold replaces the fence"); + assert_eq!( + a.r.store().record(&B16([1; 16])).unwrap().unwrap().doc, + "theirs", + "not overwritten" + ); + let Node { r, log, disk, .. } = b; + let mut b = reopen(&svc, 2, r.into_store(), log, disk); + settle(&mut [&mut a, &mut b]); + assert_eq!(b.file("a.md").as_deref(), Some("mine again")); + assert_eq!(b.r.list_holds(b.s).unwrap().len(), 1); +} + +/// A resource edited on disk (an `api` write) that the log refuses for its +/// size keeps its bytes with a notice; a later edit syncs. +#[test] +fn a_refused_resource_edit_keeps_its_bytes_until_edited() { + let svc = FakeLogService::new(); + let mut a = node(&svc, 1); + a.r.planner = Box::new(crate::plan::CorePlanner); + let config = "spec_version: 0.3.0\nsettings:\n timezone: UTC\n"; + a.disk.borrow_mut().user_write("mdbase.yaml", Some(config)); + settle(&mut [&mut a]); + assert_eq!( + a.r.store().resource("mdbase.yaml").unwrap().as_deref(), + Some(config) + ); + a.log.faults.item_bytes_limit = Some(4096); + let large = format!("{config}# {}\n", "x".repeat(8192)); + a.disk.borrow_mut().user_write("mdbase.yaml", Some(&large)); + settle(&mut [&mut a]); + assert_eq!( + a.file("mdbase.yaml"), + Some(large.clone()), + "the user's bytes are kept" + ); + assert_eq!( + a.r.store().resource("mdbase.yaml").unwrap().as_deref(), + Some(config) + ); + assert_eq!( + refused(&a), + vec![("mdbase.yaml".into(), Some("item_bytes".into()))] + ); + assert!(!integrity(&a)); + assert_eq!(a.r.store().pending_count().unwrap(), 0); + let fixed = format!("{config}# fixed\n"); + a.disk.borrow_mut().user_write("mdbase.yaml", Some(&fixed)); + settle(&mut [&mut a]); + assert_eq!( + a.r.store().resource("mdbase.yaml").unwrap().as_deref(), + Some(fixed.as_str()) + ); + assert_eq!(a.file("mdbase.yaml"), Some(fixed)); + assert!(refused(&a).is_empty()); + assert!(!integrity(&a)); +} + +/// The app's whole-document write of record 1 at `a.md`, based on `base`. +fn app_document(n: &mut Node, base: &str, doc: &str) -> mdbn_wire::client::Receipt { + app_document_at(n, base, doc, None) +} + +/// [`app_document`] at the write's own validation `level`. +fn app_document_at( + n: &mut Node, + base: &str, + doc: &str, + level: Option, +) -> mdbn_wire::client::Receipt { + use mdbn_wire::intent::{DocVersion, Document}; + let version = |d: &str| DocVersion { + path: "a.md".into(), + doc: Text::Inline(d.into()), + }; + n.r.submit( + n.s, + SubmitParams { + ops: vec![Op::Document(Document { + id: B16([1; 16]), + base: Some(version(base)), + new: Some(version(doc)), + if_revision: None, + })], + mutation_id: None, + conflict_mode: None, + timezone: None, + allow_partial: None, + mutation_ids: None, + dry_run: None, + include: None, + wait: None, + validation: level, + }, + ) + .unwrap() + .remove(0) +} + +/// An app's write refused for its size is fenced; the app's own corrected +/// write then ends the fence and reaches the disk, with no conflict hold. +#[test] +fn an_app_fix_after_an_app_refusal_reaches_disk() { + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + let refused_write = app_document(&mut a, "original", &big()).mutation; + settle(&mut [&mut a]); + rejected_with(&a, &refused_write, "item_bytes"); + assert_eq!(a.file("a.md"), Some(big())); + assert_eq!(refused(&a).len(), 1); + let fix = app_document(&mut a, "original", "small").mutation; + settle(&mut [&mut a]); + assert_eq!( + a.r.store().local_receipt(&fix).unwrap().unwrap().state, + mdbn_wire::client::ReceiptState::Confirmed + ); + assert_eq!(a.file("a.md").as_deref(), Some("small")); + assert!(a.r.list_holds(a.s).unwrap().is_empty()); + assert!(refused(&a).is_empty()); +} + +/// A hold resolved on a fenced record (the resolution is an `api` write) +/// ends the fence once confirmed, and the resolution reaches the disk. +#[test] +fn a_hold_resolution_on_a_refused_file_clears_its_fence() { + use mdbn_wire::snapshot::TextOrBlob; + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + save(&mut a, "a.md", Some(&big())); + settle(&mut [&mut a]); + assert_eq!(refused(&a).len(), 1); + a.r.store + .commit(Tx { + holds_put: vec![Hold { + id: B16([1; 16]), + path: "a.md".into(), + reason: mdbn_wire::client::HoldReason::SuspectWrite, + since: 1, + base: None, + mine: TextOrBlob::Text(big()), + theirs: Some(TextOrBlob::Text("original".into())), + saves: 1, + }], + ..Tx::default() + }) + .unwrap(); + a.r.resolve_hold(a.s, B16([1; 16]), HoldResolution::Use("resolved".into())) + .unwrap(); + settle(&mut [&mut a]); + assert_eq!( + a.r.store().record(&B16([1; 16])).unwrap().unwrap().doc, + "resolved" + ); + assert_eq!(a.file("a.md").as_deref(), Some("resolved")); + assert!(a.r.list_holds(a.s).unwrap().is_empty()); + assert!(refused(&a).is_empty()); +} + +/// An app's create refused and fenced, then the app's create of a different +/// record at that path: the new record reaches the disk and the fence ends. +#[test] +fn an_app_create_at_a_refused_path_reaches_disk() { + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + let refused_create = create(&mut a, 2, "new.md", &big()).mutation; + settle(&mut [&mut a]); + rejected_with(&a, &refused_create, "item_bytes"); + assert_eq!(a.file("new.md"), Some(big())); + let fix = create(&mut a, 3, "new.md", "small").mutation; + settle(&mut [&mut a]); + assert_eq!( + a.r.store().local_receipt(&fix).unwrap().unwrap().state, + mdbn_wire::client::ReceiptState::Confirmed + ); + assert_eq!(a.file("new.md").as_deref(), Some("small")); + assert!(a.r.list_holds(a.s).unwrap().is_empty()); + assert!(refused(&a).is_empty()); +} + +/// The user's disk edit refused for its size, then an app's update of that +/// record: a conflict hold keeps the user's bytes; the app's write does not +/// replace them. +#[test] +fn an_app_update_over_a_refused_disk_edit_is_held() { + use mdbn_wire::snapshot::TextOrBlob; + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + save(&mut a, "a.md", Some(&big())); + settle(&mut [&mut a]); + assert_eq!(refused(&a).len(), 1); + app_document(&mut a, "original", "app"); + settle(&mut [&mut a]); + assert_eq!(a.file("a.md"), Some(big())); + let holds = a.r.list_holds(a.s).unwrap(); + assert_eq!(holds.len(), 1); + assert_eq!(holds[0].reason, mdbn_wire::client::HoldReason::Conflict); + assert_eq!(holds[0].mine, TextOrBlob::Text(big())); +} + +/// The user's disk edit refused, then an app's write of that record refused +/// too: the fence stays the user's, so the app's next write is held against +/// the user's bytes rather than replacing them. +#[test] +fn an_app_refusal_over_a_refused_disk_edit_keeps_the_users_fence() { + use mdbn_wire::snapshot::TextOrBlob; + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + save(&mut a, "a.md", Some(&big())); + settle(&mut [&mut a]); + assert_eq!(refused(&a).len(), 1); + app_document(&mut a, "original", &"y".repeat(8192)); + settle(&mut [&mut a]); + assert_eq!(refused(&a).len(), 1); + assert_eq!(a.file("a.md"), Some(big())); + app_document(&mut a, "original", "app"); + settle(&mut [&mut a]); + assert_eq!(a.file("a.md"), Some(big())); + let holds = a.r.list_holds(a.s).unwrap(); + assert!( + holds.iter().any(|h| h.mine == TextOrBlob::Text(big())), + "the user's bytes are held: {holds:?}" + ); +} + +/// [`an_app_refusal_over_a_refused_disk_edit_keeps_the_users_fence`] with the +/// app writing at `warn`: the fence's provenance comes from how the change was +/// made, not the validation level it carries. +#[test] +fn a_warn_level_app_refusal_over_a_refused_disk_edit_keeps_the_users_fence() { + use mdbn_wire::snapshot::TextOrBlob; + let warn = Some(mdbn_wire::intent::Level::Warn); + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + save(&mut a, "a.md", Some(&big())); + settle(&mut [&mut a]); + assert_eq!(refused(&a).len(), 1); + app_document_at(&mut a, "original", &"y".repeat(8192), warn); + settle(&mut [&mut a]); + assert_eq!(refused(&a).len(), 1); + assert_eq!(a.file("a.md"), Some(big())); + app_document_at(&mut a, "original", "app", warn); + settle(&mut [&mut a]); + assert_eq!(a.file("a.md"), Some(big())); + let holds = a.r.list_holds(a.s).unwrap(); + assert!( + holds.iter().any(|h| h.mine == TextOrBlob::Text(big())), + "the user's bytes are held: {holds:?}" + ); +} + +/// [`an_app_fix_after_an_app_refusal_reaches_disk`] with the app writing at +/// `warn`: its own fence ends and the fix reaches the disk, with no hold. +#[test] +fn a_warn_level_app_fix_after_its_refusal_reaches_disk() { + let warn = Some(mdbn_wire::intent::Level::Warn); + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + let refused_write = app_document_at(&mut a, "original", &big(), warn).mutation; + settle(&mut [&mut a]); + rejected_with(&a, &refused_write, "item_bytes"); + assert_eq!(refused(&a).len(), 1); + app_document_at(&mut a, "original", "small", warn); + settle(&mut [&mut a]); + let holds = a.r.list_holds(a.s).unwrap(); + assert!(holds.is_empty(), "no hold: {holds:?}"); + assert_eq!(a.file("a.md").as_deref(), Some("small")); + assert!(refused(&a).is_empty()); +} + +/// The user's new file refused for its size, then an app's create of a +/// record at that path: the user's file stays fenced, not overwritten. +#[test] +fn an_app_create_at_a_refused_disk_create_keeps_the_users_file() { + let svc = FakeLogService::new(); + let mut a = item_limited(&svc, 1); + save(&mut a, "new.md", Some(&big())); + settle(&mut [&mut a]); + assert_eq!(refused(&a).len(), 1); + create(&mut a, 3, "new.md", "app"); + settle(&mut [&mut a]); + assert_eq!(a.file("new.md"), Some(big())); + assert_eq!(refused(&a).len(), 1); +} + +/// The user's resource edit refused for its size, then an app's write of +/// that resource: the user's file stays fenced, not overwritten. +#[test] +fn an_app_resource_write_over_a_refused_resource_edit_keeps_the_users_file() { + let svc = FakeLogService::new(); + let mut a = node(&svc, 1); + a.r.planner = Box::new(crate::plan::CorePlanner); + let config = "spec_version: 0.3.0\nsettings:\n timezone: UTC\n"; + a.disk.borrow_mut().user_write("mdbase.yaml", Some(config)); + settle(&mut [&mut a]); + a.log.faults.item_bytes_limit = Some(4096); + let large = format!("{config}# {}\n", "x".repeat(8192)); + a.disk.borrow_mut().user_write("mdbase.yaml", Some(&large)); + settle(&mut [&mut a]); + assert_eq!(refused(&a).len(), 1); + a.r.submit( + a.s, + SubmitParams { + ops: vec![Op::ResourcePut(mdbn_wire::intent::ResourcePut { + path: "mdbase.yaml".into(), + doc: Text::Inline(format!("{config}# app\n")), + base_revision: None, + must_not_exist: None, + })], + mutation_id: None, + conflict_mode: None, + timezone: None, + allow_partial: None, + mutation_ids: None, + dry_run: None, + include: None, + wait: None, + validation: None, + }, + ) + .unwrap(); + settle(&mut [&mut a]); + assert_eq!(a.file("mdbase.yaml"), Some(large)); + assert_eq!(refused(&a).len(), 1); +} diff --git a/runtime/crates/replica/src/tests/engine.rs b/runtime/crates/replica/src/tests/engine.rs index 50f062e9d..d287d70fb 100644 --- a/runtime/crates/replica/src/tests/engine.rs +++ b/runtime/crates/replica/src/tests/engine.rs @@ -5101,6 +5101,38 @@ fn concurrent_repairers_converge_and_late_devices_read_the_restored_items() { assert_eq!(c.doc(3).as_deref(), Some("x")); } +/// On a store without files the log's size refusal of an app's write does not +/// reject it (the app may not keep the content): the append stops with an +/// integrity incident and the row stays pending (`refused.rs`). +#[test] +fn a_refused_app_write_without_files_stops_and_stays_pending() { + let svc = FakeLogService::new(); + let mut a = node(&svc, 1, MemStore::new()); + a.create(1, "a.md", "x"); + settle(&mut [&mut a]); + a.log.faults.item_bytes_limit = Some(4096); + let m = a.create(2, "big.md", &"x".repeat(8192)).mutation; + settle(&mut [&mut a]); + assert!( + a.r.sync_status() + .incidents + .iter() + .any(|i| i.kind == mdbn_wire::client::IncidentKind::Integrity) + ); + assert_eq!(a.r.append, crate::replica::append::AppendState::Stopped); + assert!( + crate::Store::pending_get(a.r.store(), &m) + .unwrap() + .is_some() + ); + assert!( + crate::Store::local_receipt(a.r.store(), &m) + .unwrap() + .is_none() + ); + assert_eq!(a.r.refused_files().len(), 0); +} + /// When another writer already took the lost positions (`L < S`), re-appending is /// impossible. The fallback (§5) rolls this replica back to the service's history /// and resurrects its own acknowledged writes at new positions: no acknowledged @@ -7280,3 +7312,18 @@ fn change_feed_marks_file_puts_and_removals_as_files() { "{kinds:?}" ); } + +/// An app's submission on a store without files records no provenance: its +/// pending row keeps the bytes an older build decodes (a hosted or browser +/// rollback), since only a store with files fences an app's write. +#[test] +fn a_submitted_row_without_files_keeps_its_earlier_bytes() { + let svc = FakeLogService::new(); + let mut a = node(&svc, 1, MemStore::new()); + a.log.faults.offline = true; + let m = a.create(1, "a.md", "hello").mutation; + let row = crate::Store::pending_get(a.r.store(), &m).unwrap().unwrap(); + assert!(!row.submitted); + let c = mdbn_wire::cbor::decode(&row.to_bytes()).unwrap(); + assert!(matches!(c, mdbn_wire::cbor::Cbor::Array(ref a) if a.len() == 6)); +} diff --git a/runtime/crates/replica/src/tests/hosted.rs b/runtime/crates/replica/src/tests/hosted.rs index 2de2ab312..54636386d 100644 --- a/runtime/crates/replica/src/tests/hosted.rs +++ b/runtime/crates/replica/src/tests/hosted.rs @@ -1149,6 +1149,7 @@ fn open_hosted_refuses_a_store_with_durable_pending_rows() { grant: None, uploads: Vec::new(), refs: Vec::new(), + submitted: false, }], ..Tx::default() }) @@ -1280,6 +1281,7 @@ fn hosted_cache_never_reports_commit_aborted() { grant: None, uploads: Vec::new(), refs: Vec::new(), + submitted: false, }; c.commit(Tx { pending_put: vec![row(1)], @@ -1585,6 +1587,7 @@ fn growing_replan_closes_admission_until_drained() { grant: None, uploads: Vec::new(), refs: Vec::new(), + submitted: false, }; let put = |c: &mut HostedCache, r| { c.commit(Tx { @@ -1650,6 +1653,7 @@ fn replans_are_hard_capped_per_row() { grant: None, uploads: Vec::new(), refs: Vec::new(), + submitted: false, }; let put = |c: &mut HostedCache, r| { c.commit(Tx { diff --git a/runtime/crates/replica/tests/interfaces.rs b/runtime/crates/replica/tests/interfaces.rs index 1eedf0675..7b6495576 100644 --- a/runtime/crates/replica/tests/interfaces.rs +++ b/runtime/crates/replica/tests/interfaces.rs @@ -50,9 +50,29 @@ fn pending_row_round_trips() { grant: Some(B16([5; 16])), uploads: vec![], refs: Vec::new(), + submitted: false, }; let back = PendingRow::from_bytes(&row.to_bytes()).expect("decodes"); assert_eq!(back, row); + // An app's submission keeps its provenance, with or without refs; a + // captured row keeps the earlier bytes. + let submitted = PendingRow { + submitted: true, + ..row.clone() + }; + assert_ne!(submitted.to_bytes(), row.to_bytes()); + assert_eq!( + PendingRow::from_bytes(&submitted.to_bytes()).unwrap(), + submitted + ); + let with_refs = PendingRow { + refs: vec![B32([6; 32])], + ..submitted + }; + assert_eq!( + PendingRow::from_bytes(&with_refs.to_bytes()).unwrap(), + with_refs + ); } #[test] diff --git a/runtime/docs/contracts/log-entry.md b/runtime/docs/contracts/log-entry.md index de1908a5c..3aa1973a8 100644 --- a/runtime/docs/contracts/log-entry.md +++ b/runtime/docs/contracts/log-entry.md @@ -182,9 +182,10 @@ Rules: Blob-backed texts are uploaded before the append, like file blobs, and listed in the header's `refs`. -- **Writers emit whole documents today, and history depends on it.** Every record - write stores its document inline; the only text-table use is a blob-backed text - when a large unindexed Markdown file becomes a record. The history reader +- **Writers emit whole documents today, and history depends on it.** Record + writes store whole documents. A document edit can share one literal text-table + entry between its new document and the identical result. A large unindexed + Markdown file becoming a record can use a blob-backed text. The history reader (`replica-client-api.md` §4.4) reads each version from its own entry and refuses a record text that is a delta. A writer that adopts deltas must keyframe each record: write the whole document when the record's previous write is more than From 18746beda6325c67c38bf88c2b12151e747f9207 Mon Sep 17 00:00:00 2001 From: mdbase release automation Date: Sat, 28 Nov 2026 22:10:56 +1100 Subject: [PATCH 2/4] Track acknowledged revisions in the replica test disk without rescanning every file --- runtime/crates/replica/src/tests/disk.rs | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/runtime/crates/replica/src/tests/disk.rs b/runtime/crates/replica/src/tests/disk.rs index 47a075b9b..62c9e1c43 100644 --- a/runtime/crates/replica/src/tests/disk.rs +++ b/runtime/crates/replica/src/tests/disk.rs @@ -447,15 +447,21 @@ impl Store for DiskStore { d.publish_attempts += publish.len() as u64; // Acknowledged observations must not be reoffered by an earlier deferral. d.queued.retain(|o| !acks.contains(&o.token)); - // Acknowledged observations: their bytes are now known. - for a in acks { - d.outstanding.remove(&a); - } - let paths: Vec = d.files.keys().cloned().collect(); - d.known.retain(|path, _| paths.contains(path)); - for p in paths { - let r = h(&d.files[&p]); - d.known.insert(p, r); + // Like FileStore, acknowledge only the observed revisions in this commit. + for token in acks { + let Some(observation) = d.outstanding.remove(&token) else { + continue; + }; + if let Some(from) = observation.moved_from { + d.known.remove(&from); + } + match observation.now { + Some(Observed::Text(text)) => d.known.insert(observation.path, h(&text)), + Some(Observed::Attachment { digest, .. }) => { + d.known.insert(observation.path, digest) + } + None => d.known.remove(&observation.path), + }; } let mut report = CommitReport::default(); if !publish.is_empty() && d.drop_publishes > 0 { From 7ed4e0b55a8c1becfc10ddbea55d794543ca1e15 Mon Sep 17 00:00:00 2001 From: mdbase release automation Date: Sat, 28 Nov 2026 22:14:04 +1100 Subject: [PATCH 3/4] Exercise a genuinely oversized sealed edit after literal sharing --- runtime/crates/replica/src/tests/disk.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/runtime/crates/replica/src/tests/disk.rs b/runtime/crates/replica/src/tests/disk.rs index 62c9e1c43..2a81105e3 100644 --- a/runtime/crates/replica/src/tests/disk.rs +++ b/runtime/crates/replica/src/tests/disk.rs @@ -4237,7 +4237,10 @@ fn a_disk_edit_too_large_to_append_keeps_its_bytes() { let svc = FakeLogService::new(); let mut a = node(&svc, 1); a.r.planner = Box::new(crate::plan::CorePlanner); - a.disk.borrow_mut().user_write("a.md", Some("original")); + // Both documents are admissible alone. The base plus one copy of the + // replacement still exceeds the sealed limit after literal sharing. + let original = "x".repeat(64 * 1024); + a.disk.borrow_mut().user_write("a.md", Some(&original)); settle(&mut [&mut a]); assert_eq!(a.r.store().record_count().unwrap(), 1); let doc = "y".repeat(1_000_000); @@ -4247,20 +4250,23 @@ fn a_disk_edit_too_large_to_append_keeps_its_bytes() { let id = crate::Store::record_at(a.r.store(), &mdbn_core::paths::path_key("a.md")) .unwrap() .unwrap(); - assert_eq!(a.r.store().record(&id).unwrap().unwrap().doc, "original"); + assert!( + a.r.store().record(&id).unwrap().unwrap().doc == original, + "the refused edit must leave the confirmed document intact" + ); let problems: Vec<_> = a.r.refused_files() .map(|(p, problem, _)| (p.to_string(), problem.code.clone())) .collect(); assert_eq!(problems, vec![("a.md".into(), "too_large".into())]); - assert_eq!(a.file("a.md").as_deref(), Some(doc.as_str())); + assert!(a.file("a.md").as_deref() == Some(doc.as_str())); assert_eq!(a.disk.borrow().known.get("a.md"), Some(&h(&doc))); assert!(!integrity(&a)); let Node { r, log, disk, .. } = a; let mut a = reopen(&svc, 1, r.into_store(), log, disk); a.r.planner = Box::new(crate::plan::CorePlanner); settle(&mut [&mut a]); - assert_eq!(a.file("a.md").as_deref(), Some(doc.as_str())); + assert!(a.file("a.md").as_deref() == Some(doc.as_str())); assert_eq!(a.disk.borrow().known.get("a.md"), Some(&h(&doc))); assert_eq!(refused(&a).len(), 1); } From 4c0c5dcbee614bc890b3abc74756f665449504e3 Mon Sep 17 00:00:00 2001 From: mdbase release automation Date: Sat, 28 Nov 2026 22:22:40 +1100 Subject: [PATCH 4/4] Regenerate the SDK runtime pin and method inventory on b639385 --- runtime/packages/sdk/scripts/runtime-methods.json | 2 +- runtime/packages/sdk/src/application/asset-pins.json | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/runtime/packages/sdk/scripts/runtime-methods.json b/runtime/packages/sdk/scripts/runtime-methods.json index d3773318a..73726ff19 100644 --- a/runtime/packages/sdk/scripts/runtime-methods.json +++ b/runtime/packages/sdk/scripts/runtime-methods.json @@ -1,6 +1,6 @@ { "source": { - "commit": "80279ab7b08e946e1de7e20adfeb3bd5df574591", + "commit": "7ed4e0b55a8c1becfc10ddbea55d794543ca1e15", "path": "runtime/crates/replica/src/frames.rs" }, "methods": [ diff --git a/runtime/packages/sdk/src/application/asset-pins.json b/runtime/packages/sdk/src/application/asset-pins.json index 29580e3cf..197b857d8 100644 --- a/runtime/packages/sdk/src/application/asset-pins.json +++ b/runtime/packages/sdk/src/application/asset-pins.json @@ -1,11 +1,11 @@ { "runtime": { - "sha256": "440557ae32a12e79ed753291b6e29be07e999779477477ec298a30bf9626ed12", - "bytes": 4105446, - "maxBytes": 4105446, + "sha256": "a27b57d4cb9c978725922af25928bb4242eb9580fa502815ea75993bbe92fe20", + "bytes": 4135951, + "maxBytes": 4135951, "source": { "repository": "mdbase-dev/mdbase-connect", - "commit": "80279ab7b08e946e1de7e20adfeb3bd5df574591" + "commit": "7ed4e0b55a8c1becfc10ddbea55d794543ca1e15" } }, "sqlite": {