diff --git a/CHANGELOG.md b/CHANGELOG.md index 985fe52f..06f60514 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -135,6 +135,16 @@ settings, and request records. `config validate --adapter axum --store-bindings `. See the [native celld stores guide](docs/guide/native-celld-stores.md). +### 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 diff --git a/crates/edgezero-core/src/record_store.rs b/crates/edgezero-core/src/record_store.rs index 9eb802f5..42090ea7 100644 --- a/crates/edgezero-core/src/record_store.rs +++ b/crates/edgezero-core/src/record_store.rs @@ -226,6 +226,7 @@ pub mod contract { use std::collections::BTreeMap; use std::fmt; +use std::num::NonZeroU8; use std::sync::Arc; use std::time::Duration; @@ -304,6 +305,42 @@ 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), + /// 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, +} + +/// 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, + /// 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)] @@ -724,4 +761,639 @@ 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. + /// + /// 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 + /// 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's mode + // and body. + #[derive(Default)] + struct Scripted { + bodies: Mutex>, + 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 bodies(&self) -> Vec { + self.bodies.lock().unwrap().clone() + } + + fn modes(&self) -> Vec { + self.modes.lock().unwrap().clone() + } + + fn new( + lookups: impl IntoIterator, KvError>>, + 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()), + }) + } + } + + #[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.bodies + .lock() + .unwrap() + .push(Bytes::copy_from_slice(write.body)); + 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)) + } + + // 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(body), + 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(current)) + }, + )); + (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)]); + assert_eq!( + store.bodies(), + [Bytes::from_static(b"next-1"), Bytes::from_static(b"next-2")], + "should write the second plan's body" + ); + } + + #[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_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( + [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_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( + [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(None)), + )); + + 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 180ec7ce..68d214f2 100644 --- a/docs/guide/kv-records.md +++ b/docs/guide/kv-records.md @@ -139,12 +139,59 @@ 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. +``` + +- 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 + `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