forge
Explore
Log in

Don't you dare go Hollow

the queue's clock is one string shape: stamp() pins UTC with nine fractional digits, zero subsecond included, because the time crate's Rfc3339 omits a zero fraction and a whole-second stamp ('…:00Z') then sorts AFTER the same instant with one ('…:00.0Z') — Z outranks . in text comparison, so claim_sends_owed's next_attempt_at <= ? missed the row for the whole of its first due second, and the sweep, which wakes on exactly that second, read an empty ledger and slept the idle hour — a reminder minted at clock−15m with a whole-second clock was systematically late by up to an hour and only went out when unrelated queue activity woke the pass (production: meeting 08:45Z, due 08:30Z, sent 08:54:53Z, attempts=1); every stored stamp now goes out through the one STAMP description, a boot-time pass rewrites the legacy whole-second stamps in every TEXT stamp column of the live schema (the password-seal pattern: idempotent by its own WHERE, spoken only when rows moved), parse stays Rfc3339 and reads both widths, and a row that is due but untaken gets a one-minute re-check instead of the idle hour — the claim UPDATE stays the arbiter, so a re-read cannot double-send

Browse files at this commit

6f9e149c5e61becc8c9cab1574315baf4a97c2a9Ahmet Kaan GümüşParent: c9a65a3
crates/iz-core/src/store/turso_store.rsmodified+99 -2
@@ -8,7 +8,7 @@
88 use async_trait::async_trait;
99 use rand::Rng;
1010 use time::format_description::well_known::Rfc3339;
11-use time::{Duration, OffsetDateTime};
11+use time::{Duration, OffsetDateTime, UtcOffset};
1212 use turso::transaction::{Transaction, TransactionBehavior};
1313 use turso::{Builder, Connection, Row, Value, params, params_from_iter};
1414 use ulid::Ulid;
@@ -139,6 +139,7 @@ impl TursoStore {
139139 store.retire_actor_only_decisions().await?;
140140 store.retire_viewer_assignments().await?;
141141 store.encrypt_plaintext_passwords().await?;
142+ store.canonicalize_legacy_stamps().await?;
142143 store.resniff_generic_attachments().await?;
143144 store.sweep_orphan_files().await?;
144145 // The file may have been rebuilt from a backup; its permissions and
@@ -189,6 +190,78 @@ impl TursoStore {
189190 Ok(())
190191 }
191192
193+ /// Stamps written before [`stamp`] pinned its format may sit in any TEXT
194+ /// stamp column as whole seconds (`…T08:30:00Z`, twenty characters) — and
195+ /// because `Z` outranks `.` in a string compare, such a row hid from
196+ /// `claim_sends_owed` for the whole of the first second it was due. Like
197+ /// the password-sealing pass above, this is a data repair no schema
198+ /// migration can express, run once per boot and idempotent by its own
199+ /// WHERE clause: a twenty-character stamp of the whole-second shape is
200+ /// the only thing it matches, and after one boot none are left to match.
201+ /// The inventory is the live schema's stamp columns, table by table out
202+ /// of `migrations/0001` through `0006`: `workspace` (created_at,
203+ /// smtp_test_at, smtp_check_at), `user` (created_at, last_signed_in_at),
204+ /// `workspace_owner` (claimed_at), `board`, `tag`, `comment`,
205+ /// `attachment`, `transition`, `freeing`, `activity`, `mail_rule` and
206+ /// `mail_decision` (each created_at), `task` (clock_at, created_at,
207+ /// updated_at, done_at, deleted_at), `task_dependency` (created_at,
208+ /// cleared_at) and `mail_send` (claimed_at, next_attempt_at, sent_at).
209+ /// `session`, `signin_link`, `auth_attempt` and `user.feed_seen_at` died
210+ /// with migration 0003 and have no rows left to heal; `task.deadline` is
211+ /// a day, not a stamp, and the shape below never matches it.
212+ async fn canonicalize_legacy_stamps(&self) -> Result<()> {
213+ const STAMP_COLUMNS: &[(&str, &str)] = &[
214+ ("workspace", "created_at"),
215+ ("workspace", "smtp_test_at"),
216+ ("workspace", "smtp_check_at"),
217+ ("user", "created_at"),
218+ ("user", "last_signed_in_at"),
219+ ("workspace_owner", "claimed_at"),
220+ ("board", "created_at"),
221+ ("tag", "created_at"),
222+ ("task", "clock_at"),
223+ ("task", "created_at"),
224+ ("task", "updated_at"),
225+ ("task", "done_at"),
226+ ("task", "deleted_at"),
227+ ("task_dependency", "created_at"),
228+ ("task_dependency", "cleared_at"),
229+ ("comment", "created_at"),
230+ ("attachment", "created_at"),
231+ ("transition", "created_at"),
232+ ("freeing", "created_at"),
233+ ("activity", "created_at"),
234+ ("mail_rule", "created_at"),
235+ ("mail_send", "claimed_at"),
236+ ("mail_send", "next_attempt_at"),
237+ ("mail_send", "sent_at"),
238+ ("mail_decision", "created_at"),
239+ ];
240+ let conn = self.conn.lock().await;
241+ let mut changed = 0usize;
242+ for (table, column) in STAMP_COLUMNS {
243+ let n = conn
244+ .execute(
245+ &format!(
246+ "UPDATE {table} SET {column} = substr({column}, 1, 19) \
247+ || '.000000000Z' \
248+ WHERE {column} IS NOT NULL AND length({column}) = 20 \
249+ AND {column} LIKE '____-__-__T__:__:__Z'"
250+ ),
251+ (),
252+ )
253+ .await
254+ .map_err(backend)?;
255+ changed += n as usize;
256+ }
257+ // Spoken only when something actually moved: a boot log that
258+ // reports every quiet pass trains the reader to skip it.
259+ if changed > 0 {
260+ println!("iz store canonicalized {changed} legacy whole-second stamps");
261+ }
262+ Ok(())
263+ }
264+
192265 /// The actor-exclusion era's decision rows, reworded to the only
193266 /// `no_recipients` detail the logs speak now. A database from before the
194267 /// actor joined every audience carries rows whose detail says
@@ -1069,8 +1142,24 @@ enum Outcome {
10691142 Held,
10701143 }
10711144
1145+/// Every stamp the store writes goes out this one way, and the shape it
1146+/// writes is the whole point: the queue's clock is TEXT comparison —
1147+/// `claim_sends_owed` asks SQLite whether `next_attempt_at <= ?` as strings —
1148+/// and string order only agrees with instant order when every stamp spells
1149+/// its instant the same way. The `time` crate's own Rfc3339 formatter omits
1150+/// a zero subsecond, and a stamp written that way (`…T08:30:00Z`) sorts
1151+/// *after* the same instant carrying a fraction (`…T08:30:00.000000000Z`),
1152+/// because `Z` outranks `.` — so a row whose due second arrived was
1153+/// invisible to the claim until the second was over, and the sweep, which
1154+/// wakes on exactly that second, read an empty ledger and went back to
1155+/// sleep. Hence the pinned format in [`STAMP`]: always UTC, always nine
1156+/// fractional digits, zero or not. Parsing stays on [`Rfc3339`], which reads
1157+/// both widths — rows an older build wrote keep loading, and the boot pass
1158+/// in [`TursoStore::canonicalize_legacy_stamps`] rewrites them to the
1159+/// canonical shape.
10721160 fn stamp(at: OffsetDateTime) -> Result<String> {
1073- at.format(&Rfc3339)
1161+ at.to_offset(UtcOffset::UTC)
1162+ .format(&STAMP)
10741163 .map_err(|e| StoreError::Corrupt(format!("timestamp: {e}")))
10751164 }
10761165
@@ -1083,6 +1172,14 @@ fn parse_stamp(raw: &str) -> Result<OffsetDateTime> {
10831172 /// person reading the card is.
10841173 const DAY: &[BorrowedFormatItem] = format_description!("[year]-[month]-[day]");
10851174
1175+/// The one shape every stored stamp takes, UTC with nine fractional digits.
1176+/// Why the width is pinned: see [`stamp`] — the queue compares stamps as
1177+/// text, and text only compares like time when every stamp is the same
1178+/// shape. [`parse_stamp`] reads this and the shorter legacy width alike.
1179+const STAMP: &[BorrowedFormatItem] = format_description!(
1180+ "[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:9]Z"
1181+);
1182+
10861183 fn day_text(day: Date) -> Result<String> {
10871184 day.format(&DAY)
10881185 .map_err(|e| StoreError::Corrupt(format!("deadline: {e}")))
crates/iz-core/tests/store.rsmodified+164 -0
@@ -7383,6 +7383,170 @@ async fn reminder_rows_survive_a_reopen() {
73837383 assert_eq!(after[0].next_attempt_at, before[0].next_attempt_at);
73847384 let _ = std::fs::remove_dir_all(&dir);
73857385 }
7386+/// The boundary that once ate a reminder: a due instant that lands on a
7387+/// whole second. The store used to write such stamps with no fraction
7388+/// (`…:00Z`), and text comparison puts `Z` after `.` — the row was
7389+/// invisible to the claim for the whole of its first due second, and the
7390+/// sweep, which wakes on exactly the second the queue names, read an empty
7391+/// ledger and went back to sleep for an hour. Forty milliseconds past the
7392+/// due instant must therefore be enough: the row is claimable the moment it
7393+/// is owed, not a second later.
7394+#[tokio::test]
7395+async fn a_reminder_due_on_a_whole_second_is_claimable_inside_that_second() {
7396+ let (dir, store, workspace, admin) = shared().await;
7397+ let mate = member(&store, &workspace, "grace@iz.sh", "Grace").await;
7398+ // A whole-second meeting: its reminder's due instant is a whole second
7399+ // too, which is exactly the shape the old formatter wrote bare.
7400+ let clock = (OffsetDateTime::now_utc() + Duration::hours(2))
7401+ .replace_nanosecond(0)
7402+ .unwrap();
7403+ let task = clocked_task(&store, &workspace, &admin, Some(clock)).await;
7404+ store.assign_task(&task, &mate).await.unwrap();
7405+ let rows = pending_reminders(&store, &task).await;
7406+ assert_eq!(rows.len(), 1);
7407+ assert_eq!(
7408+ rows[0].next_attempt_at.unwrap(),
7409+ clock - Duration::minutes(15),
7410+ "the workspace's default lead of fifteen minutes"
7411+ );
7412+
7413+ // Forty milliseconds after the row fell due — inside the second.
7414+ let now = rows[0].next_attempt_at.unwrap() + Duration::milliseconds(40);
7415+ let claimed = store
7416+ .claim_sends_owed(now, now + iz_core::mail::LEASE, 50)
7417+ .await
7418+ .unwrap();
7419+ assert_eq!(claimed.len(), 1, "the due row is claimable: {claimed:?}");
7420+ assert_eq!(claimed[0].id, rows[0].id);
7421+ let _ = std::fs::remove_dir_all(&dir);
7422+}
7423+
7424+/// What the store writes, the claim compares: nine fractional digits,
7425+/// always. A zero subsecond goes out as `.000000000`, not as an omission,
7426+/// so two stamps of the same instant are two copies of the same string and
7427+/// the queue's TEXT comparisons never disagree with the instants they
7428+/// compare.
7429+#[tokio::test]
7430+async fn a_whole_second_stamp_is_written_with_nine_zero_digits() {
7431+ let scratch = Scratch::open().await;
7432+ let (workspace, admin) = claim(&scratch.store).await;
7433+ let mate = member(&scratch.store, &workspace, "grace@iz.sh", "Grace").await;
7434+ let clock = (OffsetDateTime::now_utc() + Duration::hours(2))
7435+ .replace_nanosecond(0)
7436+ .unwrap();
7437+ let task = clocked_task(&scratch.store, &workspace, &admin, Some(clock)).await;
7438+ scratch.store.assign_task(&task, &mate).await.unwrap();
7439+
7440+ // The way the stamp actually sits on disk, not the way the API renders
7441+ // it back: a raw read of the column.
7442+ let conn = raw_conn(&scratch).await;
7443+ let mut rows = conn
7444+ .query(
7445+ "SELECT next_attempt_at FROM mail_send \
7446+ WHERE task_id = ?1 AND kind = 'reminder'",
7447+ turso::params![task],
7448+ )
7449+ .await
7450+ .unwrap();
7451+ let mut seen = 0;
7452+ while let Some(row) = rows.next().await.unwrap() {
7453+ let raw: String = row.get(0).unwrap();
7454+ assert_eq!(raw.len(), 30, "every stamp is the one pinned shape: {raw}");
7455+ assert!(
7456+ raw.ends_with(".000000000Z"),
7457+ "a zero subsecond is nine zeros, not a missing fraction: {raw}"
7458+ );
7459+ seen += 1;
7460+ }
7461+ assert_eq!(seen, 1, "one reminder was minted");
7462+}
7463+
7464+/// A database from the era before the stamp format was pinned carries
7465+/// whole-second stamps in any of its TEXT stamp columns, and the boot
7466+/// rewrites every one of them to the canonical shape — so the queue's TEXT
7467+/// comparisons never again meet a `Z` sorting after a `.`. The row planted
7468+/// here is the production reminder, verbatim: due on a whole second,
7469+/// written without a fraction.
7470+#[tokio::test]
7471+async fn a_boot_canonicalizes_the_legacy_whole_second_stamps() {
7472+ let dir = std::env::temp_dir().join(format!("iz-test-{}", Ulid::new()));
7473+ std::fs::create_dir_all(&dir).unwrap();
7474+ let path = dir.join("iz.db").to_string_lossy().into_owned();
7475+ let store = TursoStore::open(&path, &dir.join("storage")).await.unwrap();
7476+ let (workspace, admin) = claim(&store).await;
7477+ let mate = member(&store, &workspace, "grace@iz.sh", "Grace").await;
7478+ let clock = (OffsetDateTime::now_utc() + Duration::hours(2))
7479+ .replace_nanosecond(0)
7480+ .unwrap();
7481+ let task = clocked_task(&store, &workspace, &admin, Some(clock)).await;
7482+ store.assign_task(&task, &mate).await.unwrap();
7483+ let due = clock - Duration::minutes(15);
7484+ drop(store);
7485+
7486+ // The old write path, by hand: the same instants, no fraction, in a
7487+ // handful of the columns the boot pass owns. Everything else in the
7488+ // file was written by the canonical stamp already.
7489+ let columns = [
7490+ ("mail_send", "next_attempt_at"),
7491+ ("mail_send", "claimed_at"),
7492+ ("task", "clock_at"),
7493+ ("task", "created_at"),
7494+ ("task", "updated_at"),
7495+ ];
7496+ let db = turso::Builder::new_local(&path).build().await.unwrap();
7497+ let conn = db.connect().unwrap();
7498+ for (table, column) in columns {
7499+ conn.execute(
7500+ &format!(
7501+ "UPDATE {table} SET {column} = substr({column}, 1, 19) || 'Z' \
7502+ WHERE {column} IS NOT NULL"
7503+ ),
7504+ (),
7505+ )
7506+ .await
7507+ .unwrap();
7508+ }
7509+ drop(conn);
7510+ drop(db);
7511+
7512+ // The boot that finds them rewrites them.
7513+ let reopened = TursoStore::open(&path, &dir.join("storage")).await.unwrap();
7514+ let db = turso::Builder::new_local(&path).build().await.unwrap();
7515+ let conn = db.connect().unwrap();
7516+ for (table, column) in columns {
7517+ let mut rows = conn
7518+ .query(
7519+ &format!("SELECT {column} FROM {table} WHERE {column} IS NOT NULL"),
7520+ (),
7521+ )
7522+ .await
7523+ .unwrap();
7524+ let mut seen = 0;
7525+ while let Some(row) = rows.next().await.unwrap() {
7526+ let raw: String = row.get(0).unwrap();
7527+ assert_eq!(
7528+ raw.len(),
7529+ 30,
7530+ "{table}.{column} came back canonical: {raw}"
7531+ );
7532+ seen += 1;
7533+ }
7534+ assert!(seen > 0, "{table}.{column} had rows to rewrite");
7535+ }
7536+ drop(conn);
7537+ drop(db);
7538+
7539+ // And the defect the whole exercise serves is gone: the reminder, due
7540+ // on a whole second, is claimable inside the second it fell due.
7541+ let now = due + Duration::milliseconds(40);
7542+ let claimed = reopened
7543+ .claim_sends_owed(now, now + iz_core::mail::LEASE, 50)
7544+ .await
7545+ .unwrap();
7546+ assert_eq!(claimed.len(), 1, "the canonicalized row is claimable");
7547+ let _ = std::fs::remove_dir_all(&dir);
7548+}
7549+
73867550 #[tokio::test]
73877551 async fn a_reminder_already_sent_is_never_queued_again() {
73887552 let (dir, store, workspace, admin) = shared().await;
crates/iz-web/src/main.rsmodified+21 -8
@@ -278,15 +278,20 @@ async fn shutdown_signal() {
278278 ///
279279 /// Two other things can wake it. A mail being queued announces itself on the
280280 /// live channel, so an invite goes out as soon as it is asked for instead of
281-/// waiting out somebody else's timer. And an hour is the longest it will sleep
282-/// regardless, so a clock jump or a row written by something other than this
283-/// process is picked up on its own.
281+/// waiting out somebody else's timer. And an hour is the longest it will
282+/// sleep regardless, so a clock jump or a row written by something other
283+/// than this process is picked up on its own; a row that is due but that the
284+/// last pass could not take gets a one-minute re-check instead, for the
285+/// same reason — see the wait computed below.
284286 async fn sweep(engine: std::sync::Arc<iz_core::MailEngine>, store: Arc<dyn iz_core::store::Store>) {
285287 /// Enough that a morning's backlog clears in a few passes, few enough that
286288 /// one pass cannot sit on the mail server for minutes.
287289 const PER_PASS: u32 = 50;
288290 /// The longest this will sleep with nothing due.
289291 const IDLE: std::time::Duration = std::time::Duration::from_secs(3600);
292+ /// How long it re-reads when a row is already due but the pass above
293+ /// could not take it.
294+ const RECHECK: std::time::Duration = std::time::Duration::from_secs(60);
290295
291296 let mut queued = store.subscribe();
292297 loop {
@@ -302,17 +307,25 @@ async fn sweep(engine: std::sync::Arc<iz_core::MailEngine>, store: Arc<dyn iz_co
302307 Err(problem) => eprintln!("iz mail sweep could not read the ledger: {problem}"),
303308 }
304309
305- // How long until the next mail is owed. A row already due means the
306- // pass above could not take it — it was over its limit, or something
307- // else holds it — so the wait is the idle one rather than zero, which
308- // would spin.
310+ // How long until the next mail is owed. A row that is already due
311+ // but that the pass above could not take gets a short re-check, not
312+ // the idle hour. A row can sit due for reasons the pass cannot fix
313+ // on the spot: the pass hit its limit and this row is next in line,
314+ // or it fell due inside the breath between reading the ledger and
315+ // claiming. None of that asks the pass to hurry — the claim UPDATE
316+ // is the arbiter, and a row another pass is composing has already
317+ // had its next_attempt_at pushed into the future, so re-reading
318+ // cannot send it twice — but none of it justifies an hour either:
319+ // the hour is what once turned a one-second blind spot in the stamp
320+ // compare into a reminder twenty-five minutes late. It is not zero,
321+ // which would spin: the pass above has only just run.
309322 let wait = match store.next_due_at().await {
310323 Ok(Some(at)) => {
311324 let now = time::OffsetDateTime::now_utc();
312325 if at > now {
313326 (at - now).try_into().unwrap_or(IDLE).min(IDLE)
314327 } else {
315- IDLE
328+ RECHECK
316329 }
317330 }
318331 Ok(None) => IDLE,