From 6a81dfa4669ede2a3683d754171cf19f3479ef19 Mon Sep 17 00:00:00 2001 From: Valentin Haudiquet Date: Sun, 22 Nov 2026 11:41:32 +0100 Subject: [PATCH] fix(forge): persist the account notification cursor The account poll kept its notifications cursor in a Mutex on ForgeSource. A restart emptied the map, so the next poll asked the feed from nothing, and every row the forge still considered unread came back to be triaged again. mark_read usually consumes a row, but the call is best-effort, and one failure leaves the row in the feed forever, with every pass re-deciding it and dispatching a fresh turn for a thread that already had one. The repo watches already solve this one scope over: their cursors live in the watch_cursors table, and a restart resumes from the stored row. The account poll does the same now, under SCOPE_ACCOUNT, keyed by forge and account id. The first pass of a new watch still asks from nothing, because an unread feed is news. A restart asks from the durable row, and an unreadable row reads as absent, like a repo watch's, so a corrupted cursor cannot fire a backlog. Removing an account watch deletes its cursor row with it, as removing a repo watch already does. A re-add is a new watch. The new test builds a second ForgeSource over the same store, the shape every restart takes, and checks its notifications poll carries since=2026-10-05T12:00:00Z, the cursor the first pass left. --- crates/rhema-claw/src/forge.rs | 136 ++++++++++++++++++++++----- crates/rhema-claw/src/watch_store.rs | 12 +++ 2 files changed, 126 insertions(+), 22 deletions(-) diff --git a/crates/rhema-claw/src/forge.rs b/crates/rhema-claw/src/forge.rs index 4603964..78af9c5 100644 --- a/crates/rhema-claw/src/forge.rs +++ b/crates/rhema-claw/src/forge.rs @@ -219,8 +219,6 @@ pub struct ForgeSource { /// The device-notification queue a [`Triage::Surface`] lands in. notifications: Arc, clients: Mutex>>, - /// One notifications cursor per account id. - account_cursors: Mutex>, } impl ForgeSource { @@ -245,7 +243,6 @@ impl ForgeSource { accounts, notifications, clients: Mutex::new(HashMap::new()), - account_cursors: Mutex::new(HashMap::new()), } } @@ -501,12 +498,18 @@ impl ForgeSource { }; let client = record_client(kind, watch.host.as_deref(), &credential); - let since = self - .account_cursors - .lock() - .unwrap_or_else(PoisonError::into_inner) - .get(&watch.account_id) - .cloned(); + // The cursor this poll asks from: the durable one when the watch + // has one, absent on its first pass — an unread feed is news. An + // unreadable row reads as absent, like a repo watch's: a + // corrupted cursor must not fire a backlog. The map that used to + // hold it was per-process, so every restart asked from nothing + // and re-decided the whole unread feed; the row is what a + // restart resumes from. + let stored = self + .store + .cursor(SCOPE_ACCOUNT, &watch.forge, &watch.account_id) + .map_err(|err| SourceError::Backend(format!("watch store: {err}")))?; + let since = stored.as_deref().and_then(Timestamp::parse); let page = client .notifications(since.as_ref()) .await @@ -567,11 +570,11 @@ impl ForgeSource { } // The row is decided — dispatched, surfaced, or ignored — so // consume it: `mark_read` is what stops the feed returning - // it. Deciding without consuming is a loop: the poll's cursor - // never passes a row the forge still considers unread, so - // every pass re-decides it and re-dispatches a turn for a - // thread that already has one, and a restart (the cursor is - // in memory) replays the whole unread feed. + // it, and the durable cursor is what stops the poll asking + // for it again. Deciding without consuming is a loop: a row + // the forge still considers unread comes back every pass — + // re-decided and re-dispatched as a fresh turn for a thread + // that already has one — until the cursor passes it. // // Best-effort: an unread row costs a repeat, never a lost // event, so a failed call is logged and the poll carries on. @@ -582,11 +585,15 @@ impl ForgeSource { ); } } + // Advance the durable cursor to wherever this poll got to. The + // in-memory map this replaces was per-process: a restart that + // lost it replayed the whole unread feed. A failed write is one + // pass's replay — dedup ids absorb it — so it reads as a poll + // failure, like the repo watch's cursor does. if let Some(cursor) = page.cursor { - self.account_cursors - .lock() - .unwrap_or_else(PoisonError::into_inner) - .insert(watch.account_id.clone(), cursor); + self.store + .set_cursor(SCOPE_ACCOUNT, &watch.forge, &watch.account_id, cursor.raw()) + .map_err(|err| SourceError::Backend(format!("watch store: {err}")))?; } Ok(fed) } @@ -707,10 +714,9 @@ mod tests { /// The account poll consumes what it decides. The feed is /// at-least-once — the cursor never passes a row the forge still - /// considers unread, and a restart asks for the whole unread feed - /// again — so a row that is triaged but not marked read comes back - /// with the same dedup id on the next pass, and every pass dispatches - /// a fresh turn for a thread that already has one. + /// considers unread, so a row that is triaged but not marked read + /// comes back with the same dedup id on the next pass, and every + /// pass dispatches a fresh turn for a thread that already has one. #[tokio::test] async fn a_triaged_account_notification_is_marked_read() { let server = MockServer::start().await; @@ -764,6 +770,92 @@ mod tests { assert_eq!(reads[0].url.path(), "/notifications/threads/42188"); } + /// The account cursor is durable. The pass that decides rows leaves + /// where it got to in the store, and a source built fresh over the + /// same store — the shape every restart takes — asks from that row + /// rather than from nothing: the in-memory map this replaces died + /// with the process, and every restart re-decided the whole unread + /// feed. + #[tokio::test] + async fn an_account_cursor_survives_a_restart() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/notifications")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([ + { + "id": 42188, + "unread": true, + "reason": "mention", + "updated_at": "2026-10-05T12:00:00Z", + "subject": { + "title": "Add the widget flange", + "url": "https://api.github.com/repos/acme/widgets/pulls/142", + "type": "PullRequest" + }, + "repository": { "full_name": "acme/widgets" } + } + ]))) + .mount(&server) + .await; + + let store = Arc::new(ClawStore::in_memory().expect("store opens")); + let (dispatcher, accounts, notifications) = test_parts(store.clone()); + let account = accounts + .put(rhema_identity::AccountDraft::new( + "forge bot", + "github", + rhema_identity::Secret::new(rhema_identity::SecretKind::Token, "acct-tok"), + )) + .expect("account lands"); + store + .add_account_watch("github", Some(&server.uri()), &account.id) + .expect("account watch lands"); + let source = ForgeSource::new( + &dispatcher, + "github", + store.clone(), + accounts.clone(), + notifications.clone(), + ); + source.detect().await.expect("the pass runs"); + + // Where the poll got to is in the store, spelled like the feed's + // own instants. + let cursor = store + .cursor(SCOPE_ACCOUNT, "github", &account.id) + .expect("cursor reads") + .expect("the pass persisted a cursor"); + assert_eq!( + cursor, "2026-10-05T12:00:00Z", + "the cursor is the newest instant the poll saw" + ); + + // The restart: a fresh source over the same store polls from the + // row, not from nothing. + let reborn = ForgeSource::new(&dispatcher, "github", store, accounts, notifications); + reborn.detect().await.expect("the restarted pass runs"); + let requests = server.received_requests().await.expect("recording is on"); + let polls: Vec<_> = requests + .iter() + .filter(|request| { + request.method.as_str() == "GET" && request.url.path() == "/notifications" + }) + .collect(); + assert_eq!(polls.len(), 2, "one poll per pass"); + let since = polls[1].url.query_pairs().find_map(|(key, value)| { + if key.as_ref() == "since" { + Some(value.into_owned()) + } else { + None + } + }); + assert_eq!( + since.as_deref(), + Some(cursor.as_str()), + "the restart asks from the durable cursor" + ); + } + /// The parts a test source polls through, all in memory. fn test_parts( store: Arc, diff --git a/crates/rhema-claw/src/watch_store.rs b/crates/rhema-claw/src/watch_store.rs index 46962ea..0508f5f 100644 --- a/crates/rhema-claw/src/watch_store.rs +++ b/crates/rhema-claw/src/watch_store.rs @@ -395,6 +395,13 @@ impl ClawStore { "DELETE FROM account_watches WHERE forge = ?1 AND account_id = ?2", params![forge.trim(), account_id.trim()], )?; + // The cursor goes with the watch, like a repo watch's: a re-add + // is a new watch, and its first pass asks from nothing rather + // than resuming where the old one stopped. + conn.execute( + "DELETE FROM watch_cursors WHERE scope = ?1 AND forge = ?2 AND subject = ?3", + params![SCOPE_ACCOUNT, forge.trim(), account_id.trim()], + )?; Ok(removed == 1) } @@ -406,6 +413,11 @@ impl ClawStore { "DELETE FROM account_watches WHERE account_id = ?1", params![account_id.trim()], )?; + // The cursors go with the watches, every forge at once. + conn.execute( + "DELETE FROM watch_cursors WHERE scope = ?1 AND subject = ?2", + params![SCOPE_ACCOUNT, account_id.trim()], + )?; Ok(removed) }