From 5e63adc2140e530ceafdf100035bb706d9efa255 Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Fri, 13 Nov 2026 13:24:08 +0530 Subject: [PATCH 1/2] Return structured errors for excessive KV retention --- crates/edgezero-core/src/key_value_store.rs | 192 +++++++++++++++++- docs/guide/kv.md | 54 ++++- .../plans/2026-11-13-kv-ttl-limit-error.md | 36 ++++ .../2026-11-13-kv-ttl-limit-error-design.md | 60 ++++++ 4 files changed, 329 insertions(+), 13 deletions(-) create mode 100644 docs/superpowers/plans/2026-11-13-kv-ttl-limit-error.md create mode 100644 docs/superpowers/specs/2026-11-13-kv-ttl-limit-error-design.md diff --git a/crates/edgezero-core/src/key_value_store.rs b/crates/edgezero-core/src/key_value_store.rs index a7469287c..c76341c70 100644 --- a/crates/edgezero-core/src/key_value_store.rs +++ b/crates/edgezero-core/src/key_value_store.rs @@ -324,6 +324,15 @@ pub enum KvError { #[error("serialization error: {0}")] Serialization(#[from] serde_json::Error), + /// The requested TTL exceeds the handle's portable policy cap. + #[error("TTL {requested:?} exceeds maximum of {maximum:?}")] + TtlLimitExceeded { + /// The TTL requested by the caller. + requested: Duration, + /// The maximum TTL allowed by the handle, not a provider capability. + maximum: Duration, + }, + /// The KV store backend is temporarily unavailable. #[error("kv store unavailable")] Unavailable, @@ -375,7 +384,10 @@ impl KvHandle { /// Maximum number of keys returned from a single page. pub const MAX_LIST_PAGE_SIZE: usize = 1_000; - /// Maximum TTL (1 year). Prevents overflow when adding to `SystemTime::now()`. + /// Portable policy cap of 365 days, not each provider's maximum capability. + /// + /// Larger TTLs return [`KvError::TtlLimitExceeded`] before reaching the + /// backend, protecting time arithmetic and provider TTL conversions. #[expect( clippy::duration_suboptimal_units, reason = "`Duration::from_days` is not stable in const context (1.98)" @@ -660,7 +672,9 @@ impl KvHandle { /// Put raw bytes with a TTL. /// /// # Errors - /// Returns [`KvError::Validation`] for invalid input; [`KvError::Internal`] on backend failure. + /// Returns [`KvError::TtlLimitExceeded`] above [`Self::MAX_TTL`], + /// [`KvError::Validation`] for other invalid input, or a backend error + /// (including [`KvError::Unsupported`] when TTL writes are unavailable). #[inline] pub async fn put_bytes_with_ttl( &self, @@ -683,7 +697,10 @@ impl KvHandle { /// Put a value with a TTL, serializing it to JSON. /// /// # Errors - /// Returns [`KvError`] if the value cannot be serialized or the backend rejects the write. + /// Returns [`KvError::TtlLimitExceeded`] above [`Self::MAX_TTL`], + /// [`KvError::Validation`] for other invalid input, [`KvError::Serialization`] + /// if serialization fails, or a backend error (including + /// [`KvError::Unsupported`] when TTL writes are unavailable). #[inline] pub async fn put_with_ttl(&self, key: &str, value: &T, ttl: Duration) -> Result<(), KvError> where @@ -801,9 +818,10 @@ impl KvHandle { ))); } if ttl > Self::MAX_TTL { - return Err(KvError::Validation(format!( - "TTL {ttl:?} exceeds maximum of 1 year" - ))); + return Err(KvError::TtlLimitExceeded { + requested: ttl, + maximum: Self::MAX_TTL, + }); } Ok(()) } @@ -829,6 +847,9 @@ impl From for EdgeError { KvError::Validation(msg) => { EdgeError::bad_request(format!("kv validation error: {msg}")) } + KvError::TtlLimitExceeded { requested, maximum } => EdgeError::bad_request(format!( + "kv validation error: TTL {requested:?} exceeds maximum of {maximum:?}" + )), KvError::Serialization(msg) => { EdgeError::internal(anyhow::anyhow!("kv serialization error: {msg}")) } @@ -1000,9 +1021,11 @@ mod tests { use super::*; use crate::http::StatusCode; + use crate::store_registry::KvRegistry; use futures::executor::block_on; use std::collections::HashMap; use std::sync::Mutex; + use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::SystemTime; #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)] @@ -1014,6 +1037,7 @@ mod tests { // Uses `SystemTime` instead of `Instant` for WASM compatibility. struct MockStore { data: Mutex)>>, + ttl_write_calls: AtomicUsize, } #[async_trait(?Send)] @@ -1079,6 +1103,7 @@ mod tests { value: Bytes, ttl: Duration, ) -> Result<(), KvError> { + self.ttl_write_calls.fetch_add(1, Ordering::Relaxed); let mut data = self.data.lock().unwrap(); let expires_at = SystemTime::now() .checked_add(ttl) @@ -1092,6 +1117,7 @@ mod tests { fn new() -> Self { Self { data: Mutex::new(HashMap::new()), + ttl_write_calls: AtomicUsize::new(0), } } } @@ -1247,6 +1273,31 @@ mod tests { assert!(edge_err.message().contains("max_list_keys")); } + #[test] + fn kv_error_ttl_limit_exceeded_converts_to_bad_request() { + let requested = KvHandle::MAX_TTL * 2; + let maximum = KvHandle::MAX_TTL; + let error = KvError::TtlLimitExceeded { requested, maximum }; + let message = error.to_string(); + assert_eq!( + message, + format!("TTL {requested:?} exceeds maximum of {maximum:?}"), + "should identify requested TTL and cap in diagnostics" + ); + + let edge_error = EdgeError::from(error); + assert_eq!( + edge_error.status(), + StatusCode::BAD_REQUEST, + "should preserve HTTP 400 for excessive TTLs" + ); + assert_eq!( + edge_error.message(), + format!("kv validation error: {message}"), + "should retain TTL limit details in the HTTP error" + ); + } + #[test] fn kv_handle_debug_output() { let kv = handle(); @@ -1616,11 +1667,138 @@ mod tests { .put_with_ttl("long", &"val", KvHandle::MAX_TTL + Duration::from_secs(1)) .await .unwrap_err(); - assert!(matches!(err, KvError::Validation(_))); + assert!(matches!(err, KvError::TtlLimitExceeded { .. })); assert!(format!("{err}").contains("exceeds maximum")); }); } + #[test] + fn named_handle_reports_distinguishable_ttl_limit() { + let store = Arc::new(MockStore::new()); + let registry = KvRegistry::single_id( + "events".to_owned(), + KvHandle::new(Arc::::clone(&store)), + ); + let kv = registry + .named("events") + .expect("should resolve named store"); + + block_on(async { + for ttl in [ + KvHandle::MAX_TTL + Duration::from_nanos(1), + KvHandle::MAX_TTL * 2, + Duration::MAX, + ] { + let typed_error = kv + .put_with_ttl("typed", &42_i32, ttl) + .await + .expect_err("should reject excessive TTL"); + let bytes_error = kv + .put_bytes_with_ttl("bytes", Bytes::from_static(b"value"), ttl) + .await + .expect_err("should reject excessive TTL"); + for error in [typed_error, bytes_error] { + let KvError::TtlLimitExceeded { requested, maximum } = error else { + panic!("should return a structured TTL limit error: {error}"); + }; + assert_eq!(requested, ttl, "should report the exact requested TTL"); + assert_eq!( + maximum, + KvHandle::MAX_TTL, + "should report the applicable cap" + ); + } + } + }); + + assert_eq!( + store.ttl_write_calls.load(Ordering::Relaxed), + 0, + "should reject excessive TTLs before invoking the backend" + ); + assert!( + store.data.lock().expect("should lock test data").is_empty(), + "should not store rejected writes" + ); + } + + #[test] + fn named_handle_accepts_ttl_boundaries() { + let store = Arc::new(MockStore::new()); + let registry = KvRegistry::single_id( + "events".to_owned(), + KvHandle::new(Arc::::clone(&store)), + ); + let kv = registry + .named("events") + .expect("should resolve named store"); + + block_on(async { + for ttl in [KvHandle::MIN_TTL, KvHandle::MAX_TTL] { + kv.put_with_ttl("typed", &42_i32, ttl) + .await + .expect("should accept TTL boundary"); + assert_eq!( + kv.get::("typed").await.expect("should read value"), + Some(42_i32), + "should store typed value at TTL boundary" + ); + kv.put_bytes_with_ttl("bytes", Bytes::from_static(b"value"), ttl) + .await + .expect("should accept TTL boundary"); + assert_eq!( + kv.get_bytes("bytes").await.expect("should read bytes"), + Some(Bytes::from_static(b"value")), + "should store bytes at TTL boundary" + ); + } + }); + + assert_eq!( + store.ttl_write_calls.load(Ordering::Relaxed), + 4, + "should delegate all writes at inclusive TTL boundaries" + ); + } + + #[test] + fn named_handle_rejects_ttl_below_minimum() { + let store = Arc::new(MockStore::new()); + let registry = KvRegistry::single_id( + "events".to_owned(), + KvHandle::new(Arc::::clone(&store)), + ); + let kv = registry + .named("events") + .expect("should resolve named store"); + let ttl = KvHandle::MIN_TTL + .checked_sub(Duration::from_nanos(1)) + .expect("should subtract one nanosecond from minimum TTL"); + + block_on(async { + let typed_error = kv + .put_with_ttl("typed", &42_i32, ttl) + .await + .expect_err("should reject TTL below minimum"); + let bytes_error = kv + .put_bytes_with_ttl("bytes", Bytes::from_static(b"value"), ttl) + .await + .expect_err("should reject TTL below minimum"); + for error in [typed_error, bytes_error] { + assert!( + matches!(error, KvError::Validation(_)), + "should preserve minimum TTL validation" + ); + } + }); + + assert_eq!( + store.ttl_write_calls.load(Ordering::Relaxed), + 0, + "should reject short TTLs before invoking the backend" + ); + } + #[test] fn validation_rejects_malformed_list_cursor() { let kv = handle(); diff --git a/docs/guide/kv.md b/docs/guide/kv.md index e5627b2bb..f3f5d647b 100644 --- a/docs/guide/kv.md +++ b/docs/guide/kv.md @@ -175,26 +175,68 @@ Both Fastly and Cloudflare KV stores are **eventually consistent**. - A value written at one edge location may not be immediately visible at another. - `read_modify_write()` is **not atomic**. Concurrent updates to the same key may result in lost writes. -- **TTL**: `put_with_ttl` enforces a minimum of **60 seconds** and a maximum of **1 year** before delegating to an adapter. Spin KV does not support TTL, so the Spin adapter returns `KvError::Unsupported { operation: "put_bytes_with_ttl" }` without writing the value. +- **TTL**: `put_with_ttl` and `put_bytes_with_ttl` enforce a minimum of **60 seconds** and a maximum of **365 days**, inclusive, before delegating to an adapter. Spin KV does not support TTL, so the Spin adapter returns `KvError::Unsupported { operation: "put_bytes_with_ttl" }` for requests passing handle validation, without writing the value. ## Limits & Validation -To ensure portability across all providers, `KvHandle` enforces the -strictest common limits: +`KvHandle` enforces the following portable policy limits before calling a +backend. These limits do not describe each provider's maximum capabilities; +backends can impose additional restrictions or reject unsupported operations. | Rule | Limit | | ------------- | ------------------------------------ | | Key size | Max **512 bytes** (Cloudflare limit) | | Value size | Max **25 MB** | | TTL minimum | **60 seconds** | -| TTL maximum | **1 year** | +| TTL maximum | **365 days** | | List page max | **1000 keys** | | Empty keys | Rejected | | Reserved keys | `.` and `..` rejected | | Control chars | Rejected in keys | -Violating any of these returns a `KvError::Validation`, which maps to -`400 Bad Request`. +Exceeding the TTL maximum returns +`KvError::TtlLimitExceeded { requested, maximum }`, with both fields expressed +as `Duration`. Other violations, including a TTL below the minimum, return +`KvError::Validation`. Both errors map to `400 Bad Request`. +Callers that previously matched excessive TTLs as `KvError::Validation` should +handle the new `TtlLimitExceeded` variant explicitly. + +### Retention longer than one year + +The 365-day TTL cap is a fixed `KvHandle` policy, including handles resolved +through `KvRegistry::named` or `KvRegistry::default`. Multi-year retention and +configurable caps are not currently supported. Excessive TTLs, including +`Duration::MAX`, are rejected before any backend write or expiry arithmetic. + +Applications that previously warned and clamped every retention window to +`KvHandle::MAX_TTL` can instead attempt the configured TTL and explicitly +handle `TtlLimitExceeded`. For example, this application reports that the +requested retention cannot be honored: + +```rust +use std::time::Duration; +use edgezero_core::error::EdgeError; +use edgezero_core::key_value_store::{KvError, KvHandle}; + +async fn persist_event(store: &KvHandle, retention: Duration) -> Result<(), EdgeError> { + match store.put_with_ttl("event", &"example", retention).await { + Ok(()) => Ok(()), + Err(KvError::TtlLimitExceeded { requested, maximum }) => { + Err(EdgeError::bad_request(format!( + "Requested retention {requested:?} exceeds the supported cap {maximum:?}" + ))) + } + Err(error) => Err(EdgeError::from(error)), + } +} +``` + +Alternatively, an application can deliberately select an allowed retention +window and retry, if its retention policy permits shortening it. Removing the +clamp alone still rejects multi-year writes; callers must handle that failure. +Applications requiring the full multi-year window need a future provider-aware +extension or a different storage path. TTL writes remain unsupported on Spin; +handling the cap error does not make that backend support expiry. ## Next Steps diff --git a/docs/superpowers/plans/2026-11-13-kv-ttl-limit-error.md b/docs/superpowers/plans/2026-11-13-kv-ttl-limit-error.md new file mode 100644 index 000000000..8c8aada23 --- /dev/null +++ b/docs/superpowers/plans/2026-11-13-kv-ttl-limit-error.md @@ -0,0 +1,36 @@ +# KV TTL limit error implementation plan + +**Goal:** Make rejection above the portable KV TTL cap distinguishable without +changing supported retention windows. + +**Architecture:** Keep validation in `KvHandle`; add a structured `KvError` +variant and preserve the HTTP 400 conversion. Registry and adapter code remain +unchanged. + +**Tech stack:** Rust 2024, existing asynchronous KV tests, Markdown guide. + +## Task 1: Establish regression coverage + +- [x] Run baseline `cargo +1.98.1 test --locked -p edgezero-core`. +- [x] In `crates/edgezero-core/src/key_value_store.rs`, exercise + `KvRegistry::single_id(...).named(...)` for typed and raw TTL writes. +- [x] Assert inclusive minimum/maximum, below-minimum validation, exact + over-cap error fields, and no backend call for rejected writes. +- [x] Demonstrate failure against the existing generic over-cap rejection. + +## Task 2: Implement the error contract + +- [x] Add `TtlLimitExceeded { requested: Duration, maximum: Duration }` to + `KvError` and return it only from the existing upper-bound guard. +- [x] Preserve HTTP 400 in `From for EdgeError` and test conversion. +- [x] Update TTL method and constant documentation; run core tests. + +## Task 3: Explain migration and verify + +- [x] Update `docs/guide/kv.md` with the portable policy and explicit downstream + handling, distinguishing cap rejection from unsupported backend TTLs. +- [x] Run Rust formatting, workspace tests, all-feature clippy, workspace + feature compilation and the Spin WASM check required by `CLAUDE.md`. +- [x] Check affected adapter WASM builds and documentation lint/format. +- [x] Independently review the final change against issue #323, preserve any + blocked check details, and prepare an accurate PR title and description. diff --git a/docs/superpowers/specs/2026-11-13-kv-ttl-limit-error-design.md b/docs/superpowers/specs/2026-11-13-kv-ttl-limit-error-design.md new file mode 100644 index 000000000..7e6d12324 --- /dev/null +++ b/docs/superpowers/specs/2026-11-13-kv-ttl-limit-error-design.md @@ -0,0 +1,60 @@ +# Distinguishable KV TTL limit errors + +## Problem and scope + +Issue #323 reports that `KvHandle` rejects retention windows longer than 365 +days with a generic validation error. Named handles returned by `KvRegistry` +have the same restriction. Applications cannot distinguish this rejection from +other invalid inputs without inspecting error text. + +This fix implements the issue's explicitly permitted structured-error option. +It does not enable multi-year retention or add configurable limits. + +## Contract + +- Add `KvError::TtlLimitExceeded { requested: Duration, maximum: Duration }`. +- Both JSON and raw-byte TTL writes return this error when the requested TTL + exceeds `KvHandle::MAX_TTL`, before invoking the backend. +- `maximum` identifies the handle's current portable policy: exactly 365 days. + This is not a statement of each provider's maximum capability. +- TTLs below 60 seconds continue returning `KvError::Validation`. Both + endpoints are inclusive. Excessive durations, including `Duration::MAX`, + remain rejected before time arithmetic or provider conversion. +- Converting the new error into `EdgeError` preserves HTTP 400. +- The error applies equally to directly constructed, default, and named + handles because registry lookup returns the same handle type. + +## Alternatives and provider behavior + +A configurable handle cap would enable longer retention on some backends but +needs a provider capability contract first. The pinned Fastly SDK converts TTL +seconds to `u32`, falling back to zero when conversion overflows; an arbitrary +override would expose that conversion. Cloudflare receives whole seconds, and +Axum checks addition to its system clock. Spin does not support TTL writes: +requests passing handle validation continue returning `KvError::Unsupported` +without writing. These adapter behaviors remain unchanged. + +Keeping the cap with a structured error is the smallest correction supported +by the issue. `KvError` is already non-exhaustive, so consumers must allow for +additional variants. Consumers explicitly matching `Validation` for excessive +TTLs must update their handling. + +## Downstream migration + +Applications may replace unconditional warning-and-clamp code with a match on +`TtlLimitExceeded` and an explicit retention-policy decision. They must propagate +the rejection or deliberately choose an allowed retention window and retry; +silently shortening retention is not required. Removing a clamp alone does not +make multi-year retention succeed. Applications requiring full multi-year +retention still need a future provider-aware extension or a different storage +path. Ordinary backend failures retain their existing handling. + +## Verification + +Exercise actual named registry handles with both typed and raw writes. Check +the exact minimum and maximum, one nanosecond below and above the bounds, +two-year retention, and `Duration::MAX`. Inspect exact error fields, verify no +backend invocation for rejected TTLs, and verify accepted values round-trip. +Check the HTTP status mapping. Demonstrate that the regression rejects the +previous generic error, then run core and workspace tests, formatting, clippy, +feature compilation, adapter WASM checks, and documentation checks. From c31e8f9ec374816e668368f2159dedb8219d4cb1 Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Tue, 1 Dec 2026 11:50:23 +0530 Subject: [PATCH 2/2] Deduplicate KV TTL diagnostics and note matcher migration --- CHANGELOG.md | 15 +++++++++++++++ crates/edgezero-core/src/key_value_store.rs | 6 +++--- 2 files changed, 18 insertions(+), 3 deletions(-) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..5f61ce7e3 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changelog + +## Unreleased + +### Changed + +- KV writes with a TTL above the portable 365-day cap now return + `KvError::TtlLimitExceeded { requested, maximum }` instead of + `KvError::Validation`. Callers matching `Validation` for excessive TTLs must + handle the new variant explicitly; existing catch-all branches still compile + because `KvError` is non-exhaustive. The inclusive 60-second minimum and + 365-day maximum, rejection before backend writes, and HTTP 400 mapping are + unchanged. Multi-year retention and configurable caps remain unsupported. + See the [KV migration guidance](docs/guide/kv.md#retention-longer-than-one-year) + for explicit retention-policy handling. diff --git a/crates/edgezero-core/src/key_value_store.rs b/crates/edgezero-core/src/key_value_store.rs index c76341c70..7785772de 100644 --- a/crates/edgezero-core/src/key_value_store.rs +++ b/crates/edgezero-core/src/key_value_store.rs @@ -847,9 +847,9 @@ impl From for EdgeError { KvError::Validation(msg) => { EdgeError::bad_request(format!("kv validation error: {msg}")) } - KvError::TtlLimitExceeded { requested, maximum } => EdgeError::bad_request(format!( - "kv validation error: TTL {requested:?} exceeds maximum of {maximum:?}" - )), + error @ KvError::TtlLimitExceeded { .. } => { + EdgeError::bad_request(format!("kv validation error: {error}")) + } KvError::Serialization(msg) => { EdgeError::internal(anyhow::anyhow!("kv serialization error: {msg}")) }