Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
7 changes: 0 additions & 7 deletions crates/storage-sqlite/src/sqlite_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,13 +152,6 @@ mod tests {
// Text order equals time order against a default-shaped neighbour.
assert!(s.as_str() < "2026-10-23T14:19:07.124Z");
assert!(s.as_str() > "2026-10-23T14:19:06.999Z");
// Against the retention cutoff (RFC 3339 from the `time` crate, no
// fraction on a whole second) the comparison is decided by the second
// digits in every case but the cutoff's own second, where `Z` sorts
// after `.`; that edge predates this formatter and is the default's
// behaviour too.
let cutoff = format_timestamp(OffsetDateTime::from_unix_timestamp(1_792_765_146).unwrap());
assert!(s.as_str() > cutoff.as_str(), "{s} vs {cutoff}");
}

/// A millisecond value `time` cannot represent is stamped with the current
Expand Down
69 changes: 57 additions & 12 deletions crates/storage-sqlite/src/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
//! so `init_stream_shards` (`stream_lifecycle.rs`) runs in the caller's
//! catalog transaction. Monotonic sequence numbers come from the
//! `seq_counters` table (there is no PostgreSQL sequence). Retention cleanup
//! compares an RFC 3339 cutoff computed in Rust.
//! compares a text cutoff computed in Rust in the millisecond shape of the
//! `created_at` column.

use extenddb_core::types::{DescribeStreamInput, StreamDescription, StreamRecord};
use extenddb_storage::error::StorageError;
Expand All @@ -16,9 +17,59 @@ use extenddb_storage::util::{parse_stream_arn, shard_in_stream, stream_arn};
use extenddb_storage::{StreamEngine, StreamListResult, StreamRecordsResult};
use futures::future::BoxFuture;

use crate::sqlite_util::format_timestamp;
use crate::sqlite_util::format_epoch_millis;
use crate::store::SqliteEngine;

/// Retention cutoff for `stream_records.created_at`: `now` minus
/// `retention_hours`, rendered in the column's own millisecond shape
/// (`2026-10-23T14:19:07.000Z`). The sweep compares text, so the cutoff has to
/// carry the same three fraction digits as the rows. An RFC 3339 cutoff drops
/// the fraction on a whole second (`...07Z`), and `Z` sorts after `.`, which
/// put every row of that second (`...07.000Z` to `...07.999Z`) before the
/// cutoff and deleted them up to 999 ms early.
fn retention_cutoff(now: time::OffsetDateTime, retention_hours: i64) -> String {
let cutoff = now - time::Duration::hours(retention_hours);
let cutoff_ms = cutoff
.unix_timestamp()
.saturating_mul(1_000)
.saturating_add(i64::from(cutoff.millisecond()));
format_epoch_millis(cutoff_ms)
}

/// Delete every stream record whose `created_at` sorts before `cutoff`; both
/// sides are text in the column's shape. Returns the number of rows deleted.
async fn delete_stream_records_before(
pool: &sqlx::SqlitePool,
cutoff: &str,
) -> Result<u64, StorageError> {
let result = sqlx::query("DELETE FROM stream_records WHERE created_at < ?")
.bind(cutoff)
.execute(pool)
.await
.map_err(|e| StorageError::Internal(e.to_string()))?;
Ok(result.rows_affected())
}

impl SqliteEngine {
/// The retention sweep with the clock passed in: takes the engine write
/// lock, renders the cutoff from `now`, deletes the rows before it and
/// returns the count. The trait method calls this with the wall clock;
/// tests call it with a fixed `now` so the production path is what runs.
/// The trait method reads the clock before this takes the lock, so a

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. The sentence holds for records stamped in milliseconds, as the PutItem path stamps them. A record written through write_stream_record (line 74) carries a whole-second created_at, and at retention 0 such a record written in the cutoff's own second is deleted (3 of 3 runs). The worker always passes 24 hours, and nothing in the workspace calls write_stream_record, so no request reaches this. "a record the write path stamps while the sweep waits" would scope it.

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. The sentence holds for records stamped in milliseconds, which is how the PutItem path stamps them. write_stream_record has no caller in the workspace, and the worker passes 24 hours, so no request reaches the whole-second case. I'll scope the sentence to records the write path stamps in a follow-up after this PR merges, so that your approval stands.

/// record written while the sweep waits for the lock is newer than the
/// cutoff and stays.
pub(crate) async fn cleanup_expired_stream_records_at(
&self,
now: time::OffsetDateTime,
retention_hours: i64,
) -> Result<u64, StorageError> {
// D1: every writer holds the engine write lock.
let _writer = self.write_lock.lock().await;
let cutoff = retention_cutoff(now, retention_hours);
delete_stream_records_before(&self.pool, &cutoff).await
}
}

