diff --git a/crates/storage-sqlite/src/sqlite_util.rs b/crates/storage-sqlite/src/sqlite_util.rs index 624898880..a22b902ff 100644 --- a/crates/storage-sqlite/src/sqlite_util.rs +++ b/crates/storage-sqlite/src/sqlite_util.rs @@ -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 diff --git a/crates/storage-sqlite/src/stream.rs b/crates/storage-sqlite/src/stream.rs index c273d9a6f..19e12c706 100644 --- a/crates/storage-sqlite/src/stream.rs +++ b/crates/storage-sqlite/src/stream.rs @@ -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; @@ -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 { + 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 + /// 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 { + // 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, @@ -219,17 +270,8 @@ impl StreamEngine for SqliteEngine { retention_hours: i64, ) -> BoxFuture<'_, Result> { 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) .await - .map_err(|e| StorageError::Internal(e.to_string()))?; - Ok(result.rows_affected()) }) } @@ -362,3 +404,6 @@ impl SqliteEngine { Ok(found != 0) } } + +#[cfg(test)] +mod retention_cutoff_tests; diff --git a/crates/storage-sqlite/src/stream/retention_cutoff_tests.rs b/crates/storage-sqlite/src/stream/retention_cutoff_tests.rs new file mode 100644 index 000000000..686e3a95a --- /dev/null +++ b/crates/storage-sqlite/src/stream/retention_cutoff_tests.rs @@ -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 { + 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]); +}