From 4444bc608f5a75d5f0a8e2ebb8dbb2f6488b2489 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Thu, 29 Oct 2026 23:04:56 +0000 Subject: [PATCH 01/14] feat(streams): AT_TIMESTAMP shard iterator on all four backends DynamoDB Streams added the AT_TIMESTAMP shard iterator type on 2026-10-15. GetShardIterator takes ShardIteratorType AT_TIMESTAMP with a Timestamp member (epoch seconds, fractional milliseconds allowed) and returns an iterator positioned at the first record created at or after that time. ExtendDB answered SerializationException for the type. Behaviour, measured on the service (us-east-1, 2026-10-23; raw requests and responses recorded in the issue): - The seek compares at millisecond precision. A Timestamp of 14:04:08.5 skips records written at 14:04:08.050 to .071 and starts at the next group, while the integer 14:04:08 includes them. - A timestamp older than the oldest retained record returns everything with no error; one past the newest record positions after it, so GetRecords returns records written from then on. - Validation order: the type enum, then Timestamp presence or absence for the type, then SequenceNumber presence or absence for the type, then the future check, then stream and shard existence. Every parameter message carries the prefix "One or more parameter values were invalid: ". - The future buffer is about one second: now + 1 s was accepted, now + 2 s refused. A Timestamp sent as a JSON string, boolean or object is a SerializationException; null, zero and negative are the "Valid timestamp must be provided" refusal. Implementation: - ShardIteratorType::AtTimestamp and GetShardIteratorInput.timestamp. - The handler refuses a missing or null type with the service's "Member must not be null" text, pre-validates the type enum (the service's member order, rendered without the offending value as the service does), refuses a Timestamp whose JSON type is not a number with the service's deserializer texts, then runs the parameter rules in streams_iterator_params.rs. The same module now owns the AT_SEQUENCE_NUMBER to AFTER conversion. - StreamEngine::first_sequence_number_at_or_after(shard_id, at_ms) on all four backends, each in its own stream_at_timestamp.rs. SQLite, PostgreSQL and MongoDB take MIN(sequence_number) over created_at >= T. Cassandra seeks the clustering key with the HLC millisecond prefix of T as the lower bound and filters created_at within that partition: created_at_ms <= hlc_ms holds for every record since the one-clock-read change, so created_at_ms >= T implies the sequence is at or after the bound and no qualifying record is skipped, and the filter drops a record written under a clamped clock whose prefix clears the bound while its created_at is before T. MongoDB and SQLite gain a (shard_id, created_at) index for the seek; on MongoDB the existing index walked 50,000 documents (84 ms) for a mid-range seek over a 100,000-record shard. - Resolution: a match positions AT that record (the existing n - 1 conversion); no match positions after the newest record. The tip is read before the seek so a write landing between the two reads is not skipped. - TRIM_HORIZON and LATEST with a SequenceNumber now refuse as the service does (#461), since the same check covers them. Tests: tests/test_streams_at_timestamp.py, eleven tests with every expected value from the measurement, including the at-or-after boundary at a record's own millisecond, passing on SQLite, PostgreSQL, MongoDB and Cassandra; nine of the original ten fail against a server built from the base commit. The existing tests/test_streams.py passes on all four. Unit tests cover the millisecond floor, the validation order and texts, the Timestamp JSON-type texts, the future buffer, the Cassandra bound, and the tip-then-seek order against a double that writes during the tip read (the test fails with the reads swapped). A Cassandra direct test inserts a clamped record and asserts the seek does not return it for a T after its created_at. Docs: a Streams section in differences-from-dynamodb.md, the usage guide example, the streams design doc, and EXTENDDB_STREAM_SINCE in samples/stream_consumer.py. Closes #460. Closes #461. --- crates/core/src/types/stream.rs | 7 + crates/engine/src/lib.rs | 1 + crates/engine/src/streams.rs | 133 ++--- crates/engine/src/streams_iterator_params.rs | 463 ++++++++++++++++++ crates/storage-cassandra/src/lib.rs | 1 + .../src/stream_at_timestamp.rs | 85 ++++ crates/storage-cassandra/src/stream_engine.rs | 17 +- .../storage-cassandra/tests/direct/streams.rs | 108 ++++ crates/storage-mongodb/src/bootstrapper.rs | 14 + crates/storage-mongodb/src/lib.rs | 1 + .../src/stream_at_timestamp.rs | 44 ++ crates/storage-mongodb/src/stream_engine.rs | 12 + crates/storage-postgres/src/lib.rs | 1 + .../src/stream_at_timestamp.rs | 31 ++ crates/storage-postgres/src/stream_engine.rs | 12 + crates/storage-sqlite/src/lib.rs | 1 + crates/storage-sqlite/src/schema.rs | 2 + crates/storage-sqlite/src/stream.rs | 12 + .../storage-sqlite/src/stream_at_timestamp.rs | 33 ++ crates/storage/src/lib.rs | 13 + docs/design/07-component-streams.md | 2 +- docs/differences-from-dynamodb.md | 7 + docs/manuals/03-usage-guide.md | 9 + samples/stream_consumer.py | 22 +- tests/test_streams_at_timestamp.py | 399 +++++++++++++++ 25 files changed, 1367 insertions(+), 63 deletions(-) create mode 100644 crates/engine/src/streams_iterator_params.rs create mode 100644 crates/storage-cassandra/src/stream_at_timestamp.rs create mode 100644 crates/storage-mongodb/src/stream_at_timestamp.rs create mode 100644 crates/storage-postgres/src/stream_at_timestamp.rs create mode 100644 crates/storage-sqlite/src/stream_at_timestamp.rs create mode 100644 tests/test_streams_at_timestamp.py diff --git a/crates/core/src/types/stream.rs b/crates/core/src/types/stream.rs index 870169b9a..41426e7cc 100755 --- a/crates/core/src/types/stream.rs +++ b/crates/core/src/types/stream.rs @@ -27,6 +27,9 @@ pub enum ShardIteratorType { Latest, AtSequenceNumber, AfterSequenceNumber, + /// Start at the first record whose creation time is at or after + /// `GetShardIteratorInput::timestamp`. + AtTimestamp, } /// Stream status. @@ -201,6 +204,10 @@ pub struct GetShardIteratorInput { pub shard_iterator_type: ShardIteratorType, #[serde(rename = "SequenceNumber", default)] pub sequence_number: Option, + /// Epoch seconds, fractional milliseconds allowed. Used with + /// `AT_TIMESTAMP`; the service refuses it with every other type. + #[serde(rename = "Timestamp", default)] + pub timestamp: Option, } /// `GetShardIterator` response. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 74083fbfa..46278b5d7 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -33,6 +33,7 @@ mod scan; mod search_vectors; pub mod stream_capture; mod streams; +mod streams_iterator_params; mod tagging; mod transact_get_items; mod transact_write_helpers; diff --git a/crates/engine/src/streams.rs b/crates/engine/src/streams.rs index c8ba419bc..5ba804d35 100755 --- a/crates/engine/src/streams.rs +++ b/crates/engine/src/streams.rs @@ -14,6 +14,7 @@ use serde_json::Value; use crate::OperationContext; use crate::serialize_output; +use crate::streams_iterator_params as iterator_params; /// Handle `DescribeStream`. /// @@ -75,6 +76,11 @@ pub async fn handle_list_streams( /// /// Encodes the shard ID and starting position into a base64 iterator token. /// +/// Validation runs in the service's order, measured 2026-10-23 (us-east-1): +/// the `ShardIteratorType` enum, then `Timestamp` presence or absence for the +/// type, then `SequenceNumber` presence or absence for the type, then the +/// future check, then stream and shard existence. +/// /// # Errors /// /// Returns [`DynamoDbError::ResourceNotFoundException`] if the stream/shard does not exist. @@ -83,8 +89,36 @@ pub async fn handle_get_shard_iterator( body: Value, ctx: &OperationContext, ) -> Result { - let input: GetShardIteratorInput = serde_json::from_value(body) - .map_err(|e| DynamoDbError::SerializationException(e.to_string()))?; + // The service renders both ShardIteratorType violations without the + // offending value (measured 2026-10-23): a missing member is "Member must + // not be null", a bad member lists the set in this order. + let type_value = body.get("ShardIteratorType"); + if type_value.is_none_or(serde_json::Value::is_null) { + return Err(DynamoDbError::ValidationException( + "1 validation error detected: Value at 'shardIteratorType' failed to satisfy \ + constraint: Member must not be null" + .to_owned(), + )); + } + crate::validate_enum_fields( + &body, + &[crate::EnumField { + json_name: "ShardIteratorType", + valid: &[ + "AFTER_SEQUENCE_NUMBER", + "LATEST", + "AT_TIMESTAMP", + "AT_SEQUENCE_NUMBER", + "TRIM_HORIZON", + ], + clause: crate::EnumClause::Bare(iterator_params::SHARD_ITERATOR_TYPE_ENUM_CLAUSE), + }], + )?; + iterator_params::check_timestamp_shape(&body)?; + let input: GetShardIteratorInput = + serde_json::from_value(body).map_err(crate::deserialize_error)?; + + let at_timestamp_ms = iterator_params::validate_iterator_parameters(&input)?; // Validate the stream and shard exist before issuing an iterator. ctx.storage @@ -92,6 +126,7 @@ pub async fn handle_get_shard_iterator( .await .map_err(storage_to_dynamo)?; + let width = ctx.storage.sequence_number_width(); let seq = match input.shard_iterator_type { ShardIteratorType::TrimHorizon => String::new(), ShardIteratorType::Latest => { @@ -104,33 +139,18 @@ pub async fn handle_get_shard_iterator( .unwrap_or_default() } ShardIteratorType::AtSequenceNumber => { - // Convert to AFTER_SEQUENCE_NUMBER by subtracting 1, so the - // exclusive "after" semantics produce inclusive "at" behavior. - let raw = input.sequence_number.clone().ok_or_else(|| { - DynamoDbError::ValidationException( - "SequenceNumber is required for AT_SEQUENCE_NUMBER iterator type".to_owned(), - ) - })?; - let n = raw.parse::().map_err(|_| { - DynamoDbError::ValidationException("Invalid SequenceNumber".to_owned()) - })?; - // n == 0: sequence 0 is the first possible record, so "at 0" - // means "read from the beginning" — same as TRIM_HORIZON. - if n > 0 { - // Pad to the backend's stored width so lexicographic order - // matches numeric order against stored sequence numbers. - let width = ctx.storage.sequence_number_width(); - format!("{:0>width$}", n - 1) - } else { - String::new() - } + let raw = input.sequence_number.as_deref().unwrap_or_default(); + iterator_params::at_sequence_to_after(raw, width)? } - ShardIteratorType::AfterSequenceNumber => { - input.sequence_number.clone().ok_or_else(|| { - DynamoDbError::ValidationException( - "SequenceNumber is required for AFTER_SEQUENCE_NUMBER iterator type".to_owned(), - ) - })? + ShardIteratorType::AfterSequenceNumber => input.sequence_number.clone().unwrap_or_default(), + ShardIteratorType::AtTimestamp => { + resolve_at_timestamp( + ctx.storage.as_ref(), + &input.shard_id, + at_timestamp_ms.unwrap_or_default(), + width, + ) + .await? } }; @@ -140,8 +160,8 @@ pub async fn handle_get_shard_iterator( let type_str = "AFTER_SEQUENCE_NUMBER"; // Encode creation timestamp (seconds since epoch) for 15-minute expiration. - // unwrap_or_default: returns epoch 0 if system clock is before 1970 — safe - // because the iterator would just expire immediately on the next GetRecords. + // unwrap_or_default: returns epoch 0 if the system clock is before 1970, + // which only makes the iterator expire on the next GetRecords. let created_at = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() @@ -161,6 +181,33 @@ pub async fn handle_get_shard_iterator( serialize_output(&output) } +/// The AFTER position for an `AT_TIMESTAMP` request: at the first record +/// created at or after `at_ms`, or after the newest record when none +/// qualifies (the service's tip-plus-one resolution). +/// +/// The tip is read before the seek. If the seek then finds nothing, the +/// iterator starts after that tip, and a record landing between the two +/// reads is still ahead of it. The other order would skip such a record. +pub(crate) async fn resolve_at_timestamp( + storage: &dyn extenddb_storage::StreamEngine, + shard_id: &str, + at_ms: i64, + width: usize, +) -> Result { + let tip = storage + .latest_sequence_number(shard_id) + .await + .map_err(storage_to_dynamo)?; + let first = storage + .first_sequence_number_at_or_after(shard_id, at_ms) + .await + .map_err(storage_to_dynamo)?; + match first { + Some(first) => iterator_params::at_sequence_to_after(&first, width), + None => Ok(tip.unwrap_or_default()), + } +} + /// Shard iterator expiration: 15 minutes (900 seconds), matching real `DynamoDB`. const SHARD_ITERATOR_EXPIRY_SECS: u64 = 900; @@ -419,32 +466,6 @@ fn storage_to_dynamo(e: StorageError) -> DynamoDbError { #[cfg(test)] mod tests { - /// AT_SEQUENCE_NUMBER converts to AFTER by subtracting 1 and padding to - /// the backend's stored width. Verify that an unpadded client input is - /// normalised correctly for both the 21-digit (postgres/sqlite/mongodb) - /// and 23-digit (cassandra) cases, and that the edge case n=0 maps to - /// TRIM_HORIZON (empty string). - #[test] - fn at_sequence_number_padding() { - let cases: &[(&str, usize, &str)] = &[ - ("5", 21, "000000000000000000004"), - ("000000000000000000005", 21, "000000000000000000004"), - ("5", 23, "00000000000000000000004"), - ("00000000000000000000005", 23, "00000000000000000000004"), - ("0", 21, ""), - ("1", 21, "000000000000000000000"), - ]; - for (input, width, expected) in cases { - let n: u128 = input.parse().unwrap(); - let result = if n > 0 { - format!("{:0>width$}", n - 1) - } else { - String::new() - }; - assert_eq!(&result, expected, "input={input} width={width}"); - } - } - #[test] fn shard_iterator_round_trip_backward_compat_and_fail_closed() { let stream = "arn:aws:dynamodb:us-east-1:1:table/T/stream/2026-10-20T16:17:40.188"; diff --git a/crates/engine/src/streams_iterator_params.rs b/crates/engine/src/streams_iterator_params.rs new file mode 100644 index 000000000..623199740 --- /dev/null +++ b/crates/engine/src/streams_iterator_params.rs @@ -0,0 +1,463 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! `GetShardIterator` parameter rules and position conversions. +//! +//! Messages and the order of the checks were measured on the service +//! 2026-10-23 (us-east-1); see `tests/test_streams_at_timestamp.py` for the +//! wire-level expectations taken from the same run. + +use extenddb_core::error::DynamoDbError; +use extenddb_core::types::{GetShardIteratorInput, ShardIteratorType}; + +/// How the service renders a `ShardIteratorType` that is not a member: no +/// value, and the set in this order. Measured 2026-10-23 (us-east-1) for an +/// unknown name and for a lowercase one alike. +pub(crate) const SHARD_ITERATOR_TYPE_ENUM_CLAUSE: &str = "Value at 'shardIteratorType' failed to \ + satisfy constraint: Member must satisfy enum value set: [AFTER_SEQUENCE_NUMBER, LATEST, \ + AT_TIMESTAMP, AT_SEQUENCE_NUMBER, TRIM_HORIZON]"; + +/// Refuse a `Timestamp` whose JSON type is not a number with the text the +/// service's deserializer renders for it (measured 2026-10-23): a string is +/// `STRING_VALUE`, a boolean `TRUE_VALUE` or `FALSE_VALUE`, an array or object +/// the structure message. Numbers and null pass through to the parameter +/// rules, which treat null as absent. +pub(crate) fn check_timestamp_shape(body: &serde_json::Value) -> Result<(), DynamoDbError> { + use serde_json::Value; + let Some(v) = body.get("Timestamp") else { + return Ok(()); + }; + let msg = match v { + Value::Null | Value::Number(_) => return Ok(()), + Value::String(_) => "STRING_VALUE cannot be converted to Date", + Value::Bool(true) => "TRUE_VALUE cannot be converted to Date", + Value::Bool(false) => "FALSE_VALUE cannot be converted to Date", + Value::Array(_) | Value::Object(_) => "Start of structure or map found where not expected", + }; + Err(DynamoDbError::SerializationException(msg.to_owned())) +} + +/// The service's prefix on every parameter-value refusal below. +const INVALID_PARAMETER_PREFIX: &str = "One or more parameter values were invalid: "; + +/// A future `Timestamp` is accepted up to this far ahead of the server clock. +/// Measured 2026-10-23 (us-east-1): now + 1 s accepted, now + 2 s refused. +const AT_TIMESTAMP_FUTURE_BUFFER_MS: i64 = 1_000; + +/// Check the per-type parameter rules in the service's order and return the +/// `AT_TIMESTAMP` position in milliseconds when that is the type. +/// +/// Messages and order measured on the service 2026-10-23 (us-east-1). +pub(crate) fn validate_iterator_parameters( + input: &GetShardIteratorInput, +) -> Result, DynamoDbError> { + let refuse = |msg: &str| { + Err(DynamoDbError::ValidationException(format!( + "{INVALID_PARAMETER_PREFIX}{msg}" + ))) + }; + let is_at_timestamp = input.shard_iterator_type == ShardIteratorType::AtTimestamp; + let takes_sequence = matches!( + input.shard_iterator_type, + ShardIteratorType::AtSequenceNumber | ShardIteratorType::AfterSequenceNumber + ); + + // Timestamp presence or absence for the type comes first. + let at_ms = if is_at_timestamp { + match input.timestamp { + Some(t) if t > 0.0 && t.is_finite() => Some(timestamp_to_millis(t)), + _ => { + return refuse( + "Valid timestamp must be provided when the iterator type is AT_TIMESTAMP", + ); + } + } + } else { + if input.timestamp.is_some() { + return refuse("Timestamp should not be passed for this iterator type"); + } + None + }; + + // Then SequenceNumber presence or absence for the type. + if takes_sequence { + if input.sequence_number.is_none() { + return refuse("SequenceNumber cannot be null"); + } + } else if input.sequence_number.is_some() { + return refuse("SequenceNumber should not be passed for this iterator type"); + } + + // Then the future check. + if let Some(at_ms) = at_ms { + let now_ms = i64::try_from( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis(), + ) + .unwrap_or(i64::MAX); + if at_ms > now_ms.saturating_add(AT_TIMESTAMP_FUTURE_BUFFER_MS) { + return refuse("Timestamp parameter cannot be greater than the current timestamp"); + } + } + Ok(at_ms) +} + +/// Epoch seconds with an optional fraction to whole milliseconds, floored. +/// Saturates at the `i64` edge; the caller has already refused values that +/// are not positive and finite. +pub(crate) fn timestamp_to_millis(secs: f64) -> i64 { + let ms = (secs * 1000.0).floor(); + if ms >= 9.2e18 { + i64::MAX + } else { + // Non-negative and in range after the guard above. + #[allow(clippy::cast_possible_truncation)] + let v = ms as i64; + v + } +} + +/// Convert an AT_SEQUENCE_NUMBER position to the AFTER position the token +/// carries: `n - 1`, zero-padded to the backend's stored width so lexicographic +/// order matches numeric order. `n == 0` is the first possible record, so +/// "at 0" reads from the beginning, the same as TRIM_HORIZON. +pub(crate) fn at_sequence_to_after(raw: &str, width: usize) -> Result { + let n = raw + .parse::() + .map_err(|_| DynamoDbError::ValidationException("Invalid SequenceNumber".to_owned()))?; + Ok(if n > 0 { + format!("{:0>width$}", n - 1) + } else { + String::new() + }) +} + +#[cfg(test)] +mod tests { + use extenddb_core::error::DynamoDbError; + use extenddb_core::types::{GetShardIteratorInput, ShardIteratorType}; + + /// AT_SEQUENCE_NUMBER converts to AFTER by subtracting 1 and padding to + /// the backend's stored width. Verify that an unpadded client input is + /// normalised correctly for both the 21-digit (postgres/sqlite/mongodb) + /// and 23-digit (cassandra) cases, and that the edge case n=0 maps to + /// TRIM_HORIZON (empty string). + #[test] + fn at_sequence_number_padding() { + let cases: &[(&str, usize, &str)] = &[ + ("5", 21, "000000000000000000004"), + ("000000000000000000005", 21, "000000000000000000004"), + ("5", 23, "00000000000000000000004"), + ("00000000000000000000005", 23, "00000000000000000000004"), + ("0", 21, ""), + ("1", 21, "000000000000000000000"), + ]; + for (input, width, expected) in cases { + let result = super::at_sequence_to_after(input, *width).unwrap(); + assert_eq!(&result, expected, "input={input} width={width}"); + } + assert!(super::at_sequence_to_after("abc", 21).is_err()); + } + + /// Epoch seconds with a fraction floor to whole milliseconds, as the + /// service seeks at millisecond precision (measured: a `Timestamp` of + /// `.5` skipped records written at `.050`). + #[test] + fn timestamp_to_millis_floors_to_the_millisecond() { + assert_eq!( + super::timestamp_to_millis(1_792_764_248.0), + 1_792_764_248_000 + ); + assert_eq!( + super::timestamp_to_millis(1_792_764_248.05), + 1_792_764_248_050 + ); + assert_eq!( + super::timestamp_to_millis(1_792_764_248.999), + 1_792_764_248_999 + ); + assert_eq!( + super::timestamp_to_millis(1_792_764_248.123_456), + 1_792_764_248_123 + ); + // Floors, never rounds: .9996 ms stays at 123. + assert_eq!( + super::timestamp_to_millis(1_792_764_248.123_999_6), + 1_792_764_248_123 + ); + assert_eq!(super::timestamp_to_millis(1e18), i64::MAX); + } + + fn input(t: ShardIteratorType, seq: Option<&str>, ts: Option) -> GetShardIteratorInput { + GetShardIteratorInput { + stream_arn: + "arn:aws:dynamodb:us-east-1:123456789012:table/T/stream/2026-10-23T14:03:56.871" + .to_owned(), + shard_id: "shardId-00000001792764241200-b719fef1".to_owned(), + shard_iterator_type: t, + sequence_number: seq.map(str::to_owned), + timestamp: ts, + } + } + + fn message(r: Result, DynamoDbError>) -> String { + match r { + Err(DynamoDbError::ValidationException(m)) => m, + other => panic!("expected ValidationException, got {other:?}"), + } + } + + /// Messages, their prefix, and the order of the checks, as measured on + /// the service 2026-10-23 (us-east-1). + #[test] + fn parameter_validation_matches_the_service_order_and_text() { + use ShardIteratorType::{ + AfterSequenceNumber, AtSequenceNumber, AtTimestamp, Latest, TrimHorizon, + }; + const P: &str = "One or more parameter values were invalid: "; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs_f64(); + let past = 1_792_764_148.0; + let v = super::validate_iterator_parameters; + + // AT_TIMESTAMP needs a positive Timestamp; null, zero and negative all refuse. + for ts in [None, Some(0.0), Some(-1.0), Some(f64::NAN)] { + assert_eq!( + message(v(&input(AtTimestamp, None, ts))), + format!( + "{P}Valid timestamp must be provided when the iterator type is AT_TIMESTAMP" + ), + "ts={ts:?}" + ); + } + // The Timestamp check runs before the SequenceNumber check. + assert_eq!( + message(v(&input(AtTimestamp, Some("1"), None))), + format!("{P}Valid timestamp must be provided when the iterator type is AT_TIMESTAMP") + ); + // SequenceNumber with AT_TIMESTAMP refuses, and does so before the future check. + for ts in [past, now + 3_600.0] { + assert_eq!( + message(v(&input(AtTimestamp, Some("1"), Some(ts)))), + format!("{P}SequenceNumber should not be passed for this iterator type") + ); + } + // Timestamp with any other type refuses, before the SequenceNumber check. + for t in [TrimHorizon, Latest, AtSequenceNumber, AfterSequenceNumber] { + for seq in [None, Some("1")] { + assert_eq!( + message(v(&input(t, seq, Some(past)))), + format!("{P}Timestamp should not be passed for this iterator type"), + "type={t:?} seq={seq:?}" + ); + } + } + // SequenceNumber rules for the four other types. + for t in [TrimHorizon, Latest] { + assert_eq!( + message(v(&input(t, Some("1"), None))), + format!("{P}SequenceNumber should not be passed for this iterator type") + ); + assert_eq!(v(&input(t, None, None)).unwrap(), None); + } + for t in [AtSequenceNumber, AfterSequenceNumber] { + assert_eq!( + message(v(&input(t, None, None))), + format!("{P}SequenceNumber cannot be null") + ); + assert_eq!(v(&input(t, Some("1"), None)).unwrap(), None); + } + // A far-future Timestamp refuses; a past one resolves to milliseconds. + assert_eq!( + message(v(&input(AtTimestamp, None, Some(now + 3_600.0)))), + format!("{P}Timestamp parameter cannot be greater than the current timestamp") + ); + assert_eq!( + v(&input(AtTimestamp, None, Some(past))).unwrap(), + Some(1_792_764_148_000) + ); + } + + /// Malformed `Timestamp` JSON types render the service's deserializer + /// texts (measured); numbers and null pass to the parameter rules. + #[test] + fn timestamp_shape_texts_match_the_service() { + use serde_json::json; + let msg = + |v: serde_json::Value| match super::check_timestamp_shape(&json!({"Timestamp": v})) { + Err(DynamoDbError::SerializationException(m)) => m, + other => panic!("expected SerializationException, got {other:?}"), + }; + assert_eq!( + msg(json!("1792764248.5")), + "STRING_VALUE cannot be converted to Date" + ); + assert_eq!(msg(json!("")), "STRING_VALUE cannot be converted to Date"); + assert_eq!(msg(json!(true)), "TRUE_VALUE cannot be converted to Date"); + assert_eq!(msg(json!(false)), "FALSE_VALUE cannot be converted to Date"); + assert_eq!( + msg(json!({"S": "x"})), + "Start of structure or map found where not expected" + ); + assert_eq!( + msg(json!([1])), + "Start of structure or map found where not expected" + ); + assert!(super::check_timestamp_shape(&json!({"Timestamp": 1.5})).is_ok()); + assert!(super::check_timestamp_shape(&json!({"Timestamp": null})).is_ok()); + assert!(super::check_timestamp_shape(&json!({})).is_ok()); + } + + /// The future buffer is about one second: now + 0.5 s is accepted, now + + /// 2 s is refused (measured; the 1 s to 2 s band depends on clock skew). + #[test] + fn future_buffer_admits_half_a_second_and_refuses_two() { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs_f64(); + let v = super::validate_iterator_parameters; + assert!( + v(&input( + ShardIteratorType::AtTimestamp, + None, + Some(now + 0.5) + )) + .is_ok() + ); + assert!( + v(&input( + ShardIteratorType::AtTimestamp, + None, + Some(now + 2.0) + )) + .is_err() + ); + } + + /// A write that lands while the tip is being read is still ahead of the + /// resolved position. The double performs that write inside + /// `latest_sequence_number` and reports the tip including it. Tip first: + /// the seek then finds the new record and the iterator positions AT it. + /// Seek first: the seek finds nothing, the tip read then includes the new + /// record, and the iterator starts after it, skipping it. + #[tokio::test] + async fn at_timestamp_positions_before_a_write_that_lands_between_the_two_reads() { + use std::sync::Mutex; + + use extenddb_storage::BoxedFuture as BoxFuture; + use extenddb_storage::error::StorageError; + use extenddb_storage::{StreamEngine, StreamListResult, StreamRecordsResult}; + + struct RacingShard { + /// Sequence numbers in the shard, with their creation ms. + records: Mutex>, + /// The record the racing writer adds during the tip read. + late: (String, i64), + } + impl StreamEngine for RacingShard { + fn write_stream_record( + &self, + _: &str, + _: &extenddb_core::types::StreamRecord, + _: &str, + _: &str, + ) -> BoxFuture<'_, Result<(), StorageError>> { + unreachable!() + } + fn get_stream_records( + &self, + _: &str, + _: &str, + _: &str, + _: Option<&str>, + _: i64, + ) -> BoxFuture<'_, StreamRecordsResult> { + unreachable!() + } + fn describe_stream( + &self, + _: &str, + _: &extenddb_core::types::DescribeStreamInput, + ) -> BoxFuture<'_, Result> + { + unreachable!() + } + fn list_streams( + &self, + _: &str, + _: Option<&str>, + _: i64, + _: Option<&str>, + ) -> BoxFuture<'_, StreamListResult> { + unreachable!() + } + fn cleanup_expired_stream_records( + &self, + _: i64, + ) -> BoxFuture<'_, Result> { + unreachable!() + } + fn assign_shard( + &self, + _: &str, + _: &str, + _: &str, + ) -> BoxFuture<'_, Result> { + unreachable!() + } + fn next_sequence_number(&self, _: &str) -> BoxFuture<'_, Result> { + unreachable!() + } + fn validate_shard( + &self, + _: &str, + _: &str, + _: &str, + ) -> BoxFuture<'_, Result<(), StorageError>> { + Box::pin(async { Ok(()) }) + } + fn latest_sequence_number( + &self, + _: &str, + ) -> BoxFuture<'_, Result, StorageError>> { + Box::pin(async move { + let mut recs = self.records.lock().unwrap(); + // The racing write lands while this read runs; the store + // reports the tip as it stands, which includes it. + recs.push(self.late.clone()); + Ok(recs.last().map(|(s, _)| s.clone())) + }) + } + fn first_sequence_number_at_or_after( + &self, + _: &str, + at_ms: i64, + ) -> BoxFuture<'_, Result, StorageError>> { + Box::pin(async move { + let recs = self.records.lock().unwrap(); + Ok(recs + .iter() + .filter(|(_, ms)| *ms >= at_ms) + .map(|(s, _)| s.clone()) + .min()) + }) + } + } + + let shard = RacingShard { + records: Mutex::new(vec![("000000000000000000005".to_owned(), 1_000)]), + late: ("000000000000000000006".to_owned(), 2_500), + }; + // T is after the only stored record and before the racing write. + let pos = crate::streams::resolve_at_timestamp(&shard, "shardId-x", 2_000, 21) + .await + .unwrap(); + // AT record 6 is encoded as AFTER record 5: GetRecords returns 6 first. + assert_eq!(pos, "000000000000000000005"); + } +} diff --git a/crates/storage-cassandra/src/lib.rs b/crates/storage-cassandra/src/lib.rs index 7dbfe98c4..c38891fa5 100644 --- a/crates/storage-cassandra/src/lib.rs +++ b/crates/storage-cassandra/src/lib.rs @@ -28,6 +28,7 @@ pub mod migrations; pub mod operations; pub(crate) mod propagation_hold; mod snapshot_engine; +pub mod stream_at_timestamp; mod stream_engine; pub mod stream_util; pub mod table_engine; diff --git a/crates/storage-cassandra/src/stream_at_timestamp.rs b/crates/storage-cassandra/src/stream_at_timestamp.rs new file mode 100644 index 000000000..5654744e3 --- /dev/null +++ b/crates/storage-cassandra/src/stream_at_timestamp.rs @@ -0,0 +1,85 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! `AT_TIMESTAMP` seek: the first stream record in a shard created at or +//! after a point in time. +//! +//! `created_at` is not a clustering column, so the seek uses the sequence +//! number's millisecond prefix as a clustering-key lower bound and then +//! filters `created_at` within that single partition. For every record +//! `created_at_ms <= hlc_ms`: the `HybridClock` clamps its physical +//! component upward and never below the wall-clock read that `created_at` +//! stores. So `created_at_ms >= at_ms` implies `hlc_ms >= at_ms`, and every +//! qualifying record sits at or after the bound; the seek never skips one. +//! The filter removes the other case: a record written under a clamped clock +//! (after a backwards step) whose prefix clears the bound while its +//! `created_at` is before `at_ms`. The filter walks at most that clamp +//! window, which is zero under a monotonic clock. + +use cdrs_tokio::types::IntoRustByName; +use extenddb_storage::error::StorageError; + +use crate::engine::CassandraEngine; + +/// The smallest sequence number whose millisecond prefix is `at_ms`. +#[must_use] +pub fn sequence_lower_bound(at_ms: i64) -> String { + format!("{:013}{:06}{:04}", at_ms.max(0), 0, 0) +} + +impl CassandraEngine { + pub(crate) async fn first_sequence_number_at_or_after_impl( + &self, + shard_id: &str, + at_ms: i64, + ) -> Result, StorageError> { + let keyspace = self.account_keyspace_for_shard(shard_id).await?; + let bound = sequence_lower_bound(at_ms); + // A single-partition clustering range with one non-key filter; the + // rows come back in clustering (sequence) order, so the first is the + // minimum qualifying sequence. + let query = format!( + "SELECT sequence_number FROM {keyspace}.stream_records \ + WHERE shard_id = ? AND sequence_number >= ? AND created_at >= ? \ + LIMIT 1 ALLOW FILTERING" + ); + let result = self + .session + .query_with_values( + &query, + cdrs_tokio::query_values!(shard_id, bound.as_str(), at_ms), + ) + .await + .map_err(|e| StorageError::Internal(e.to_string()))?; + let rows = result + .response_body() + .map_err(|e| StorageError::Internal(e.to_string()))? + .into_rows() + .unwrap_or_default(); + Ok(rows + .into_iter() + .next() + .and_then(|row| row.get_r_by_name("sequence_number").ok())) + } +} + +#[cfg(test)] +mod tests { + use super::sequence_lower_bound; + + #[test] + fn lower_bound_is_the_first_sequence_in_that_millisecond() { + let b = sequence_lower_bound(1_792_764_248_050); + assert_eq!(b, "17927642480500000000000"); + assert_eq!(b.len(), 23); + // Any real sequence in that millisecond sorts at or after the bound, + // and every sequence from the previous millisecond sorts before it. + assert!("17927642480500000010042" > b.as_str()); + assert!("17927642480499999990042" < b.as_str()); + } + + #[test] + fn negative_timestamps_clamp_to_the_epoch() { + assert_eq!(sequence_lower_bound(-5), "00000000000000000000000"); + } +} diff --git a/crates/storage-cassandra/src/stream_engine.rs b/crates/storage-cassandra/src/stream_engine.rs index 8c83b0927..62bbea71b 100755 --- a/crates/storage-cassandra/src/stream_engine.rs +++ b/crates/storage-cassandra/src/stream_engine.rs @@ -24,7 +24,10 @@ impl CassandraEngine { /// (embedded in the shard ID) via the secondary index on `tables.table_id`. /// /// Shard ID format: `shardId-{table_id}-{index:012}` - async fn account_keyspace_for_shard(&self, shard_id: &str) -> Result { + pub(crate) async fn account_keyspace_for_shard( + &self, + shard_id: &str, + ) -> Result { // Strip "shardId-" prefix and trailing "-{12 digits}" to get table_id. let without_prefix = shard_id.strip_prefix("shardId-").ok_or_else(|| { StorageError::Internal(format!("Invalid shard_id format: {shard_id}")) @@ -595,4 +598,16 @@ impl StreamEngine for CassandraEngine { .map(|row| row.get_r_by_name("sequence_number").unwrap_or_default())) }) } + + fn first_sequence_number_at_or_after( + &self, + shard_id: &str, + at_ms: i64, + ) -> BoxFuture<'_, Result, StorageError>> { + let shard_id = shard_id.to_owned(); + Box::pin(async move { + self.first_sequence_number_at_or_after_impl(&shard_id, at_ms) + .await + }) + } } diff --git a/crates/storage-cassandra/tests/direct/streams.rs b/crates/storage-cassandra/tests/direct/streams.rs index bc0efa206..075d8cf2e 100644 --- a/crates/storage-cassandra/tests/direct/streams.rs +++ b/crates/storage-cassandra/tests/direct/streams.rs @@ -742,3 +742,111 @@ async fn test_stream_record_created_at_matches_the_record_and_sequence() { ); } } + +/// A record written under a clamped clock (after a backwards step) carries a +/// sequence prefix later than its `created_at`. The `AT_TIMESTAMP` seek must +/// not return it for a `T` after its `created_at`, and must still return a +/// record created at or after `T`. +#[tokio::test] +async fn test_at_timestamp_seek_skips_a_clamped_record_older_than_t() { + use extenddb_storage::StreamEngine; + + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let table = TestTable::new(&engine, "StreamClampSeek", false).await; + let view = StreamViewType::NewAndOldImages; + + let mut item = BTreeMap::new(); + item.insert("id".to_string(), AttributeValue::S("pk-clamp".to_string())); + item.insert("val".to_string(), AttributeValue::S("real".to_string())); + engine + .put_item( + &table.key_info, + item, + false, + None, + &Default::default(), + Some(&capture(view)), + ) + .await + .unwrap(); + + let shard_id = shard_for("pk-clamp", &table.key_info.table_id); + let keyspace = format!("extenddb_ttl_test_account_{}", table.key_info.account_id); + let rows = engine + .session_arc() + .query_with_values( + &format!( + "SELECT sequence_number, created_at, record_data FROM {keyspace}.stream_records \ + WHERE shard_id = ?" + ), + cdrs_tokio::query_values!(shard_id.as_str()), + ) + .await + .unwrap() + .response_body() + .unwrap() + .into_rows() + .unwrap_or_default(); + assert_eq!(rows.len(), 1); + let real_seq: String = rows[0].get_r_by_name("sequence_number").unwrap(); + let real_created: i64 = rows[0].get_r_by_name("created_at").unwrap(); + let data: String = rows[0].get_r_by_name("record_data").unwrap(); + + // Model the clamped record: sequence prefix 8 s after the real record, + // created_at 8 s before it. T sits between the two: after the clamped + // created_at, before the real record's. + let clamped_hlc = real_created + 8_000; + let clamped_created = real_created - 8_000; + let clamped_seq = format!("{clamped_hlc:013}{:06}{:04}", 0, 9999); + engine + .session_arc() + .query_with_values( + &format!( + "INSERT INTO {keyspace}.stream_records \ + (shard_id, sequence_number, table_id, event_name, record_data, created_at) \ + VALUES (?, ?, ?, 'Insert', ?, ?)" + ), + cdrs_tokio::query_values!( + shard_id.as_str(), + clamped_seq.as_str(), + table.key_info.table_id.as_str(), + data.as_str(), + clamped_created + ), + ) + .await + .unwrap(); + + // T after the clamped created_at and before the real record: the real + // record qualifies, the clamped one does not. + let t = real_created - 1_000; + let got = engine + .first_sequence_number_at_or_after(&shard_id, t) + .await + .unwrap(); + assert_eq!( + got.as_deref(), + Some(real_seq.as_str()), + "the real record is first at or after T" + ); + + // T after every created_at: nothing qualifies, even though the clamped + // sequence prefix clears the bound. + let t = real_created + 1_000; + let got = engine + .first_sequence_number_at_or_after(&shard_id, t) + .await + .unwrap(); + assert_eq!(got, None, "a clamped record older than T is not returned"); + + // T before everything: the clamped record is the first, as its + // created_at is the oldest. + let got = engine + .first_sequence_number_at_or_after(&shard_id, clamped_created - 1) + .await + .unwrap(); + assert!(got.is_some()); +} diff --git a/crates/storage-mongodb/src/bootstrapper.rs b/crates/storage-mongodb/src/bootstrapper.rs index c37c3f36f..4487651e6 100644 --- a/crates/storage-mongodb/src/bootstrapper.rs +++ b/crates/storage-mongodb/src/bootstrapper.rs @@ -183,6 +183,20 @@ impl Bootstrapper for MongoBootstrapper { .await .map_err(|e| OpError::Internal(format!("stream_records shard index: {e}")))?; + // (shard_id, created_at) serves the AT_TIMESTAMP seek, which filters + // one shard by creation time and takes the lowest sequence. Without + // it the (shard_id, sequence_number) index walks every document up to + // the first match: 84 ms over 50,000 documents measured on one shard + // of 100,000. + stream_records + .create_index( + IndexModel::builder() + .keys(doc! { "shard_id": 1, "created_at": 1 }) + .build(), + ) + .await + .map_err(|e| OpError::Internal(format!("stream_records created_at index: {e}")))?; + Ok(()) } diff --git a/crates/storage-mongodb/src/lib.rs b/crates/storage-mongodb/src/lib.rs index b27cc0baf..fef02e4c3 100644 --- a/crates/storage-mongodb/src/lib.rs +++ b/crates/storage-mongodb/src/lib.rs @@ -22,6 +22,7 @@ mod metadata_engine; mod operations; pub mod pushdown; mod snapshot_engine; +mod stream_at_timestamp; mod stream_engine; mod table_engine; mod ttl_worker; diff --git a/crates/storage-mongodb/src/stream_at_timestamp.rs b/crates/storage-mongodb/src/stream_at_timestamp.rs new file mode 100644 index 000000000..964fe0ab1 --- /dev/null +++ b/crates/storage-mongodb/src/stream_at_timestamp.rs @@ -0,0 +1,44 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! `AT_TIMESTAMP` seek: the first stream record in a shard created at or +//! after a point in time. + +use extenddb_storage::error::StorageError; +use futures::TryStreamExt; +use mongodb::bson::{DateTime as BsonDateTime, Document, doc}; +use mongodb::options::FindOptions; + +use crate::MongoEngine; + +impl MongoEngine { + pub(crate) async fn first_sequence_number_at_or_after_impl( + &self, + shard_id: &str, + at_ms: i64, + ) -> Result, StorageError> { + let records_coll = self.data_db.collection::("stream_records"); + let opts = FindOptions::builder() + .sort(doc! { "sequence_number": 1 }) + .limit(1) + .projection(doc! { "sequence_number": 1 }) + .build(); + let cursor = records_coll + .find(doc! { + "shard_id": shard_id, + "created_at": { "$gte": BsonDateTime::from_millis(at_ms) }, + }) + .with_options(opts) + .await + .map_err(|e| StorageError::Internal(e.to_string()))?; + let docs: Vec = cursor + .try_collect() + .await + .map_err(|e| StorageError::Internal(e.to_string()))?; + Ok(docs.first().and_then(|d| { + d.get_str("sequence_number") + .ok() + .map(std::borrow::ToOwned::to_owned) + })) + } +} diff --git a/crates/storage-mongodb/src/stream_engine.rs b/crates/storage-mongodb/src/stream_engine.rs index 097b3bb2a..85e5392e1 100644 --- a/crates/storage-mongodb/src/stream_engine.rs +++ b/crates/storage-mongodb/src/stream_engine.rs @@ -751,6 +751,18 @@ impl StreamEngine for MongoEngine { })) }) } + + fn first_sequence_number_at_or_after( + &self, + shard_id: &str, + at_ms: i64, + ) -> BoxFuture<'_, Result, StorageError>> { + let shard_id = shard_id.to_owned(); + Box::pin(async move { + self.first_sequence_number_at_or_after_impl(&shard_id, at_ms) + .await + }) + } } #[cfg(test)] diff --git a/crates/storage-postgres/src/lib.rs b/crates/storage-postgres/src/lib.rs index 9603d68ff..a90a5a9a3 100755 --- a/crates/storage-postgres/src/lib.rs +++ b/crates/storage-postgres/src/lib.rs @@ -27,6 +27,7 @@ mod pg_util; mod snapshot_engine; #[doc(hidden)] pub use snapshot_engine::map_fetch_error; +mod stream_at_timestamp; mod stream_engine; #[doc(hidden)] pub mod stream_records_sql; diff --git a/crates/storage-postgres/src/stream_at_timestamp.rs b/crates/storage-postgres/src/stream_at_timestamp.rs new file mode 100644 index 000000000..1f43a12b2 --- /dev/null +++ b/crates/storage-postgres/src/stream_at_timestamp.rs @@ -0,0 +1,31 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! `AT_TIMESTAMP` seek: the first stream record in a shard created at or +//! after a point in time. + +use extenddb_storage::error::StorageError; + +use crate::PostgresEngine; + +impl PostgresEngine { + pub(crate) async fn first_sequence_number_at_or_after_impl( + &self, + shard_id: &str, + at_ms: i64, + ) -> Result, StorageError> { + let bound = time::OffsetDateTime::from_unix_timestamp_nanos(i128::from(at_ms) * 1_000_000) + .map_err(|e| StorageError::Validation(format!("Invalid Timestamp: {e}")))?; + // MIN over no rows is one NULL row, so the column is read as Option. + let row: Option<(Option,)> = sqlx::query_as( + "SELECT MIN(sequence_number) FROM stream_records \ + WHERE shard_id = $1 AND created_at >= $2", + ) + .bind(shard_id) + .bind(bound) + .fetch_optional(&self.data_pool) + .await + .map_err(|e| StorageError::Internal(e.to_string()))?; + Ok(row.and_then(|(s,)| s)) + } +} diff --git a/crates/storage-postgres/src/stream_engine.rs b/crates/storage-postgres/src/stream_engine.rs index da7fd122d..0a546a717 100755 --- a/crates/storage-postgres/src/stream_engine.rs +++ b/crates/storage-postgres/src/stream_engine.rs @@ -616,4 +616,16 @@ impl StreamEngine for PostgresEngine { Ok(row.map(|(s,)| s)) }) } + + fn first_sequence_number_at_or_after( + &self, + shard_id: &str, + at_ms: i64, + ) -> BoxFuture<'_, Result, StorageError>> { + let shard_id = shard_id.to_owned(); + Box::pin(async move { + self.first_sequence_number_at_or_after_impl(&shard_id, at_ms) + .await + }) + } } diff --git a/crates/storage-sqlite/src/lib.rs b/crates/storage-sqlite/src/lib.rs index 7e8085ff9..2ce3b45fe 100644 --- a/crates/storage-sqlite/src/lib.rs +++ b/crates/storage-sqlite/src/lib.rs @@ -41,6 +41,7 @@ mod snapshot_engine; mod sqlite_util; mod store; mod stream; +mod stream_at_timestamp; #[cfg(test)] mod stream_tests; mod table_engine; diff --git a/crates/storage-sqlite/src/schema.rs b/crates/storage-sqlite/src/schema.rs index d04ee5b56..a6c5a974b 100644 --- a/crates/storage-sqlite/src/schema.rs +++ b/crates/storage-sqlite/src/schema.rs @@ -181,6 +181,8 @@ CREATE TABLE IF NOT EXISTS stream_records ( ); CREATE INDEX IF NOT EXISTS idx_stream_records_created ON stream_records (created_at); +-- Serves the AT_TIMESTAMP seek: one shard filtered by creation time. +CREATE INDEX IF NOT EXISTS idx_stream_records_shard_created ON stream_records (shard_id, created_at); -- Admin users. CREATE TABLE IF NOT EXISTS admin_users ( diff --git a/crates/storage-sqlite/src/stream.rs b/crates/storage-sqlite/src/stream.rs index 5b00eabfb..719b78914 100644 --- a/crates/storage-sqlite/src/stream.rs +++ b/crates/storage-sqlite/src/stream.rs @@ -517,4 +517,16 @@ impl StreamEngine for SqliteEngine { Ok(row.map(|(s,)| s)) }) } + + fn first_sequence_number_at_or_after( + &self, + shard_id: &str, + at_ms: i64, + ) -> BoxFuture<'_, Result, StorageError>> { + let shard_id = shard_id.to_owned(); + Box::pin(async move { + self.first_sequence_number_at_or_after_impl(&shard_id, at_ms) + .await + }) + } } diff --git a/crates/storage-sqlite/src/stream_at_timestamp.rs b/crates/storage-sqlite/src/stream_at_timestamp.rs new file mode 100644 index 000000000..04e903249 --- /dev/null +++ b/crates/storage-sqlite/src/stream_at_timestamp.rs @@ -0,0 +1,33 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! `AT_TIMESTAMP` seek: the first stream record in a shard created at or +//! after a point in time. + +use extenddb_storage::error::StorageError; + +use crate::SqliteEngine; +use crate::sqlite_util::format_epoch_millis; + +impl SqliteEngine { + /// `created_at` is stored as fixed-width millisecond text in the column + /// default's shape, so a bound in the same shape compares chronologically. + pub(crate) async fn first_sequence_number_at_or_after_impl( + &self, + shard_id: &str, + at_ms: i64, + ) -> Result, StorageError> { + let bound = format_epoch_millis(at_ms); + // MIN over no rows is one NULL row, so the column is read as Option. + let row: Option<(Option,)> = sqlx::query_as( + "SELECT MIN(sequence_number) FROM stream_records \ + WHERE shard_id = ? AND created_at >= ?", + ) + .bind(shard_id) + .bind(&bound) + .fetch_optional(&self.pool) + .await + .map_err(|e| StorageError::Internal(e.to_string()))?; + Ok(row.and_then(|(s,)| s)) + } +} diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index b7aec12ff..529a6da21 100755 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -689,6 +689,19 @@ pub trait StreamEngine: Send + Sync { &self, shard_id: &str, ) -> BoxFuture<'_, Result, StorageError>>; + + /// Sequence number of the first record in the shard whose creation time + /// is at or after `at_ms` (milliseconds since the Unix epoch), or `None` + /// when no stored record qualifies. + /// + /// Used by `GetShardIterator` with `AT_TIMESTAMP`. The comparison is + /// against the stored `created_at`, which every backend takes from the + /// same clock read as the record's `ApproximateCreationDateTime`. + fn first_sequence_number_at_or_after( + &self, + shard_id: &str, + at_ms: i64, + ) -> BoxFuture<'_, Result, StorageError>>; } /// Background worker operations that require storage access. diff --git a/docs/design/07-component-streams.md b/docs/design/07-component-streams.md index dbff306b5..ac2468d4d 100755 --- a/docs/design/07-component-streams.md +++ b/docs/design/07-component-streams.md @@ -18,7 +18,7 @@ Four operations, served on the same HTTP endpoint as DynamoDB operations: |-----------|-------------| | `DescribeStream` | Return stream ARN, status, shard list with parent/child relationships | | `ListStreams` | List streams, optionally filtered by table name | -| `GetShardIterator` | Get an iterator for a shard (TRIM_HORIZON, LATEST, AT_SEQUENCE_NUMBER, AFTER_SEQUENCE_NUMBER) | +| `GetShardIterator` | Get an iterator for a shard (TRIM_HORIZON, LATEST, AT_SEQUENCE_NUMBER, AFTER_SEQUENCE_NUMBER, AT_TIMESTAMP) | | `GetRecords` | Read up to 1000 records (or 1 MB) from a shard using an iterator | **Note:** In real DynamoDB, Streams is a separate service with its own endpoint (`streams.dynamodb..amazonaws.com`) and its own SDK client (`boto3.client('dynamodbstreams')` in Python, `DynamoDbStreamsClient` in Java). extenddb serves both services on a single port. This works because SDK clients accept `endpoint_url` overrides — the user sets both `AWS_ENDPOINT_URL_DYNAMODB` and `AWS_ENDPOINT_URL_DYNAMODB_STREAMS` to the same extenddb address. The `X-Amz-Target` prefix distinguishes the two services: DynamoDB operations use `DynamoDB_20120810.`, Streams operations use `DynamoDBStreams_20120810.`. Both use `dynamodb` as the SigV4 signing name, so authentication is identical. See `01-requirements.md` §11 and `08-component-config.md` §10 for SDK configuration details. diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index 80c1f671b..68fd37ff7 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -49,6 +49,13 @@ adaptation when switching between ExtendDB and the real service. | Table creation delay | Returns `CREATING` immediately; transitions to `ACTIVE` typically within seconds. Same behavior for on-demand and provisioned | Configurable via `control_plane_delay_seconds` runtime setting (default: 5s) | | DeletionProtectionEnabled | Enforced | Enforced (accepted and stored, DeleteTable rejects when enabled) | +## Streams + +| Area | DynamoDB | ExtendDB | +|------|----------|------| +| Shards | Shards open and close over time, with parent and child shards | A fixed number of shards per table (default 4), assigned by partition key hash; shards never close | +| `AT_TIMESTAMP` iterator | The first record created at or after `Timestamp`, compared at millisecond precision; older than retention resolves to the oldest record; past the newest record resolves to after it; more than about a second in the future is a `ValidationException` | The same, on all four backends. The seek compares the record's stored creation time, taken from the same clock read as its `ApproximateCreationDateTime`. The future buffer is one second against the server clock | + ## Time to Live (TTL) | Area | DynamoDB | ExtendDB | diff --git a/docs/manuals/03-usage-guide.md b/docs/manuals/03-usage-guide.md index 861f6bba9..9d8c5e84e 100755 --- a/docs/manuals/03-usage-guide.md +++ b/docs/manuals/03-usage-guide.md @@ -391,6 +391,15 @@ aws dynamodbstreams get-shard-iterator \ --shard-id "shard-0" \ --shard-iterator-type TRIM_HORIZON +# Get a shard iterator positioned at the first record created at or after a +# point in time (epoch seconds, fractional milliseconds allowed) +aws dynamodbstreams get-shard-iterator \ + --endpoint-url https://127.0.0.1:18443 \ + --stream-arn "" \ + --shard-id "shard-0" \ + --shard-iterator-type AT_TIMESTAMP \ + --timestamp 1792764248.050 + # Read records aws dynamodbstreams get-records \ --endpoint-url https://127.0.0.1:18443 \ diff --git a/samples/stream_consumer.py b/samples/stream_consumer.py index b360f82b6..2b254c6ae 100755 --- a/samples/stream_consumer.py +++ b/samples/stream_consumer.py @@ -125,11 +125,23 @@ def refresh_shards(): for shard in resp["StreamDescription"]["Shards"]: sid = shard["ShardId"] if sid not in shard_iterators: - it = streams_client.get_shard_iterator( - StreamArn=stream_arn, - ShardId=sid, - ShardIteratorType="TRIM_HORIZON", - ) + # EXTENDDB_STREAM_SINCE (epoch seconds) starts each shard at + # the first record created at or after that time instead of + # the oldest retained record. + since = os.environ.get("EXTENDDB_STREAM_SINCE") + if since: + it = streams_client.get_shard_iterator( + StreamArn=stream_arn, + ShardId=sid, + ShardIteratorType="AT_TIMESTAMP", + Timestamp=float(since), + ) + else: + it = streams_client.get_shard_iterator( + StreamArn=stream_arn, + ShardId=sid, + ShardIteratorType="TRIM_HORIZON", + ) shard_iterators[sid] = it["ShardIterator"] log("POLLER", f"Tracking shard {sid}") diff --git a/tests/test_streams_at_timestamp.py b/tests/test_streams_at_timestamp.py new file mode 100644 index 000000000..10811b02f --- /dev/null +++ b/tests/test_streams_at_timestamp.py @@ -0,0 +1,399 @@ +# Copyright 2026 ExtendDB contributors +# SPDX-License-Identifier: Apache-2.0 + +"""DynamoDB Streams AT_TIMESTAMP shard iterator. + +Every expected value here was measured on the service (us-east-1, +2026-10-23): positioning at millisecond precision, the four validation +messages and their order, the future buffer, and the error classes for +malformed Timestamp values. + +These tests require a running extenddb server (EXTENDDB_TEST_ENDPOINT must be +set) because the service routes Streams to a separate endpoint; extenddb +serves both on the same endpoint. +""" + +from __future__ import annotations + +import json +import os +import time +import uuid +from datetime import datetime, timezone + +import boto3 +import pytest +from botocore.config import Config +from botocore.exceptions import ClientError +from conftest import wait_for_active, wait_for_deleted + +PREFIX = "One or more parameter values were invalid: " + + +@pytest.fixture(scope="module") +def endpoint_url() -> str: + return os.environ["EXTENDDB_TEST_ENDPOINT"].strip() + + +def _client(service: str, endpoint_url: str, validate: bool = True): + kwargs: dict = dict( + service_name=service, + region_name=os.environ.get("AWS_DEFAULT_REGION", "us-east-1"), + endpoint_url=endpoint_url, + config=Config(parameter_validation=validate, retries={"max_attempts": 1}), + ) + if endpoint_url.startswith("https://"): + kwargs["verify"] = False + return boto3.client(**kwargs) + + +@pytest.fixture(scope="module") +def dynamodb_client(endpoint_url: str): + return _client("dynamodb", endpoint_url) + + +@pytest.fixture(scope="module") +def streams_client(endpoint_url: str): + return _client("dynamodbstreams", endpoint_url) + + +@pytest.fixture(scope="module") +def raw_streams_client(endpoint_url: str): + """Parameter validation off, so malformed Timestamp shapes reach the server.""" + return _client("dynamodbstreams", endpoint_url, validate=False) + + +@pytest.fixture() +def stream_table(dynamodb_client): + table_name = f"extenddb-ts-{uuid.uuid4().hex[:8]}" + dynamodb_client.create_table( + TableName=table_name, + AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}], + KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}], + BillingMode="PAY_PER_REQUEST", + StreamSpecification={"StreamEnabled": True, "StreamViewType": "NEW_AND_OLD_IMAGES"}, + ) + wait_for_active(dynamodb_client, table_name) + stream_arn = dynamodb_client.describe_table(TableName=table_name)["Table"]["LatestStreamArn"] + yield table_name, stream_arn + try: + dynamodb_client.delete_table(TableName=table_name) + wait_for_deleted(dynamodb_client, table_name) + except Exception: + pass + + +def _shard_with_records(streams_client, stream_arn: str) -> str: + """The one shard holding a single partition key's records.""" + for shard in streams_client.describe_stream(StreamArn=stream_arn)["StreamDescription"]["Shards"]: + it = streams_client.get_shard_iterator( + StreamArn=stream_arn, ShardId=shard["ShardId"], ShardIteratorType="TRIM_HORIZON" + )["ShardIterator"] + if streams_client.get_records(ShardIterator=it)["Records"]: + return shard["ShardId"] + raise AssertionError("no shard holds records") + + +def _drain(streams_client, iterator: str, rounds: int = 6) -> list[dict]: + out: list[dict] = [] + it = iterator + for _ in range(rounds): + resp = streams_client.get_records(ShardIterator=it) + out.extend(resp.get("Records", [])) + it = resp.get("NextShardIterator") + if not resp.get("Records") or not it: + break + return out + + +def _values(records: list[dict]) -> list[str]: + return [r["dynamodb"]["NewImage"]["v"]["S"] for r in records] + + +def _at(streams_client, stream_arn: str, shard_id: str, ts) -> list[dict]: + it = streams_client.get_shard_iterator( + StreamArn=stream_arn, ShardId=shard_id, ShardIteratorType="AT_TIMESTAMP", Timestamp=ts + )["ShardIterator"] + return _drain(streams_client, it) + + +def _write_group(dynamodb_client, table: str, tag: str, n: int) -> tuple[float, float]: + """Write n items just after a second boundary; return (start, end) wall times.""" + now = time.time() + time.sleep((1.0 - (now % 1.0)) + 0.05) + start = time.time() + for i in range(n): + dynamodb_client.put_item(TableName=table, Item={"pk": {"S": "k"}, "v": {"S": f"{tag}-{i}"}}) + return start, time.time() + + +def _error(fn, **kw) -> tuple[str, str]: + try: + fn(**kw) + except ClientError as e: + err = e.response["Error"] + return err["Code"], err["Message"] + raise AssertionError("expected a ClientError") + + +def _raw_error(endpoint_url: str, body: dict) -> tuple[str, str]: + """POST a GetShardIterator body exactly as given, SigV4-signed with the + test user's key from the environment, for shapes the SDK cannot + serialise (JSON null, an object). Returns (code, message).""" + import ssl + import urllib.request + + from botocore.auth import SigV4Auth + from botocore.awsrequest import AWSRequest + from botocore.credentials import Credentials + + data = json.dumps(body).encode() + req = AWSRequest(method="POST", url=endpoint_url, data=data, headers={ + "Content-Type": "application/x-amz-json-1.0", + "X-Amz-Target": "DynamoDBStreams_20120810.GetShardIterator", + }) + signer_creds = Credentials(os.environ["AWS_ACCESS_KEY_ID"], os.environ["AWS_SECRET_ACCESS_KEY"]) + SigV4Auth(signer_creds, "dynamodb", os.environ.get("AWS_DEFAULT_REGION", "us-east-1")).add_auth(req) + prepped = req.prepare() + ctx = ssl.create_default_context() + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + hr = urllib.request.Request(prepped.url, data=data, headers=dict(prepped.headers), method="POST") + try: + with urllib.request.urlopen(hr, timeout=30, context=ctx) as r: + raise AssertionError(f"expected an error, got {r.status}") + except urllib.error.HTTPError as e: + parsed = json.loads(e.read().decode()) + return parsed.get("__type", "").split("#")[-1], parsed.get("message") or parsed.get("Message") or "" + + +class TestPositioning: + """Measured on the service with three groups written in distinct seconds.""" + + def test_seek_positions_at_millisecond_precision(self, dynamodb_client, streams_client, stream_table): + table, arn = stream_table + g1 = _write_group(dynamodb_client, table, "g1", 3) + time.sleep(2.2) + g2 = _write_group(dynamodb_client, table, "g2", 3) + time.sleep(2.2) + g3 = _write_group(dynamodb_client, table, "g3", 2) + shard = _shard_with_records(streams_client, arn) + all_vals = ["g1-0", "g1-1", "g1-2", "g2-0", "g2-1", "g2-2", "g3-0", "g3-1"] + + def ts(secs: float): + return datetime.fromtimestamp(secs, tz=timezone.utc) + + # Before the first record and 25 hours ago both return everything, no error. + assert _values(_at(streams_client, arn, shard, ts(g1[0] - 10))) == all_vals + assert _values(_at(streams_client, arn, shard, ts(time.time() - 25 * 3600))) == all_vals + # Between groups. + assert _values(_at(streams_client, arn, shard, ts(g1[1] + 1.0))) == all_vals[3:] + assert _values(_at(streams_client, arn, shard, ts(g2[1] + 1.0))) == all_vals[6:] + # The group's own second, as an integer, includes the group. + assert _values(_at(streams_client, arn, shard, ts(int(g2[0])))) == all_vals[3:] + assert _values(_at(streams_client, arn, shard, ts(int(g3[0])))) == all_vals[6:] + # Fractional seconds inside the group's second skip it: the writes + # landed at +0.050 to about +0.100, so .5 and .999 start at group 3. + # Guard on the measured span so a slow write on a loaded host skips + # the probe instead of failing it. + if g2[1] < int(g2[0]) + 0.5: + assert _values(_at(streams_client, arn, shard, ts(int(g2[0]) + 0.5))) == all_vals[6:] + assert _values(_at(streams_client, arn, shard, ts(int(g2[0]) + 0.999))) == all_vals[6:] + else: + pytest.skip(f"group 2 spanned past +0.5 s ({g2[1] - int(g2[0]):.3f}); boundary probe not meaningful") + # One second after the last record: nothing. + assert _at(streams_client, arn, shard, ts(int(g3[1]) + 1)) == [] + # ApproximateCreationDateTime is whole seconds. + recs = _at(streams_client, arn, shard, ts(g1[0] - 10)) + for r in recs: + assert r["dynamodb"]["ApproximateCreationDateTime"].microsecond == 0 + + def test_boundary_is_at_or_after_the_record_millisecond(self, dynamodb_client, streams_client, stream_table): + """T equal to a record's own creation millisecond returns that record + (the service's at-or-after); one millisecond later does not.""" + table, arn = stream_table + dynamodb_client.put_item(TableName=table, Item={"pk": {"S": "k"}, "v": {"S": "only"}}) + shard = _shard_with_records(streams_client, arn) + it = streams_client.get_shard_iterator(StreamArn=arn, ShardId=shard, ShardIteratorType="TRIM_HORIZON")["ShardIterator"] + rec = _drain(streams_client, it)[0] + second = int(rec["dynamodb"]["ApproximateCreationDateTime"].timestamp()) + + def returns_it(ms: int) -> bool: + t = datetime.fromtimestamp(second + ms / 1000.0, tz=timezone.utc) + return _values(_at(streams_client, arn, shard, t)) == ["only"] + + # Bisect within the record's second for the last millisecond that + # still returns it: that is the record's own creation millisecond. + assert returns_it(0) + lo, hi = 0, 1000 + while hi - lo > 1: + mid = (lo + hi) // 2 + if returns_it(mid): + lo = mid + else: + hi = mid + assert returns_it(lo), "T at the record's millisecond returns it" + assert not returns_it(lo + 1), "T one millisecond later does not" + + def test_after_tip_returns_only_later_writes(self, dynamodb_client, streams_client, stream_table): + table, arn = stream_table + _write_group(dynamodb_client, table, "old", 2) + shard = _shard_with_records(streams_client, arn) + time.sleep(0.3) + it = streams_client.get_shard_iterator( + StreamArn=arn, + ShardId=shard, + ShardIteratorType="AT_TIMESTAMP", + Timestamp=datetime.fromtimestamp(time.time() - 0.2, tz=timezone.utc), + )["ShardIterator"] + dynamodb_client.put_item(TableName=table, Item={"pk": {"S": "k"}, "v": {"S": "post-tip"}}) + assert _values(_drain(streams_client, it)) == ["post-tip"] + + +class TestTimestampShapes: + def test_integer_and_fractional_numbers_are_accepted(self, dynamodb_client, streams_client, raw_streams_client, stream_table): + table, arn = stream_table + g = _write_group(dynamodb_client, table, "g", 2) + shard = _shard_with_records(streams_client, arn) + for ts in (int(g[0]), round(g[0], 3), g[0] + 0.123456): + resp = raw_streams_client.get_shard_iterator( + StreamArn=arn, ShardId=shard, ShardIteratorType="AT_TIMESTAMP", Timestamp=ts + ) + assert "ShardIterator" in resp, ts + + def test_zero_negative_and_null_refuse(self, dynamodb_client, streams_client, raw_streams_client, stream_table, endpoint_url): + table, arn = stream_table + _write_group(dynamodb_client, table, "g", 1) + shard = _shard_with_records(streams_client, arn) + expected = PREFIX + "Valid timestamp must be provided when the iterator type is AT_TIMESTAMP" + for ts in (0, -1): + code, msg = _error( + raw_streams_client.get_shard_iterator, + StreamArn=arn, ShardId=shard, ShardIteratorType="AT_TIMESTAMP", Timestamp=ts, + ) + assert (code, msg) == ("ValidationException", expected), ts + # JSON null cannot go through the SDK; send it as the service saw it. + code, msg = _raw_error(endpoint_url, { + "StreamArn": arn, "ShardId": shard, "ShardIteratorType": "AT_TIMESTAMP", "Timestamp": None, + }) + assert (code, msg) == ("ValidationException", expected), "null" + + def test_milliseconds_as_seconds_is_in_the_future(self, dynamodb_client, streams_client, stream_table, endpoint_url): + table, arn = stream_table + g = _write_group(dynamodb_client, table, "g", 1) + shard = _shard_with_records(streams_client, arn) + for ts in (int(g[0]) * 1000, 10**18): + code, msg = _raw_error(endpoint_url, { + "StreamArn": arn, "ShardId": shard, "ShardIteratorType": "AT_TIMESTAMP", "Timestamp": ts, + }) + assert code == "ValidationException", ts + assert msg == PREFIX + "Timestamp parameter cannot be greater than the current timestamp", ts + + def test_non_numeric_timestamp_is_a_serialization_error(self, dynamodb_client, streams_client, stream_table, endpoint_url): + table, arn = stream_table + g = _write_group(dynamodb_client, table, "g", 1) + shard = _shard_with_records(streams_client, arn) + cases = [ + (f"{int(g[0])}.5", "STRING_VALUE cannot be converted to Date"), + ("", "STRING_VALUE cannot be converted to Date"), + (True, "TRUE_VALUE cannot be converted to Date"), + ({"S": "x"}, "Start of structure or map found where not expected"), + ] + for ts, expected in cases: + code, msg = _raw_error(endpoint_url, { + "StreamArn": arn, "ShardId": shard, "ShardIteratorType": "AT_TIMESTAMP", "Timestamp": ts, + }) + assert (code, msg) == ("SerializationException", expected), ts + + +class TestValidationMatrix: + """Messages and check order measured on the service.""" + + def test_matrix(self, dynamodb_client, streams_client, raw_streams_client, stream_table): + table, arn = stream_table + g = _write_group(dynamodb_client, table, "g", 1) + shard = _shard_with_records(streams_client, arn) + it = streams_client.get_shard_iterator(StreamArn=arn, ShardId=shard, ShardIteratorType="TRIM_HORIZON")["ShardIterator"] + seq = _drain(streams_client, it)[0]["dynamodb"]["SequenceNumber"] + ts = int(g[0]) + future = int(time.time()) + 3600 + ts_required = "Valid timestamp must be provided when the iterator type is AT_TIMESTAMP" + seq_refused = "SequenceNumber should not be passed for this iterator type" + ts_refused = "Timestamp should not be passed for this iterator type" + future_refused = "Timestamp parameter cannot be greater than the current timestamp" + cases = [ + (dict(ShardIteratorType="AT_TIMESTAMP"), ts_required), + (dict(ShardIteratorType="AT_TIMESTAMP", SequenceNumber=seq), ts_required), + (dict(ShardIteratorType="AT_TIMESTAMP", SequenceNumber=seq, Timestamp=ts), seq_refused), + (dict(ShardIteratorType="AT_TIMESTAMP", SequenceNumber=seq, Timestamp=future), seq_refused), + (dict(ShardIteratorType="AT_TIMESTAMP", SequenceNumber=seq, Timestamp=0), ts_required), + (dict(ShardIteratorType="AT_TIMESTAMP", Timestamp=future), future_refused), + (dict(ShardIteratorType="TRIM_HORIZON", Timestamp=ts), ts_refused), + (dict(ShardIteratorType="LATEST", Timestamp=ts), ts_refused), + (dict(ShardIteratorType="AT_SEQUENCE_NUMBER", SequenceNumber=seq, Timestamp=ts), ts_refused), + (dict(ShardIteratorType="AFTER_SEQUENCE_NUMBER", SequenceNumber=seq, Timestamp=ts), ts_refused), + (dict(ShardIteratorType="TRIM_HORIZON", SequenceNumber=seq, Timestamp=ts), ts_refused), + (dict(ShardIteratorType="TRIM_HORIZON", SequenceNumber=seq), seq_refused), + (dict(ShardIteratorType="LATEST", SequenceNumber=seq), seq_refused), + (dict(ShardIteratorType="AT_SEQUENCE_NUMBER"), "SequenceNumber cannot be null"), + ] + for extra, expected in cases: + code, msg = _error(raw_streams_client.get_shard_iterator, StreamArn=arn, ShardId=shard, **extra) + assert code == "ValidationException", extra + assert msg == PREFIX + expected, extra + + def test_unknown_or_missing_type_renders_without_the_value(self, dynamodb_client, streams_client, raw_streams_client, stream_table, endpoint_url): + table, arn = stream_table + _write_group(dynamodb_client, table, "g", 1) + shard = _shard_with_records(streams_client, arn) + members = "[AFTER_SEQUENCE_NUMBER, LATEST, AT_TIMESTAMP, AT_SEQUENCE_NUMBER, TRIM_HORIZON]" + # The service omits the offending value from the enum violation. + for bad in ("BOGUS", "at_timestamp"): + code, msg = _error(raw_streams_client.get_shard_iterator, StreamArn=arn, ShardId=shard, ShardIteratorType=bad) + assert code == "ValidationException" + assert msg == ( + "1 validation error detected: Value at 'shardIteratorType' failed to satisfy " + f"constraint: Member must satisfy enum value set: {members}" + ) + # A missing or null type is a ValidationException, not a serialization error. + for body in ({"Timestamp": 1792764248.0}, {"ShardIteratorType": None}): + code, msg = _raw_error(endpoint_url, {"StreamArn": arn, "ShardId": shard, **body}) + assert (code, msg) == ( + "ValidationException", + "1 validation error detected: Value at 'shardIteratorType' failed to satisfy " + "constraint: Member must not be null", + ), body + + def test_future_check_runs_before_shard_existence(self, dynamodb_client, streams_client, raw_streams_client, stream_table): + table, arn = stream_table + _write_group(dynamodb_client, table, "g", 1) + shard = _shard_with_records(streams_client, arn) + code, msg = _error( + raw_streams_client.get_shard_iterator, + StreamArn=arn, ShardId="shardId-00000000000000000000-00000000", + ShardIteratorType="AT_TIMESTAMP", Timestamp=int(time.time()) + 3600, + ) + assert (code, msg) == ("ValidationException", PREFIX + "Timestamp parameter cannot be greater than the current timestamp") + code, _ = _error( + raw_streams_client.get_shard_iterator, + StreamArn=arn, ShardId="shardId-00000000000000000000-00000000", + ShardIteratorType="AT_TIMESTAMP", Timestamp=int(time.time()) - 60, + ) + assert code == "ResourceNotFoundException" + assert shard # the real shard still exists + + def test_near_future_is_accepted(self, dynamodb_client, streams_client, stream_table): + table, arn = stream_table + _write_group(dynamodb_client, table, "g", 1) + shard = _shard_with_records(streams_client, arn) + resp = streams_client.get_shard_iterator( + StreamArn=arn, ShardId=shard, ShardIteratorType="AT_TIMESTAMP", + Timestamp=datetime.fromtimestamp(time.time() + 0.5, tz=timezone.utc), + ) + assert "ShardIterator" in resp + code, _ = _error( + streams_client.get_shard_iterator, + StreamArn=arn, ShardId=shard, ShardIteratorType="AT_TIMESTAMP", + Timestamp=datetime.fromtimestamp(time.time() + 5, tz=timezone.utc), + ) + assert code == "ValidationException" From b734787aeedf18578835d3e4fee403b675c7e50b Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:59:55 +0000 Subject: [PATCH 02/14] fix(streams): seek the shard's own range on Cassandra, and adapt AT_TIMESTAMP to main Main names each stream's shards by stream. On Cassandra it keeps a shard's records in the partition of its index, which every stream of the table shares. The Cassandra seek bound the client's shard id, which no record row carries, so every AT_TIMESTAMP iterator started after the newest record. The seek now reads the shard's partition and sequence range through shard_range, as latest_sequence_number does. Its lower bound is the higher of the shard's start (exclusive) and the time bound (inclusive), because CQL takes one start bound per clustering column. The direct test seeks with the stream's shard id. A new test checks that a closed shard and the next stream's shard each answer only their own records. The missing ShardIteratorType sentence now comes from the constraint helper that main added for the streams constraint sentences. On PostgreSQL the seek numbers the shard's committed writes first, as the LATEST read does, so it sees every write that committed before it. The Shards row in docs/differences-from-dynamodb.md now says four shards per stream that close when a disable closes the stream, which is what main does. The AT_TIMESTAMP usage example takes a placeholder, because main refuses a shard id under 28 characters. --- crates/engine/src/streams.rs | 9 +- .../src/stream_at_timestamp.rs | 50 ++++++++-- .../storage-cassandra/tests/direct/streams.rs | 98 +++++++++++++++++-- crates/storage-postgres/src/stream_engine.rs | 3 + docs/differences-from-dynamodb.md | 2 +- docs/manuals/03-usage-guide.md | 2 +- 6 files changed, 144 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/streams.rs b/crates/engine/src/streams.rs index 5baa725c0..8e14ac740 100755 --- a/crates/engine/src/streams.rs +++ b/crates/engine/src/streams.rs @@ -119,11 +119,10 @@ pub async fn handle_get_shard_iterator( // not be null", a bad member lists the set in this order. let type_value = body.get("ShardIteratorType"); if type_value.is_none_or(serde_json::Value::is_null) { - return Err(DynamoDbError::ValidationException( - "1 validation error detected: Value at 'shardIteratorType' failed to satisfy \ - constraint: Member must not be null" - .to_owned(), - )); + return Err(DynamoDbError::ValidationException(constraint( + "shardIteratorType", + "not be null", + ))); } crate::validate_enum_fields( &body, diff --git a/crates/storage-cassandra/src/stream_at_timestamp.rs b/crates/storage-cassandra/src/stream_at_timestamp.rs index 5654744e3..c07ea7d0b 100644 --- a/crates/storage-cassandra/src/stream_at_timestamp.rs +++ b/crates/storage-cassandra/src/stream_at_timestamp.rs @@ -27,28 +27,54 @@ pub fn sequence_lower_bound(at_ms: i64) -> String { format!("{:013}{:06}{:04}", at_ms.max(0), 0, 0) } +/// The one lower-bound clause the seek sends: CQL takes a single start bound +/// per clustering column. The shard's range starts after `after` +/// (exclusive) and the seek at `bound` (inclusive); both are 23-digit +/// sequence numbers, so string order is numeric order and the higher one +/// decides, with its own operator. +fn lower_bound_clause<'a>(bound: &'a str, after: &'a str) -> (&'static str, &'a str) { + if bound > after { + (">=", bound) + } else { + (">", after) + } +} + impl CassandraEngine { + /// The seek reads the shard's own range of its partition, as + /// `last_sequence_in` does: a stream's shard keeps its records in the + /// partition of its index, which every stream of the table shares. pub(crate) async fn first_sequence_number_at_or_after_impl( &self, shard_id: &str, at_ms: i64, ) -> Result, StorageError> { let keyspace = self.account_keyspace_for_shard(shard_id).await?; + let range = self.shard_range(&keyspace, shard_id).await?; let bound = sequence_lower_bound(at_ms); + let (lower_op, lower) = lower_bound_clause(&bound, &range.after); + let upper = if range.until.is_some() { + " AND sequence_number <= ?" + } else { + "" + }; // A single-partition clustering range with one non-key filter; the // rows come back in clustering (sequence) order, so the first is the // minimum qualifying sequence. let query = format!( "SELECT sequence_number FROM {keyspace}.stream_records \ - WHERE shard_id = ? AND sequence_number >= ? AND created_at >= ? \ + WHERE shard_id = ? AND sequence_number {lower_op} ?{upper} AND created_at >= ? \ LIMIT 1 ALLOW FILTERING" ); + let values = match &range.until { + Some(until) => { + cdrs_tokio::query_values!(range.physical.as_str(), lower, until.as_str(), at_ms) + } + None => cdrs_tokio::query_values!(range.physical.as_str(), lower, at_ms), + }; let result = self .session - .query_with_values( - &query, - cdrs_tokio::query_values!(shard_id, bound.as_str(), at_ms), - ) + .query_with_values(&query, values) .await .map_err(|e| StorageError::Internal(e.to_string()))?; let rows = result @@ -65,7 +91,19 @@ impl CassandraEngine { #[cfg(test)] mod tests { - use super::sequence_lower_bound; + use super::{lower_bound_clause, sequence_lower_bound}; + + /// The seek's lower bound is the higher of the shard's start (exclusive) + /// and the time bound (inclusive), each with its own operator. + #[test] + fn the_higher_lower_bound_decides_with_its_own_operator() { + let start = "17927642400000000000007"; + let later = sequence_lower_bound(1_792_764_248_050); + let earlier = sequence_lower_bound(1_792_764_000_000); + assert_eq!(lower_bound_clause(&later, start), (">=", later.as_str())); + assert_eq!(lower_bound_clause(&earlier, start), (">", start)); + assert_eq!(lower_bound_clause(start, start), (">", start)); + } #[test] fn lower_bound_is_the_first_sequence_in_that_millisecond() { diff --git a/crates/storage-cassandra/tests/direct/streams.rs b/crates/storage-cassandra/tests/direct/streams.rs index 14a145d7a..81098a107 100644 --- a/crates/storage-cassandra/tests/direct/streams.rs +++ b/crates/storage-cassandra/tests/direct/streams.rs @@ -790,7 +790,7 @@ async fn test_at_timestamp_seek_skips_a_clamped_record_older_than_t() { return; } let engine = setup_engine().await; - let table = TestTable::new(&engine, "StreamClampSeek", false).await; + let (key_info, label) = setup_stream_table(&engine, "StreamClampSeek").await; let view = StreamViewType::NewAndOldImages; let mut item = BTreeMap::new(); @@ -798,7 +798,7 @@ async fn test_at_timestamp_seek_skips_a_clamped_record_older_than_t() { item.insert("val".to_string(), AttributeValue::S("real".to_string())); engine .put_item( - &table.key_info, + &key_info, item, false, None, @@ -808,8 +808,11 @@ async fn test_at_timestamp_seek_skips_a_clamped_record_older_than_t() { .await .unwrap(); - let shard_id = shard_for("pk-clamp", &table.key_info.table_id); - let keyspace = format!("extenddb_ttl_test_account_{}", table.key_info.account_id); + // The records sit in the partition `shard_for` names; the seek takes the + // stream's shard id, as a client does. + let partition = shard_for("pk-clamp", &key_info.table_id); + let shard_id = stream_shard_for("pk-clamp", &key_info.table_id, &label, view); + let keyspace = format!("extenddb_ttl_test_account_{}", key_info.account_id); let rows = engine .session_arc() .query_with_values( @@ -817,7 +820,7 @@ async fn test_at_timestamp_seek_skips_a_clamped_record_older_than_t() { "SELECT sequence_number, created_at, record_data FROM {keyspace}.stream_records \ WHERE shard_id = ?" ), - cdrs_tokio::query_values!(shard_id.as_str()), + cdrs_tokio::query_values!(partition.as_str()), ) .await .unwrap() @@ -845,9 +848,9 @@ async fn test_at_timestamp_seek_skips_a_clamped_record_older_than_t() { VALUES (?, ?, ?, 'Insert', ?, ?)" ), cdrs_tokio::query_values!( - shard_id.as_str(), + partition.as_str(), clamped_seq.as_str(), - table.key_info.table_id.as_str(), + key_info.table_id.as_str(), data.as_str(), clamped_created ), @@ -885,3 +888,84 @@ async fn test_at_timestamp_seek_skips_a_clamped_record_older_than_t() { .unwrap(); assert!(got.is_some()); } + +/// Every stream of a table keeps its records in the partition of the shard +/// index, and the seek reads only the shard's own range of it. A closed shard +/// answers nothing for a time after its close, even once the next stream has +/// written to the same partition; the next stream's shard does not answer the +/// record of the stream before it. +#[tokio::test] +async fn test_at_timestamp_seek_reads_only_the_shards_range() { + use crate::stream_disable::{activate, put, set_stream}; + use extenddb_storage::StreamEngine; + use extenddb_storage_cassandra::cassandra_util::now_millis; + + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let name = "StreamSeekRange"; + let (key_info, old_label) = setup_stream_table(&engine, name).await; + activate(&engine).await; + let account = key_info.account_id.as_str(); + let view = StreamViewType::NewAndOldImages; + + let start = now_millis() - 1_000; + put(&engine, account, name, "pk-range", view).await; + let old_shard = stream_shard_for("pk-range", &key_info.table_id, &old_label, view); + let old_seq = engine + .first_sequence_number_at_or_after(&old_shard, start) + .await + .unwrap() + .expect("the first stream's record"); + + set_stream( + &engine, + account, + name, + serde_json::json!({"StreamEnabled": false}), + ) + .await + .unwrap(); + let after_close = now_millis(); + let enabled = set_stream( + &engine, + account, + name, + serde_json::json!({"StreamEnabled": true, "StreamViewType": "NEW_AND_OLD_IMAGES"}), + ) + .await + .unwrap(); + let new_label = enabled.latest_stream_label.expect("the new stream's label"); + put(&engine, account, name, "pk-range", view).await; + let new_shard = stream_shard_for("pk-range", &key_info.table_id, &new_label, view); + + // The closed shard keeps its record and ends at it, so the new stream's + // record in the same partition is not its answer after the close. + assert_eq!( + engine + .first_sequence_number_at_or_after(&old_shard, start) + .await + .unwrap(), + Some(old_seq.clone()) + ); + assert_eq!( + engine + .first_sequence_number_at_or_after(&old_shard, after_close) + .await + .unwrap(), + None + ); + // The new stream's shard starts after the enable: for a time before the + // first stream's record, its answer is its own record. + let new_seq = engine + .first_sequence_number_at_or_after(&new_shard, start) + .await + .unwrap() + .expect("the new stream's record"); + assert_ne!(new_seq, old_seq); + assert_eq!( + engine.latest_sequence_number(&new_shard).await.unwrap(), + Some(new_seq) + ); +} diff --git a/crates/storage-postgres/src/stream_engine.rs b/crates/storage-postgres/src/stream_engine.rs index 27d32efcd..2736442f3 100755 --- a/crates/storage-postgres/src/stream_engine.rs +++ b/crates/storage-postgres/src/stream_engine.rs @@ -729,6 +729,9 @@ impl StreamEngine for PostgresEngine { ) -> BoxFuture<'_, Result, StorageError>> { let shard_id = shard_id.to_owned(); Box::pin(async move { + // The seek reads `stream_records`, so the shard's committed writes + // are numbered first, as for LATEST above. + self.number_before_read_or_log(&shard_id, None).await; self.first_sequence_number_at_or_after_impl(&shard_id, at_ms) .await }) diff --git a/docs/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index ffdf02c0c..38c95ab30 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -64,7 +64,7 @@ from a request sent to that service or backend. | Area | DynamoDB | ExtendDB | |------|----------|------| -| Shards | Shards open and close over time, with parent and child shards | A fixed number of shards per table (default 4), assigned by partition key hash; shards never close | +| Shards | Shards open and close over time, with parent and child shards | Four shards per stream, assigned by partition key hash. They close when the stream is disabled (see Stream disable and enable under Control Plane) | | `AT_TIMESTAMP` iterator | The first record created at or after `Timestamp`, compared at millisecond precision; older than retention resolves to the oldest record; past the newest record resolves to after it; more than about a second in the future is a `ValidationException` | The same, on all four backends. The seek compares the record's stored creation time, taken from the same clock read as its `ApproximateCreationDateTime`. The future buffer is one second against the server clock | ## Time to Live (TTL) diff --git a/docs/manuals/03-usage-guide.md b/docs/manuals/03-usage-guide.md index 6674988b1..8f04d34aa 100755 --- a/docs/manuals/03-usage-guide.md +++ b/docs/manuals/03-usage-guide.md @@ -396,7 +396,7 @@ aws dynamodbstreams get-shard-iterator \ aws dynamodbstreams get-shard-iterator \ --endpoint-url https://127.0.0.1:18443 \ --stream-arn "" \ - --shard-id "shard-0" \ + --shard-id "" \ --shard-iterator-type AT_TIMESTAMP \ --timestamp 1792764248.050 From 944ebe6a0854db8090319ac85354b9a218fd6175 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:14:32 +0000 Subject: [PATCH 03/14] fix(streams): GetShardIterator rounds Timestamp and checks in the service's order Timestamp is now rounded half up to the millisecond, as the service does. Measured on us-east-1, 2026-11-20, against a record created at millisecond ...389: a Timestamp of ...389.4900 returns the record and ...389.5000 does not. The service refuses 0.0004 with "Valid timestamp must be provided when the iterator type is AT_TIMESTAMP" and accepts 0.0005. So the rounded value must be at least one millisecond. The checks run in the order the service runs them: - A member of the wrong JSON type is a SerializationException before any other check. The check reads SequenceNumber before Timestamp, the model order. An array has no message, as on the service. - The constraints on SequenceNumber length, ShardIteratorType and ShardId length join one "N validation errors detected" message, in that order. - AT_SEQUENCE_NUMBER and AFTER_SEQUENCE_NUMBER refuse a missing SequenceNumber before they refuse a Timestamp. - TRIM_HORIZON and LATEST refuse a SequenceNumber after the shard check. On a shard that does not exist the answer is "Shard does not exist". The envelope of the combined message moves into validation_errors_detected in lib.rs, which validate_enum_fields now calls too. --- crates/engine/src/lib.rs | 17 +- crates/engine/src/streams.rs | 116 ++--- crates/engine/src/streams_iterator_params.rs | 465 ++++++++++++------- crates/engine/src/streams_tests.rs | 69 +++ 4 files changed, 429 insertions(+), 238 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 9e0df1ccc..18273a0f7 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -298,13 +298,20 @@ pub(crate) fn validate_enum_fields( if errors.is_empty() { return Ok(()); } - let count = errors.len(); - let msg = format!( + Err(DynamoDbError::ValidationException( + validation_errors_detected(&errors), + )) +} + +/// The service's envelope for one or more constraint clauses: `N validation +/// error(s) detected: ` and the clauses joined by `; `. +pub(crate) fn validation_errors_detected(clauses: &[String]) -> String { + let count = clauses.len(); + format!( "{count} validation error{} detected: {}", if count == 1 { "" } else { "s" }, - errors.join("; ") - ); - Err(DynamoDbError::ValidationException(msg)) + clauses.join("; ") + ) } /// Validate the `ReturnValues` field for `PutItem` / `DeleteItem`, which accept diff --git a/crates/engine/src/streams.rs b/crates/engine/src/streams.rs index 8e14ac740..51a02296b 100755 --- a/crates/engine/src/streams.rs +++ b/crates/engine/src/streams.rs @@ -101,10 +101,11 @@ pub async fn handle_list_streams( /// /// Encodes the shard ID and starting position into a base64 iterator token. /// -/// Validation runs in the service's order, measured 2026-10-23 (us-east-1): -/// the `ShardIteratorType` enum, then `Timestamp` presence or absence for the -/// type, then `SequenceNumber` presence or absence for the type, then the -/// future check, then stream and shard existence. +/// Validation runs in the service's order, measured 2026-10-23 and 2026-11-20 +/// (us-east-1): the members' JSON types, then the model's constraints in one +/// message (`SequenceNumber` length, `ShardIteratorType` null or enum, +/// `ShardId` length), then the parameter rules per type, then stream and shard +/// existence, then the `SequenceNumber` refusal of `TRIM_HORIZON` and `LATEST`. /// /// # Errors /// @@ -114,58 +115,12 @@ pub async fn handle_get_shard_iterator( body: Value, ctx: &OperationContext, ) -> Result { - // The service renders both ShardIteratorType violations without the - // offending value (measured 2026-10-23): a missing member is "Member must - // not be null", a bad member lists the set in this order. - let type_value = body.get("ShardIteratorType"); - if type_value.is_none_or(serde_json::Value::is_null) { - return Err(DynamoDbError::ValidationException(constraint( - "shardIteratorType", - "not be null", - ))); - } - crate::validate_enum_fields( - &body, - &[crate::EnumField { - json_name: "ShardIteratorType", - valid: &[ - "AFTER_SEQUENCE_NUMBER", - "LATEST", - "AT_TIMESTAMP", - "AT_SEQUENCE_NUMBER", - "TRIM_HORIZON", - ], - clause: crate::EnumClause::Bare(iterator_params::SHARD_ITERATOR_TYPE_ENUM_CLAUSE), - }], - )?; - iterator_params::check_timestamp_shape(&body)?; + iterator_params::check_member_shapes(&body)?; + constraint_violations(&body)?; + let input: GetShardIteratorInput = serde_json::from_value(body).map_err(crate::deserialize_error)?; - - // The service's ShardId bound is 28 to 65 characters, checked before any - // lookup with the model's constraint sentences (both measured 2026-10-24). - // A SequenceNumber, when given, is at least 21 characters (measured with - // "0" on AT_SEQUENCE_NUMBER). The maximum is applied once the shard is - // not found (`shard_lookup_error`): the shards a release before v0.1.14 - // wrote are named after the table, and a table name over 40 characters - // puts them past 65. let shard_len = input.shard_id.chars().count(); - if shard_len < SHARD_ID_MIN_LEN { - return Err(DynamoDbError::ValidationException( - SHARD_ID_TOO_SHORT.to_owned(), - )); - } - if input - .sequence_number - .as_ref() - .is_some_and(|n| n.chars().count() < 21) - { - return Err(DynamoDbError::ValidationException(constraint( - "sequenceNumber", - "have length greater than or equal to 21", - ))); - } - let at_timestamp_ms = iterator_params::validate_iterator_parameters(&input)?; // Validate the stream and shard exist before issuing an iterator. @@ -173,6 +128,7 @@ pub async fn handle_get_shard_iterator( .validate_shard(&ctx.account_id, &input.stream_arn, &input.shard_id) .await .map_err(|e| shard_lookup_error(shard_len, e))?; + iterator_params::refuse_sequence_number_after_shard(&input)?; let width = ctx.storage.sequence_number_width(); let seq = match input.shard_iterator_type { @@ -229,6 +185,49 @@ pub async fn handle_get_shard_iterator( serialize_output(&output) } +/// The model's constraints on a `GetShardIterator` body, in one message: the +/// `SequenceNumber` is at least 21 characters (measured 2026-10-24 with "0"), +/// the `ShardIteratorType` is present and a member, the `ShardId` is at least +/// 28 characters. The service joins every violation under one `N validation +/// errors detected`, in this order and with no value quoted (measured +/// 2026-11-20, us-east-1). The `ShardId` maximum is applied once the shard is +/// not found (`shard_lookup_error`): the shards a release before v0.1.14 wrote +/// are named after the table, and a table name over 40 characters puts them +/// past 65. +fn constraint_violations(body: &Value) -> Result<(), DynamoDbError> { + let mut clauses = Vec::new(); + if body + .get("SequenceNumber") + .and_then(Value::as_str) + .is_some_and(|n| n.chars().count() < 21) + { + clauses.push(clause( + "sequenceNumber", + "have length greater than or equal to 21", + )); + } + match body.get("ShardIteratorType") { + None | Some(Value::Null) => clauses.push(clause("shardIteratorType", "not be null")), + Some(Value::String(t)) if !iterator_params::SHARD_ITERATOR_TYPES.contains(&t.as_str()) => { + clauses.push(iterator_params::SHARD_ITERATOR_TYPE_ENUM_CLAUSE.to_owned()); + } + _ => {} + } + if body + .get("ShardId") + .and_then(Value::as_str) + .is_some_and(|s| s.chars().count() < SHARD_ID_MIN_LEN) + { + clauses.push(clause("shardId", "have length greater than or equal to 28")); + } + if clauses.is_empty() { + return Ok(()); + } + Err(DynamoDbError::ValidationException( + crate::validation_errors_detected(&clauses), + )) +} + /// The AFTER position for an `AT_TIMESTAMP` request: at the first record /// created at or after `at_ms`, or after the newest record when none /// qualifies (the service's tip-plus-one resolution). @@ -284,9 +283,14 @@ const SHARD_ID_MAX_LEN: usize = 65; /// `exclusiveStartShardId`, `sequenceNumber`, `limit` and /// `exclusiveStartStreamArn`). fn constraint(member: &str, rule: &str) -> String { - format!( - "1 validation error detected: Value at '{member}' failed to satisfy constraint: Member must {rule}" - ) + crate::validation_errors_detected(&[clause(member, rule)]) +} + +/// One constraint clause of [`constraint`], as the service joins several of +/// them under one `N validation errors detected` (measured 2026-11-20 on +/// `GetShardIterator`). +fn clause(member: &str, rule: &str) -> String { + format!("Value at '{member}' failed to satisfy constraint: Member must {rule}") } /// `GetShardIterator` with a `ShardId` under 28 characters (measured 2026-10-24 diff --git a/crates/engine/src/streams_iterator_params.rs b/crates/engine/src/streams_iterator_params.rs index 623199740..a903661df 100644 --- a/crates/engine/src/streams_iterator_params.rs +++ b/crates/engine/src/streams_iterator_params.rs @@ -4,12 +4,22 @@ //! `GetShardIterator` parameter rules and position conversions. //! //! Messages and the order of the checks were measured on the service -//! 2026-10-23 (us-east-1); see `tests/test_streams_at_timestamp.py` for the -//! wire-level expectations taken from the same run. +//! 2026-10-23 and 2026-11-20 (us-east-1); see `tests/test_streams_at_timestamp.py` +//! for the wire-level expectations taken from the same runs. use extenddb_core::error::DynamoDbError; use extenddb_core::types::{GetShardIteratorInput, ShardIteratorType}; +/// The `ShardIteratorType` members, in the order the service lists them in +/// [`SHARD_ITERATOR_TYPE_ENUM_CLAUSE`]. +pub(crate) const SHARD_ITERATOR_TYPES: &[&str] = &[ + "AFTER_SEQUENCE_NUMBER", + "LATEST", + "AT_TIMESTAMP", + "AT_SEQUENCE_NUMBER", + "TRIM_HORIZON", +]; + /// How the service renders a `ShardIteratorType` that is not a member: no /// value, and the set in this order. Measured 2026-10-23 (us-east-1) for an /// unknown name and for a lowercase one alike. @@ -17,24 +27,44 @@ pub(crate) const SHARD_ITERATOR_TYPE_ENUM_CLAUSE: &str = "Value at 'shardIterato satisfy constraint: Member must satisfy enum value set: [AFTER_SEQUENCE_NUMBER, LATEST, \ AT_TIMESTAMP, AT_SEQUENCE_NUMBER, TRIM_HORIZON]"; -/// Refuse a `Timestamp` whose JSON type is not a number with the text the -/// service's deserializer renders for it (measured 2026-10-23): a string is -/// `STRING_VALUE`, a boolean `TRUE_VALUE` or `FALSE_VALUE`, an array or object -/// the structure message. Numbers and null pass through to the parameter -/// rules, which treat null as absent. -pub(crate) fn check_timestamp_shape(body: &serde_json::Value) -> Result<(), DynamoDbError> { +/// The members whose JSON type the service checks as it reads the body, with +/// the type name its texts use, in the model's order. The service reports the +/// first member in body order that does not fit (measured 2026-11-20: +/// `"SequenceNumber": 5, "Timestamp": "x"` is the String text and the other +/// way round the Date text). The parsed body keeps no order, so the model +/// order stands in; it is the order the SDKs send. +const TYPED_MEMBERS: &[(&str, &str)] = &[("SequenceNumber", "String"), ("Timestamp", "Date")]; + +/// Refuse the first member whose JSON type does not fit with the text the +/// service's deserializer renders for it (measured 2026-10-23 and 2026-11-20): +/// `STRING_VALUE`, `NUMBER_VALUE`, `TRUE_VALUE` or `FALSE_VALUE` `cannot be +/// converted to `, an object the structure message, an array a +/// `SerializationException` with no message. Null passes through to the +/// parameter rules, which treat it as absent. The service runs this before +/// every constraint and parameter check, the `ShardIteratorType` ones +/// included. +pub(crate) fn check_member_shapes(body: &serde_json::Value) -> Result<(), DynamoDbError> { use serde_json::Value; - let Some(v) = body.get("Timestamp") else { - return Ok(()); - }; - let msg = match v { - Value::Null | Value::Number(_) => return Ok(()), - Value::String(_) => "STRING_VALUE cannot be converted to Date", - Value::Bool(true) => "TRUE_VALUE cannot be converted to Date", - Value::Bool(false) => "FALSE_VALUE cannot be converted to Date", - Value::Array(_) | Value::Object(_) => "Start of structure or map found where not expected", - }; - Err(DynamoDbError::SerializationException(msg.to_owned())) + for (member, kind) in TYPED_MEMBERS { + let Some(v) = body.get(member) else { + continue; + }; + let msg = match (*kind, v) { + (_, Value::Null) | ("String", Value::String(_)) | ("Date", Value::Number(_)) => { + continue; + } + (_, Value::String(_)) => format!("STRING_VALUE cannot be converted to {kind}"), + (_, Value::Number(_)) => format!("NUMBER_VALUE cannot be converted to {kind}"), + (_, Value::Bool(true)) => format!("TRUE_VALUE cannot be converted to {kind}"), + (_, Value::Bool(false)) => format!("FALSE_VALUE cannot be converted to {kind}"), + (_, Value::Array(_)) => String::new(), + (_, Value::Object(_)) => { + "Start of structure or map found where not expected".to_owned() + } + }; + return Err(DynamoDbError::SerializationException(msg)); + } + Ok(()) } /// The service's prefix on every parameter-value refusal below. @@ -44,79 +74,102 @@ const INVALID_PARAMETER_PREFIX: &str = "One or more parameter values were invali /// Measured 2026-10-23 (us-east-1): now + 1 s accepted, now + 2 s refused. const AT_TIMESTAMP_FUTURE_BUFFER_MS: i64 = 1_000; -/// Check the per-type parameter rules in the service's order and return the -/// `AT_TIMESTAMP` position in milliseconds when that is the type. +const SEQUENCE_NUMBER_REFUSED: &str = "SequenceNumber should not be passed for this iterator type"; + +fn refuse(msg: &str) -> Result { + Err(DynamoDbError::ValidationException(format!( + "{INVALID_PARAMETER_PREFIX}{msg}" + ))) +} + +/// Check the per-type parameter rules that the service runs before it looks +/// the shard up, in its order, and return the `AT_TIMESTAMP` position in +/// milliseconds when that is the type. /// -/// Messages and order measured on the service 2026-10-23 (us-east-1). +/// Measured 2026-10-23 and 2026-11-20 (us-east-1). `AT_TIMESTAMP`: a valid +/// `Timestamp`, then no `SequenceNumber`, then the future check. +/// `AT_SEQUENCE_NUMBER` and `AFTER_SEQUENCE_NUMBER`: a `SequenceNumber`, then +/// no `Timestamp`. `TRIM_HORIZON` and `LATEST`: no `Timestamp`; their +/// `SequenceNumber` refusal comes after the shard check +/// ([`refuse_sequence_number_after_shard`]). pub(crate) fn validate_iterator_parameters( input: &GetShardIteratorInput, ) -> Result, DynamoDbError> { - let refuse = |msg: &str| { - Err(DynamoDbError::ValidationException(format!( - "{INVALID_PARAMETER_PREFIX}{msg}" - ))) - }; - let is_at_timestamp = input.shard_iterator_type == ShardIteratorType::AtTimestamp; - let takes_sequence = matches!( - input.shard_iterator_type, - ShardIteratorType::AtSequenceNumber | ShardIteratorType::AfterSequenceNumber - ); - - // Timestamp presence or absence for the type comes first. - let at_ms = if is_at_timestamp { - match input.timestamp { - Some(t) if t > 0.0 && t.is_finite() => Some(timestamp_to_millis(t)), - _ => { + match input.shard_iterator_type { + ShardIteratorType::AtTimestamp => { + let Some(at_ms) = input.timestamp.and_then(timestamp_to_millis) else { return refuse( "Valid timestamp must be provided when the iterator type is AT_TIMESTAMP", ); + }; + if input.sequence_number.is_some() { + return refuse(SEQUENCE_NUMBER_REFUSED); + } + let now_ms = i64::try_from( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis(), + ) + .unwrap_or(i64::MAX); + if at_ms > now_ms.saturating_add(AT_TIMESTAMP_FUTURE_BUFFER_MS) { + return refuse("Timestamp parameter cannot be greater than the current timestamp"); } + Ok(Some(at_ms)) } - } else { - if input.timestamp.is_some() { - return refuse("Timestamp should not be passed for this iterator type"); + ShardIteratorType::AtSequenceNumber | ShardIteratorType::AfterSequenceNumber => { + if input.sequence_number.is_none() { + return refuse("SequenceNumber cannot be null"); + } + if input.timestamp.is_some() { + return refuse("Timestamp should not be passed for this iterator type"); + } + Ok(None) } - None - }; - - // Then SequenceNumber presence or absence for the type. - if takes_sequence { - if input.sequence_number.is_none() { - return refuse("SequenceNumber cannot be null"); + ShardIteratorType::TrimHorizon | ShardIteratorType::Latest => { + if input.timestamp.is_some() { + return refuse("Timestamp should not be passed for this iterator type"); + } + Ok(None) } - } else if input.sequence_number.is_some() { - return refuse("SequenceNumber should not be passed for this iterator type"); } +} - // Then the future check. - if let Some(at_ms) = at_ms { - let now_ms = i64::try_from( - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default() - .as_millis(), - ) - .unwrap_or(i64::MAX); - if at_ms > now_ms.saturating_add(AT_TIMESTAMP_FUTURE_BUFFER_MS) { - return refuse("Timestamp parameter cannot be greater than the current timestamp"); - } +/// `TRIM_HORIZON` and `LATEST` refuse a `SequenceNumber` only once the shard +/// exists: on a shard that does not, the service answers `Shard does not +/// exist` (measured 2026-11-20, us-east-1). +pub(crate) fn refuse_sequence_number_after_shard( + input: &GetShardIteratorInput, +) -> Result<(), DynamoDbError> { + if matches!( + input.shard_iterator_type, + ShardIteratorType::TrimHorizon | ShardIteratorType::Latest + ) && input.sequence_number.is_some() + { + return refuse(SEQUENCE_NUMBER_REFUSED); } - Ok(at_ms) + Ok(()) } -/// Epoch seconds with an optional fraction to whole milliseconds, floored. -/// Saturates at the `i64` edge; the caller has already refused values that -/// are not positive and finite. -pub(crate) fn timestamp_to_millis(secs: f64) -> i64 { - let ms = (secs * 1000.0).floor(); - if ms >= 9.2e18 { +/// Epoch seconds with an optional fraction to whole milliseconds, rounded +/// half up as the service does: for a record at millisecond ...389, +/// `...389.4900` returns it and `...389.5000` does not, and `0.0004` is +/// refused while `0.0005` is accepted (measured 2026-11-20, us-east-1). `None` +/// when the result is not at least one millisecond: zero, negative, NaN. The +/// `i64` edge saturates; the future check refuses it. +pub(crate) fn timestamp_to_millis(secs: f64) -> Option { + let ms = (secs * 1000.0).round(); + if ms.is_nan() || ms < 1.0 { + return None; + } + Some(if ms >= 9.2e18 { i64::MAX } else { - // Non-negative and in range after the guard above. + // Positive and in range after the guards above. #[allow(clippy::cast_possible_truncation)] let v = ms as i64; v - } + }) } /// Convert an AT_SEQUENCE_NUMBER position to the AFTER position the token @@ -161,33 +214,35 @@ mod tests { assert!(super::at_sequence_to_after("abc", 21).is_err()); } - /// Epoch seconds with a fraction floor to whole milliseconds, as the - /// service seeks at millisecond precision (measured: a `Timestamp` of - /// `.5` skipped records written at `.050`). + /// Epoch seconds round half up to whole milliseconds, as the service + /// does. Rows measured 2026-11-20 (us-east-1) on a record at ms ...389: + /// `.3894900` returned it, `.3894999` (whose double times 1000 is exactly + /// ...389.5) and `.3895000` did not, `.3885100` did. `0.0004` and + /// `0.00049` were refused, `0.0005` and `0.00051` accepted. A floor fails + /// the `.3894999` and `.3885100` rows. #[test] - fn timestamp_to_millis_floors_to_the_millisecond() { - assert_eq!( - super::timestamp_to_millis(1_792_764_248.0), - 1_792_764_248_000 - ); - assert_eq!( - super::timestamp_to_millis(1_792_764_248.05), - 1_792_764_248_050 - ); - assert_eq!( - super::timestamp_to_millis(1_792_764_248.999), - 1_792_764_248_999 - ); - assert_eq!( - super::timestamp_to_millis(1_792_764_248.123_456), - 1_792_764_248_123 - ); - // Floors, never rounds: .9996 ms stays at 123. - assert_eq!( - super::timestamp_to_millis(1_792_764_248.123_999_6), - 1_792_764_248_123 - ); - assert_eq!(super::timestamp_to_millis(1e18), i64::MAX); + fn timestamp_rounds_half_up_to_the_millisecond() { + let cases: &[(f64, Option)] = &[ + (1_795_171_973.389_49, Some(1_795_171_973_389)), + (1_795_171_973.389_499_9, Some(1_795_171_973_390)), + (1_795_171_973.389_5, Some(1_795_171_973_390)), + (1_795_171_973.388_51, Some(1_795_171_973_389)), + (1_792_764_248.0, Some(1_792_764_248_000)), + (1_792_764_248.123_456, Some(1_792_764_248_123)), + (0.0004, None), + (0.00049, None), + (0.0005, Some(1)), + (0.00051, Some(1)), + (0.0009, Some(1)), + (1.0005, Some(1_001)), + (0.0, None), + (-5.0, None), + (f64::NAN, None), + (1e18, Some(i64::MAX)), + ]; + for (secs, expected) in cases { + assert_eq!(super::timestamp_to_millis(*secs), *expected, "secs={secs}"); + } } fn input(t: ShardIteratorType, seq: Option<&str>, ts: Option) -> GetShardIteratorInput { @@ -209,107 +264,163 @@ mod tests { } } - /// Messages, their prefix, and the order of the checks, as measured on - /// the service 2026-10-23 (us-east-1). + const TS_REQUIRED: &str = + "Valid timestamp must be provided when the iterator type is AT_TIMESTAMP"; + const SEQ_REFUSED: &str = "SequenceNumber should not be passed for this iterator type"; + const TS_REFUSED: &str = "Timestamp should not be passed for this iterator type"; + const SEQ_NULL: &str = "SequenceNumber cannot be null"; + const FUTURE: &str = "Timestamp parameter cannot be greater than the current timestamp"; + + /// The pre-lookup rules, their prefix and their order per type, as + /// measured on the service 2026-10-23 and 2026-11-20 (us-east-1). `Err` + /// rows carry the sentence after the prefix; `Ok` rows the position. #[test] fn parameter_validation_matches_the_service_order_and_text() { use ShardIteratorType::{ AfterSequenceNumber, AtSequenceNumber, AtTimestamp, Latest, TrimHorizon, }; - const P: &str = "One or more parameter values were invalid: "; let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs_f64(); let past = 1_792_764_148.0; - let v = super::validate_iterator_parameters; - - // AT_TIMESTAMP needs a positive Timestamp; null, zero and negative all refuse. - for ts in [None, Some(0.0), Some(-1.0), Some(f64::NAN)] { - assert_eq!( - message(v(&input(AtTimestamp, None, ts))), - format!( - "{P}Valid timestamp must be provided when the iterator type is AT_TIMESTAMP" + let future = now + 3_600.0; + let cases: &[( + ShardIteratorType, + Option<&str>, + Option, + Result, &str>, + )] = &[ + // AT_TIMESTAMP: a valid Timestamp first; null, zero, 0.0004 and negative refuse. + (AtTimestamp, None, None, Err(TS_REQUIRED)), + (AtTimestamp, None, Some(0.0), Err(TS_REQUIRED)), + (AtTimestamp, None, Some(0.0004), Err(TS_REQUIRED)), + (AtTimestamp, None, Some(-1.0), Err(TS_REQUIRED)), + (AtTimestamp, None, Some(f64::NAN), Err(TS_REQUIRED)), + (AtTimestamp, Some("1"), None, Err(TS_REQUIRED)), + // Then no SequenceNumber, before the future check. + (AtTimestamp, Some("1"), Some(past), Err(SEQ_REFUSED)), + (AtTimestamp, Some("1"), Some(future), Err(SEQ_REFUSED)), + // Then the future check; a past Timestamp resolves to milliseconds. + (AtTimestamp, None, Some(future), Err(FUTURE)), + (AtTimestamp, None, Some(past), Ok(Some(1_792_764_148_000))), + (AtTimestamp, None, Some(0.0005), Ok(Some(1))), + // AT_/AFTER_SEQUENCE_NUMBER: a SequenceNumber first, then no Timestamp. + (AtSequenceNumber, None, None, Err(SEQ_NULL)), + (AtSequenceNumber, None, Some(past), Err(SEQ_NULL)), + (AfterSequenceNumber, None, None, Err(SEQ_NULL)), + (AfterSequenceNumber, None, Some(past), Err(SEQ_NULL)), + (AtSequenceNumber, Some("1"), Some(past), Err(TS_REFUSED)), + (AfterSequenceNumber, Some("1"), Some(past), Err(TS_REFUSED)), + (AtSequenceNumber, Some("1"), None, Ok(None)), + (AfterSequenceNumber, Some("1"), None, Ok(None)), + // TRIM_HORIZON and LATEST: no Timestamp; a SequenceNumber passes + // here and is refused after the shard check. + (TrimHorizon, None, Some(past), Err(TS_REFUSED)), + (Latest, None, Some(past), Err(TS_REFUSED)), + (TrimHorizon, Some("1"), Some(past), Err(TS_REFUSED)), + (Latest, Some("1"), Some(past), Err(TS_REFUSED)), + (TrimHorizon, Some("1"), None, Ok(None)), + (Latest, Some("1"), None, Ok(None)), + (TrimHorizon, None, None, Ok(None)), + (Latest, None, None, Ok(None)), + ]; + for (t, seq, ts, expected) in cases { + let got = super::validate_iterator_parameters(&input(*t, *seq, *ts)); + match expected { + Ok(pos) => assert_eq!(got.unwrap(), *pos, "type={t:?} seq={seq:?} ts={ts:?}"), + Err(sentence) => assert_eq!( + message(got), + format!("One or more parameter values were invalid: {sentence}"), + "type={t:?} seq={seq:?} ts={ts:?}" ), - "ts={ts:?}" - ); - } - // The Timestamp check runs before the SequenceNumber check. - assert_eq!( - message(v(&input(AtTimestamp, Some("1"), None))), - format!("{P}Valid timestamp must be provided when the iterator type is AT_TIMESTAMP") - ); - // SequenceNumber with AT_TIMESTAMP refuses, and does so before the future check. - for ts in [past, now + 3_600.0] { - assert_eq!( - message(v(&input(AtTimestamp, Some("1"), Some(ts)))), - format!("{P}SequenceNumber should not be passed for this iterator type") - ); - } - // Timestamp with any other type refuses, before the SequenceNumber check. - for t in [TrimHorizon, Latest, AtSequenceNumber, AfterSequenceNumber] { - for seq in [None, Some("1")] { - assert_eq!( - message(v(&input(t, seq, Some(past)))), - format!("{P}Timestamp should not be passed for this iterator type"), - "type={t:?} seq={seq:?}" - ); } } - // SequenceNumber rules for the four other types. + } + + /// Only TRIM_HORIZON and LATEST refuse a SequenceNumber after the shard + /// check; the other types never reach it with one to refuse. + #[test] + fn the_positional_types_refuse_a_sequence_number_after_the_shard_check() { + use ShardIteratorType::{AtSequenceNumber, AtTimestamp, Latest, TrimHorizon}; for t in [TrimHorizon, Latest] { + let got = super::refuse_sequence_number_after_shard(&input(t, Some("1"), None)); assert_eq!( - message(v(&input(t, Some("1"), None))), - format!("{P}SequenceNumber should not be passed for this iterator type") + message(got.map(|()| None)), + format!("One or more parameter values were invalid: {SEQ_REFUSED}") ); - assert_eq!(v(&input(t, None, None)).unwrap(), None); + assert!(super::refuse_sequence_number_after_shard(&input(t, None, None)).is_ok()); } - for t in [AtSequenceNumber, AfterSequenceNumber] { - assert_eq!( - message(v(&input(t, None, None))), - format!("{P}SequenceNumber cannot be null") - ); - assert_eq!(v(&input(t, Some("1"), None)).unwrap(), None); + for t in [AtTimestamp, AtSequenceNumber] { + assert!(super::refuse_sequence_number_after_shard(&input(t, Some("1"), None)).is_ok()); } - // A far-future Timestamp refuses; a past one resolves to milliseconds. - assert_eq!( - message(v(&input(AtTimestamp, None, Some(now + 3_600.0)))), - format!("{P}Timestamp parameter cannot be greater than the current timestamp") - ); - assert_eq!( - v(&input(AtTimestamp, None, Some(past))).unwrap(), - Some(1_792_764_148_000) - ); } - /// Malformed `Timestamp` JSON types render the service's deserializer - /// texts (measured); numbers and null pass to the parameter rules. + /// The deserializer texts for a member whose JSON type does not fit, + /// measured 2026-10-23 and 2026-11-20: SequenceNumber is checked before + /// Timestamp (the model order), an array has no message, and null or a + /// fitting type passes to the parameter rules. #[test] - fn timestamp_shape_texts_match_the_service() { - use serde_json::json; - let msg = - |v: serde_json::Value| match super::check_timestamp_shape(&json!({"Timestamp": v})) { - Err(DynamoDbError::SerializationException(m)) => m, - other => panic!("expected SerializationException, got {other:?}"), - }; - assert_eq!( - msg(json!("1792764248.5")), - "STRING_VALUE cannot be converted to Date" - ); - assert_eq!(msg(json!("")), "STRING_VALUE cannot be converted to Date"); - assert_eq!(msg(json!(true)), "TRUE_VALUE cannot be converted to Date"); - assert_eq!(msg(json!(false)), "FALSE_VALUE cannot be converted to Date"); - assert_eq!( - msg(json!({"S": "x"})), - "Start of structure or map found where not expected" - ); - assert_eq!( - msg(json!([1])), - "Start of structure or map found where not expected" - ); - assert!(super::check_timestamp_shape(&json!({"Timestamp": 1.5})).is_ok()); - assert!(super::check_timestamp_shape(&json!({"Timestamp": null})).is_ok()); - assert!(super::check_timestamp_shape(&json!({})).is_ok()); + fn member_shape_texts_match_the_service() { + use serde_json::{Value, json}; + let cases: &[(Value, Option<&str>)] = &[ + ( + json!({"Timestamp": "1792764248.5"}), + Some("STRING_VALUE cannot be converted to Date"), + ), + ( + json!({"Timestamp": ""}), + Some("STRING_VALUE cannot be converted to Date"), + ), + ( + json!({"Timestamp": true}), + Some("TRUE_VALUE cannot be converted to Date"), + ), + ( + json!({"Timestamp": false}), + Some("FALSE_VALUE cannot be converted to Date"), + ), + ( + json!({"Timestamp": {"S": "x"}}), + Some("Start of structure or map found where not expected"), + ), + (json!({"Timestamp": []}), Some("")), + (json!({"Timestamp": [1]}), Some("")), + ( + json!({"SequenceNumber": 5}), + Some("NUMBER_VALUE cannot be converted to String"), + ), + ( + json!({"SequenceNumber": true}), + Some("TRUE_VALUE cannot be converted to String"), + ), + (json!({"SequenceNumber": []}), Some("")), + ( + json!({"SequenceNumber": {}}), + Some("Start of structure or map found where not expected"), + ), + ( + json!({"SequenceNumber": 5, "Timestamp": "x"}), + Some("NUMBER_VALUE cannot be converted to String"), + ), + ( + json!({"ShardIteratorType": "BOGUS", "Timestamp": "x"}), + Some("STRING_VALUE cannot be converted to Date"), + ), + (json!({"Timestamp": 1.5}), None), + (json!({"Timestamp": null, "SequenceNumber": null}), None), + (json!({"SequenceNumber": "1"}), None), + (json!({}), None), + ]; + for (body, expected) in cases { + match (super::check_member_shapes(body), expected) { + (Ok(()), None) => {} + (Err(DynamoDbError::SerializationException(m)), Some(e)) => { + assert_eq!(m, *e, "body={body}"); + } + (got, _) => panic!("body={body}: expected {expected:?}, got {got:?}"), + } + } } /// The future buffer is about one second: now + 0.5 s is accepted, now + diff --git a/crates/engine/src/streams_tests.rs b/crates/engine/src/streams_tests.rs index ef07dde79..b987bc6b3 100644 --- a/crates/engine/src/streams_tests.rs +++ b/crates/engine/src/streams_tests.rs @@ -108,6 +108,75 @@ fn the_shard_id_maximum_applies_once_the_shard_is_not_found() { } } +/// Every constraint violation of a body joins one message, in the service's +/// order (measured 2026-11-20): sequenceNumber, shardIteratorType, shardId. +#[test] +fn constraint_violations_join_one_message_in_the_service_order() { + use serde_json::json; + const SEQ: &str = "Value at 'sequenceNumber' failed to satisfy constraint: Member must have length greater than or equal to 21"; + const NULL: &str = + "Value at 'shardIteratorType' failed to satisfy constraint: Member must not be null"; + const SHARD: &str = "Value at 'shardId' failed to satisfy constraint: Member must have length greater than or equal to 28"; + let long = "shardId-00000001792764241200-b719fef1"; + let cases: &[(serde_json::Value, Option)] = &[ + ( + json!({"ShardId": "shardId-short"}), + Some(format!("2 validation errors detected: {NULL}; {SHARD}")), + ), + ( + json!({"ShardId": "shardId-short", "ShardIteratorType": null}), + Some(format!("2 validation errors detected: {NULL}; {SHARD}")), + ), + ( + json!({"ShardId": "shardId-short", "ShardIteratorType": "BOGUS"}), + Some(format!( + "2 validation errors detected: {}; {SHARD}", + super::iterator_params::SHARD_ITERATOR_TYPE_ENUM_CLAUSE + )), + ), + ( + json!({"ShardId": long, "SequenceNumber": "0"}), + Some(format!("2 validation errors detected: {SEQ}; {NULL}")), + ), + ( + json!({"ShardId": "shardId-short", "SequenceNumber": "0"}), + Some(format!( + "3 validation errors detected: {SEQ}; {NULL}; {SHARD}" + )), + ), + ( + json!({"ShardId": long, "Timestamp": 1792764248.0}), + Some(format!("1 validation error detected: {NULL}")), + ), + ( + json!({"ShardId": long, "ShardIteratorType": "at_timestamp"}), + Some(format!( + "1 validation error detected: {}", + super::iterator_params::SHARD_ITERATOR_TYPE_ENUM_CLAUSE + )), + ), + ( + json!({"ShardId": "shardId-short", "ShardIteratorType": "TRIM_HORIZON"}), + Some(super::SHARD_ID_TOO_SHORT.to_owned()), + ), + ( + json!({"ShardId": long, "ShardIteratorType": "AT_TIMESTAMP", "SequenceNumber": "000000000000000000001"}), + None, + ), + // A ShardIteratorType of another JSON type is the deserializer's case. + (json!({"ShardId": long, "ShardIteratorType": 5}), None), + ]; + for (body, expected) in cases { + match (super::constraint_violations(body), expected) { + (Ok(()), None) => {} + (Err(super::DynamoDbError::ValidationException(m)), Some(e)) => { + assert_eq!(&m, e, "body={body}"); + } + (got, _) => panic!("body={body}: expected {expected:?}, got {got:?}"), + } + } +} + #[test] fn the_constraint_sentences_match_the_measured_ones() { assert_eq!( From 73d45e8cc794994145ddd04f9b46838371ae4e45 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:36:36 +0000 Subject: [PATCH 04/14] fix(storage-cassandra): run the AT_TIMESTAMP seek through the policy session Main now sends every Cassandra statement through PolicySession::run (#945), and tests/consistency_policy.rs fails on the seek's query_with_values call. The seek now calls query_rows, as last_sequence_in does, so it reads at LOCAL_QUORUM like the tip read. The two AT_TIMESTAMP tests move from tests/direct/streams.rs to tests/direct/stream_at_timestamp.rs unchanged. streams.rs is back at its length on main. --- .../src/stream_at_timestamp.rs | 19 +- .../tests/direct/stream_at_timestamp.rs | 206 ++++++++++++++++++ .../storage-cassandra/tests/direct/streams.rs | 194 +---------------- .../tests/direct_integration.rs | 2 + 4 files changed, 218 insertions(+), 203 deletions(-) create mode 100644 crates/storage-cassandra/tests/direct/stream_at_timestamp.rs diff --git a/crates/storage-cassandra/src/stream_at_timestamp.rs b/crates/storage-cassandra/src/stream_at_timestamp.rs index c07ea7d0b..68a8ee2e3 100644 --- a/crates/storage-cassandra/src/stream_at_timestamp.rs +++ b/crates/storage-cassandra/src/stream_at_timestamp.rs @@ -19,6 +19,7 @@ use cdrs_tokio::types::IntoRustByName; use extenddb_storage::error::StorageError; +use crate::cassandra_util::query_rows; use crate::engine::CassandraEngine; /// The smallest sequence number whose millisecond prefix is `at_ms`. @@ -72,16 +73,14 @@ impl CassandraEngine { } None => cdrs_tokio::query_values!(range.physical.as_str(), lower, at_ms), }; - let result = self - .session - .query_with_values(&query, values) - .await - .map_err(|e| StorageError::Internal(e.to_string()))?; - let rows = result - .response_body() - .map_err(|e| StorageError::Internal(e.to_string()))? - .into_rows() - .unwrap_or_default(); + // The same read as `last_sequence_in`: `Stmt::Read`, LOCAL_QUORUM. + let rows = query_rows::( + &self.session, + &query, + values, + "first_sequence_number_at_or_after", + ) + .await?; Ok(rows .into_iter() .next() diff --git a/crates/storage-cassandra/tests/direct/stream_at_timestamp.rs b/crates/storage-cassandra/tests/direct/stream_at_timestamp.rs new file mode 100644 index 000000000..7595505cf --- /dev/null +++ b/crates/storage-cassandra/tests/direct/stream_at_timestamp.rs @@ -0,0 +1,206 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Direct integration tests for the `AT_TIMESTAMP` seek +//! (`first_sequence_number_at_or_after`) on the Cassandra engine. + +use std::collections::BTreeMap; + +use cdrs_tokio::types::IntoRustByName; +use extenddb_core::types::{AttributeValue, StreamViewType}; +use extenddb_storage::DataEngine; + +use crate::helpers::setup_engine; +use crate::streams::{capture, setup_stream_table, shard_for, stream_shard_for}; + +/// A record written under a clamped clock (after a backwards step) carries a +/// sequence prefix later than its `created_at`. The `AT_TIMESTAMP` seek must +/// not return it for a `T` after its `created_at`, and must still return a +/// record created at or after `T`. +#[tokio::test] +async fn test_at_timestamp_seek_skips_a_clamped_record_older_than_t() { + use extenddb_storage::StreamEngine; + + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let (key_info, label) = setup_stream_table(&engine, "StreamClampSeek").await; + let view = StreamViewType::NewAndOldImages; + + let mut item = BTreeMap::new(); + item.insert("id".to_string(), AttributeValue::S("pk-clamp".to_string())); + item.insert("val".to_string(), AttributeValue::S("real".to_string())); + engine + .put_item( + &key_info, + item, + false, + None, + &Default::default(), + Some(&capture(view)), + ) + .await + .unwrap(); + + // The records sit in the partition `shard_for` names; the seek takes the + // stream's shard id, as a client does. + let partition = shard_for("pk-clamp", &key_info.table_id); + let shard_id = stream_shard_for("pk-clamp", &key_info.table_id, &label, view); + let keyspace = format!("extenddb_ttl_test_account_{}", key_info.account_id); + let rows = engine + .session_arc() + .query_with_values( + &format!( + "SELECT sequence_number, created_at, record_data FROM {keyspace}.stream_records \ + WHERE shard_id = ?" + ), + cdrs_tokio::query_values!(partition.as_str()), + ) + .await + .unwrap() + .response_body() + .unwrap() + .into_rows() + .unwrap_or_default(); + assert_eq!(rows.len(), 1); + let real_seq: String = rows[0].get_r_by_name("sequence_number").unwrap(); + let real_created: i64 = rows[0].get_r_by_name("created_at").unwrap(); + let data: String = rows[0].get_r_by_name("record_data").unwrap(); + + // Model the clamped record: sequence prefix 8 s after the real record, + // created_at 8 s before it. T sits between the two: after the clamped + // created_at, before the real record's. + let clamped_hlc = real_created + 8_000; + let clamped_created = real_created - 8_000; + let clamped_seq = format!("{clamped_hlc:013}{:06}{:04}", 0, 9999); + engine + .session_arc() + .query_with_values( + &format!( + "INSERT INTO {keyspace}.stream_records \ + (shard_id, sequence_number, table_id, event_name, record_data, created_at) \ + VALUES (?, ?, ?, 'Insert', ?, ?)" + ), + cdrs_tokio::query_values!( + partition.as_str(), + clamped_seq.as_str(), + key_info.table_id.as_str(), + data.as_str(), + clamped_created + ), + ) + .await + .unwrap(); + + // T after the clamped created_at and before the real record: the real + // record qualifies, the clamped one does not. + let t = real_created - 1_000; + let got = engine + .first_sequence_number_at_or_after(&shard_id, t) + .await + .unwrap(); + assert_eq!( + got.as_deref(), + Some(real_seq.as_str()), + "the real record is first at or after T" + ); + + // T after every created_at: nothing qualifies, even though the clamped + // sequence prefix clears the bound. + let t = real_created + 1_000; + let got = engine + .first_sequence_number_at_or_after(&shard_id, t) + .await + .unwrap(); + assert_eq!(got, None, "a clamped record older than T is not returned"); + + // T before everything: the clamped record is the first, as its + // created_at is the oldest. + let got = engine + .first_sequence_number_at_or_after(&shard_id, clamped_created - 1) + .await + .unwrap(); + assert!(got.is_some()); +} + +/// Every stream of a table keeps its records in the partition of the shard +/// index, and the seek reads only the shard's own range of it. A closed shard +/// answers nothing for a time after its close, even once the next stream has +/// written to the same partition; the next stream's shard does not answer the +/// record of the stream before it. +#[tokio::test] +async fn test_at_timestamp_seek_reads_only_the_shards_range() { + use crate::stream_disable::{activate, put, set_stream}; + use extenddb_storage::StreamEngine; + use extenddb_storage_cassandra::cassandra_util::now_millis; + + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = setup_engine().await; + let name = "StreamSeekRange"; + let (key_info, old_label) = setup_stream_table(&engine, name).await; + activate(&engine).await; + let account = key_info.account_id.as_str(); + let view = StreamViewType::NewAndOldImages; + + let start = now_millis() - 1_000; + put(&engine, account, name, "pk-range", view).await; + let old_shard = stream_shard_for("pk-range", &key_info.table_id, &old_label, view); + let old_seq = engine + .first_sequence_number_at_or_after(&old_shard, start) + .await + .unwrap() + .expect("the first stream's record"); + + set_stream( + &engine, + account, + name, + serde_json::json!({"StreamEnabled": false}), + ) + .await + .unwrap(); + let after_close = now_millis(); + let enabled = set_stream( + &engine, + account, + name, + serde_json::json!({"StreamEnabled": true, "StreamViewType": "NEW_AND_OLD_IMAGES"}), + ) + .await + .unwrap(); + let new_label = enabled.latest_stream_label.expect("the new stream's label"); + put(&engine, account, name, "pk-range", view).await; + let new_shard = stream_shard_for("pk-range", &key_info.table_id, &new_label, view); + + // The closed shard keeps its record and ends at it, so the new stream's + // record in the same partition is not its answer after the close. + assert_eq!( + engine + .first_sequence_number_at_or_after(&old_shard, start) + .await + .unwrap(), + Some(old_seq.clone()) + ); + assert_eq!( + engine + .first_sequence_number_at_or_after(&old_shard, after_close) + .await + .unwrap(), + None + ); + // The new stream's shard starts after the enable: for a time before the + // first stream's record, its answer is its own record. + let new_seq = engine + .first_sequence_number_at_or_after(&new_shard, start) + .await + .unwrap() + .expect("the new stream's record"); + assert_ne!(new_seq, old_seq); + assert_eq!( + engine.latest_sequence_number(&new_shard).await.unwrap(), + Some(new_seq) + ); +} diff --git a/crates/storage-cassandra/tests/direct/streams.rs b/crates/storage-cassandra/tests/direct/streams.rs index 81098a107..a604fadda 100644 --- a/crates/storage-cassandra/tests/direct/streams.rs +++ b/crates/storage-cassandra/tests/direct/streams.rs @@ -13,7 +13,7 @@ use extenddb_storage_cassandra::CassandraEngine; use crate::helpers::{TestTable, setup_engine}; -fn capture(view_type: StreamViewType) -> StreamCapture { +pub(crate) fn capture(view_type: StreamViewType) -> StreamCapture { StreamCapture { view_type, user_identity: None, @@ -777,195 +777,3 @@ async fn test_stream_record_created_at_matches_the_record_and_sequence() { ); } } - -/// A record written under a clamped clock (after a backwards step) carries a -/// sequence prefix later than its `created_at`. The `AT_TIMESTAMP` seek must -/// not return it for a `T` after its `created_at`, and must still return a -/// record created at or after `T`. -#[tokio::test] -async fn test_at_timestamp_seek_skips_a_clamped_record_older_than_t() { - use extenddb_storage::StreamEngine; - - if crate::helpers::skip_without_cassandra() { - return; - } - let engine = setup_engine().await; - let (key_info, label) = setup_stream_table(&engine, "StreamClampSeek").await; - let view = StreamViewType::NewAndOldImages; - - let mut item = BTreeMap::new(); - item.insert("id".to_string(), AttributeValue::S("pk-clamp".to_string())); - item.insert("val".to_string(), AttributeValue::S("real".to_string())); - engine - .put_item( - &key_info, - item, - false, - None, - &Default::default(), - Some(&capture(view)), - ) - .await - .unwrap(); - - // The records sit in the partition `shard_for` names; the seek takes the - // stream's shard id, as a client does. - let partition = shard_for("pk-clamp", &key_info.table_id); - let shard_id = stream_shard_for("pk-clamp", &key_info.table_id, &label, view); - let keyspace = format!("extenddb_ttl_test_account_{}", key_info.account_id); - let rows = engine - .session_arc() - .query_with_values( - &format!( - "SELECT sequence_number, created_at, record_data FROM {keyspace}.stream_records \ - WHERE shard_id = ?" - ), - cdrs_tokio::query_values!(partition.as_str()), - ) - .await - .unwrap() - .response_body() - .unwrap() - .into_rows() - .unwrap_or_default(); - assert_eq!(rows.len(), 1); - let real_seq: String = rows[0].get_r_by_name("sequence_number").unwrap(); - let real_created: i64 = rows[0].get_r_by_name("created_at").unwrap(); - let data: String = rows[0].get_r_by_name("record_data").unwrap(); - - // Model the clamped record: sequence prefix 8 s after the real record, - // created_at 8 s before it. T sits between the two: after the clamped - // created_at, before the real record's. - let clamped_hlc = real_created + 8_000; - let clamped_created = real_created - 8_000; - let clamped_seq = format!("{clamped_hlc:013}{:06}{:04}", 0, 9999); - engine - .session_arc() - .query_with_values( - &format!( - "INSERT INTO {keyspace}.stream_records \ - (shard_id, sequence_number, table_id, event_name, record_data, created_at) \ - VALUES (?, ?, ?, 'Insert', ?, ?)" - ), - cdrs_tokio::query_values!( - partition.as_str(), - clamped_seq.as_str(), - key_info.table_id.as_str(), - data.as_str(), - clamped_created - ), - ) - .await - .unwrap(); - - // T after the clamped created_at and before the real record: the real - // record qualifies, the clamped one does not. - let t = real_created - 1_000; - let got = engine - .first_sequence_number_at_or_after(&shard_id, t) - .await - .unwrap(); - assert_eq!( - got.as_deref(), - Some(real_seq.as_str()), - "the real record is first at or after T" - ); - - // T after every created_at: nothing qualifies, even though the clamped - // sequence prefix clears the bound. - let t = real_created + 1_000; - let got = engine - .first_sequence_number_at_or_after(&shard_id, t) - .await - .unwrap(); - assert_eq!(got, None, "a clamped record older than T is not returned"); - - // T before everything: the clamped record is the first, as its - // created_at is the oldest. - let got = engine - .first_sequence_number_at_or_after(&shard_id, clamped_created - 1) - .await - .unwrap(); - assert!(got.is_some()); -} - -/// Every stream of a table keeps its records in the partition of the shard -/// index, and the seek reads only the shard's own range of it. A closed shard -/// answers nothing for a time after its close, even once the next stream has -/// written to the same partition; the next stream's shard does not answer the -/// record of the stream before it. -#[tokio::test] -async fn test_at_timestamp_seek_reads_only_the_shards_range() { - use crate::stream_disable::{activate, put, set_stream}; - use extenddb_storage::StreamEngine; - use extenddb_storage_cassandra::cassandra_util::now_millis; - - if crate::helpers::skip_without_cassandra() { - return; - } - let engine = setup_engine().await; - let name = "StreamSeekRange"; - let (key_info, old_label) = setup_stream_table(&engine, name).await; - activate(&engine).await; - let account = key_info.account_id.as_str(); - let view = StreamViewType::NewAndOldImages; - - let start = now_millis() - 1_000; - put(&engine, account, name, "pk-range", view).await; - let old_shard = stream_shard_for("pk-range", &key_info.table_id, &old_label, view); - let old_seq = engine - .first_sequence_number_at_or_after(&old_shard, start) - .await - .unwrap() - .expect("the first stream's record"); - - set_stream( - &engine, - account, - name, - serde_json::json!({"StreamEnabled": false}), - ) - .await - .unwrap(); - let after_close = now_millis(); - let enabled = set_stream( - &engine, - account, - name, - serde_json::json!({"StreamEnabled": true, "StreamViewType": "NEW_AND_OLD_IMAGES"}), - ) - .await - .unwrap(); - let new_label = enabled.latest_stream_label.expect("the new stream's label"); - put(&engine, account, name, "pk-range", view).await; - let new_shard = stream_shard_for("pk-range", &key_info.table_id, &new_label, view); - - // The closed shard keeps its record and ends at it, so the new stream's - // record in the same partition is not its answer after the close. - assert_eq!( - engine - .first_sequence_number_at_or_after(&old_shard, start) - .await - .unwrap(), - Some(old_seq.clone()) - ); - assert_eq!( - engine - .first_sequence_number_at_or_after(&old_shard, after_close) - .await - .unwrap(), - None - ); - // The new stream's shard starts after the enable: for a time before the - // first stream's record, its answer is its own record. - let new_seq = engine - .first_sequence_number_at_or_after(&new_shard, start) - .await - .unwrap() - .expect("the new stream's record"); - assert_ne!(new_seq, old_seq); - assert_eq!( - engine.latest_sequence_number(&new_shard).await.unwrap(), - Some(new_seq) - ); -} diff --git a/crates/storage-cassandra/tests/direct_integration.rs b/crates/storage-cassandra/tests/direct_integration.rs index 1971d1317..1a7efefab 100644 --- a/crates/storage-cassandra/tests/direct_integration.rs +++ b/crates/storage-cassandra/tests/direct_integration.rs @@ -70,6 +70,8 @@ mod secret_rows; mod settings_store; #[path = "direct/snapshot_engine.rs"] mod snapshot_engine; +#[path = "direct/stream_at_timestamp.rs"] +mod stream_at_timestamp; #[path = "direct/stream_disable.rs"] mod stream_disable; #[path = "direct/stream_endings.rs"] From 716aa4e1756e50cbdd9959c7c3a9fbeaaa273524 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:36:36 +0000 Subject: [PATCH 05/14] test(streams): pin the AT_TIMESTAMP boundary to the record's millisecond The wire test bisects the record's second and asserted only that one millisecond returns the record and the next does not. A seek with a strict comparison, or a store that keeps whole seconds, passes that. The test now writes mid-second, keeps the write's wall-clock window, and checks that the bisected millisecond lies in that window. It also seeks a fraction before the window, which returns the record, and one after it, which does not. The strict comparison moves the boundary by one millisecond inside the window. The wire carries creation time in whole seconds. So a wire test cannot tell the two comparisons apart on every run. The SQLite stream tests get a seek over records with known created_at values: a record's own millisecond returns it and the next one does not. The wire test file is dual-target now. Without EXTENDDB_TEST_ENDPOINT the streams client and the raw requests go to the region's Streams endpoint. The matrix gains the rows of this review round: - The service refuses a Timestamp of 0.0004 and accepts 0.0005. - AT_SEQUENCE_NUMBER refuses a missing SequenceNumber before a Timestamp. - TRIM_HORIZON and LATEST answer a missing shard before a SequenceNumber. - The constraint violations join one message. - An ill-typed member is a SerializationException before the enum check. --- crates/engine/src/streams.rs | 4 - crates/engine/src/streams_tests.rs | 6 +- crates/storage-sqlite/src/stream_tests.rs | 54 +++++++ tests/test_streams_at_timestamp.py | 176 +++++++++++++++------- 4 files changed, 182 insertions(+), 58 deletions(-) diff --git a/crates/engine/src/streams.rs b/crates/engine/src/streams.rs index 51a02296b..171ca8f6f 100755 --- a/crates/engine/src/streams.rs +++ b/crates/engine/src/streams.rs @@ -293,10 +293,6 @@ fn clause(member: &str, rule: &str) -> String { format!("Value at '{member}' failed to satisfy constraint: Member must {rule}") } -/// `GetShardIterator` with a `ShardId` under 28 characters (measured 2026-10-24 -/// with `nope`); the same shape `constraint` renders. -pub const SHARD_ID_TOO_SHORT: &str = "1 validation error detected: Value at 'shardId' failed to satisfy constraint: Member must have length greater than or equal to 28"; - /// The message `DynamoDB` returns for an expired shard iterator (measured live, /// `live-r2/iter-live.json`: an iterator 990 seconds old returns /// `ExpiredIteratorException` with exactly this text). Shared so the diff --git a/crates/engine/src/streams_tests.rs b/crates/engine/src/streams_tests.rs index b987bc6b3..f7a56dd6d 100644 --- a/crates/engine/src/streams_tests.rs +++ b/crates/engine/src/streams_tests.rs @@ -157,7 +157,7 @@ fn constraint_violations_join_one_message_in_the_service_order() { ), ( json!({"ShardId": "shardId-short", "ShardIteratorType": "TRIM_HORIZON"}), - Some(super::SHARD_ID_TOO_SHORT.to_owned()), + Some(format!("1 validation error detected: {SHARD}")), ), ( json!({"ShardId": long, "ShardIteratorType": "AT_TIMESTAMP", "SequenceNumber": "000000000000000000001"}), @@ -179,9 +179,11 @@ fn constraint_violations_join_one_message_in_the_service_order() { #[test] fn the_constraint_sentences_match_the_measured_ones() { + // `GetShardIterator` with a `ShardId` under 28 characters (measured + // 2026-10-24 with `nope`). assert_eq!( super::constraint("shardId", "have length greater than or equal to 28"), - super::SHARD_ID_TOO_SHORT + "1 validation error detected: Value at 'shardId' failed to satisfy constraint: Member must have length greater than or equal to 28" ); assert_eq!( super::constraint("limit", "have value greater than or equal to 1"), diff --git a/crates/storage-sqlite/src/stream_tests.rs b/crates/storage-sqlite/src/stream_tests.rs index 3630e48e7..64e9cb226 100644 --- a/crates/storage-sqlite/src/stream_tests.rs +++ b/crates/storage-sqlite/src/stream_tests.rs @@ -462,3 +462,57 @@ async fn the_newer_arn_with_a_legacy_shard_of_the_closed_stream_is_not_found() { .expect("the new stream reads under its own ARN"); assert_eq!(records.len(), 1); } + +/// A record with the `created_at` the write path stores: the clock read in +/// milliseconds, in the column's fixed-width shape. +async fn write_record_at(engine: &SqliteEngine, shard_id: &str, table_id: &str, seq: u64, ms: i64) { + sqlx::query( + "INSERT INTO stream_records (sequence_number, shard_id, table_id, event_name, \ + record_data, created_at) VALUES (?, ?, ?, 'Insert', ?, ?)", + ) + .bind(format!("{seq:021}")) + .bind(shard_id) + .bind(table_id) + .bind(record_json(seq)) + .bind(crate::sqlite_util::format_epoch_millis(ms)) + .execute(&engine.pool) + .await + .expect("record"); +} + +/// The `AT_TIMESTAMP` seek answers the first record created at or after the +/// millisecond asked for: a record's own millisecond returns it, the next one +/// does not, and another shard's records do not count. +#[tokio::test] +async fn at_timestamp_seek_is_at_or_after_the_records_millisecond() { + let engine = engine().await; + let table_id = stream_table(&engine, ACCOUNT, "t", "2026-01-01T00:00:00.000").await; + let own = shard(&table_id, 0); + let other = shard(&table_id, 1); + let base = 1_700_000_000_250; + write_record_at(&engine, &own, &table_id, 5, base).await; + write_record_at(&engine, &own, &table_id, 6, base + 1).await; + write_record_at(&engine, &own, &table_id, 7, base + 750).await; + write_record_at(&engine, &other, &table_id, 8, base - 1_000).await; + + let cases: &[(i64, Option)] = &[ + (0, Some(5)), + (base - 1, Some(5)), + (base, Some(5)), + (base + 1, Some(6)), + (base + 2, Some(7)), + (base + 750, Some(7)), + (base + 751, None), + ]; + for (at_ms, expected) in cases { + let got = engine + .first_sequence_number_at_or_after(&own, *at_ms) + .await + .expect("seek"); + assert_eq!( + got, + expected.map(|seq| format!("{seq:021}")), + "at_ms={at_ms}" + ); + } +} diff --git a/tests/test_streams_at_timestamp.py b/tests/test_streams_at_timestamp.py index 10811b02f..fa7cc1893 100644 --- a/tests/test_streams_at_timestamp.py +++ b/tests/test_streams_at_timestamp.py @@ -4,13 +4,13 @@ """DynamoDB Streams AT_TIMESTAMP shard iterator. Every expected value here was measured on the service (us-east-1, -2026-10-23): positioning at millisecond precision, the four validation -messages and their order, the future buffer, and the error classes for -malformed Timestamp values. +2026-10-23 and 2026-11-20): positioning at millisecond precision with the +Timestamp rounded half up, the validation messages and their order, the +future buffer, and the error classes for malformed member values. -These tests require a running extenddb server (EXTENDDB_TEST_ENDPOINT must be -set) because the service routes Streams to a separate endpoint; extenddb -serves both on the same endpoint. +Dual-target: with EXTENDDB_TEST_ENDPOINT set, both clients use that endpoint; +without it, the streams client and the raw requests go to the service's +Streams endpoint of the region. """ from __future__ import annotations @@ -30,20 +30,19 @@ PREFIX = "One or more parameter values were invalid: " -@pytest.fixture(scope="module") -def endpoint_url() -> str: - return os.environ["EXTENDDB_TEST_ENDPOINT"].strip() +REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") -def _client(service: str, endpoint_url: str, validate: bool = True): +def _client(service: str, endpoint_url: str | None, validate: bool = True): kwargs: dict = dict( service_name=service, - region_name=os.environ.get("AWS_DEFAULT_REGION", "us-east-1"), - endpoint_url=endpoint_url, + region_name=REGION, config=Config(parameter_validation=validate, retries={"max_attempts": 1}), ) - if endpoint_url.startswith("https://"): - kwargs["verify"] = False + if endpoint_url: + kwargs["endpoint_url"] = endpoint_url + if endpoint_url.startswith("https://"): + kwargs["verify"] = False return boto3.client(**kwargs) @@ -136,28 +135,30 @@ def _error(fn, **kw) -> tuple[str, str]: raise AssertionError("expected a ClientError") -def _raw_error(endpoint_url: str, body: dict) -> tuple[str, str]: +def _raw_error(endpoint_url: str | None, body: dict) -> tuple[str, str]: """POST a GetShardIterator body exactly as given, SigV4-signed with the - test user's key from the environment, for shapes the SDK cannot - serialise (JSON null, an object). Returns (code, message).""" + session's credentials, for shapes the SDK cannot serialise (JSON null, an + object, a member of the wrong type). Returns (code, message); the message + is "" when the answer carries none.""" import ssl import urllib.request from botocore.auth import SigV4Auth from botocore.awsrequest import AWSRequest - from botocore.credentials import Credentials + url = endpoint_url or f"https://streams.dynamodb.{REGION}.amazonaws.com/" data = json.dumps(body).encode() - req = AWSRequest(method="POST", url=endpoint_url, data=data, headers={ + req = AWSRequest(method="POST", url=url, data=data, headers={ "Content-Type": "application/x-amz-json-1.0", "X-Amz-Target": "DynamoDBStreams_20120810.GetShardIterator", }) - signer_creds = Credentials(os.environ["AWS_ACCESS_KEY_ID"], os.environ["AWS_SECRET_ACCESS_KEY"]) - SigV4Auth(signer_creds, "dynamodb", os.environ.get("AWS_DEFAULT_REGION", "us-east-1")).add_auth(req) + creds = boto3.Session().get_credentials().get_frozen_credentials() + SigV4Auth(creds, "dynamodb", REGION).add_auth(req) prepped = req.prepare() ctx = ssl.create_default_context() - ctx.check_hostname = False - ctx.verify_mode = ssl.CERT_NONE + if endpoint_url: + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE hr = urllib.request.Request(prepped.url, data=data, headers=dict(prepped.headers), method="POST") try: with urllib.request.urlopen(hr, timeout=30, context=ctx) as r: @@ -208,19 +209,30 @@ def ts(secs: float): for r in recs: assert r["dynamodb"]["ApproximateCreationDateTime"].microsecond == 0 - def test_boundary_is_at_or_after_the_record_millisecond(self, dynamodb_client, streams_client, stream_table): + def test_boundary_is_at_or_after_the_record_millisecond(self, dynamodb_client, streams_client, raw_streams_client, stream_table): """T equal to a record's own creation millisecond returns that record - (the service's at-or-after); one millisecond later does not.""" + (the service's at-or-after); one millisecond later does not. The + record's millisecond lies in the write's wall-clock window, so a + store that keeps whole seconds fails here: the write lands mid-second.""" table, arn = stream_table + now = time.time() + time.sleep((1.3 - (now % 1.0)) % 1.0) + start = time.time() dynamodb_client.put_item(TableName=table, Item={"pk": {"S": "k"}, "v": {"S": "only"}}) + end = time.time() + assert 0.25 < start % 1.0 < 0.75, f"the write did not land mid-second ({start:.3f})" shard = _shard_with_records(streams_client, arn) it = streams_client.get_shard_iterator(StreamArn=arn, ShardId=shard, ShardIteratorType="TRIM_HORIZON")["ShardIterator"] rec = _drain(streams_client, it)[0] second = int(rec["dynamodb"]["ApproximateCreationDateTime"].timestamp()) + assert second == int(start), "ApproximateCreationDateTime is the write's second" def returns_it(ms: int) -> bool: - t = datetime.fromtimestamp(second + ms / 1000.0, tz=timezone.utc) - return _values(_at(streams_client, arn, shard, t)) == ["only"] + # A raw number, so the fraction reaches the server as written. + resp = raw_streams_client.get_shard_iterator( + StreamArn=arn, ShardId=shard, ShardIteratorType="AT_TIMESTAMP", Timestamp=second + ms / 1000.0 + ) + return _values(_drain(streams_client, resp["ShardIterator"])) == ["only"] # Bisect within the record's second for the last millisecond that # still returns it: that is the record's own creation millisecond. @@ -234,6 +246,13 @@ def returns_it(ms: int) -> bool: hi = mid assert returns_it(lo), "T at the record's millisecond returns it" assert not returns_it(lo + 1), "T one millisecond later does not" + # The record's millisecond is inside the write's window (50 ms of + # clock skew allowed). A seek at a fraction before the window returns + # the record, one past the window does not. + window = (int(start * 1000) - second * 1000, int(end * 1000) - second * 1000) + assert window[0] - 50 <= lo <= window[1] + 50, f"record ms {lo} outside the write window {window}" + assert returns_it(window[0] - 50) + assert not returns_it(window[1] + 51) def test_after_tip_returns_only_later_writes(self, dynamodb_client, streams_client, stream_table): table, arn = stream_table @@ -255,18 +274,20 @@ def test_integer_and_fractional_numbers_are_accepted(self, dynamodb_client, stre table, arn = stream_table g = _write_group(dynamodb_client, table, "g", 2) shard = _shard_with_records(streams_client, arn) - for ts in (int(g[0]), round(g[0], 3), g[0] + 0.123456): + for ts in (int(g[0]), round(g[0], 3), g[0] + 0.123456, 0.0005, 0.00051): resp = raw_streams_client.get_shard_iterator( StreamArn=arn, ShardId=shard, ShardIteratorType="AT_TIMESTAMP", Timestamp=ts ) assert "ShardIterator" in resp, ts def test_zero_negative_and_null_refuse(self, dynamodb_client, streams_client, raw_streams_client, stream_table, endpoint_url): + """The Timestamp rounds to a millisecond first: 0.0004 and 0.00049 + round to zero and are refused (0.0005 is accepted above).""" table, arn = stream_table _write_group(dynamodb_client, table, "g", 1) shard = _shard_with_records(streams_client, arn) expected = PREFIX + "Valid timestamp must be provided when the iterator type is AT_TIMESTAMP" - for ts in (0, -1): + for ts in (0, -1, 0.0004, 0.00049, -0.0004): code, msg = _error( raw_streams_client.get_shard_iterator, StreamArn=arn, ShardId=shard, ShardIteratorType="AT_TIMESTAMP", Timestamp=ts, @@ -289,21 +310,36 @@ def test_milliseconds_as_seconds_is_in_the_future(self, dynamodb_client, streams assert code == "ValidationException", ts assert msg == PREFIX + "Timestamp parameter cannot be greater than the current timestamp", ts - def test_non_numeric_timestamp_is_a_serialization_error(self, dynamodb_client, streams_client, stream_table, endpoint_url): + def test_ill_typed_members_are_serialization_errors(self, dynamodb_client, streams_client, stream_table, endpoint_url): + """A member of the wrong JSON type is refused before the enum, null and + length checks, with the deserializer's text; SequenceNumber is read + before Timestamp; an array has no message.""" table, arn = stream_table g = _write_group(dynamodb_client, table, "g", 1) shard = _shard_with_records(streams_client, arn) + date_s = "STRING_VALUE cannot be converted to Date" + structure = "Start of structure or map found where not expected" cases = [ - (f"{int(g[0])}.5", "STRING_VALUE cannot be converted to Date"), - ("", "STRING_VALUE cannot be converted to Date"), - (True, "TRUE_VALUE cannot be converted to Date"), - ({"S": "x"}, "Start of structure or map found where not expected"), + ({"ShardIteratorType": "AT_TIMESTAMP", "Timestamp": f"{int(g[0])}.5"}, date_s), + ({"ShardIteratorType": "AT_TIMESTAMP", "Timestamp": ""}, date_s), + ({"ShardIteratorType": "AT_TIMESTAMP", "Timestamp": True}, "TRUE_VALUE cannot be converted to Date"), + ({"ShardIteratorType": "AT_TIMESTAMP", "Timestamp": {"S": "x"}}, structure), + ({"ShardIteratorType": "AT_TIMESTAMP", "Timestamp": []}, ""), + ({"ShardIteratorType": "BOGUS", "Timestamp": "1792764248"}, date_s), + ({"Timestamp": "1792764248"}, date_s), + ({"ShardIteratorType": "BOGUS", "SequenceNumber": 5}, "NUMBER_VALUE cannot be converted to String"), + ({"ShardIteratorType": "TRIM_HORIZON", "SequenceNumber": True}, "TRUE_VALUE cannot be converted to String"), + ({"ShardIteratorType": "TRIM_HORIZON", "SequenceNumber": {}}, structure), + ({"ShardIteratorType": "AT_TIMESTAMP", "SequenceNumber": 5, "Timestamp": "x"}, "NUMBER_VALUE cannot be converted to String"), ] - for ts, expected in cases: - code, msg = _raw_error(endpoint_url, { - "StreamArn": arn, "ShardId": shard, "ShardIteratorType": "AT_TIMESTAMP", "Timestamp": ts, - }) - assert (code, msg) == ("SerializationException", expected), ts + for extra, expected in cases: + code, msg = _raw_error(endpoint_url, {"StreamArn": arn, "ShardId": shard, **extra}) + assert (code, msg) == ("SerializationException", expected), extra + # The type check comes before the ShardId length constraint too. + code, msg = _raw_error(endpoint_url, { + "StreamArn": arn, "ShardId": "shardId-short", "ShardIteratorType": "AT_TIMESTAMP", "Timestamp": "x", + }) + assert (code, msg) == ("SerializationException", date_s) class TestValidationMatrix: @@ -336,33 +372,69 @@ def test_matrix(self, dynamodb_client, streams_client, raw_streams_client, strea (dict(ShardIteratorType="TRIM_HORIZON", SequenceNumber=seq), seq_refused), (dict(ShardIteratorType="LATEST", SequenceNumber=seq), seq_refused), (dict(ShardIteratorType="AT_SEQUENCE_NUMBER"), "SequenceNumber cannot be null"), + (dict(ShardIteratorType="AFTER_SEQUENCE_NUMBER"), "SequenceNumber cannot be null"), + # The missing SequenceNumber is refused before the Timestamp. + (dict(ShardIteratorType="AT_SEQUENCE_NUMBER", Timestamp=ts), "SequenceNumber cannot be null"), + (dict(ShardIteratorType="AFTER_SEQUENCE_NUMBER", Timestamp=ts), "SequenceNumber cannot be null"), ] for extra, expected in cases: code, msg = _error(raw_streams_client.get_shard_iterator, StreamArn=arn, ShardId=shard, **extra) assert code == "ValidationException", extra assert msg == PREFIX + expected, extra + def test_positional_types_check_the_shard_before_refusing_a_sequence_number(self, dynamodb_client, streams_client, raw_streams_client, stream_table): + """On a shard that does not exist, TRIM_HORIZON and LATEST answer the + shard before the SequenceNumber; AT_TIMESTAMP refuses the + SequenceNumber first, and a Timestamp is refused first for every type.""" + table, arn = stream_table + g = _write_group(dynamodb_client, table, "g", 1) + _shard_with_records(streams_client, arn) + missing = "shardId-00000000000000000000-ffffffff" + seq = "000000000000000000001" + not_found = ("ResourceNotFoundException", "Requested resource not found: Shard does not exist") + seq_refused = ("ValidationException", PREFIX + "SequenceNumber should not be passed for this iterator type") + ts_refused = ("ValidationException", PREFIX + "Timestamp should not be passed for this iterator type") + cases = [ + (dict(ShardIteratorType="TRIM_HORIZON", SequenceNumber=seq), not_found), + (dict(ShardIteratorType="LATEST", SequenceNumber=seq), not_found), + (dict(ShardIteratorType="TRIM_HORIZON"), not_found), + (dict(ShardIteratorType="AT_TIMESTAMP", SequenceNumber=seq, Timestamp=int(g[0])), seq_refused), + (dict(ShardIteratorType="TRIM_HORIZON", Timestamp=int(g[0])), ts_refused), + (dict(ShardIteratorType="LATEST", SequenceNumber=seq, Timestamp=int(g[0])), ts_refused), + (dict(ShardIteratorType="AT_SEQUENCE_NUMBER"), ("ValidationException", PREFIX + "SequenceNumber cannot be null")), + ] + for extra, expected in cases: + got = _error(raw_streams_client.get_shard_iterator, StreamArn=arn, ShardId=missing, **extra) + assert got == expected, extra + def test_unknown_or_missing_type_renders_without_the_value(self, dynamodb_client, streams_client, raw_streams_client, stream_table, endpoint_url): table, arn = stream_table _write_group(dynamodb_client, table, "g", 1) shard = _shard_with_records(streams_client, arn) members = "[AFTER_SEQUENCE_NUMBER, LATEST, AT_TIMESTAMP, AT_SEQUENCE_NUMBER, TRIM_HORIZON]" + enum_clause = f"Value at 'shardIteratorType' failed to satisfy constraint: Member must satisfy enum value set: {members}" + null_clause = "Value at 'shardIteratorType' failed to satisfy constraint: Member must not be null" + shard_clause = "Value at 'shardId' failed to satisfy constraint: Member must have length greater than or equal to 28" + seq_clause = "Value at 'sequenceNumber' failed to satisfy constraint: Member must have length greater than or equal to 21" # The service omits the offending value from the enum violation. for bad in ("BOGUS", "at_timestamp"): code, msg = _error(raw_streams_client.get_shard_iterator, StreamArn=arn, ShardId=shard, ShardIteratorType=bad) - assert code == "ValidationException" - assert msg == ( - "1 validation error detected: Value at 'shardIteratorType' failed to satisfy " - f"constraint: Member must satisfy enum value set: {members}" - ) - # A missing or null type is a ValidationException, not a serialization error. - for body in ({"Timestamp": 1792764248.0}, {"ShardIteratorType": None}): - code, msg = _raw_error(endpoint_url, {"StreamArn": arn, "ShardId": shard, **body}) - assert (code, msg) == ( - "ValidationException", - "1 validation error detected: Value at 'shardIteratorType' failed to satisfy " - "constraint: Member must not be null", - ), body + assert (code, msg) == ("ValidationException", f"1 validation error detected: {enum_clause}") + # A missing or null type is a ValidationException, not a serialization + # error, and it joins the other constraint violations in one message: + # sequenceNumber, shardIteratorType, shardId. + cases = [ + ({"ShardId": shard, "Timestamp": 1792764248.0}, f"1 validation error detected: {null_clause}"), + ({"ShardId": shard, "ShardIteratorType": None}, f"1 validation error detected: {null_clause}"), + ({"ShardId": "shardId-short"}, f"2 validation errors detected: {null_clause}; {shard_clause}"), + ({"ShardId": "shardId-short", "ShardIteratorType": "BOGUS"}, f"2 validation errors detected: {enum_clause}; {shard_clause}"), + ({"ShardId": shard, "SequenceNumber": "0"}, f"2 validation errors detected: {seq_clause}; {null_clause}"), + ({"ShardId": "shardId-short", "SequenceNumber": "0"}, f"3 validation errors detected: {seq_clause}; {null_clause}; {shard_clause}"), + ({"ShardId": "shardId-short", "ShardIteratorType": "TRIM_HORIZON"}, f"1 validation error detected: {shard_clause}"), + ] + for body, expected in cases: + code, msg = _raw_error(endpoint_url, {"StreamArn": arn, **body}) + assert (code, msg) == ("ValidationException", expected), body def test_future_check_runs_before_shard_existence(self, dynamodb_client, streams_client, raw_streams_client, stream_table): table, arn = stream_table From 7387d6fefb2d5ca9942efc29e90d2c170b1cf25e Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:51:24 +0000 Subject: [PATCH 06/14] test(streams): sign the raw requests with the default session's credentials A new boto3.Session() does not see a profile set with setup_default_session, so the raw requests had no credentials against the service. The signer now takes the default session when there is one. --- tests/test_streams_at_timestamp.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_streams_at_timestamp.py b/tests/test_streams_at_timestamp.py index fa7cc1893..d3dd916e2 100644 --- a/tests/test_streams_at_timestamp.py +++ b/tests/test_streams_at_timestamp.py @@ -152,7 +152,7 @@ def _raw_error(endpoint_url: str | None, body: dict) -> tuple[str, str]: "Content-Type": "application/x-amz-json-1.0", "X-Amz-Target": "DynamoDBStreams_20120810.GetShardIterator", }) - creds = boto3.Session().get_credentials().get_frozen_credentials() + creds = (boto3.DEFAULT_SESSION or boto3.Session()).get_credentials().get_frozen_credentials() SigV4Auth(creds, "dynamodb", REGION).add_auth(req) prepped = req.prepare() ctx = ssl.create_default_context() From 984ab05597d29b88b633321bb7467d014ad455a3 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:03:12 +0000 Subject: [PATCH 07/14] refactor(core): share the validation errors envelope The "N validation errors detected" envelope moves next to validation_errors in extenddb_core::error, which now builds on it. The engine's enum check and the GetShardIterator constraint check call it from there. The engine's lib.rs goes back under 600 lines. --- crates/core/src/error/messages.rs | 11 +++++++++-- crates/core/src/error/mod.rs | 4 +++- crates/engine/src/lib.rs | 13 +------------ crates/engine/src/streams.rs | 4 ++-- 4 files changed, 15 insertions(+), 17 deletions(-) diff --git a/crates/core/src/error/messages.rs b/crates/core/src/error/messages.rs index 18d3e521d..d425cde66 100755 --- a/crates/core/src/error/messages.rs +++ b/crates/core/src/error/messages.rs @@ -15,17 +15,24 @@ pub fn validation_error(value: &str, field: &str, constraint: &str) -> String { /// Format multiple validation constraint errors in `DynamoDB`'s exact format. #[must_use] pub fn validation_errors(errors: &[(&str, &str, &str)]) -> String { - let count = errors.len(); let details: Vec = errors .iter() .map(|(value, field, constraint)| { format!("Value '{value}' at '{field}' failed to satisfy constraint: {constraint}") }) .collect(); + validation_errors_detected(&details) +} + +/// The service's envelope for one or more constraint clauses: `N validation +/// error(s) detected: ` and the clauses joined by `; `. +#[must_use] +pub fn validation_errors_detected(clauses: &[String]) -> String { + let count = clauses.len(); format!( "{count} validation error{} detected: {}", if count == 1 { "" } else { "s" }, - details.join("; ") + clauses.join("; ") ) } diff --git a/crates/core/src/error/mod.rs b/crates/core/src/error/mod.rs index 499f20fb5..da765afdc 100755 --- a/crates/core/src/error/mod.rs +++ b/crates/core/src/error/mod.rs @@ -2,7 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 mod messages; -pub use messages::{ErrorMessageKey, error_message, validation_error, validation_errors}; +pub use messages::{ + ErrorMessageKey, error_message, validation_error, validation_errors, validation_errors_detected, +}; use crate::types::{CancellationReason, Item}; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 18273a0f7..6ccf609e7 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -299,21 +299,10 @@ pub(crate) fn validate_enum_fields( return Ok(()); } Err(DynamoDbError::ValidationException( - validation_errors_detected(&errors), + extenddb_core::error::validation_errors_detected(&errors), )) } -/// The service's envelope for one or more constraint clauses: `N validation -/// error(s) detected: ` and the clauses joined by `; `. -pub(crate) fn validation_errors_detected(clauses: &[String]) -> String { - let count = clauses.len(); - format!( - "{count} validation error{} detected: {}", - if count == 1 { "" } else { "s" }, - clauses.join("; ") - ) -} - /// Validate the `ReturnValues` field for `PutItem` / `DeleteItem`, which accept /// only `NONE` or `ALL_OLD`. Matches real DynamoDB's two distinct messages: /// diff --git a/crates/engine/src/streams.rs b/crates/engine/src/streams.rs index 171ca8f6f..1cd196100 100755 --- a/crates/engine/src/streams.rs +++ b/crates/engine/src/streams.rs @@ -224,7 +224,7 @@ fn constraint_violations(body: &Value) -> Result<(), DynamoDbError> { return Ok(()); } Err(DynamoDbError::ValidationException( - crate::validation_errors_detected(&clauses), + extenddb_core::error::validation_errors_detected(&clauses), )) } @@ -283,7 +283,7 @@ const SHARD_ID_MAX_LEN: usize = 65; /// `exclusiveStartShardId`, `sequenceNumber`, `limit` and /// `exclusiveStartStreamArn`). fn constraint(member: &str, rule: &str) -> String { - crate::validation_errors_detected(&[clause(member, rule)]) + extenddb_core::error::validation_errors_detected(&[clause(member, rule)]) } /// One constraint clause of [`constraint`], as the service joins several of From 65fd853a2e30835d8ae19efee82c8ec0a5c8d33d Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:09:13 +0000 Subject: [PATCH 08/14] test(streams): name the parameter table's row type Clippy 1.97.0 refuses the tuple type of the parameter rows and a float literal with more digits than its double holds. The rows get a type alias, and the row for the measured .3894999 literal uses .3895, the double it is. --- crates/engine/src/streams_iterator_params.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/streams_iterator_params.rs b/crates/engine/src/streams_iterator_params.rs index a903661df..adcc82f47 100644 --- a/crates/engine/src/streams_iterator_params.rs +++ b/crates/engine/src/streams_iterator_params.rs @@ -216,15 +216,14 @@ mod tests { /// Epoch seconds round half up to whole milliseconds, as the service /// does. Rows measured 2026-11-20 (us-east-1) on a record at ms ...389: - /// `.3894900` returned it, `.3894999` (whose double times 1000 is exactly - /// ...389.5) and `.3895000` did not, `.3885100` did. `0.0004` and + /// `.3894900` returned it, `.3895000` did not (so did `.3894999`, whose + /// double is the same as `.3895`), `.3885100` did. `0.0004` and /// `0.00049` were refused, `0.0005` and `0.00051` accepted. A floor fails - /// the `.3894999` and `.3885100` rows. + /// the `.3895` and `.3885100` rows. #[test] fn timestamp_rounds_half_up_to_the_millisecond() { let cases: &[(f64, Option)] = &[ (1_795_171_973.389_49, Some(1_795_171_973_389)), - (1_795_171_973.389_499_9, Some(1_795_171_973_390)), (1_795_171_973.389_5, Some(1_795_171_973_390)), (1_795_171_973.388_51, Some(1_795_171_973_389)), (1_792_764_248.0, Some(1_792_764_248_000)), @@ -285,12 +284,13 @@ mod tests { .as_secs_f64(); let past = 1_792_764_148.0; let future = now + 3_600.0; - let cases: &[( + type Row = ( ShardIteratorType, - Option<&str>, + Option<&'static str>, Option, - Result, &str>, - )] = &[ + Result, &'static str>, + ); + let cases: &[Row] = &[ // AT_TIMESTAMP: a valid Timestamp first; null, zero, 0.0004 and negative refuse. (AtTimestamp, None, None, Err(TS_REQUIRED)), (AtTimestamp, None, Some(0.0), Err(TS_REQUIRED)), From fc876786f54e95b4b6e9235e7e6f8cc7d070b477 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:44:58 +0000 Subject: [PATCH 09/14] fix(streams): refuse a missing StreamArn and name a missing ShardId in the joined constraints GetShardIterator answered a body without a StreamArn or without a ShardId with a SerializationException and serde's text. The service answers `Invalid StreamArn` for an absent, null or empty StreamArn, before any constraint clause. For an absent or null ShardId it puts `Value at 'shardId' failed to satisfy constraint: Member must not be null` in the shardId position of the joined message. Both were measured 2026-11-23 in us-east-1 on a stream that does not exist. The member type checks still run first. The text moves to `extenddb_core::error::INVALID_STREAM_ARN`, and the server's shape gate reads it from there. The unit table gets the StreamArn on every row and rows for the seven measured bodies. The wire test gets the same rows, plus two that put the type check before the StreamArn check. --- crates/core/src/error/messages.rs | 7 ++ crates/core/src/error/mod.rs | 3 +- crates/engine/src/streams.rs | 54 ++++++++------ crates/engine/src/streams_iterator_params.rs | 4 +- crates/engine/src/streams_tests.rs | 74 ++++++++++++++++---- crates/server/src/authz_resource.rs | 6 +- tests/test_streams_at_timestamp.py | 50 ++++++++----- 7 files changed, 145 insertions(+), 53 deletions(-) diff --git a/crates/core/src/error/messages.rs b/crates/core/src/error/messages.rs index d425cde66..c99a20a64 100755 --- a/crates/core/src/error/messages.rs +++ b/crates/core/src/error/messages.rs @@ -36,6 +36,13 @@ pub fn validation_errors_detected(clauses: &[String]) -> String { ) } +/// The service's answer to a `StreamArn` that is not a stream ARN of the +/// right shape (`DescribeStream` and `GetShardIterator`, measured 2026-10-23, +/// us-east-1), and to a `GetShardIterator` whose `StreamArn` is absent, null +/// or empty (measured 2026-11-23). The server checks the shape before +/// authorization; the `GetShardIterator` handler checks the presence. +pub const INVALID_STREAM_ARN: &str = "Invalid StreamArn"; + /// Keys for error message templates. Compile-time checked — no stringly-typed lookups. #[derive(Debug, Clone, Copy)] pub enum ErrorMessageKey { diff --git a/crates/core/src/error/mod.rs b/crates/core/src/error/mod.rs index da765afdc..4e15e3bed 100755 --- a/crates/core/src/error/mod.rs +++ b/crates/core/src/error/mod.rs @@ -3,7 +3,8 @@ mod messages; pub use messages::{ - ErrorMessageKey, error_message, validation_error, validation_errors, validation_errors_detected, + ErrorMessageKey, INVALID_STREAM_ARN, error_message, validation_error, validation_errors, + validation_errors_detected, }; use crate::types::{CancellationReason, Item}; diff --git a/crates/engine/src/streams.rs b/crates/engine/src/streams.rs index 1cd196100..e5a1da58f 100755 --- a/crates/engine/src/streams.rs +++ b/crates/engine/src/streams.rs @@ -101,11 +101,12 @@ pub async fn handle_list_streams( /// /// Encodes the shard ID and starting position into a base64 iterator token. /// -/// Validation runs in the service's order, measured 2026-10-23 and 2026-11-20 -/// (us-east-1): the members' JSON types, then the model's constraints in one -/// message (`SequenceNumber` length, `ShardIteratorType` null or enum, -/// `ShardId` length), then the parameter rules per type, then stream and shard -/// existence, then the `SequenceNumber` refusal of `TRIM_HORIZON` and `LATEST`. +/// Validation runs in the service's order, measured 2026-10-23, 2026-11-20 and +/// 2026-11-23 (us-east-1): the members' JSON types, then the `StreamArn` +/// presence, then the model's constraints in one message (`SequenceNumber` +/// length, `ShardIteratorType` null or enum, `ShardId` null or length), then +/// the parameter rules per type, then stream and shard existence, then the +/// `SequenceNumber` refusal of `TRIM_HORIZON` and `LATEST`. /// /// # Errors /// @@ -185,16 +186,29 @@ pub async fn handle_get_shard_iterator( serialize_output(&output) } -/// The model's constraints on a `GetShardIterator` body, in one message: the -/// `SequenceNumber` is at least 21 characters (measured 2026-10-24 with "0"), -/// the `ShardIteratorType` is present and a member, the `ShardId` is at least -/// 28 characters. The service joins every violation under one `N validation -/// errors detected`, in this order and with no value quoted (measured -/// 2026-11-20, us-east-1). The `ShardId` maximum is applied once the shard is -/// not found (`shard_lookup_error`): the shards a release before v0.1.14 wrote -/// are named after the table, and a table name over 40 characters puts them -/// past 65. +/// The model's checks on a `GetShardIterator` body before it is deserialized. +/// +/// An absent, null or empty `StreamArn` is `Invalid StreamArn` on its own, +/// before any clause (measured 2026-11-23, us-east-1; the server refuses a +/// malformed one before the handler). Then the constraints join one message: +/// the `SequenceNumber` is at least 21 characters (measured 2026-10-24 with +/// "0"), the `ShardIteratorType` is present and a member, the `ShardId` is +/// present and at least 28 characters. The service joins every violation under +/// one `N validation errors detected`, in this order and with no value quoted +/// (measured 2026-11-20 and 2026-11-23, us-east-1). The `ShardId` maximum is +/// applied once the shard is not found (`shard_lookup_error`): the shards a +/// release before v0.1.14 wrote are named after the table, and a table name +/// over 40 characters puts them past 65. fn constraint_violations(body: &Value) -> Result<(), DynamoDbError> { + if body + .get("StreamArn") + .and_then(Value::as_str) + .is_none_or(str::is_empty) + { + return Err(DynamoDbError::ValidationException( + extenddb_core::error::INVALID_STREAM_ARN.to_owned(), + )); + } let mut clauses = Vec::new(); if body .get("SequenceNumber") @@ -213,12 +227,12 @@ fn constraint_violations(body: &Value) -> Result<(), DynamoDbError> { } _ => {} } - if body - .get("ShardId") - .and_then(Value::as_str) - .is_some_and(|s| s.chars().count() < SHARD_ID_MIN_LEN) - { - clauses.push(clause("shardId", "have length greater than or equal to 28")); + match body.get("ShardId") { + None | Some(Value::Null) => clauses.push(clause("shardId", "not be null")), + Some(Value::String(s)) if s.chars().count() < SHARD_ID_MIN_LEN => { + clauses.push(clause("shardId", "have length greater than or equal to 28")); + } + _ => {} } if clauses.is_empty() { return Ok(()); diff --git a/crates/engine/src/streams_iterator_params.rs b/crates/engine/src/streams_iterator_params.rs index adcc82f47..9a67179ca 100644 --- a/crates/engine/src/streams_iterator_params.rs +++ b/crates/engine/src/streams_iterator_params.rs @@ -41,8 +41,8 @@ const TYPED_MEMBERS: &[(&str, &str)] = &[("SequenceNumber", "String"), ("Timesta /// converted to `, an object the structure message, an array a /// `SerializationException` with no message. Null passes through to the /// parameter rules, which treat it as absent. The service runs this before -/// every constraint and parameter check, the `ShardIteratorType` ones -/// included. +/// every constraint and parameter check, the `ShardIteratorType` ones and +/// the `StreamArn` presence (measured 2026-11-23) included. pub(crate) fn check_member_shapes(body: &serde_json::Value) -> Result<(), DynamoDbError> { use serde_json::Value; for (member, kind) in TYPED_MEMBERS { diff --git a/crates/engine/src/streams_tests.rs b/crates/engine/src/streams_tests.rs index f7a56dd6d..47f6ef771 100644 --- a/crates/engine/src/streams_tests.rs +++ b/crates/engine/src/streams_tests.rs @@ -108,8 +108,10 @@ fn the_shard_id_maximum_applies_once_the_shard_is_not_found() { } } -/// Every constraint violation of a body joins one message, in the service's -/// order (measured 2026-11-20): sequenceNumber, shardIteratorType, shardId. +/// An absent, null or empty `StreamArn` is `Invalid StreamArn` before any +/// clause, and every constraint violation of a body joins one message, in the +/// service's order (measured 2026-11-20 and 2026-11-23): sequenceNumber, +/// shardIteratorType, shardId (null before length). #[test] fn constraint_violations_join_one_message_in_the_service_order() { use serde_json::json; @@ -117,54 +119,102 @@ fn constraint_violations_join_one_message_in_the_service_order() { const NULL: &str = "Value at 'shardIteratorType' failed to satisfy constraint: Member must not be null"; const SHARD: &str = "Value at 'shardId' failed to satisfy constraint: Member must have length greater than or equal to 28"; + const SHARD_NULL: &str = + "Value at 'shardId' failed to satisfy constraint: Member must not be null"; + const INVALID_ARN: &str = "Invalid StreamArn"; + let arn = "arn:aws:dynamodb:us-east-1:123456789012:table/T/stream/2026-10-23T14:03:56.871"; let long = "shardId-00000001792764241200-b719fef1"; let cases: &[(serde_json::Value, Option)] = &[ ( - json!({"ShardId": "shardId-short"}), + json!({"StreamArn": arn, "ShardId": "shardId-short"}), Some(format!("2 validation errors detected: {NULL}; {SHARD}")), ), ( - json!({"ShardId": "shardId-short", "ShardIteratorType": null}), + json!({"StreamArn": arn, "ShardId": "shardId-short", "ShardIteratorType": null}), Some(format!("2 validation errors detected: {NULL}; {SHARD}")), ), ( - json!({"ShardId": "shardId-short", "ShardIteratorType": "BOGUS"}), + json!({"StreamArn": arn, "ShardId": "shardId-short", "ShardIteratorType": "BOGUS"}), Some(format!( "2 validation errors detected: {}; {SHARD}", super::iterator_params::SHARD_ITERATOR_TYPE_ENUM_CLAUSE )), ), ( - json!({"ShardId": long, "SequenceNumber": "0"}), + json!({"StreamArn": arn, "ShardId": long, "SequenceNumber": "0"}), Some(format!("2 validation errors detected: {SEQ}; {NULL}")), ), ( - json!({"ShardId": "shardId-short", "SequenceNumber": "0"}), + json!({"StreamArn": arn, "ShardId": "shardId-short", "SequenceNumber": "0"}), Some(format!( "3 validation errors detected: {SEQ}; {NULL}; {SHARD}" )), ), ( - json!({"ShardId": long, "Timestamp": 1792764248.0}), + json!({"StreamArn": arn, "ShardId": long, "Timestamp": 1792764248.0}), Some(format!("1 validation error detected: {NULL}")), ), ( - json!({"ShardId": long, "ShardIteratorType": "at_timestamp"}), + json!({"StreamArn": arn, "ShardId": long, "ShardIteratorType": "at_timestamp"}), Some(format!( "1 validation error detected: {}", super::iterator_params::SHARD_ITERATOR_TYPE_ENUM_CLAUSE )), ), ( - json!({"ShardId": "shardId-short", "ShardIteratorType": "TRIM_HORIZON"}), + json!({"StreamArn": arn, "ShardId": "shardId-short", "ShardIteratorType": "TRIM_HORIZON"}), Some(format!("1 validation error detected: {SHARD}")), ), + // A missing or null ShardId is its null clause, in the shardId position. + ( + json!({"StreamArn": arn, "ShardIteratorType": "TRIM_HORIZON"}), + Some(format!("1 validation error detected: {SHARD_NULL}")), + ), ( - json!({"ShardId": long, "ShardIteratorType": "AT_TIMESTAMP", "SequenceNumber": "000000000000000000001"}), + json!({"StreamArn": arn, "ShardId": null, "ShardIteratorType": "TRIM_HORIZON"}), + Some(format!("1 validation error detected: {SHARD_NULL}")), + ), + ( + json!({"StreamArn": arn, "SequenceNumber": "0"}), + Some(format!( + "3 validation errors detected: {SEQ}; {NULL}; {SHARD_NULL}" + )), + ), + // An absent, null or empty StreamArn is refused alone, whatever else + // the body would violate. + ( + json!({"ShardId": long, "ShardIteratorType": "TRIM_HORIZON"}), + Some(INVALID_ARN.to_owned()), + ), + ( + json!({"ShardId": "shardId-short"}), + Some(INVALID_ARN.to_owned()), + ), + ( + json!({"StreamArn": null, "ShardId": long, "ShardIteratorType": "TRIM_HORIZON"}), + Some(INVALID_ARN.to_owned()), + ), + ( + json!({"StreamArn": "", "ShardId": long, "ShardIteratorType": "TRIM_HORIZON"}), + Some(INVALID_ARN.to_owned()), + ), + ( + json!({"StreamArn": null, "SequenceNumber": "0"}), + Some(INVALID_ARN.to_owned()), + ), + ( + json!({"StreamArn": "", "ShardId": "shardId-short"}), + Some(INVALID_ARN.to_owned()), + ), + ( + json!({"StreamArn": arn, "ShardId": long, "ShardIteratorType": "AT_TIMESTAMP", "SequenceNumber": "000000000000000000001"}), None, ), // A ShardIteratorType of another JSON type is the deserializer's case. - (json!({"ShardId": long, "ShardIteratorType": 5}), None), + ( + json!({"StreamArn": arn, "ShardId": long, "ShardIteratorType": 5}), + None, + ), ]; for (body, expected) in cases { match (super::constraint_violations(body), expected) { diff --git a/crates/server/src/authz_resource.rs b/crates/server/src/authz_resource.rs index 4261d9efb..0bb62bf82 100644 --- a/crates/server/src/authz_resource.rs +++ b/crates/server/src/authz_resource.rs @@ -295,8 +295,10 @@ fn tag_resource_arn(arn: &str, region: &str, account_id: &str) -> String { /// Messages DynamoDB returns, before the IAM decision, for a request field /// whose ARN is not a valid resource ARN of the kind the field requires -/// (measured live, `live-r2/arn-kinds-live.json`). -const INVALID_STREAM_ARN_MESSAGE: &str = "Invalid StreamArn"; +/// (measured live, `live-r2/arn-kinds-live.json`). The stream text is the +/// core constant, which the `GetShardIterator` handler also answers for an +/// absent `StreamArn`. +const INVALID_STREAM_ARN_MESSAGE: &str = extenddb_core::error::INVALID_STREAM_ARN; const INVALID_BACKUP_ARN_MESSAGE: &str = "Invalid Backup ARN"; const INVALID_EXPORT_TABLE_ARN_MESSAGE: &str = "One or more parameter values were invalid: tableArn is not a valid ARN"; diff --git a/tests/test_streams_at_timestamp.py b/tests/test_streams_at_timestamp.py index d3dd916e2..458292614 100644 --- a/tests/test_streams_at_timestamp.py +++ b/tests/test_streams_at_timestamp.py @@ -335,11 +335,17 @@ def test_ill_typed_members_are_serialization_errors(self, dynamodb_client, strea for extra, expected in cases: code, msg = _raw_error(endpoint_url, {"StreamArn": arn, "ShardId": shard, **extra}) assert (code, msg) == ("SerializationException", expected), extra - # The type check comes before the ShardId length constraint too. - code, msg = _raw_error(endpoint_url, { - "StreamArn": arn, "ShardId": "shardId-short", "ShardIteratorType": "AT_TIMESTAMP", "Timestamp": "x", - }) - assert (code, msg) == ("SerializationException", date_s) + # The type check comes before the ShardId length constraint too, and + # before the StreamArn check (measured 2026-11-23 with no StreamArn + # and with an empty one). + for body in ( + {"StreamArn": arn, "ShardId": "shardId-short", "ShardIteratorType": "AT_TIMESTAMP", "Timestamp": "x"}, + {"Timestamp": "x"}, + ): + code, msg = _raw_error(endpoint_url, body) + assert (code, msg) == ("SerializationException", date_s), body + code, msg = _raw_error(endpoint_url, {"StreamArn": "", "SequenceNumber": 5}) + assert (code, msg) == ("SerializationException", "NUMBER_VALUE cannot be converted to String") class TestValidationMatrix: @@ -420,20 +426,32 @@ def test_unknown_or_missing_type_renders_without_the_value(self, dynamodb_client for bad in ("BOGUS", "at_timestamp"): code, msg = _error(raw_streams_client.get_shard_iterator, StreamArn=arn, ShardId=shard, ShardIteratorType=bad) assert (code, msg) == ("ValidationException", f"1 validation error detected: {enum_clause}") - # A missing or null type is a ValidationException, not a serialization - # error, and it joins the other constraint violations in one message: - # sequenceNumber, shardIteratorType, shardId. + # A missing or null type or shard id is a ValidationException, not a + # serialization error, and it joins the other constraint violations in + # one message: sequenceNumber, shardIteratorType, shardId. An absent, + # null or empty StreamArn is refused alone, before the clauses + # (measured 2026-11-23). + shard_null = "Value at 'shardId' failed to satisfy constraint: Member must not be null" cases = [ - ({"ShardId": shard, "Timestamp": 1792764248.0}, f"1 validation error detected: {null_clause}"), - ({"ShardId": shard, "ShardIteratorType": None}, f"1 validation error detected: {null_clause}"), - ({"ShardId": "shardId-short"}, f"2 validation errors detected: {null_clause}; {shard_clause}"), - ({"ShardId": "shardId-short", "ShardIteratorType": "BOGUS"}, f"2 validation errors detected: {enum_clause}; {shard_clause}"), - ({"ShardId": shard, "SequenceNumber": "0"}, f"2 validation errors detected: {seq_clause}; {null_clause}"), - ({"ShardId": "shardId-short", "SequenceNumber": "0"}, f"3 validation errors detected: {seq_clause}; {null_clause}; {shard_clause}"), - ({"ShardId": "shardId-short", "ShardIteratorType": "TRIM_HORIZON"}, f"1 validation error detected: {shard_clause}"), + ({"StreamArn": arn, "ShardId": shard, "Timestamp": 1792764248.0}, f"1 validation error detected: {null_clause}"), + ({"StreamArn": arn, "ShardId": shard, "ShardIteratorType": None}, f"1 validation error detected: {null_clause}"), + ({"StreamArn": arn, "ShardId": "shardId-short"}, f"2 validation errors detected: {null_clause}; {shard_clause}"), + ({"StreamArn": arn, "ShardId": "shardId-short", "ShardIteratorType": "BOGUS"}, f"2 validation errors detected: {enum_clause}; {shard_clause}"), + ({"StreamArn": arn, "ShardId": shard, "SequenceNumber": "0"}, f"2 validation errors detected: {seq_clause}; {null_clause}"), + ({"StreamArn": arn, "ShardId": "shardId-short", "SequenceNumber": "0"}, f"3 validation errors detected: {seq_clause}; {null_clause}; {shard_clause}"), + ({"StreamArn": arn, "ShardId": "shardId-short", "ShardIteratorType": "TRIM_HORIZON"}, f"1 validation error detected: {shard_clause}"), + ({"StreamArn": arn, "ShardIteratorType": "TRIM_HORIZON"}, f"1 validation error detected: {shard_null}"), + ({"StreamArn": arn, "ShardId": None, "ShardIteratorType": "TRIM_HORIZON"}, f"1 validation error detected: {shard_null}"), + ({"StreamArn": arn, "SequenceNumber": "0"}, f"3 validation errors detected: {seq_clause}; {null_clause}; {shard_null}"), + ({"ShardId": shard, "ShardIteratorType": "TRIM_HORIZON"}, "Invalid StreamArn"), + ({"ShardId": "shardId-short"}, "Invalid StreamArn"), + ({"StreamArn": None, "ShardId": shard, "ShardIteratorType": "TRIM_HORIZON"}, "Invalid StreamArn"), + ({"StreamArn": "", "ShardId": shard, "ShardIteratorType": "TRIM_HORIZON"}, "Invalid StreamArn"), + ({"StreamArn": None, "SequenceNumber": "0"}, "Invalid StreamArn"), + ({"StreamArn": "", "ShardId": "shardId-short"}, "Invalid StreamArn"), ] for body, expected in cases: - code, msg = _raw_error(endpoint_url, {"StreamArn": arn, **body}) + code, msg = _raw_error(endpoint_url, body) assert (code, msg) == ("ValidationException", expected), body def test_future_check_runs_before_shard_existence(self, dynamodb_client, streams_client, raw_streams_client, stream_table): From 527d811bbf5aeda3dfa2ecadbe3b2ed3d842498e Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:57:39 +0000 Subject: [PATCH 10/14] test(streams): pin the at-or-after seek on PostgreSQL and MongoDB, and the SQLite shard filter The `>=` of the seek had a unit test on SQLite only. PostgreSQL gets `tests/stream_at_timestamp.rs` on a scratch database, and MongoDB a `records_live` test beside the page tests. Both use the rows of the SQLite table on records with known `created_at` values. With `>` in place of `>=`, each fails at the record's own millisecond. The other shard's record in all three tests is now sequence 4 at `base + 2` instead of sequence 8 at `base - 1000`. It has the lowest sequence number and sits inside the table's range. A seek without the shard filter answers it for the first five rows. The old record was never the minimum, so the SQLite test passed without the filter. --- .../src/stream_records_live_tests.rs | 89 +++++++++++++++---- .../tests/stream_at_timestamp.rs | 84 +++++++++++++++++ crates/storage-sqlite/src/stream_tests.rs | 6 +- 3 files changed, 162 insertions(+), 17 deletions(-) create mode 100644 crates/storage-postgres/tests/stream_at_timestamp.rs diff --git a/crates/storage-mongodb/src/stream_records_live_tests.rs b/crates/storage-mongodb/src/stream_records_live_tests.rs index 8c346d088..fadf3f6fb 100644 --- a/crates/storage-mongodb/src/stream_records_live_tests.rs +++ b/crates/storage-mongodb/src/stream_records_live_tests.rs @@ -3,7 +3,9 @@ //! Live MongoDB tests for `get_stream_records`: the shard is resolved against //! the stream its iterator names, and a page is streamed record by record so -//! its size is bounded by `Limit`, not by the 16 MB document cap. +//! its size is bounded by `Limit`, not by the 16 MB document cap. The +//! `AT_TIMESTAMP` seek is pinned here too, on records with known +//! `created_at` values. //! //! They read a MongoDB URI from `EXTENDDB_TEST_MONGODB_URI` (a replica set is //! not needed here) and are `#[ignore]`d so `cargo test --lib` passes without @@ -93,23 +95,36 @@ impl Fixture { async fn write_records(&self, shard_id: &str, table_id: &str, seqs: &[u64], blob: usize) { for seq in seqs { - let record_bson = bson::to_bson(&record_json(*seq, blob)).expect("record json to bson"); - self.engine - .data_db - .collection::("stream_records") - .insert_one(doc! { - "sequence_number": format!("{seq:021}"), - "shard_id": shard_id, - "table_id": table_id, - "event_name": "INSERT", - "record_data": record_bson, - "created_at": bson::DateTime::now(), - }) - .await - .expect("record"); + self.write_record(shard_id, table_id, *seq, blob, bson::DateTime::now()) + .await; } } + /// One record in the shape the engine writes, with the `created_at` given. + async fn write_record( + &self, + shard_id: &str, + table_id: &str, + seq: u64, + blob: usize, + created_at: bson::DateTime, + ) { + let record_bson = bson::to_bson(&record_json(seq, blob)).expect("record json to bson"); + self.engine + .data_db + .collection::("stream_records") + .insert_one(doc! { + "sequence_number": format!("{seq:021}"), + "shard_id": shard_id, + "table_id": table_id, + "event_name": "INSERT", + "record_data": record_bson, + "created_at": created_at, + }) + .await + .expect("record"); + } + async fn relabel(&self, account: &str, name: &str, label: &str) { self.engine .catalog_db @@ -396,3 +411,47 @@ async fn records_live_an_idle_shard_reads_an_empty_page() { } f.finish().await; } + +/// The `AT_TIMESTAMP` seek answers the first record of the shard created at +/// or after the millisecond asked for: a record's own millisecond returns it, +/// the next one does not, and another shard's records do not count. The rows +/// are those of the SQLite `stream_tests`. The other shard's record has the +/// lowest sequence number and a `created_at` inside the table's range, so +/// without the shard filter it is the answer to the first five rows. +#[tokio::test] +#[ignore = "needs a MongoDB server in EXTENDDB_TEST_MONGODB_URI"] +async fn records_live_at_timestamp_seek_is_at_or_after_the_records_millisecond() { + let f = Fixture::new().await; + let table_id = f.stream_table(ACCOUNT, "t", LABEL).await; + let own = legacy_shard_id(&table_id, 0); + let other = legacy_shard_id(&table_id, 1); + let base = 1_700_000_000_250; + let at = bson::DateTime::from_millis; + f.write_record(&own, &table_id, 5, 10, at(base)).await; + f.write_record(&own, &table_id, 6, 10, at(base + 1)).await; + f.write_record(&own, &table_id, 7, 10, at(base + 750)).await; + f.write_record(&other, &table_id, 4, 10, at(base + 2)).await; + + let cases: &[(i64, Option)] = &[ + (0, Some(5)), + (base - 1, Some(5)), + (base, Some(5)), + (base + 1, Some(6)), + (base + 2, Some(7)), + (base + 750, Some(7)), + (base + 751, None), + ]; + for (at_ms, expected) in cases { + let got = f + .engine + .first_sequence_number_at_or_after(&own, *at_ms) + .await + .expect("seek"); + assert_eq!( + got, + expected.map(|seq| format!("{seq:021}")), + "at_ms={at_ms}" + ); + } + f.finish().await; +} diff --git a/crates/storage-postgres/tests/stream_at_timestamp.rs b/crates/storage-postgres/tests/stream_at_timestamp.rs new file mode 100644 index 000000000..41404d323 --- /dev/null +++ b/crates/storage-postgres/tests/stream_at_timestamp.rs @@ -0,0 +1,84 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! The `AT_TIMESTAMP` seek answers the first record of the shard created at +//! or after the millisecond asked for: a record's own millisecond returns it, +//! the next one does not, and another shard's records do not count. The rows +//! are those of the SQLite `stream_tests`, written here with known +//! `created_at` values, so the `>=` of the seek is pinned on this backend. +//! +//! Needs `EXTENDDB_TEST_PG_CONNECTION_STRING` (host-only, e.g. +//! `postgres://user:pass@127.0.0.1:5432`); skips otherwise. The test builds +//! its own scratch database and drops it afterwards. + +#[path = "common/stream_disable_fixture.rs"] +mod fixture; + +use fixture::*; + +/// A record with the `created_at` the write path stores: the clock read, in +/// milliseconds. +async fn write_record_at(s: &Scratch, shard_id: &str, table_id: &str, seq: u64, ms: i64) { + let created_at = + time::OffsetDateTime::from_unix_timestamp_nanos(i128::from(ms) * 1_000_000).expect("ms"); + sqlx::query( + "INSERT INTO stream_records (shard_id, sequence_number, table_id, event_name, \ + record_data, created_at) VALUES ($1, $2, $3, 'INSERT', $4::jsonb, $5)", + ) + .bind(shard_id) + .bind(format!("{seq:021}")) + .bind(table_id) + .bind(serde_json::json!({"eventID": format!("e{seq}")}).to_string()) + .bind(created_at) + .execute(&s.db) + .await + .expect("record"); +} + +/// The other shard's record has the lowest sequence number and a `created_at` +/// inside the table's range, so without the shard filter it is the answer to +/// the first five rows. +#[tokio::test] +async fn at_timestamp_seek_is_at_or_after_the_records_millisecond() { + if base_conn().is_none() { + eprintln!("SKIP: EXTENDDB_TEST_PG_CONNECTION_STRING is not set"); + return; + } + let s = scratch().await; + let desc = s + .engine + .create_table(ACCOUNT, table_input("t", true)) + .await + .expect("create a stream-enabled table"); + let table_id = desc.table_id.clone(); + let shards = open_shard_ids(&s, &table_id).await; + let (own, other) = (shards[0].as_str(), shards[1].as_str()); + let base = 1_700_000_000_250; + write_record_at(&s, own, &table_id, 5, base).await; + write_record_at(&s, own, &table_id, 6, base + 1).await; + write_record_at(&s, own, &table_id, 7, base + 750).await; + write_record_at(&s, other, &table_id, 4, base + 2).await; + + let cases: &[(i64, Option)] = &[ + (0, Some(5)), + (base - 1, Some(5)), + (base, Some(5)), + (base + 1, Some(6)), + (base + 2, Some(7)), + (base + 750, Some(7)), + (base + 751, None), + ]; + for (at_ms, expected) in cases { + let got = s + .engine + .first_sequence_number_at_or_after(own, *at_ms) + .await + .expect("seek"); + assert_eq!( + got, + expected.map(|seq| format!("{seq:021}")), + "at_ms={at_ms}" + ); + } + s.cleanup().await; +} diff --git a/crates/storage-sqlite/src/stream_tests.rs b/crates/storage-sqlite/src/stream_tests.rs index 64e9cb226..753c8e68f 100644 --- a/crates/storage-sqlite/src/stream_tests.rs +++ b/crates/storage-sqlite/src/stream_tests.rs @@ -482,7 +482,9 @@ async fn write_record_at(engine: &SqliteEngine, shard_id: &str, table_id: &str, /// The `AT_TIMESTAMP` seek answers the first record created at or after the /// millisecond asked for: a record's own millisecond returns it, the next one -/// does not, and another shard's records do not count. +/// does not, and another shard's records do not count. The other shard's +/// record has the lowest sequence number and a `created_at` inside the table's +/// range, so without the shard filter it is the answer to the first five rows. #[tokio::test] async fn at_timestamp_seek_is_at_or_after_the_records_millisecond() { let engine = engine().await; @@ -493,7 +495,7 @@ async fn at_timestamp_seek_is_at_or_after_the_records_millisecond() { write_record_at(&engine, &own, &table_id, 5, base).await; write_record_at(&engine, &own, &table_id, 6, base + 1).await; write_record_at(&engine, &own, &table_id, 7, base + 750).await; - write_record_at(&engine, &other, &table_id, 8, base - 1_000).await; + write_record_at(&engine, &other, &table_id, 4, base + 2).await; let cases: &[(i64, Option)] = &[ (0, Some(5)), From 6c1203db5fd4a0f5a44de94e4c51a0965d2e119a Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:00:50 +0000 Subject: [PATCH 11/14] fix(storage-cassandra): keep the seek module private and assert the clamp test's first record `stream_at_timestamp` and `sequence_lower_bound` were `pub` with no user outside the file. Both are private now. The clamp test's last probe, T before every record, asserted only that some record came back. Its comment named the clamped record as the answer. The seek returns the lowest sequence number that passes the filter, and the real record's prefix is 8 s before the clamped one. So the real record is the answer, and the test now asserts it by equality. --- crates/storage-cassandra/src/lib.rs | 2 +- crates/storage-cassandra/src/stream_at_timestamp.rs | 3 +-- .../tests/direct/stream_at_timestamp.rs | 10 +++++++--- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/crates/storage-cassandra/src/lib.rs b/crates/storage-cassandra/src/lib.rs index 4fe7aa379..71f0f9bb7 100644 --- a/crates/storage-cassandra/src/lib.rs +++ b/crates/storage-cassandra/src/lib.rs @@ -41,7 +41,7 @@ mod password_hash_store; pub(crate) mod propagation_hold; mod restore_engine; mod snapshot_engine; -pub mod stream_at_timestamp; +mod stream_at_timestamp; mod stream_engine; mod stream_lifecycle; pub mod stream_util; diff --git a/crates/storage-cassandra/src/stream_at_timestamp.rs b/crates/storage-cassandra/src/stream_at_timestamp.rs index 68a8ee2e3..77a74fb8b 100644 --- a/crates/storage-cassandra/src/stream_at_timestamp.rs +++ b/crates/storage-cassandra/src/stream_at_timestamp.rs @@ -23,8 +23,7 @@ use crate::cassandra_util::query_rows; use crate::engine::CassandraEngine; /// The smallest sequence number whose millisecond prefix is `at_ms`. -#[must_use] -pub fn sequence_lower_bound(at_ms: i64) -> String { +fn sequence_lower_bound(at_ms: i64) -> String { format!("{:013}{:06}{:04}", at_ms.max(0), 0, 0) } diff --git a/crates/storage-cassandra/tests/direct/stream_at_timestamp.rs b/crates/storage-cassandra/tests/direct/stream_at_timestamp.rs index 7595505cf..e6b9e8772 100644 --- a/crates/storage-cassandra/tests/direct/stream_at_timestamp.rs +++ b/crates/storage-cassandra/tests/direct/stream_at_timestamp.rs @@ -115,13 +115,17 @@ async fn test_at_timestamp_seek_skips_a_clamped_record_older_than_t() { .unwrap(); assert_eq!(got, None, "a clamped record older than T is not returned"); - // T before everything: the clamped record is the first, as its - // created_at is the oldest. + // T before everything: both records pass the filter, and the first by + // sequence is the real one, whose prefix is 8 s before the clamped one. let got = engine .first_sequence_number_at_or_after(&shard_id, clamped_created - 1) .await .unwrap(); - assert!(got.is_some()); + assert_eq!( + got.as_deref(), + Some(real_seq.as_str()), + "the first record by sequence, the real one, is the answer" + ); } /// Every stream of a table keeps its records in the partition of the shard From 1f0bf1201fb567abedd40286077195c885f074c6 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:05:58 +0000 Subject: [PATCH 12/14] test(streams): assert the measured messages and run the guarded probe last Three assertions checked the error code alone. They now compare the code and the full message. A past Timestamp on a shard that does not exist is `Requested resource not found: Shard does not exist` (measured 2026-11-20). Now + 5 s on the wire and now + 2 s in the unit test are the future refusal (measured 2026-10-23). The positioning test skipped when group 2 spanned past +0.5 s, and the skip also dropped the two checks after it. The guarded probe runs last now, so a slow write skips that probe alone. --- crates/engine/src/streams_iterator_params.rs | 8 +++---- tests/test_streams_at_timestamp.py | 25 ++++++++++---------- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/streams_iterator_params.rs b/crates/engine/src/streams_iterator_params.rs index 9a67179ca..321beb42e 100644 --- a/crates/engine/src/streams_iterator_params.rs +++ b/crates/engine/src/streams_iterator_params.rs @@ -440,13 +440,13 @@ mod tests { )) .is_ok() ); - assert!( - v(&input( + assert_eq!( + message(v(&input( ShardIteratorType::AtTimestamp, None, Some(now + 2.0) - )) - .is_err() + ))), + format!("One or more parameter values were invalid: {FUTURE}") ); } diff --git a/tests/test_streams_at_timestamp.py b/tests/test_streams_at_timestamp.py index 458292614..176e6eee9 100644 --- a/tests/test_streams_at_timestamp.py +++ b/tests/test_streams_at_timestamp.py @@ -193,21 +193,20 @@ def ts(secs: float): # The group's own second, as an integer, includes the group. assert _values(_at(streams_client, arn, shard, ts(int(g2[0])))) == all_vals[3:] assert _values(_at(streams_client, arn, shard, ts(int(g3[0])))) == all_vals[6:] - # Fractional seconds inside the group's second skip it: the writes - # landed at +0.050 to about +0.100, so .5 and .999 start at group 3. - # Guard on the measured span so a slow write on a loaded host skips - # the probe instead of failing it. - if g2[1] < int(g2[0]) + 0.5: - assert _values(_at(streams_client, arn, shard, ts(int(g2[0]) + 0.5))) == all_vals[6:] - assert _values(_at(streams_client, arn, shard, ts(int(g2[0]) + 0.999))) == all_vals[6:] - else: - pytest.skip(f"group 2 spanned past +0.5 s ({g2[1] - int(g2[0]):.3f}); boundary probe not meaningful") # One second after the last record: nothing. assert _at(streams_client, arn, shard, ts(int(g3[1]) + 1)) == [] # ApproximateCreationDateTime is whole seconds. recs = _at(streams_client, arn, shard, ts(g1[0] - 10)) for r in recs: assert r["dynamodb"]["ApproximateCreationDateTime"].microsecond == 0 + # Fractional seconds inside the group's second skip it: the writes + # landed at +0.050 to about +0.100, so .5 and .999 start at group 3. + # Last, and guarded on the measured span, so a slow write on a loaded + # host skips this probe alone instead of failing it. + if g2[1] >= int(g2[0]) + 0.5: + pytest.skip(f"group 2 spanned past +0.5 s ({g2[1] - int(g2[0]):.3f}); boundary probe not meaningful") + assert _values(_at(streams_client, arn, shard, ts(int(g2[0]) + 0.5))) == all_vals[6:] + assert _values(_at(streams_client, arn, shard, ts(int(g2[0]) + 0.999))) == all_vals[6:] def test_boundary_is_at_or_after_the_record_millisecond(self, dynamodb_client, streams_client, raw_streams_client, stream_table): """T equal to a record's own creation millisecond returns that record @@ -464,12 +463,12 @@ def test_future_check_runs_before_shard_existence(self, dynamodb_client, streams ShardIteratorType="AT_TIMESTAMP", Timestamp=int(time.time()) + 3600, ) assert (code, msg) == ("ValidationException", PREFIX + "Timestamp parameter cannot be greater than the current timestamp") - code, _ = _error( + code, msg = _error( raw_streams_client.get_shard_iterator, StreamArn=arn, ShardId="shardId-00000000000000000000-00000000", ShardIteratorType="AT_TIMESTAMP", Timestamp=int(time.time()) - 60, ) - assert code == "ResourceNotFoundException" + assert (code, msg) == ("ResourceNotFoundException", "Requested resource not found: Shard does not exist") assert shard # the real shard still exists def test_near_future_is_accepted(self, dynamodb_client, streams_client, stream_table): @@ -481,9 +480,9 @@ def test_near_future_is_accepted(self, dynamodb_client, streams_client, stream_t Timestamp=datetime.fromtimestamp(time.time() + 0.5, tz=timezone.utc), ) assert "ShardIterator" in resp - code, _ = _error( + code, msg = _error( streams_client.get_shard_iterator, StreamArn=arn, ShardId=shard, ShardIteratorType="AT_TIMESTAMP", Timestamp=datetime.fromtimestamp(time.time() + 5, tz=timezone.utc), ) - assert code == "ValidationException" + assert (code, msg) == ("ValidationException", PREFIX + "Timestamp parameter cannot be greater than the current timestamp") From d75f1f595afa3b8a65adb891e806d17374541c79 Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:10:07 +0000 Subject: [PATCH 13/14] docs(streams): list AT_TIMESTAMP and the sample's EXTENDDB_STREAM_SINCE The iterator type lists in the design guide, REQ-STREAM-003 and the MongoDB storage design gain AT_TIMESTAMP. The sample's usage docstring and its walkthrough describe EXTENDDB_STREAM_SINCE, which the sample reads to start each shard with AT_TIMESTAMP. --- .../skills/extenddb/references/samples/03-stream-consumer.md | 4 +++- docs/design/01-requirements.md | 2 +- docs/design/13-storage-mongodb.md | 3 ++- docs/manuals/02-design-guide.md | 1 + samples/stream_consumer.py | 4 ++++ 5 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.agents/skills/extenddb/references/samples/03-stream-consumer.md b/.agents/skills/extenddb/references/samples/03-stream-consumer.md index 9737b1b21..d1f5df8ac 100644 --- a/.agents/skills/extenddb/references/samples/03-stream-consumer.md +++ b/.agents/skills/extenddb/references/samples/03-stream-consumer.md @@ -17,6 +17,8 @@ export AWS_CA_BUNDLE=~/.extenddb/tls/cert.pem Note: `samples/stream_consumer.py` reads its endpoint from `EXTENDDB_TEST_ENDPOINT` rather than `EXTENDDB_ENDPOINT`. Set both to the same value, or export `EXTENDDB_TEST_ENDPOINT` in place of `EXTENDDB_ENDPOINT` before running this sample. +One optional variable: `EXTENDDB_STREAM_SINCE`, an epoch time in seconds. When set, the poller starts each shard at the first record created at or after that time (`AT_TIMESTAMP`) instead of the oldest retained record (`TRIM_HORIZON`). + ## 3. Run command ```bash @@ -41,7 +43,7 @@ The sample runs three phases on a freshly created table, with a poller thread re 1. **Create a table with streams enabled.** The main thread calls `CreateTable` with a `StreamSpecification` of `StreamEnabled=True` and `StreamViewType=NEW_AND_OLD_IMAGES`, then waits for the table to reach `ACTIVE`. 2. **Discover the stream ARN.** The poller thread calls `DescribeTable` in a loop and reads `Table.LatestStreamArn`. The ARN appears once the stream is provisioned. -3. **Iterate shards.** The poller calls `DescribeStream` on the `dynamodbstreams` client to list shards, then calls `GetShardIterator` with `ShardIteratorType=TRIM_HORIZON` for each new shard. It periodically refreshes the shard list to pick up splits. +3. **Iterate shards.** The poller calls `DescribeStream` on the `dynamodbstreams` client to list shards, then calls `GetShardIterator` for each new shard: with `ShardIteratorType=AT_TIMESTAMP` and `Timestamp=EXTENDDB_STREAM_SINCE` when that variable is set, otherwise with `ShardIteratorType=TRIM_HORIZON`. It periodically refreshes the shard list to pick up splits. 4. **Read records.** The poller calls `GetRecords` on each shard iterator, advances to `NextShardIterator`, and prints one line per record. 5. **Writer phases.** A separate writer thread runs three sequential phases on items `item-1` through `item-5`: `PutItem` inserts (event `INSERT`), `UpdateItem` changes (event `MODIFY`), then `DeleteItem` removes (event `REMOVE`). 6. **Cleanup.** When the writer completes, the main thread gives the poller five seconds to drain, signals stop, and deletes the table. diff --git a/docs/design/01-requirements.md b/docs/design/01-requirements.md index dd1358d9a..282e0dbd5 100755 --- a/docs/design/01-requirements.md +++ b/docs/design/01-requirements.md @@ -219,7 +219,7 @@ These are the core CRUD operations. All must be fully implemented. **Key requirements:** - REQ-STREAM-001: Support all four stream view types: KEYS_ONLY, NEW_IMAGE, OLD_IMAGE, NEW_AND_OLD_IMAGES - REQ-STREAM-002: Stream records must capture changes from PutItem, UpdateItem, DeleteItem, BatchWriteItem, TransactWriteItems -- REQ-STREAM-003: Support shard iterator types: TRIM_HORIZON, LATEST, AT_SEQUENCE_NUMBER, AFTER_SEQUENCE_NUMBER +- REQ-STREAM-003: Support shard iterator types: TRIM_HORIZON, LATEST, AT_SEQUENCE_NUMBER, AFTER_SEQUENCE_NUMBER, AT_TIMESTAMP - REQ-STREAM-004: Stream records must be ordered by sequence number within a shard - REQ-STREAM-005: Detailed shard management and retention design is deferred diff --git a/docs/design/13-storage-mongodb.md b/docs/design/13-storage-mongodb.md index f43516099..ce7a9d493 100644 --- a/docs/design/13-storage-mongodb.md +++ b/docs/design/13-storage-mongodb.md @@ -1059,7 +1059,8 @@ The backend implements every trait in `extenddb-storage`: subset. - `StreamEngine` — session-scoped per-shard sequence numbers, four shards per stream, CRC32 pk routing, TRIM_HORIZON / LATEST / - AT_SEQUENCE_NUMBER / AFTER_SEQUENCE_NUMBER iterators, 24h retention. + AT_SEQUENCE_NUMBER / AFTER_SEQUENCE_NUMBER / AT_TIMESTAMP iterators, + 24h retention. - `MetadataEngine` — TTL lifecycle, tags, table-size tracking. - `BackupEngine` — CreateBackup, RestoreTableFromBackup, DeleteBackup via server-side `$out` aggregation. diff --git a/docs/manuals/02-design-guide.md b/docs/manuals/02-design-guide.md index 5e489365d..e28cb66a3 100755 --- a/docs/manuals/02-design-guide.md +++ b/docs/manuals/02-design-guide.md @@ -150,6 +150,7 @@ Each stream has a fixed set of shards (currently 4 shards per stream). On Postgr - `LATEST`: Start from the most recent record - `AT_SEQUENCE_NUMBER`: Start at a specific sequence number - `AFTER_SEQUENCE_NUMBER`: Start after a specific sequence number +- `AT_TIMESTAMP`: Start at the first record created at or after the `Timestamp` (epoch seconds, rounded to the millisecond) Iterators expire after 15 minutes of inactivity. diff --git a/samples/stream_consumer.py b/samples/stream_consumer.py index 2b254c6ae..5a067cbe0 100755 --- a/samples/stream_consumer.py +++ b/samples/stream_consumer.py @@ -9,6 +9,10 @@ Usage: EXTENDDB_TEST_ENDPOINT=http://localhost:18443 python samples/stream_consumer.py + + EXTENDDB_STREAM_SINCE, an epoch time in seconds, is optional. When set, + the poller starts each shard at the first record created at or after + that time (AT_TIMESTAMP) instead of the oldest one (TRIM_HORIZON). """ from __future__ import annotations From ed4269f793fa6e7d3273699257e78e004316a4bd Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:20:06 +0000 Subject: [PATCH 14/14] test(storage-postgres): allow the fixture's unused re-exports in the seek test The shared fixture re-exports the types the stream disable tests use. The seek test uses its scratch database and shard helpers only, so clippy's `-D warnings` failed on the `StreamStatus` re-export. The module declaration allows unused imports. --- crates/storage-postgres/tests/stream_at_timestamp.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/storage-postgres/tests/stream_at_timestamp.rs b/crates/storage-postgres/tests/stream_at_timestamp.rs index 41404d323..47641f97b 100644 --- a/crates/storage-postgres/tests/stream_at_timestamp.rs +++ b/crates/storage-postgres/tests/stream_at_timestamp.rs @@ -11,7 +11,10 @@ //! `postgres://user:pass@127.0.0.1:5432`); skips otherwise. The test builds //! its own scratch database and drops it afterwards. +// The fixture re-exports the types the stream disable tests need; this test +// uses its scratch database and shard helpers only. #[path = "common/stream_disable_fixture.rs"] +#[allow(unused_imports)] mod fixture; use fixture::*;