Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
4444bc6
feat(streams): AT_TIMESTAMP shard iterator on all four backends
LeeroyHannigan Oct 29, 2026
b6f4643
Merge origin/main into feat/streams-at-timestamp
LeeroyHannigan Nov 14, 2026
b734787
fix(streams): seek the shard's own range on Cassandra, and adapt AT_T…
LeeroyHannigan Nov 14, 2026
386b9f3
Merge remote-tracking branch 'origin/main' into fb1120/468
LeeroyHannigan Nov 20, 2026
944ebe6
fix(streams): GetShardIterator rounds Timestamp and checks in the ser…
LeeroyHannigan Nov 20, 2026
73d45e8
fix(storage-cassandra): run the AT_TIMESTAMP seek through the policy …
LeeroyHannigan Nov 20, 2026
716aa4e
test(streams): pin the AT_TIMESTAMP boundary to the record's millisecond
LeeroyHannigan Nov 20, 2026
7387d6f
test(streams): sign the raw requests with the default session's crede…
LeeroyHannigan Nov 20, 2026
984ab05
refactor(core): share the validation errors envelope
LeeroyHannigan Nov 20, 2026
65fd853
test(streams): name the parameter table's row type
LeeroyHannigan Nov 20, 2026
34279f4
Merge branch 'main' into feat/streams-at-timestamp
LeeroyHannigan Nov 23, 2026
fc87678
fix(streams): refuse a missing StreamArn and name a missing ShardId i…
LeeroyHannigan Nov 23, 2026
527d811
test(streams): pin the at-or-after seek on PostgreSQL and MongoDB, an…
LeeroyHannigan Nov 23, 2026
6c1203d
fix(storage-cassandra): keep the seek module private and assert the c…
LeeroyHannigan Nov 24, 2026
1f0bf12
test(streams): assert the measured messages and run the guarded probe…
LeeroyHannigan Nov 24, 2026
d75f1f5
docs(streams): list AT_TIMESTAMP and the sample's EXTENDDB_STREAM_SINCE
LeeroyHannigan Nov 24, 2026
ed4269f
test(storage-postgres): allow the fixture's unused re-exports in the …
LeeroyHannigan Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down
18 changes: 16 additions & 2 deletions crates/core/src/error/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = 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 {
Expand Down
5 changes: 4 additions & 1 deletion crates/core/src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down
7 changes: 7 additions & 0 deletions crates/core/src/types/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -201,6 +204,10 @@ pub struct GetShardIteratorInput {
pub shard_iterator_type: ShardIteratorType,
#[serde(rename = "SequenceNumber", default)]
pub sequence_number: Option<String>,
/// Epoch seconds, fractional milliseconds allowed. Used with
/// `AT_TIMESTAMP`; the service refuses it with every other type.
#[serde(rename = "Timestamp", default)]
pub timestamp: Option<f64>,
}

/// `GetShardIterator` response.
Expand Down
11 changes: 4 additions & 7 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down
179 changes: 118 additions & 61 deletions crates/engine/src/streams.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
///
Expand Down Expand Up @@ -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.
Expand All @@ -108,39 +116,22 @@ pub async fn handle_get_shard_iterator(
body: Value,
ctx: &OperationContext,
) -> Result<Value, DynamoDbError> {
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)?;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For TRIM_HORIZON and LATEST, the service checks the shard before it refuses a SequenceNumber. On shardId-00000000000000000000-ffffffff, with SequenceNumber: "1500001062930352702901", the service and main return "ResourceNotFoundException: Requested resource not found: Shard does not exist" in two rounds. This branch returns "SequenceNumber should not be passed for this iterator type". For AT_TIMESTAMP, the service refuses the SequenceNumber before the shard check, so only the TRIM_HORIZON and LATEST refusal moves after validate_shard.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Measured on 2026-11-20: TRIM_HORIZON and LATEST with a SequenceNumber on shardId-00000000000000000000-ffffffff get "Shard does not exist". On a stream that does not exist they get "Stream does not exist". A Timestamp on those types is still refused before the lookup, and AT_TIMESTAMP refuses its SequenceNumber before the lookup. In 944ebe6 the SequenceNumber refusal for TRIM_HORIZON and LATEST runs after the shard lookup, and the wire test covers the missing-shard rows.


// Validate the stream and shard exist before issuing an iterator.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional. With both members of the wrong type, the service reports the one that comes first in the body: "Timestamp": "x" before "SequenceNumber": 5 returns STRING_VALUE cannot be converted to Date (4 of 4), and this head returns the String text. The earlier comment implied a fixed order, and the reply is right that body order decides. Only a hand-built body with two wrong-typed members reaches this.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right. With both members of the wrong type, the service names the one that comes first in the body. With Timestamp first, this head names the SequenceNumber text. Only a hand-built body with two wrong-typed members reaches it. I'll handle it in a follow-up after this PR merges, so that your approval stands.

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 => {
Expand All @@ -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::<u128>().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?
}
};

Expand All @@ -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()
Expand All @@ -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<String, DynamoDbError> {
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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading