Repository navigation
fix(sqlite): render the stream retention cutoff in the created_at column shape #503
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
828ed9a
a7cc92b
45d9a76
5197767
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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<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 | ||
| /// 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, | ||
|
|
@@ -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) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added |
||
| .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; | ||
| 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]); | ||
| } |
There was a problem hiding this comment.
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-secondcreated_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 callswrite_stream_record, so no request reaches this. "a record the write path stamps while the sweep waits" would scope it.There was a problem hiding this comment.
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_recordhas 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.