fix(forge): persist the account notification cursor

The account poll kept its notifications cursor in a Mutex<HashMap> 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.
This commit is contained in:
vhaudiquet committed 2026-11-22 11:41:32 +01:00
1 parent d887026ff6
commit 6a81dfa466
2 files changed
+126 -22

No files matched your search

+114 -22
View File
@@ -219,8 +219,6 @@ pub struct ForgeSource {
/// The device-notification queue a [`Triage::Surface`] lands in. /// The device-notification queue a [`Triage::Surface`] lands in.
notifications: Arc<crate::notifications::NotificationStore>, notifications: Arc<crate::notifications::NotificationStore>,
clients: Mutex<HashMap<ClientKey, Arc<dyn Forge>>>, clients: Mutex<HashMap<ClientKey, Arc<dyn Forge>>>,
/// One notifications cursor per account id.
account_cursors: Mutex<HashMap<String, rhema_forge_integration::Timestamp>>,
} }
impl ForgeSource { impl ForgeSource {
@@ -245,7 +243,6 @@ impl ForgeSource {
accounts, accounts,
notifications, notifications,
clients: Mutex::new(HashMap::new()), 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 client = record_client(kind, watch.host.as_deref(), &credential);
let since = self // The cursor this poll asks from: the durable one when the watch
.account_cursors // has one, absent on its first pass — an unread feed is news. An
.lock() // unreadable row reads as absent, like a repo watch's: a
.unwrap_or_else(PoisonError::into_inner) // corrupted cursor must not fire a backlog. The map that used to
.get(&watch.account_id) // hold it was per-process, so every restart asked from nothing
.cloned(); // 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 let page = client
.notifications(since.as_ref()) .notifications(since.as_ref())
.await .await
@@ -567,11 +570,11 @@ impl ForgeSource {
} }
// The row is decided — dispatched, surfaced, or ignored — so // The row is decided — dispatched, surfaced, or ignored — so
// consume it: `mark_read` is what stops the feed returning // consume it: `mark_read` is what stops the feed returning
// it. Deciding without consuming is a loop: the poll's cursor // it, and the durable cursor is what stops the poll asking
// never passes a row the forge still considers unread, so // for it again. Deciding without consuming is a loop: a row
// every pass re-decides it and re-dispatches a turn for a // the forge still considers unread comes back every pass —
// thread that already has one, and a restart (the cursor is // re-decided and re-dispatched as a fresh turn for a thread
// in memory) replays the whole unread feed. // that already has one — until the cursor passes it.
// //
// Best-effort: an unread row costs a repeat, never a lost // Best-effort: an unread row costs a repeat, never a lost
// event, so a failed call is logged and the poll carries on. // 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 { if let Some(cursor) = page.cursor {
self.account_cursors self.store
.lock() .set_cursor(SCOPE_ACCOUNT, &watch.forge, &watch.account_id, cursor.raw())
.unwrap_or_else(PoisonError::into_inner) .map_err(|err| SourceError::Backend(format!("watch store: {err}")))?;
.insert(watch.account_id.clone(), cursor);
} }
Ok(fed) Ok(fed)
} }
@@ -707,10 +714,9 @@ mod tests {
/// The account poll consumes what it decides. The feed is /// The account poll consumes what it decides. The feed is
/// at-least-once — the cursor never passes a row the forge still /// at-least-once — the cursor never passes a row the forge still
/// considers unread, and a restart asks for the whole unread feed /// considers unread, so a row that is triaged but not marked read
/// again — so a row that is triaged but not marked read comes back /// comes back with the same dedup id on the next pass, and every
/// with the same dedup id on the next pass, and every pass dispatches /// pass dispatches a fresh turn for a thread that already has one.
/// a fresh turn for a thread that already has one.
#[tokio::test] #[tokio::test]
async fn a_triaged_account_notification_is_marked_read() { async fn a_triaged_account_notification_is_marked_read() {
let server = MockServer::start().await; let server = MockServer::start().await;
@@ -764,6 +770,92 @@ mod tests {
assert_eq!(reads[0].url.path(), "/notifications/threads/42188"); 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. /// The parts a test source polls through, all in memory.
fn test_parts( fn test_parts(
store: Arc<ClawStore>, store: Arc<ClawStore>,
+12
View File
@@ -395,6 +395,13 @@ impl ClawStore {
"DELETE FROM account_watches WHERE forge = ?1 AND account_id = ?2", "DELETE FROM account_watches WHERE forge = ?1 AND account_id = ?2",
params![forge.trim(), account_id.trim()], 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) Ok(removed == 1)
} }
@@ -406,6 +413,11 @@ impl ClawStore {
"DELETE FROM account_watches WHERE account_id = ?1", "DELETE FROM account_watches WHERE account_id = ?1",
params![account_id.trim()], 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) Ok(removed)
} }