From 828ed9a59a82739e91d2cd45a024a8dec77738eb Mon Sep 17 00:00:00 2001 From: Lee Hannigan Date: Sat, 24 Oct 2026 10:05:16 +0000 Subject: [PATCH 1/2] fix(sqlite): render the stream retention cutoff in the created_at column shape The retention sweep deletes stream_records rows with created_at < cutoff as a text comparison. The column default writes three fraction digits (2026-10-23T14:19:07.123Z); the cutoff was RFC 3339 from the time crate, which drops the fraction on a whole second (2026-10-23T14:19:07Z) and a trailing zero (07.450 renders as 07.45Z). '.' sorts before 'Z' and '0' to '9' sort before 'Z', so every row in the cutoff's own second, and every row in a tenth whose cutoff ended in a zero, compared below it and was deleted up to 999 ms early. The cutoff is now rendered with format_epoch_millis in the same 24-character shape as the column. The sweep runs through SqliteEngine::cleanup_expired_stream_records_at(now, retention_hours), which takes the engine write lock, renders the cutoff and deletes; the trait method calls it with the wall clock and the test calls it with a fixed clock, so the production path is the one under test. Unit tests: the cutoff on a whole second renders as ...07.000Z and sorts at or below same-second rows; a cutoff at .450 keeps its three digits; a sweep over rows at 06.999Z, 07.000Z and 07.123Z with the cutoff on second 07 deletes one row and keeps both same-second rows. Closes #464 --- crates/storage-sqlite/src/sqlite_util.rs | 20 ++++ crates/storage-sqlite/src/stream.rs | 65 ++++++++--- .../src/stream/retention_cutoff_tests.rs | 110 ++++++++++++++++++ 3 files changed, 182 insertions(+), 13 deletions(-) create mode 100644 crates/storage-sqlite/src/stream/retention_cutoff_tests.rs diff --git a/crates/storage-sqlite/src/sqlite_util.rs b/crates/storage-sqlite/src/sqlite_util.rs index c37ce480f..de6b46b11 100644 --- a/crates/storage-sqlite/src/sqlite_util.rs +++ b/crates/storage-sqlite/src/sqlite_util.rs @@ -53,6 +53,26 @@ pub(crate) fn format_epoch_seconds(secs: f64) -> String { ) } +/// Format epoch milliseconds in the shape the `stream_records.created_at` +/// column default produces (`strftime('%Y-%m-%dT%H:%M:%fZ')`, millisecond +/// precision, 24 characters): `2026-10-15T12:00:00.438Z`. Same width as the +/// default, so rows written before and after this formatter was introduced +/// sort together as text in time order. +pub(crate) fn format_epoch_millis(ms: i64) -> String { + let dt = OffsetDateTime::from_unix_timestamp_nanos(i128::from(ms) * 1_000_000) + .unwrap_or(OffsetDateTime::UNIX_EPOCH); + format!( + "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z", + dt.year(), + u8::from(dt.month()), + dt.day(), + dt.hour(), + dt.minute(), + dt.second(), + dt.millisecond() + ) +} + /// Epoch seconds, sub-second precision, of a catalog timestamp; 0 if it does /// not parse. #[allow(clippy::cast_precision_loss)] // epoch seconds fit f64's mantissa diff --git a/crates/storage-sqlite/src/stream.rs b/crates/storage-sqlite/src/stream.rs index 62943f678..575b964d6 100644 --- a/crates/storage-sqlite/src/stream.rs +++ b/crates/storage-sqlite/src/stream.rs @@ -6,8 +6,8 @@ //! Shards, records, and the sequence counter all live in the one SQLite file, //! so `init_stream_shards` 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. +//! PostgreSQL sequence). Retention cleanup compares a text cutoff computed in +//! Rust in the millisecond shape of the `created_at` column. use extenddb_core::types::{ DescribeStreamInput, SequenceNumberRange, Shard, StreamDescription, StreamRecord, StreamStatus, @@ -18,13 +18,58 @@ use extenddb_storage::util::{parse_stream_arn, 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; /// Fixed shards per stream (hash-based partition-key assignment). const SHARDS_PER_STREAM: u32 = 4; +/// 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. + 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 + } + /// Initialize stream shards and set `stream_label`, within the caller's /// transaction. Returns the assigned stream label. pub(crate) async fn init_stream_shards( @@ -365,17 +410,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()) }) } @@ -500,3 +536,6 @@ impl StreamEngine for SqliteEngine { }) } } + +#[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..e4b2924a6 --- /dev/null +++ b/crates/storage-sqlite/src/stream/retention_cutoff_tests.rs @@ -0,0 +1,110 @@ +// 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 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()); +} + +/// 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 = SqliteEngine::new(":memory:", 1, "us-east-1", 409_600) + .await + .expect("engine"); + crate::schema::apply(&engine.pool).await.expect("schema"); + 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 [ + ("1", "2026-10-23T14:19:06.999Z"), + ("2", "2026-10-23T14:19:07.000Z"), + ("3", "2026-10-23T14:19:07.123Z"), + ] { + 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) + .bind(created_at) + .execute(&engine.pool) + .await + .expect("record"); + } + + 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); + + let remaining: Vec<(String,)> = + sqlx::query_as("SELECT created_at FROM stream_records ORDER BY created_at") + .fetch_all(&engine.pool) + .await + .expect("remaining"); + let remaining: Vec<&str> = remaining.iter().map(|(s,)| s.as_str()).collect(); + assert_eq!( + remaining, + ["2026-10-23T14:19:07.000Z", "2026-10-23T14:19:07.123Z"] + ); +} From 5197767b2b43c1a89091cc64a1f5dfb5c500907f Mon Sep 17 00:00:00 2001 From: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:04:30 +0000 Subject: [PATCH 2/2] test(sqlite): sweep stream records through the retention worker's entry point The retention tests called cleanup_expired_stream_records_at with a fixed clock. The one test that called StreamEngine::cleanup_expired_stream_records, which the worker runs, checked the write lock and discarded the count. So nothing checked what that method deletes. The storage-sqlite lib tests passed with it sweeping at retention_hours + 1, and with it taking the lock and returning 0. A new test stamps one record 24.5 hours before now and one 23.5 hours before now. It sweeps through the trait method with a retention of 24 hours, and expects one deletion. The epoch_millis test in sqlite_util.rs compared a row with an RFC 3339 cutoff from format_timestamp and described its same-second edge. The sweep's cutoff now comes from retention_cutoff, so that comparison and its comment are gone. The doc comment of cleanup_expired_stream_records_at says that the trait method reads the clock before the sweep takes the lock. --- crates/storage-sqlite/src/sqlite_util.rs | 7 -- crates/storage-sqlite/src/stream.rs | 3 + .../src/stream/retention_cutoff_tests.rs | 66 ++++++++++++++----- 3 files changed, 51 insertions(+), 25 deletions(-) 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 dbbb141e1..19e12c706 100644 --- a/crates/storage-sqlite/src/stream.rs +++ b/crates/storage-sqlite/src/stream.rs @@ -55,6 +55,9 @@ impl SqliteEngine { /// 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, diff --git a/crates/storage-sqlite/src/stream/retention_cutoff_tests.rs b/crates/storage-sqlite/src/stream/retention_cutoff_tests.rs index 294fa7135..686e3a95a 100644 --- a/crates/storage-sqlite/src/stream/retention_cutoff_tests.rs +++ b/crates/storage-sqlite/src/stream/retention_cutoff_tests.rs @@ -5,6 +5,8 @@ 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 @@ -46,10 +48,9 @@ fn cutoff_with_a_fraction_keeps_the_column_shape() { assert!("2026-10-23T14:19:07.459Z" > cutoff.as_str()); } -/// 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() { +/// 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"); @@ -74,21 +75,38 @@ async fn sweep_on_a_whole_second_keeps_same_second_rows() { .execute(&engine.pool) .await .expect("shard"); - for (seq, created_at) in [ - ("1", "2026-10-23T14:19:06.999Z"), - ("2", "2026-10-23T14:19:07.000Z"), - ("3", "2026-10-23T14:19:07.123Z"), - ] { + 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) + .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 @@ -96,15 +114,27 @@ async fn sweep_on_a_whole_second_keeps_same_second_rows() { .await .expect("sweep"); assert_eq!(deleted, 1); - - let remaining: Vec<(String,)> = - sqlx::query_as("SELECT created_at FROM stream_records ORDER BY created_at") - .fetch_all(&engine.pool) - .await - .expect("remaining"); - let remaining: Vec<&str> = remaining.iter().map(|(s,)| s.as_str()).collect(); assert_eq!( - remaining, + 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]); +}