impl StreamEngine for SqliteEngine {
fn write_stream_record(
&self,
Expand Down Expand Up @@ -219,17 +270,8 @@ impl StreamEngine for SqliteEngine {
retention_hours: i64,
) -> BoxFuture<'_, Result<u64, StorageError>> {
Box::pin(async move {
// D1: every writer holds the engine write lock.
let _writer = self.write_lock.lock().await;
let cutoff = format_timestamp(
time::OffsetDateTime::now_utc() - time::Duration::hours(retention_hours),
);
let result = sqlx::query("DELETE FROM stream_records WHERE created_at < ?")
.bind(&cutoff)
.execute(&self.pool)
self.cleanup_expired_stream_records_at(time::OffsetDateTime::now_utc(), retention_hours)

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.

No test reaches this line. The worker calls this trait method. With this body replaced by the previous inline cutoff code, by retention_hours + 1, or by a lock followed by Ok(0), the storage-sqlite lib suite passes 313 of 313 each time. A test that calls StreamEngine::cleanup_expired_stream_records(&engine, 24) on rows stamped 24.5 h and 23.5 h before now and asserts one deletion fails under the second and third changes with left: 0, right: 1.

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.

Added the_worker_entry_point_deletes_only_records_past_the_retention in 5197767. It stamps one record 24.5 hours and one 23.5 hours before now, sweeps through StreamEngine::cleanup_expired_stream_records(&engine, 24) and expects one deletion. Before it, the lib suite passed with the trait method at retention_hours + 1 and with a lock followed by Ok(0). With the test, both fail with left: 0, right: 1.

.await
.map_err(|e| StorageError::Internal(e.to_string()))?;
Ok(result.rows_affected())
})
}

Expand Down Expand Up @@ -362,3 +404,6 @@ impl SqliteEngine {
Ok(found != 0)
}
}

#[cfg(test)]
mod retention_cutoff_tests;
140 changes: 140 additions & 0 deletions crates/storage-sqlite/src/stream/retention_cutoff_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
// Copyright 2026 ExtendDB contributors
// SPDX-License-Identifier: Apache-2.0

//! Unit tests for the stream retention cutoff and sweep in `super`.

use super::retention_cutoff;
use crate::SqliteEngine;
use crate::sqlite_util::format_epoch_millis;
use extenddb_storage::StreamEngine;
use time::OffsetDateTime;

/// 2026-10-24T14:19:07Z: a `now` with a zero sub-second, so the cutoff 24
/// hours earlier lands on the whole second 2026-10-23T14:19:07Z.
const WHOLE_SECOND_NOW: i64 = 1_792_851_547;

/// The cutoff carries the column's three fraction digits even on a whole
/// second, so same-second rows do not sort before it.
#[test]
fn cutoff_on_a_whole_second_keeps_the_column_shape() {
let now = OffsetDateTime::from_unix_timestamp(WHOLE_SECOND_NOW).expect("now");
let cutoff = retention_cutoff(now, 24);
assert_eq!(cutoff, "2026-10-23T14:19:07.000Z");
assert!("2026-10-23T14:19:07.000Z" >= cutoff.as_str());
assert!("2026-10-23T14:19:07.123Z" > cutoff.as_str());
assert!("2026-10-23T14:19:06.999Z" < cutoff.as_str());
}

