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/crates/core/src/error/messages.rs b/crates/core/src/error/messages.rs index 18d3e521d..c99a20a64 100755 --- a/crates/core/src/error/messages.rs +++ b/crates/core/src/error/messages.rs @@ -15,20 +15,34 @@ 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("; ") ) } +/// 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 499f20fb5..4e15e3bed 100755 --- a/crates/core/src/error/mod.rs +++ b/crates/core/src/error/mod.rs @@ -2,7 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 mod messages; -pub use messages::{ErrorMessageKey, error_message, validation_error, validation_errors}; +pub use messages::{ + ErrorMessageKey, INVALID_STREAM_ARN, error_message, validation_error, validation_errors, + validation_errors_detected, +}; use crate::types::{CancellationReason, Item}; 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 10cee947d..061f68cbd 100755 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -48,6 +48,7 @@ mod search_vectors; mod start_key; pub mod stream_capture; mod streams; +mod streams_iterator_params; mod tagging; mod transact_get_items; mod transact_write_helpers; @@ -298,13 +299,9 @@ pub(crate) fn validate_enum_fields( if errors.is_empty() { return Ok(()); } - let count = errors.len(); - let msg = format!( - "{count} validation error{} detected: {}", - if count == 1 { "" } else { "s" }, - errors.join("; ") - ); - Err(DynamoDbError::ValidationException(msg)) + Err(DynamoDbError::ValidationException( + extenddb_core::error::validation_errors_detected(&errors), + )) } /// Validate the `ReturnValues` field for `PutItem` / `DeleteItem`, which accept diff --git a/crates/engine/src/streams.rs b/crates/engine/src/streams.rs index f9ac9fed6..e5a1da58f 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`. /// @@ -100,6 +101,13 @@ 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, 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 /// /// Returns [`DynamoDbError::ResourceNotFoundException`] if the stream/shard does not exist. @@ -108,39 +116,22 @@ 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()))?; + iterator_params::check_member_shapes(&body)?; + constraint_violations(&body)?; - // 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 input: GetShardIteratorInput = + serde_json::from_value(body).map_err(crate::deserialize_error)?; 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. ctx.storage .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 { ShardIteratorType::TrimHorizon => String::new(), ShardIteratorType::Latest => { @@ -153,36 +144,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. - // Measured 2026-10-24 for AT_SEQUENCE_NUMBER; AFTER_SEQUENCE_NUMBER - // without a number is not measured and keeps its sentence below. - let raw = input.sequence_number.clone().ok_or_else(|| { - DynamoDbError::ValidationException( - "One or more parameter values were invalid: SequenceNumber cannot be null" - .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? } }; @@ -192,8 +165,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() @@ -213,6 +186,89 @@ pub async fn handle_get_shard_iterator( serialize_output(&output) } +/// 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") + .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()); + } + _ => {} + } + 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(()); + } + Err(DynamoDbError::ValidationException( + extenddb_core::error::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). +/// +/// 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()), + } +} + /// The answer when the shard a `GetShardIterator` names is not found: for a /// `ShardId` of `shard_len` characters over the service's maximum, the model's /// constraint sentence (the service checks it before any lookup, and never has @@ -241,14 +297,15 @@ 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}" - ) + extenddb_core::error::validation_errors_detected(&[clause(member, 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"; +/// 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}") +} /// The message `DynamoDB` returns for an expired shard iterator (measured live, /// `live-r2/iter-live.json`: an iterator 990 seconds old returns diff --git a/crates/engine/src/streams_iterator_params.rs b/crates/engine/src/streams_iterator_params.rs new file mode 100644 index 000000000..321beb42e --- /dev/null +++ b/crates/engine/src/streams_iterator_params.rs @@ -0,0 +1,574 @@ +// 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 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. +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]"; + +/// 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 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 { + 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. +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; + +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. +/// +/// 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> { + 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)) + } + 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) + } + ShardIteratorType::TrimHorizon | ShardIteratorType::Latest => { + if input.timestamp.is_some() { + return refuse("Timestamp should not be passed for this iterator type"); + } + Ok(None) + } + } +} + +/// `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(()) +} + +/// 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 { + // 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 +/// 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 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, `.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 `.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_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 { + 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:?}"), + } + } + + 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, + }; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs_f64(); + let past = 1_792_764_148.0; + let future = now + 3_600.0; + type Row = ( + ShardIteratorType, + Option<&'static str>, + Option, + 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)), + (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:?}" + ), + } + } + } + + /// 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(got.map(|()| None)), + format!("One or more parameter values were invalid: {SEQ_REFUSED}") + ); + assert!(super::refuse_sequence_number_after_shard(&input(t, None, None)).is_ok()); + } + for t in [AtTimestamp, AtSequenceNumber] { + assert!(super::refuse_sequence_number_after_shard(&input(t, Some("1"), None)).is_ok()); + } + } + + /// 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 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 + + /// 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_eq!( + message(v(&input( + ShardIteratorType::AtTimestamp, + None, + Some(now + 2.0) + ))), + format!("One or more parameter values were invalid: {FUTURE}") + ); + } + + /// 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/engine/src/streams_tests.rs b/crates/engine/src/streams_tests.rs index 1504421fd..47f6ef771 100644 --- a/crates/engine/src/streams_tests.rs +++ b/crates/engine/src/streams_tests.rs @@ -4,32 +4,6 @@ //! Unit tests for the streams request handlers: iterator tokens, the measured //! constraint sentences and the not-found answers. -/// 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"; @@ -134,11 +108,132 @@ fn the_shard_id_maximum_applies_once_the_shard_is_not_found() { } } +/// 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; + 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"; + 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!({"StreamArn": arn, "ShardId": "shardId-short"}), + Some(format!("2 validation errors detected: {NULL}; {SHARD}")), + ), + ( + json!({"StreamArn": arn, "ShardId": "shardId-short", "ShardIteratorType": null}), + Some(format!("2 validation errors detected: {NULL}; {SHARD}")), + ), + ( + json!({"StreamArn": arn, "ShardId": "shardId-short", "ShardIteratorType": "BOGUS"}), + Some(format!( + "2 validation errors detected: {}; {SHARD}", + super::iterator_params::SHARD_ITERATOR_TYPE_ENUM_CLAUSE + )), + ), + ( + json!({"StreamArn": arn, "ShardId": long, "SequenceNumber": "0"}), + Some(format!("2 validation errors detected: {SEQ}; {NULL}")), + ), + ( + json!({"StreamArn": arn, "ShardId": "shardId-short", "SequenceNumber": "0"}), + Some(format!( + "3 validation errors detected: {SEQ}; {NULL}; {SHARD}" + )), + ), + ( + json!({"StreamArn": arn, "ShardId": long, "Timestamp": 1792764248.0}), + Some(format!("1 validation error detected: {NULL}")), + ), + ( + json!({"StreamArn": arn, "ShardId": long, "ShardIteratorType": "at_timestamp"}), + Some(format!( + "1 validation error detected: {}", + super::iterator_params::SHARD_ITERATOR_TYPE_ENUM_CLAUSE + )), + ), + ( + 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!({"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!({"StreamArn": arn, "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() { + // `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/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/crates/storage-cassandra/src/lib.rs b/crates/storage-cassandra/src/lib.rs index 5d2c81b46..71f0f9bb7 100644 --- a/crates/storage-cassandra/src/lib.rs +++ b/crates/storage-cassandra/src/lib.rs @@ -41,6 +41,7 @@ mod password_hash_store; pub(crate) mod propagation_hold; mod restore_engine; mod snapshot_engine; +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 new file mode 100644 index 000000000..77a74fb8b --- /dev/null +++ b/crates/storage-cassandra/src/stream_at_timestamp.rs @@ -0,0 +1,121 @@ +// 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::cassandra_util::query_rows; +use crate::engine::CassandraEngine; + +/// The smallest sequence number whose millisecond prefix is `at_ms`. +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 {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), + }; + // 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() + .and_then(|row| row.get_r_by_name("sequence_number").ok())) + } +} + +#[cfg(test)] +mod tests { + 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() { + 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 99b8055f0..a928fb9da 100755 --- a/crates/storage-cassandra/src/stream_engine.rs +++ b/crates/storage-cassandra/src/stream_engine.rs @@ -25,7 +25,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}")) @@ -393,4 +396,16 @@ impl StreamEngine for CassandraEngine { self.last_sequence_in(&keyspace, &range).await }) } + + 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/stream_at_timestamp.rs b/crates/storage-cassandra/tests/direct/stream_at_timestamp.rs new file mode 100644 index 000000000..e6b9e8772 --- /dev/null +++ b/crates/storage-cassandra/tests/direct/stream_at_timestamp.rs @@ -0,0 +1,210 @@ +// 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: 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_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 +/// 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 989848a9e..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, 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"] diff --git a/crates/storage-mongodb/src/lib.rs b/crates/storage-mongodb/src/lib.rs index 24c08b6c1..ab9750f95 100644 --- a/crates/storage-mongodb/src/lib.rs +++ b/crates/storage-mongodb/src/lib.rs @@ -26,6 +26,7 @@ mod password_hash_store; pub mod pushdown; mod restore_engine; mod snapshot_engine; +mod stream_at_timestamp; mod stream_engine; mod stream_lifecycle; mod table_engine; 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 7309a5c9d..ea19158a9 100644 --- a/crates/storage-mongodb/src/stream_engine.rs +++ b/crates/storage-mongodb/src/stream_engine.rs @@ -546,6 +546,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-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/src/lib.rs b/crates/storage-postgres/src/lib.rs index 237fcf728..8707c14d9 100755 --- a/crates/storage-postgres/src/lib.rs +++ b/crates/storage-postgres/src/lib.rs @@ -33,6 +33,7 @@ mod snapshot_engine; pub use snapshot_engine::{ MIN_NEXT_PAGE_ROWS, MIN_PAGE_ROWS, SNAPSHOT_SLOT_BOUND, map_fetch_error, page_sql_for, }; +mod stream_at_timestamp; mod stream_engine; mod stream_lifecycle; #[doc(hidden)] 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 07136eac5..2736442f3 100755 --- a/crates/storage-postgres/src/stream_engine.rs +++ b/crates/storage-postgres/src/stream_engine.rs @@ -721,6 +721,21 @@ 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 { + // 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 + }) + } } impl PostgresEngine { 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..47641f97b --- /dev/null +++ b/crates/storage-postgres/tests/stream_at_timestamp.rs @@ -0,0 +1,87 @@ +// 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. + +// 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::*; + +/// 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/lib.rs b/crates/storage-sqlite/src/lib.rs index b0c5fa050..58b08f951 100644 --- a/crates/storage-sqlite/src/lib.rs +++ b/crates/storage-sqlite/src/lib.rs @@ -47,6 +47,7 @@ mod snapshot_engine; mod sqlite_util; mod store; mod stream; +mod stream_at_timestamp; mod stream_lifecycle; #[cfg(test)] mod stream_tests; diff --git a/crates/storage-sqlite/src/stream.rs b/crates/storage-sqlite/src/stream.rs index c273d9a6f..595d7a636 100644 --- a/crates/storage-sqlite/src/stream.rs +++ b/crates/storage-sqlite/src/stream.rs @@ -341,6 +341,18 @@ 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 + }) + } } impl SqliteEngine { 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-sqlite/src/stream_tests.rs b/crates/storage-sqlite/src/stream_tests.rs index 3630e48e7..753c8e68f 100644 --- a/crates/storage-sqlite/src/stream_tests.rs +++ b/crates/storage-sqlite/src/stream_tests.rs @@ -462,3 +462,59 @@ 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. 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; + 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, 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 = 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/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index 8773caea0..7580c0bc1 100755 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -722,6 +722,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/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/07-component-streams.md b/docs/design/07-component-streams.md index e80379495..47d7bdeb1 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/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/differences-from-dynamodb.md b/docs/differences-from-dynamodb.md index c44479284..33ac80bb4 100755 --- a/docs/differences-from-dynamodb.md +++ b/docs/differences-from-dynamodb.md @@ -60,6 +60,13 @@ from a request sent to that service or backend. | U+0000 in a key attribute name, an index key attribute name or a projected attribute name | Accepted; `DescribeTable` returns each name byte for byte (measured 2026-09-18 and 2026-10-24, and again on 2026-11-04) | The same on all four backends. PostgreSQL `jsonb` cannot hold U+0000, so a PostgreSQL deployment stores these names through an escape, U+0000 as U+0001 U+0001 and U+0001 as U+0001 U+0002. Catalog migration 11 applies the escape to the names an earlier release stored (see the [Upgrade Manual](manuals/07-upgrade-manual.md#general-upgrade-procedure)) | | Stream disable and enable | `UpdateTable StreamEnabled=false` answers `UPDATING`; the stream reports `DISABLED` a few seconds later with every shard closed, and every write acknowledged before that lands in the closed stream. `StreamEnabled=true` afterwards creates a new stream with a later label; both streams stay listed, and a disabled stream stays describable after its table is deleted | The shards close inside the `UpdateTable` call and the response says `ACTIVE`. A write that reaches storage after the close is acknowledged and recorded in no stream (on MongoDB it is recorded past the shard's `EndingSequenceNumber` instead); the window is one write wide. A disabled stream is removed with its table. A stream created by a release before this one loses its ARN once the table is disabled and re-enabled (its label lived only in the table row) | +## Streams + +| Area | DynamoDB | ExtendDB | +|------|----------|------| +| 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) | Area | DynamoDB | ExtendDB | 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/docs/manuals/03-usage-guide.md b/docs/manuals/03-usage-guide.md index fe1b4f67b..8f04d34aa 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-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..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 @@ -125,11 +129,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..176e6eee9 --- /dev/null +++ b/tests/test_streams_at_timestamp.py @@ -0,0 +1,488 @@ +# 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 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. + +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 + +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: " + + +REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") + + +def _client(service: str, endpoint_url: str | None, validate: bool = True): + kwargs: dict = dict( + service_name=service, + region_name=REGION, + config=Config(parameter_validation=validate, retries={"max_attempts": 1}), + ) + if endpoint_url: + kwargs["endpoint_url"] = endpoint_url + 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 | None, body: dict) -> tuple[str, str]: + """POST a GetShardIterator body exactly as given, SigV4-signed with the + 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 + + url = endpoint_url or f"https://streams.dynamodb.{REGION}.amazonaws.com/" + data = json.dumps(body).encode() + req = AWSRequest(method="POST", url=url, data=data, headers={ + "Content-Type": "application/x-amz-json-1.0", + "X-Amz-Target": "DynamoDBStreams_20120810.GetShardIterator", + }) + 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() + 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: + 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:] + # 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 + (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: + # 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. + 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" + # 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 + _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, 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, 0.0004, 0.00049, -0.0004): + 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_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 = [ + ({"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 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, 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: + """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"), + (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, msg) == ("ValidationException", f"1 validation error detected: {enum_clause}") + # 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 = [ + ({"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, 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 + _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, msg = _error( + raw_streams_client.get_shard_iterator, + StreamArn=arn, ShardId="shardId-00000000000000000000-00000000", + ShardIteratorType="AT_TIMESTAMP", Timestamp=int(time.time()) - 60, + ) + 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): + 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, 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, msg) == ("ValidationException", PREFIX + "Timestamp parameter cannot be greater than the current timestamp")