From 4931c173f2508a89bcb0b8328852bdbb5a3c85c4 Mon Sep 17 00:00:00 2001 From: dhruv8sh Date: Wed, 25 Nov 2026 19:24:43 +0530 Subject: [PATCH 1/7] Add a bounded re-read and re-plan update for records RecordHandle::update reads a record, plans its replacement and writes it with IfGenerationMatch, or Add after a miss. After a lost precondition it reads and plans again up to the given attempts, stops on a stale re-read, never replays an uncertain mutation, and reports the conflict count. Providers without record operations report Unsupported. Closes #535 Signed-off-by: dhruv8sh --- CHANGELOG.md | 10 + crates/edgezero-core/src/record_store.rs | 575 +++++++++++++++++++++++ docs/guide/kv-records.md | 47 +- 3 files changed, 631 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 448c45324..526932c29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +### Bounded record update (#535) + +`RecordHandle::update` reads a record, asks a caller's planner for its replacement and writes +it with `IfGenerationMatch`, or `Add` after a miss. After a lost precondition it reads and +plans again, up to a caller-supplied number of attempts, and reports `Written`, `Skipped`, +`Conflict` or `StaleRead` with the number of conflicts. A re-read that returns the rejected +generation or misses ends the update as `StaleRead`. Errors are not retried and +`MutationUncertain` is never replayed. Providers without record operations report +`Unsupported`. + ### Axum buffered JSON limits and body API Axum now defaults framework-managed JSON buffering to 2 MiB, exactly 2,097,152 bytes. diff --git a/crates/edgezero-core/src/record_store.rs b/crates/edgezero-core/src/record_store.rs index f3ba6edfb..2d4520ed4 100644 --- a/crates/edgezero-core/src/record_store.rs +++ b/crates/edgezero-core/src/record_store.rs @@ -221,6 +221,7 @@ pub mod contract { use std::collections::BTreeMap; use std::fmt; +use std::num::NonZeroU8; use std::sync::Arc; use std::time::Duration; @@ -297,6 +298,40 @@ pub enum RecordWriteOutcome { Written, } +/// A replacement planned against the record [`RecordHandle::update`] read. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct RecordReplacement { + /// Replacement value bytes. + pub body: Bytes, + /// Optional UTF-8 text, normalized before provider I/O. + pub metadata: Option, + /// Native provider TTL, or no expiry. + pub ttl: Option, +} + +/// How a [`RecordHandle::update`] ended when no read or write failed. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum RecordUpdateOutcome { + /// Every attempt lost its Add/CAS precondition. Nothing was written. + Conflict, + /// The planner declined the record as read, with its reason. + Skipped(Reason), + /// A re-read after a lost precondition was older than the rejection. Nothing + /// was written. + StaleRead, + /// One replacement won its precondition and was acknowledged. + Written, +} + +/// The result of a [`RecordHandle::update`] and the conflicts it met. +#[derive(Debug)] +pub struct RecordUpdate { + /// Add/CAS precondition rejections, counted even when the update fails. + pub conflicts: u8, + /// The outcome, or the read or write error that ended the update. + pub result: Result, KvError>, +} + /// Full logical keys from one strong partition page, without ordering promises. /// Empty and short pages may have continuation. Only `cursor == None` ends a traversal. #[derive(Clone, Debug, Default, Eq, PartialEq)] @@ -707,4 +742,544 @@ impl RecordHandle { pub fn partition(&self, prefix: &str) -> Result { self.binding.layout.partition(prefix) } + + /// Read a record, plan its replacement and write it conditionally, re-planning + /// after a lost precondition for at most `attempts` writes. + /// + /// Each attempt looks the record up and passes it to `plan`, then writes the + /// replacement with [`RecordWriteMode::IfGenerationMatch`] on the generation + /// read, or [`RecordWriteMode::Add`] when the lookup missed. `plan` returns + /// `Err` with its reason to leave the record unchanged. A definitive + /// precondition rejection wrote nothing, so the record is read and planned + /// again; the update stops at the first acknowledged write, so at most one + /// replacement lands. + /// + /// A lost precondition proves the record exists under another generation. A + /// re-read that returns the rejected generation or misses is older than that + /// rejection, as an eventually consistent lookup can be, and ends the update + /// with [`RecordUpdateOutcome::StaleRead`]. A record deleted after the + /// rejection reads the same way. Generations are not ordered, so an older + /// distinct generation cannot be detected; a replacement planned on it loses + /// its precondition. + /// + /// Read and write errors end the update without a retry. A + /// [`KvError::MutationUncertain`] write is never replayed. A binding whose + /// provider lacks record operations reports [`KvError::Unsupported`]. + /// + /// # Performance + /// One lookup and at most one conditional insert per attempt. + #[inline] + pub async fn update( + &self, + key: &str, + attempts: NonZeroU8, + mut plan: Plan, + ) -> RecordUpdate + where + Plan: FnMut(Option<&Record>) -> Result, + { + let mut conflicts = 0_u8; + let mut rejected = None; + let result = loop { + let current = match self.lookup(key).await { + Ok(current) => current, + Err(error) => break Err(error), + }; + if let Some(lost) = rejected + && current.as_ref().is_none_or(|record| { + lost == RecordWriteMode::IfGenerationMatch(record.generation) + }) + { + break Ok(RecordUpdateOutcome::StaleRead); + } + let mode = current.as_ref().map_or(RecordWriteMode::Add, |record| { + RecordWriteMode::IfGenerationMatch(record.generation) + }); + let replacement = match plan(current.as_ref()) { + Ok(replacement) => replacement, + Err(reason) => break Ok(RecordUpdateOutcome::Skipped(reason)), + }; + let write = RecordWrite { + body: &replacement.body, + metadata: replacement.metadata.as_deref(), + mode, + ttl: replacement.ttl, + }; + match self.insert(key, write).await { + Ok(RecordWriteOutcome::Written) => break Ok(RecordUpdateOutcome::Written), + Ok(RecordWriteOutcome::PreconditionFailed) => { + conflicts = conflicts.saturating_add(1); + if conflicts >= attempts.get() { + break Ok(RecordUpdateOutcome::Conflict); + } + rejected = Some(mode); + } + Err(error) => break Err(error), + } + }; + RecordUpdate { conflicts, result } + } +} + +#[cfg(test)] +mod tests { + use std::collections::VecDeque; + use std::sync::Mutex; + + use async_trait::async_trait; + use futures::executor::block_on; + + use super::*; + use crate::key_value_store::KvPage; + + // Advertises a record binding but keeps every record operation Unsupported. + struct BindingOnly; + + struct FirstSegment; + + // Replays scripted lookups and insert outcomes, recording each insert mode. + #[derive(Default)] + struct Scripted { + lookups: Mutex, KvError>>>, + modes: Mutex>, + writes: Mutex>>, + } + + impl RecordKeyLayout for FirstSegment { + fn id(&self) -> &'static str { + "test-first-segment" + } + + fn partition_prefix<'key>(&self, key: &'key str) -> Result<&'key str, KvError> { + key.find('/') + .and_then(|slash| key.get(..=slash)) + .ok_or_else(|| KvError::Validation("missing key group".to_owned())) + } + + fn validate(&self) -> Result<(), KvError> { + Ok(()) + } + + fn validate_partition(&self, _prefix: &str) -> Result<(), KvError> { + Ok(()) + } + + fn version(&self) -> u32 { + 1 + } + } + + impl Scripted { + fn modes(&self) -> Vec { + self.modes.lock().unwrap().clone() + } + + fn new( + lookups: impl IntoIterator, KvError>>, + writes: impl IntoIterator>, + ) -> Arc { + Arc::new(Self { + lookups: Mutex::new(lookups.into_iter().collect()), + modes: Mutex::default(), + writes: Mutex::new(writes.into_iter().collect()), + }) + } + } + + #[async_trait(?Send)] + #[expect( + clippy::missing_trait_methods, + reason = "update uses only lookup and insert, so the other record operations stay Unsupported" + )] + impl KvStore for Scripted { + async fn delete(&self, _key: &str) -> Result<(), KvError> { + Err(KvError::Unavailable) + } + + async fn get_bytes(&self, _key: &str) -> Result, KvError> { + Err(KvError::Unavailable) + } + + async fn list_keys_page( + &self, + _prefix: &str, + _cursor: Option<&str>, + _limit: usize, + ) -> Result { + Err(KvError::Unavailable) + } + + async fn put_bytes(&self, _key: &str, _value: Bytes) -> Result<(), KvError> { + Err(KvError::Unavailable) + } + + async fn put_bytes_with_ttl( + &self, + _key: &str, + _value: Bytes, + _ttl: Duration, + ) -> Result<(), KvError> { + Err(KvError::Unavailable) + } + + fn record_binding(&self) -> Option { + Some(binding()) + } + + async fn record_insert( + &self, + _key: &str, + _partition: &RecordPartition, + write: RecordWrite<'_>, + ) -> Result { + self.modes.lock().unwrap().push(write.mode); + self.writes + .lock() + .unwrap() + .pop_front() + .expect("should script every insert") + } + + async fn record_lookup( + &self, + _key: &str, + _partition: &RecordPartition, + ) -> Result, KvError> { + self.lookups + .lock() + .unwrap() + .pop_front() + .expect("should script every lookup") + } + } + + #[async_trait(?Send)] + #[expect( + clippy::missing_trait_methods, + reason = "the provider intentionally retains Unsupported record operations" + )] + impl KvStore for BindingOnly { + async fn delete(&self, _key: &str) -> Result<(), KvError> { + Ok(()) + } + + async fn get_bytes(&self, _key: &str) -> Result, KvError> { + Ok(None) + } + + async fn list_keys_page( + &self, + _prefix: &str, + _cursor: Option<&str>, + _limit: usize, + ) -> Result { + Ok(KvPage::default()) + } + + async fn put_bytes(&self, _key: &str, _value: Bytes) -> Result<(), KvError> { + Ok(()) + } + + async fn put_bytes_with_ttl( + &self, + _key: &str, + _value: Bytes, + _ttl: Duration, + ) -> Result<(), KvError> { + Ok(()) + } + + fn record_binding(&self) -> Option { + Some(binding()) + } + } + + fn record(generation: u64) -> Record { + Record { + body: Bytes::from_static(b"current"), + generation: RecordGeneration::from_u64(generation), + metadata: None, + } + } + + fn binding() -> RecordBinding { + RecordBinding { + format: "test-v1".to_owned(), + layout: RecordLayout::new(FirstSegment).unwrap(), + max_metadata_bytes: 1024, + scope: "test".to_owned(), + } + } + + fn handle(store: &Arc) -> RecordHandle { + let shared: Arc = Arc::clone(store); + RecordHandle::new(shared).unwrap() + } + + fn if_match(generation: u64) -> RecordWriteMode { + RecordWriteMode::IfGenerationMatch(RecordGeneration::from_u64(generation)) + } + + fn replacement() -> RecordReplacement { + RecordReplacement { + body: Bytes::from_static(b"next"), + metadata: None, + ttl: None, + } + } + + // Runs an update that always plans a replacement and returns the generations + // each attempt planned against. + fn update( + store: &Arc, + attempts: u8, + ) -> (RecordUpdate<&'static str>, Vec>) { + let records = handle(store); + let mut planned = Vec::new(); + let result = block_on(records.update( + "group/key", + NonZeroU8::new(attempts).unwrap(), + |current: Option<&Record>| { + planned.push(current.map(|record| record.generation)); + Ok(replacement()) + }, + )); + (result, planned) + } + + #[test] + fn update_writes_against_the_generation_read() { + let store = Scripted::new([Ok(Some(record(1)))], [Ok(RecordWriteOutcome::Written)]); + + let (result, planned) = update(&store, 2); + + assert_eq!( + result.result.unwrap(), + RecordUpdateOutcome::Written, + "should write on the first attempt" + ); + assert_eq!(result.conflicts, 0, "should report no conflicts"); + assert_eq!(planned, [Some(RecordGeneration::from_u64(1))]); + assert_eq!( + store.modes(), + [if_match(1)], + "should CAS on the read generation" + ); + } + + #[test] + fn update_adds_when_the_lookup_misses() { + let store = Scripted::new([Ok(None)], [Ok(RecordWriteOutcome::Written)]); + + let (result, planned) = update(&store, 2); + + assert_eq!(result.result.unwrap(), RecordUpdateOutcome::Written); + assert_eq!(planned, [None], "should plan against the missing record"); + assert_eq!( + store.modes(), + [RecordWriteMode::Add], + "should write with Add" + ); + } + + #[test] + fn update_replans_against_a_fresh_read_after_a_conflict() { + let store = Scripted::new( + [Ok(Some(record(1))), Ok(Some(record(2)))], + [ + Ok(RecordWriteOutcome::PreconditionFailed), + Ok(RecordWriteOutcome::Written), + ], + ); + + let (result, planned) = update(&store, 2); + + assert_eq!( + result.result.unwrap(), + RecordUpdateOutcome::Written, + "should land the re-planned write" + ); + assert_eq!(result.conflicts, 1, "should count the lost CAS"); + assert_eq!( + planned, + [ + Some(RecordGeneration::from_u64(1)), + Some(RecordGeneration::from_u64(2)) + ], + "should plan again against the re-read" + ); + assert_eq!(store.modes(), [if_match(1), if_match(2)]); + } + + #[test] + fn update_gives_up_when_every_attempt_conflicts() { + let store = Scripted::new( + [Ok(Some(record(1))), Ok(Some(record(2)))], + [ + Ok(RecordWriteOutcome::PreconditionFailed), + Ok(RecordWriteOutcome::PreconditionFailed), + ], + ); + + let (result, _planned) = update(&store, 2); + + assert_eq!( + result.result.unwrap(), + RecordUpdateOutcome::Conflict, + "should give up after the attempt bound" + ); + assert_eq!(result.conflicts, 2, "should count both lost CAS writes"); + assert_eq!(store.modes().len(), 2, "should write at most twice"); + } + + #[test] + fn update_with_one_attempt_does_not_reread() { + let store = Scripted::new( + [Ok(Some(record(1)))], + [Ok(RecordWriteOutcome::PreconditionFailed)], + ); + + let (result, planned) = update(&store, 1); + + assert_eq!(result.result.unwrap(), RecordUpdateOutcome::Conflict); + assert_eq!(result.conflicts, 1); + assert_eq!(planned.len(), 1, "should read and plan once"); + } + + #[test] + fn update_returns_the_planner_reason_without_writing() { + let store = Scripted::new([Ok(Some(record(1)))], []); + let records = handle(&store); + + let result = block_on(records.update( + "group/key", + NonZeroU8::MIN, + |_current: Option<&Record>| Err("withdrawn"), + )); + + assert_eq!( + result.result.unwrap(), + RecordUpdateOutcome::Skipped("withdrawn"), + "should return the planner reason" + ); + assert_eq!(result.conflicts, 0); + assert!( + store.modes().is_empty(), + "should not write a skipped record" + ); + } + + #[test] + fn update_stops_when_the_reread_returns_the_rejected_generation() { + let store = Scripted::new( + [Ok(Some(record(1))), Ok(Some(record(1)))], + [Ok(RecordWriteOutcome::PreconditionFailed)], + ); + + let (result, planned) = update(&store, 2); + + assert_eq!( + result.result.unwrap(), + RecordUpdateOutcome::StaleRead, + "should treat the rejected generation as stale" + ); + assert_eq!(result.conflicts, 1); + assert_eq!(planned.len(), 1, "should not plan against a stale read"); + assert_eq!(store.modes().len(), 1, "should not write again"); + } + + #[test] + fn update_stops_when_the_reread_misses_after_a_lost_cas() { + let store = Scripted::new( + [Ok(Some(record(1))), Ok(None)], + [Ok(RecordWriteOutcome::PreconditionFailed)], + ); + + let (result, _planned) = update(&store, 2); + + assert_eq!( + result.result.unwrap(), + RecordUpdateOutcome::StaleRead, + "should treat a miss after a lost CAS as stale" + ); + assert_eq!(result.conflicts, 1); + assert_eq!(store.modes().len(), 1, "should not Add after a lost CAS"); + } + + #[test] + fn update_stops_when_the_reread_misses_after_a_lost_add() { + let store = Scripted::new( + [Ok(None), Ok(None)], + [Ok(RecordWriteOutcome::PreconditionFailed)], + ); + + let (result, _planned) = update(&store, 2); + + assert_eq!( + result.result.unwrap(), + RecordUpdateOutcome::StaleRead, + "should treat a miss after a lost Add as stale" + ); + assert_eq!(store.modes(), [RecordWriteMode::Add]); + } + + #[test] + fn update_keeps_the_conflict_count_when_the_reread_fails() { + let store = Scripted::new( + [Ok(Some(record(1))), Err(KvError::Unavailable)], + [Ok(RecordWriteOutcome::PreconditionFailed)], + ); + + let (result, _planned) = update(&store, 2); + + assert!( + matches!(result.result, Err(KvError::Unavailable)), + "should return the read error" + ); + assert_eq!(result.conflicts, 1, "should keep the conflict count"); + } + + #[test] + fn update_does_not_retry_a_store_error() { + let store = Scripted::new([Ok(Some(record(1)))], [Err(KvError::Unavailable)]); + + let (result, _planned) = update(&store, 2); + + assert!( + matches!(result.result, Err(KvError::Unavailable)), + "should return the write error" + ); + assert_eq!(result.conflicts, 0); + assert_eq!(store.modes().len(), 1, "should write once"); + } + + #[test] + fn update_does_not_replay_an_uncertain_mutation() { + let store = Scripted::new([Ok(Some(record(1)))], [Err(KvError::MutationUncertain)]); + + let (result, _planned) = update(&store, 2); + + assert!( + matches!(result.result, Err(KvError::MutationUncertain)), + "should return the uncertain mutation" + ); + assert_eq!(store.modes().len(), 1, "should not replay the write"); + } + + #[test] + fn update_reports_unsupported_record_operations() { + let records = RecordHandle::new(Arc::new(BindingOnly)).unwrap(); + + let result = block_on(records.update( + "group/key", + NonZeroU8::MIN, + |_current: Option<&Record>| Ok::<_, ()>(replacement()), + )); + + assert!( + matches!(result.result, Err(KvError::Unsupported { .. })), + "should report Unsupported" + ); + assert_eq!(result.conflicts, 0); + } } diff --git a/docs/guide/kv-records.md b/docs/guide/kv-records.md index a5413e4f7..5d02f1533 100644 --- a/docs/guide/kv-records.md +++ b/docs/guide/kv-records.md @@ -121,12 +121,57 @@ if outcome == RecordWriteOutcome::Written { An acknowledged insert returns `Written`, not a fabricated post-write generation. `PreconditionFailed` means a definitive Add/CAS rejection. Reloading, merging, -retrying or deferring is application policy. +retrying or deferring is application policy; `update` below covers the bounded +re-read and re-plan case. `KvError::MutationUncertain` means a mutation may have committed. EdgeZero does not replay it. Reconcile with storage before deciding what to do next; blindly retrying an overwrite or delete can erase another writer's work. +## Re-plan after a lost precondition + +`update` reads a record, asks a planner for its replacement and writes it with +`IfGenerationMatch` on the generation read, or `Add` when the lookup missed. When +the write loses its precondition, nothing was written, so the record is read and +planned again, up to the given number of attempts. At most one replacement lands. + +```rust +use std::num::NonZeroU8; + +use bytes::Bytes; +use edgezero_core::record_store::{RecordReplacement, RecordUpdateOutcome}; + +let attempts = NonZeroU8::new(2).expect("should be nonzero"); +let update = records.update("session/42", attempts, |current| match current { + Some(record) => Ok(RecordReplacement { + body: Bytes::from(merge(&record.body)), + metadata: None, + ttl: None, + }), + None => Err("no session"), +}).await; + +match update.result? { + RecordUpdateOutcome::Written => {} + RecordUpdateOutcome::Skipped(_reason) => { /* the planner declined */ } + RecordUpdateOutcome::Conflict | RecordUpdateOutcome::StaleRead => { + // Nothing was written. + } +} +// `update.conflicts` counts lost preconditions, even when the update failed. +``` + +- A lost precondition proves the record exists under another generation. A + re-read that returns the rejected generation or misses is stale, as an + eventually consistent lookup can be, and ends with `StaleRead` instead of + planning on it. A record deleted after the rejection reads the same way. +- Generations are not ordered, so an older distinct generation cannot be + detected. A replacement planned on it loses its precondition. +- Read and write errors end the update without a retry. A + `KvError::MutationUncertain` write is never replayed. +- A provider without record operations reports `KvError::Unsupported`. Falling + back, for example to an ordinary last-write-wins put, is application policy. + ## Ordinary access and TTL Ordinary get/put/TTL-put/delete on this binding use the same record rows. Every From 601ae8db31161b5ddc383cc1dcfe695efb496716 Mon Sep 17 00:00:00 2001 From: Aram Grigoryan <132480+aram356@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:24:05 -0800 Subject: [PATCH 2/7] Place the bounded record update changelog entry after the Axum JSON section Moving the entry below the first existing Unreleased section avoids a merge conflict with the after-response entries at the top of the integration branch. The entry's content is unchanged. --- CHANGELOG.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f1aedef4..702343cc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,16 +2,6 @@ ## Unreleased -### Bounded record update (#535) - -`RecordHandle::update` reads a record, asks a caller's planner for its replacement and writes -it with `IfGenerationMatch`, or `Add` after a miss. After a lost precondition it reads and -plans again, up to a caller-supplied number of attempts, and reports `Written`, `Skipped`, -`Conflict` or `StaleRead` with the number of conflicts. A re-read that returns the rejected -generation or misses ends the update as `StaleRead`. Errors are not retried and -`MutationUncertain` is never replayed. Providers without record operations report -`Unsupported`. - ### Axum buffered JSON limits and body API Axum now defaults framework-managed JSON buffering to 2 MiB, exactly 2,097,152 bytes. @@ -24,6 +14,16 @@ The current `Body`/`BodyPayload` representation and exact egress ownership remai Ingress buffering policy and cache provenance survive context reconstruction independently of mutable headers and extensions, and are removed at raw payload transport boundaries. +### Bounded record update (#535) + +`RecordHandle::update` reads a record, asks a caller's planner for its replacement and writes +it with `IfGenerationMatch`, or `Add` after a miss. After a lost precondition it reads and +plans again, up to a caller-supplied number of attempts, and reports `Written`, `Skipped`, +`Conflict` or `StaleRead` with the number of conflicts. A re-read that returns the rejected +generation or misses ends the update as `StaleRead`. Errors are not retried and +`MutationUncertain` is never replayed. Providers without record operations report +`Unsupported`. + ### Portable HTTP And Request Lifecycles (PR #275) The changes below cover [PR #275](https://github.com/IABTechLab/edgezero/pull/275), including its From c8318ce1de4dbee4589dd118e6726ab2ea8897ed Mon Sep 17 00:00:00 2001 From: dhruv8sh Date: Mon, 30 Nov 2026 18:49:46 +0530 Subject: [PATCH 3/7] Note that celld's unswept expired rows also end a record update as StaleRead celld's lookup hides expired rows that still block Add/CAS until its sweep, so a lost precondition there need not mean another generation exists and StaleRead can repeat until the sweep. Say so in the update docs, the StaleRead variant and the records guide. Signed-off-by: dhruv8sh --- crates/edgezero-core/src/record_store.rs | 17 ++++++++++------- docs/guide/kv-records.md | 12 ++++++++---- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/crates/edgezero-core/src/record_store.rs b/crates/edgezero-core/src/record_store.rs index 2d4520ed4..c5aafc0fc 100644 --- a/crates/edgezero-core/src/record_store.rs +++ b/crates/edgezero-core/src/record_store.rs @@ -316,8 +316,8 @@ pub enum RecordUpdateOutcome { Conflict, /// The planner declined the record as read, with its reason. Skipped(Reason), - /// A re-read after a lost precondition was older than the rejection. Nothing - /// was written. + /// A re-read after a lost precondition was older than the rejection, or + /// hid an expired row that still blocks Add/CAS. Nothing was written. StaleRead, /// One replacement won its precondition and was acknowledged. Written, @@ -754,11 +754,14 @@ impl RecordHandle { /// again; the update stops at the first acknowledged write, so at most one /// replacement lands. /// - /// A lost precondition proves the record exists under another generation. A - /// re-read that returns the rejected generation or misses is older than that - /// rejection, as an eventually consistent lookup can be, and ends the update - /// with [`RecordUpdateOutcome::StaleRead`]. A record deleted after the - /// rejection reads the same way. Generations are not ordered, so an older + /// A lost precondition proves the record exists under another generation, + /// or, on a provider whose lookup hides expired rows that still block + /// Add/CAS (celld until its sweep), that an expired row remains. A re-read + /// that returns the rejected generation or misses is older than that + /// rejection, as an eventually consistent lookup can be, or sees past such + /// an expired row, and ends the update with + /// [`RecordUpdateOutcome::StaleRead`]. A record deleted after the rejection + /// reads the same way. Generations are not ordered, so an older /// distinct generation cannot be detected; a replacement planned on it loses /// its precondition. /// diff --git a/docs/guide/kv-records.md b/docs/guide/kv-records.md index 5d02f1533..a18813821 100644 --- a/docs/guide/kv-records.md +++ b/docs/guide/kv-records.md @@ -161,10 +161,14 @@ match update.result? { // `update.conflicts` counts lost preconditions, even when the update failed. ``` -- A lost precondition proves the record exists under another generation. A - re-read that returns the rejected generation or misses is stale, as an - eventually consistent lookup can be, and ends with `StaleRead` instead of - planning on it. A record deleted after the rejection reads the same way. +- A lost precondition proves the record exists under another generation, or, + on a provider whose lookup hides expired rows that still block Add/CAS + (celld until its sweep), that an expired row remains. A re-read that returns + the rejected generation or misses is stale, as an eventually consistent + lookup can be, or sees past such an expired row, and ends with `StaleRead` + instead of planning on it. On celld that repeats until the sweep removes the + row, so `StaleRead` does not always mean a retry soon will succeed. A record + deleted after the rejection reads the same way. - Generations are not ordered, so an older distinct generation cannot be detected. A replacement planned on it loses its precondition. - Read and write errors end the update without a retry. A From 242f70c7af2676b22b1146304c04fb6c022b9057 Mon Sep 17 00:00:00 2001 From: Aram Grigoryan <132480+aram356@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:57:15 -0800 Subject: [PATCH 4/7] Assert that a re-planned update writes the second plan's body The scripted store recorded only write modes, so a regression that reused the first plan's bytes under the re-read generation passed. --- crates/edgezero-core/src/record_store.rs | 31 ++++++++++++++++++++---- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/crates/edgezero-core/src/record_store.rs b/crates/edgezero-core/src/record_store.rs index b6f691568..390982e6f 100644 --- a/crates/edgezero-core/src/record_store.rs +++ b/crates/edgezero-core/src/record_store.rs @@ -857,9 +857,11 @@ mod tests { struct FirstSegment; - // Replays scripted lookups and insert outcomes, recording each insert mode. + // Replays scripted lookups and insert outcomes, recording each insert's mode + // and body. #[derive(Default)] struct Scripted { + bodies: Mutex>, lookups: Mutex, KvError>>>, modes: Mutex>, writes: Mutex>>, @@ -890,6 +892,10 @@ mod tests { } impl Scripted { + fn bodies(&self) -> Vec { + self.bodies.lock().unwrap().clone() + } + fn modes(&self) -> Vec { self.modes.lock().unwrap().clone() } @@ -899,6 +905,7 @@ mod tests { writes: impl IntoIterator>, ) -> Arc { Arc::new(Self { + bodies: Mutex::default(), lookups: Mutex::new(lookups.into_iter().collect()), modes: Mutex::default(), writes: Mutex::new(writes.into_iter().collect()), @@ -952,6 +959,10 @@ mod tests { _partition: &RecordPartition, write: RecordWrite<'_>, ) -> Result { + self.bodies + .lock() + .unwrap() + .push(Bytes::copy_from_slice(write.body)); self.modes.lock().unwrap().push(write.mode); self.writes .lock() @@ -1040,9 +1051,14 @@ mod tests { RecordWriteMode::IfGenerationMatch(RecordGeneration::from_u64(generation)) } - fn replacement() -> RecordReplacement { + // Plans a body naming the generation it was planned against. + fn replacement(current: Option<&Record>) -> RecordReplacement { + let body = current.map_or_else( + || "next-new".to_owned(), + |record| format!("next-{}", record.generation.as_u64()), + ); RecordReplacement { - body: Bytes::from_static(b"next"), + body: Bytes::from(body), metadata: None, ttl: None, } @@ -1061,7 +1077,7 @@ mod tests { NonZeroU8::new(attempts).unwrap(), |current: Option<&Record>| { planned.push(current.map(|record| record.generation)); - Ok(replacement()) + Ok(replacement(current)) }, )); (result, planned) @@ -1129,6 +1145,11 @@ mod tests { "should plan again against the re-read" ); assert_eq!(store.modes(), [if_match(1), if_match(2)]); + assert_eq!( + store.bodies(), + [Bytes::from_static(b"next-1"), Bytes::from_static(b"next-2")], + "should write the second plan's body" + ); } #[test] @@ -1293,7 +1314,7 @@ mod tests { let result = block_on(records.update( "group/key", NonZeroU8::MIN, - |_current: Option<&Record>| Ok::<_, ()>(replacement()), + |_current: Option<&Record>| Ok::<_, ()>(replacement(None)), )); assert!( From 182cf39e5430b8ac01b39609e58c47cb751b216d Mon Sep 17 00:00:00 2001 From: Aram Grigoryan <132480+aram356@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:58:16 -0800 Subject: [PATCH 5/7] Test that an update re-plans with CAS after losing an Add to a new record Also cover a planner that declines on the re-plan. Neither the concurrent-create path nor a late skip had a test. --- crates/edgezero-core/src/record_store.rs | 72 ++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/crates/edgezero-core/src/record_store.rs b/crates/edgezero-core/src/record_store.rs index 390982e6f..67181c8ec 100644 --- a/crates/edgezero-core/src/record_store.rs +++ b/crates/edgezero-core/src/record_store.rs @@ -1210,6 +1210,40 @@ mod tests { ); } + #[test] + fn update_returns_the_planner_reason_when_the_replan_declines() { + let store = Scripted::new( + [Ok(Some(record(1))), Ok(Some(record(2)))], + [Ok(RecordWriteOutcome::PreconditionFailed)], + ); + let records = handle(&store); + + let result = block_on(records.update( + "group/key", + NonZeroU8::new(2).unwrap(), + |current: Option<&Record>| { + if current.is_some_and(|record| record.generation == RecordGeneration::from_u64(1)) + { + Ok(replacement(current)) + } else { + Err("withdrawn") + } + }, + )); + + assert_eq!( + result.result.unwrap(), + RecordUpdateOutcome::Skipped("withdrawn"), + "should return the reason the re-plan gave" + ); + assert_eq!(result.conflicts, 1, "should keep the conflict count"); + assert_eq!( + store.modes(), + [if_match(1)], + "should not write after the re-plan declines" + ); + } + #[test] fn update_stops_when_the_reread_returns_the_rejected_generation() { let store = Scripted::new( @@ -1264,6 +1298,44 @@ mod tests { assert_eq!(store.modes(), [RecordWriteMode::Add]); } + #[test] + fn update_replans_with_cas_after_a_lost_add_finds_the_winner() { + let store = Scripted::new( + [Ok(None), Ok(Some(record(7)))], + [ + Ok(RecordWriteOutcome::PreconditionFailed), + Ok(RecordWriteOutcome::Written), + ], + ); + + let (result, planned) = update(&store, 2); + + assert_eq!( + result.result.unwrap(), + RecordUpdateOutcome::Written, + "should land the re-planned write on the winner's record" + ); + assert_eq!(result.conflicts, 1, "should count the lost Add"); + assert_eq!( + planned, + [None, Some(RecordGeneration::from_u64(7))], + "should plan again against the winner's record" + ); + assert_eq!( + store.modes(), + [RecordWriteMode::Add, if_match(7)], + "should CAS on the winner's generation" + ); + assert_eq!( + store.bodies(), + [ + Bytes::from_static(b"next-new"), + Bytes::from_static(b"next-7") + ], + "should write the re-plan's body" + ); + } + #[test] fn update_keeps_the_conflict_count_when_the_reread_fails() { let store = Scripted::new( From 0061ba89da7a5069fe295c672785cce9a2be52b3 Mon Sep 17 00:00:00 2001 From: Aram Grigoryan <132480+aram356@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:00:09 -0800 Subject: [PATCH 6/7] Warn when a record update result is discarded A dropped update hid its read and write errors, MutationUncertain included, that a direct insert's Result warns about. --- crates/edgezero-core/src/record_store.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/edgezero-core/src/record_store.rs b/crates/edgezero-core/src/record_store.rs index 67181c8ec..37e9469c1 100644 --- a/crates/edgezero-core/src/record_store.rs +++ b/crates/edgezero-core/src/record_store.rs @@ -332,6 +332,7 @@ pub enum RecordUpdateOutcome { /// The result of a [`RecordHandle::update`] and the conflicts it met. #[derive(Debug)] +#[must_use = "an update can fail or end without writing; inspect `result`"] pub struct RecordUpdate { /// Add/CAS precondition rejections, counted even when the update fails. pub conflicts: u8, From 04340a1893504ccd6d4e2c12763335730b53a410 Mon Sep 17 00:00:00 2001 From: Aram Grigoryan <132480+aram356@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:00:51 -0800 Subject: [PATCH 7/7] Describe StaleRead as what update observed, not proof the record exists A CAS on a row deleted or expired before the write also fails, so the miss that follows can be current. --- crates/edgezero-core/src/record_store.rs | 24 ++++++++++++------------ docs/guide/kv-records.md | 14 ++++++-------- 2 files changed, 18 insertions(+), 20 deletions(-) diff --git a/crates/edgezero-core/src/record_store.rs b/crates/edgezero-core/src/record_store.rs index 37e9469c1..42090ea76 100644 --- a/crates/edgezero-core/src/record_store.rs +++ b/crates/edgezero-core/src/record_store.rs @@ -323,8 +323,9 @@ pub enum RecordUpdateOutcome { Conflict, /// The planner declined the record as read, with its reason. Skipped(Reason), - /// A re-read after a lost precondition was older than the rejection, or - /// hid an expired row that still blocks Add/CAS. Nothing was written. + /// After a lost precondition, the re-read returned the rejected generation + /// or missed, so the planner did not run again. The miss can be current or + /// stale. Nothing was written. StaleRead, /// One replacement won its precondition and was acknowledged. Written, @@ -772,16 +773,15 @@ impl RecordHandle { /// again; the update stops at the first acknowledged write, so at most one /// replacement lands. /// - /// A lost precondition proves the record exists under another generation, - /// or, on a provider whose lookup hides expired rows that still block - /// Add/CAS (celld until its sweep), that an expired row remains. A re-read - /// that returns the rejected generation or misses is older than that - /// rejection, as an eventually consistent lookup can be, or sees past such - /// an expired row, and ends the update with - /// [`RecordUpdateOutcome::StaleRead`]. A record deleted after the rejection - /// reads the same way. Generations are not ordered, so an older - /// distinct generation cannot be detected; a replacement planned on it loses - /// its precondition. + /// After a lost precondition, a re-read that returns the rejected + /// generation or misses ends the update with + /// [`RecordUpdateOutcome::StaleRead`] without running `plan` again. A miss + /// can be current if the record was deleted or expired before or after the + /// rejection. It can also come from an eventually consistent lookup. On a + /// provider whose lookup hides expired rows that still block Add/CAS + /// (celld until its sweep), `StaleRead` can repeat until that row is swept. + /// Generations are not ordered, so an older distinct generation cannot be + /// detected; a replacement planned on it loses its precondition. /// /// Read and write errors end the update without a retry. A /// [`KvError::MutationUncertain`] write is never replayed. A binding whose diff --git a/docs/guide/kv-records.md b/docs/guide/kv-records.md index 42d6746fa..68d214f24 100644 --- a/docs/guide/kv-records.md +++ b/docs/guide/kv-records.md @@ -179,14 +179,12 @@ match update.result? { // `update.conflicts` counts lost preconditions, even when the update failed. ``` -- A lost precondition proves the record exists under another generation, or, - on a provider whose lookup hides expired rows that still block Add/CAS - (celld until its sweep), that an expired row remains. A re-read that returns - the rejected generation or misses is stale, as an eventually consistent - lookup can be, or sees past such an expired row, and ends with `StaleRead` - instead of planning on it. On celld that repeats until the sweep removes the - row, so `StaleRead` does not always mean a retry soon will succeed. A record - deleted after the rejection reads the same way. +- After a precondition rejection, a miss or a re-read of the rejected + generation ends the update as `StaleRead` without running the planner again. + A miss can be current if the row was deleted or expired before or after the + rejection. It can also come from an eventually consistent lookup. On celld, + lookup hides expired rows that still block Add/CAS until the sweep, so + `StaleRead` can repeat until that row is swept. - Generations are not ordered, so an older distinct generation cannot be detected. A replacement planned on it loses its precondition. - Read and write errors end the update without a retry. A