/// A `now` with a fraction renders the fraction, same width.
#[test]
fn cutoff_with_a_fraction_keeps_the_column_shape() {
let now = OffsetDateTime::from_unix_timestamp_nanos(
i128::from(WHOLE_SECOND_NOW) * 1_000_000_000 + 456_000_000,
)
.expect("now");
assert_eq!(retention_cutoff(now, 24), "2026-10-23T14:19:07.456Z");
assert_eq!(retention_cutoff(now, 0), "2026-10-24T14:19:07.456Z");

// A fraction with a trailing zero keeps all three digits. RFC 3339
// rendering dropped it (`07.45Z`), and `07.450Z` to `07.459Z` sort before
// `07.45Z` as text, so those rows were deleted early as well.
let now_450 = OffsetDateTime::from_unix_timestamp_nanos(
i128::from(WHOLE_SECOND_NOW) * 1_000_000_000 + 450_000_000,
)
.expect("now");
let cutoff = retention_cutoff(now_450, 24);
assert_eq!(cutoff, "2026-10-23T14:19:07.450Z");
assert!("2026-10-23T14:19:07.450Z" >= cutoff.as_str());
assert!("2026-10-23T14:19:07.459Z" > cutoff.as_str());
}

/// An in-memory engine with one table and one shard, holding a stream record
/// per `created_at` value.
async fn engine_with_records(created_at: &[&str]) -> SqliteEngine {
let engine = SqliteEngine::new(":memory:", 1, "us-east-1", 409_600)
.await
.expect("engine");
crate::migrations::apply_for_tests(&engine.pool).await;
sqlx::query(
"INSERT INTO accounts (account_id, account_name) VALUES ('000000000000', 'default')",
)
.execute(&engine.pool)
.await
.expect("account");
sqlx::query(
"INSERT INTO tables (account_id, table_name, key_schema, attribute_definitions, \
table_arn, table_id) VALUES ('000000000000', 't', '[]', '[]', 'arn', 'tid')",
)
.execute(&engine.pool)
.await
.expect("table");
sqlx::query(
"INSERT INTO stream_shards (shard_id, table_id, starting_sequence_number) \
VALUES ('shard-1', 'tid', '1')",
)
.execute(&engine.pool)
.await
.expect("shard");
for (seq, created_at) in created_at.iter().enumerate() {
sqlx::query(
"INSERT INTO stream_records (shard_id, sequence_number, table_id, event_name, \
record_data, created_at) VALUES ('shard-1', ?, 'tid', 'INSERT', '{}', ?)",
)
.bind((seq + 1).to_string())
.bind(created_at)
.execute(&engine.pool)
.await
.expect("record");
}
engine
}

/// The `created_at` values left in `stream_records`, oldest first.
async fn remaining(engine: &SqliteEngine) -> Vec<String> {
sqlx::query_scalar::<_, String>("SELECT created_at FROM stream_records ORDER BY created_at")
.fetch_all(&engine.pool)
.await
.expect("remaining")
}

/// Rows in the cutoff's own second survive the sweep; only the row in the
/// previous second is deleted.
#[tokio::test]
async fn sweep_on_a_whole_second_keeps_same_second_rows() {
let engine = engine_with_records(&[
"2026-10-23T14:19:06.999Z",
"2026-10-23T14:19:07.000Z",
"2026-10-23T14:19:07.123Z",
])
.await;

let now = OffsetDateTime::from_unix_timestamp(WHOLE_SECOND_NOW).expect("now");
let deleted = engine
.cleanup_expired_stream_records_at(now, 24)
.await
.expect("sweep");
assert_eq!(deleted, 1);
assert_eq!(
remaining(&engine).await,
["2026-10-23T14:19:07.000Z", "2026-10-23T14:19:07.123Z"]
);
}

/// The retention worker's entry point sweeps with the wall clock and the
/// retention it is given: a record stamped 24.5 hours ago is deleted and one
/// stamped 23.5 hours ago stays.
#[tokio::test]
async fn the_worker_entry_point_deletes_only_records_past_the_retention() {
let now_ms = i64::try_from(OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000)
.expect("now in milliseconds");
let half_hour_ms = 30 * 60 * 1_000;
let older = format_epoch_millis(now_ms - 49 * half_hour_ms);
let newer = format_epoch_millis(now_ms - 47 * half_hour_ms);
let engine = engine_with_records(&[older.as_str(), newer.as_str()]).await;

let deleted = StreamEngine::cleanup_expired_stream_records(&engine, 24)
.await
.expect("sweep");
assert_eq!(deleted, 1);
assert_eq!(remaining(&engine).await, [newer]);
}
Loading