diff --git a/crates/iz-core/src/store/turso_store.rs b/crates/iz-core/src/store/turso_store.rs index e454045..071db68 100644 --- a/crates/iz-core/src/store/turso_store.rs +++ b/crates/iz-core/src/store/turso_store.rs @@ -8,7 +8,7 @@ use async_trait::async_trait; use rand::Rng; use time::format_description::well_known::Rfc3339; -use time::{Duration, OffsetDateTime}; +use time::{Duration, OffsetDateTime, UtcOffset}; use turso::transaction::{Transaction, TransactionBehavior}; use turso::{Builder, Connection, Row, Value, params, params_from_iter}; use ulid::Ulid; @@ -139,6 +139,7 @@ impl TursoStore { store.retire_actor_only_decisions().await?; store.retire_viewer_assignments().await?; store.encrypt_plaintext_passwords().await?; + store.canonicalize_legacy_stamps().await?; store.resniff_generic_attachments().await?; store.sweep_orphan_files().await?; // The file may have been rebuilt from a backup; its permissions and @@ -189,6 +190,78 @@ impl TursoStore { Ok(()) } + /// Stamps written before [`stamp`] pinned its format may sit in any TEXT + /// stamp column as whole seconds (`…T08:30:00Z`, twenty characters) — and + /// because `Z` outranks `.` in a string compare, such a row hid from + /// `claim_sends_owed` for the whole of the first second it was due. Like + /// the password-sealing pass above, this is a data repair no schema + /// migration can express, run once per boot and idempotent by its own + /// WHERE clause: a twenty-character stamp of the whole-second shape is + /// the only thing it matches, and after one boot none are left to match. + /// The inventory is the live schema's stamp columns, table by table out + /// of `migrations/0001` through `0006`: `workspace` (created_at, + /// smtp_test_at, smtp_check_at), `user` (created_at, last_signed_in_at), + /// `workspace_owner` (claimed_at), `board`, `tag`, `comment`, + /// `attachment`, `transition`, `freeing`, `activity`, `mail_rule` and + /// `mail_decision` (each created_at), `task` (clock_at, created_at, + /// updated_at, done_at, deleted_at), `task_dependency` (created_at, + /// cleared_at) and `mail_send` (claimed_at, next_attempt_at, sent_at). + /// `session`, `signin_link`, `auth_attempt` and `user.feed_seen_at` died + /// with migration 0003 and have no rows left to heal; `task.deadline` is + /// a day, not a stamp, and the shape below never matches it. + async fn canonicalize_legacy_stamps(&self) -> Result<()> { + const STAMP_COLUMNS: &[(&str, &str)] = &[ + ("workspace", "created_at"), + ("workspace", "smtp_test_at"), + ("workspace", "smtp_check_at"), + ("user", "created_at"), + ("user", "last_signed_in_at"), + ("workspace_owner", "claimed_at"), + ("board", "created_at"), + ("tag", "created_at"), + ("task", "clock_at"), + ("task", "created_at"), + ("task", "updated_at"), + ("task", "done_at"), + ("task", "deleted_at"), + ("task_dependency", "created_at"), + ("task_dependency", "cleared_at"), + ("comment", "created_at"), + ("attachment", "created_at"), + ("transition", "created_at"), + ("freeing", "created_at"), + ("activity", "created_at"), + ("mail_rule", "created_at"), + ("mail_send", "claimed_at"), + ("mail_send", "next_attempt_at"), + ("mail_send", "sent_at"), + ("mail_decision", "created_at"), + ]; + let conn = self.conn.lock().await; + let mut changed = 0usize; + for (table, column) in STAMP_COLUMNS { + let n = conn + .execute( + &format!( + "UPDATE {table} SET {column} = substr({column}, 1, 19) \ + || '.000000000Z' \ + WHERE {column} IS NOT NULL AND length({column}) = 20 \ + AND {column} LIKE '____-__-__T__:__:__Z'" + ), + (), + ) + .await + .map_err(backend)?; + changed += n as usize; + } + // Spoken only when something actually moved: a boot log that + // reports every quiet pass trains the reader to skip it. + if changed > 0 { + println!("iz store canonicalized {changed} legacy whole-second stamps"); + } + Ok(()) + } + /// The actor-exclusion era's decision rows, reworded to the only /// `no_recipients` detail the logs speak now. A database from before the /// actor joined every audience carries rows whose detail says @@ -1069,8 +1142,24 @@ enum Outcome { Held, } +/// Every stamp the store writes goes out this one way, and the shape it +/// writes is the whole point: the queue's clock is TEXT comparison — +/// `claim_sends_owed` asks SQLite whether `next_attempt_at <= ?` as strings — +/// and string order only agrees with instant order when every stamp spells +/// its instant the same way. The `time` crate's own Rfc3339 formatter omits +/// a zero subsecond, and a stamp written that way (`…T08:30:00Z`) sorts +/// *after* the same instant carrying a fraction (`…T08:30:00.000000000Z`), +/// because `Z` outranks `.` — so a row whose due second arrived was +/// invisible to the claim until the second was over, and the sweep, which +/// wakes on exactly that second, read an empty ledger and went back to +/// sleep. Hence the pinned format in [`STAMP`]: always UTC, always nine +/// fractional digits, zero or not. Parsing stays on [`Rfc3339`], which reads +/// both widths — rows an older build wrote keep loading, and the boot pass +/// in [`TursoStore::canonicalize_legacy_stamps`] rewrites them to the +/// canonical shape. fn stamp(at: OffsetDateTime) -> Result { - at.format(&Rfc3339) + at.to_offset(UtcOffset::UTC) + .format(&STAMP) .map_err(|e| StoreError::Corrupt(format!("timestamp: {e}"))) } @@ -1083,6 +1172,14 @@ fn parse_stamp(raw: &str) -> Result { /// person reading the card is. const DAY: &[BorrowedFormatItem] = format_description!("[year]-[month]-[day]"); +/// The one shape every stored stamp takes, UTC with nine fractional digits. +/// Why the width is pinned: see [`stamp`] — the queue compares stamps as +/// text, and text only compares like time when every stamp is the same +/// shape. [`parse_stamp`] reads this and the shorter legacy width alike. +const STAMP: &[BorrowedFormatItem] = format_description!( + "[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:9]Z" +); + fn day_text(day: Date) -> Result { day.format(&DAY) .map_err(|e| StoreError::Corrupt(format!("deadline: {e}"))) diff --git a/crates/iz-core/tests/store.rs b/crates/iz-core/tests/store.rs index 442175e..880b0f5 100644 --- a/crates/iz-core/tests/store.rs +++ b/crates/iz-core/tests/store.rs @@ -7383,6 +7383,170 @@ async fn reminder_rows_survive_a_reopen() { assert_eq!(after[0].next_attempt_at, before[0].next_attempt_at); let _ = std::fs::remove_dir_all(&dir); } +/// The boundary that once ate a reminder: a due instant that lands on a +/// whole second. The store used to write such stamps with no fraction +/// (`…:00Z`), and text comparison puts `Z` after `.` — the row was +/// invisible to the claim for the whole of its first due second, and the +/// sweep, which wakes on exactly the second the queue names, read an empty +/// ledger and went back to sleep for an hour. Forty milliseconds past the +/// due instant must therefore be enough: the row is claimable the moment it +/// is owed, not a second later. +#[tokio::test] +async fn a_reminder_due_on_a_whole_second_is_claimable_inside_that_second() { + let (dir, store, workspace, admin) = shared().await; + let mate = member(&store, &workspace, "grace@iz.sh", "Grace").await; + // A whole-second meeting: its reminder's due instant is a whole second + // too, which is exactly the shape the old formatter wrote bare. + let clock = (OffsetDateTime::now_utc() + Duration::hours(2)) + .replace_nanosecond(0) + .unwrap(); + let task = clocked_task(&store, &workspace, &admin, Some(clock)).await; + store.assign_task(&task, &mate).await.unwrap(); + let rows = pending_reminders(&store, &task).await; + assert_eq!(rows.len(), 1); + assert_eq!( + rows[0].next_attempt_at.unwrap(), + clock - Duration::minutes(15), + "the workspace's default lead of fifteen minutes" + ); + + // Forty milliseconds after the row fell due — inside the second. + let now = rows[0].next_attempt_at.unwrap() + Duration::milliseconds(40); + let claimed = store + .claim_sends_owed(now, now + iz_core::mail::LEASE, 50) + .await + .unwrap(); + assert_eq!(claimed.len(), 1, "the due row is claimable: {claimed:?}"); + assert_eq!(claimed[0].id, rows[0].id); + let _ = std::fs::remove_dir_all(&dir); +} + +/// What the store writes, the claim compares: nine fractional digits, +/// always. A zero subsecond goes out as `.000000000`, not as an omission, +/// so two stamps of the same instant are two copies of the same string and +/// the queue's TEXT comparisons never disagree with the instants they +/// compare. +#[tokio::test] +async fn a_whole_second_stamp_is_written_with_nine_zero_digits() { + let scratch = Scratch::open().await; + let (workspace, admin) = claim(&scratch.store).await; + let mate = member(&scratch.store, &workspace, "grace@iz.sh", "Grace").await; + let clock = (OffsetDateTime::now_utc() + Duration::hours(2)) + .replace_nanosecond(0) + .unwrap(); + let task = clocked_task(&scratch.store, &workspace, &admin, Some(clock)).await; + scratch.store.assign_task(&task, &mate).await.unwrap(); + + // The way the stamp actually sits on disk, not the way the API renders + // it back: a raw read of the column. + let conn = raw_conn(&scratch).await; + let mut rows = conn + .query( + "SELECT next_attempt_at FROM mail_send \ + WHERE task_id = ?1 AND kind = 'reminder'", + turso::params![task], + ) + .await + .unwrap(); + let mut seen = 0; + while let Some(row) = rows.next().await.unwrap() { + let raw: String = row.get(0).unwrap(); + assert_eq!(raw.len(), 30, "every stamp is the one pinned shape: {raw}"); + assert!( + raw.ends_with(".000000000Z"), + "a zero subsecond is nine zeros, not a missing fraction: {raw}" + ); + seen += 1; + } + assert_eq!(seen, 1, "one reminder was minted"); +} + +/// A database from the era before the stamp format was pinned carries +/// whole-second stamps in any of its TEXT stamp columns, and the boot +/// rewrites every one of them to the canonical shape — so the queue's TEXT +/// comparisons never again meet a `Z` sorting after a `.`. The row planted +/// here is the production reminder, verbatim: due on a whole second, +/// written without a fraction. +#[tokio::test] +async fn a_boot_canonicalizes_the_legacy_whole_second_stamps() { + let dir = std::env::temp_dir().join(format!("iz-test-{}", Ulid::new())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("iz.db").to_string_lossy().into_owned(); + let store = TursoStore::open(&path, &dir.join("storage")).await.unwrap(); + let (workspace, admin) = claim(&store).await; + let mate = member(&store, &workspace, "grace@iz.sh", "Grace").await; + let clock = (OffsetDateTime::now_utc() + Duration::hours(2)) + .replace_nanosecond(0) + .unwrap(); + let task = clocked_task(&store, &workspace, &admin, Some(clock)).await; + store.assign_task(&task, &mate).await.unwrap(); + let due = clock - Duration::minutes(15); + drop(store); + + // The old write path, by hand: the same instants, no fraction, in a + // handful of the columns the boot pass owns. Everything else in the + // file was written by the canonical stamp already. + let columns = [ + ("mail_send", "next_attempt_at"), + ("mail_send", "claimed_at"), + ("task", "clock_at"), + ("task", "created_at"), + ("task", "updated_at"), + ]; + let db = turso::Builder::new_local(&path).build().await.unwrap(); + let conn = db.connect().unwrap(); + for (table, column) in columns { + conn.execute( + &format!( + "UPDATE {table} SET {column} = substr({column}, 1, 19) || 'Z' \ + WHERE {column} IS NOT NULL" + ), + (), + ) + .await + .unwrap(); + } + drop(conn); + drop(db); + + // The boot that finds them rewrites them. + let reopened = TursoStore::open(&path, &dir.join("storage")).await.unwrap(); + let db = turso::Builder::new_local(&path).build().await.unwrap(); + let conn = db.connect().unwrap(); + for (table, column) in columns { + let mut rows = conn + .query( + &format!("SELECT {column} FROM {table} WHERE {column} IS NOT NULL"), + (), + ) + .await + .unwrap(); + let mut seen = 0; + while let Some(row) = rows.next().await.unwrap() { + let raw: String = row.get(0).unwrap(); + assert_eq!( + raw.len(), + 30, + "{table}.{column} came back canonical: {raw}" + ); + seen += 1; + } + assert!(seen > 0, "{table}.{column} had rows to rewrite"); + } + drop(conn); + drop(db); + + // And the defect the whole exercise serves is gone: the reminder, due + // on a whole second, is claimable inside the second it fell due. + let now = due + Duration::milliseconds(40); + let claimed = reopened + .claim_sends_owed(now, now + iz_core::mail::LEASE, 50) + .await + .unwrap(); + assert_eq!(claimed.len(), 1, "the canonicalized row is claimable"); + let _ = std::fs::remove_dir_all(&dir); +} + #[tokio::test] async fn a_reminder_already_sent_is_never_queued_again() { let (dir, store, workspace, admin) = shared().await; diff --git a/crates/iz-web/src/main.rs b/crates/iz-web/src/main.rs index 82d604a..89d1e86 100644 --- a/crates/iz-web/src/main.rs +++ b/crates/iz-web/src/main.rs @@ -278,15 +278,20 @@ async fn shutdown_signal() { /// /// Two other things can wake it. A mail being queued announces itself on the /// live channel, so an invite goes out as soon as it is asked for instead of -/// waiting out somebody else's timer. And an hour is the longest it will sleep -/// regardless, so a clock jump or a row written by something other than this -/// process is picked up on its own. +/// waiting out somebody else's timer. And an hour is the longest it will +/// sleep regardless, so a clock jump or a row written by something other +/// than this process is picked up on its own; a row that is due but that the +/// last pass could not take gets a one-minute re-check instead, for the +/// same reason — see the wait computed below. async fn sweep(engine: std::sync::Arc, store: Arc) { /// Enough that a morning's backlog clears in a few passes, few enough that /// one pass cannot sit on the mail server for minutes. const PER_PASS: u32 = 50; /// The longest this will sleep with nothing due. const IDLE: std::time::Duration = std::time::Duration::from_secs(3600); + /// How long it re-reads when a row is already due but the pass above + /// could not take it. + const RECHECK: std::time::Duration = std::time::Duration::from_secs(60); let mut queued = store.subscribe(); loop { @@ -302,17 +307,25 @@ async fn sweep(engine: std::sync::Arc, store: Arc eprintln!("iz mail sweep could not read the ledger: {problem}"), } - // How long until the next mail is owed. A row already due means the - // pass above could not take it — it was over its limit, or something - // else holds it — so the wait is the idle one rather than zero, which - // would spin. + // How long until the next mail is owed. A row that is already due + // but that the pass above could not take gets a short re-check, not + // the idle hour. A row can sit due for reasons the pass cannot fix + // on the spot: the pass hit its limit and this row is next in line, + // or it fell due inside the breath between reading the ledger and + // claiming. None of that asks the pass to hurry — the claim UPDATE + // is the arbiter, and a row another pass is composing has already + // had its next_attempt_at pushed into the future, so re-reading + // cannot send it twice — but none of it justifies an hour either: + // the hour is what once turned a one-second blind spot in the stamp + // compare into a reminder twenty-five minutes late. It is not zero, + // which would spin: the pass above has only just run. let wait = match store.next_due_at().await { Ok(Some(at)) => { let now = time::OffsetDateTime::now_utc(); if at > now { (at - now).try_into().unwrap_or(IDLE).min(IDLE) } else { - IDLE + RECHECK } } Ok(None) => IDLE,