From 9a7558da8bbf47b5f0bda3ec37a05e8b1802591b Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 16:27:45 -0600 Subject: [PATCH 1/3] fix(id): count intra-interval revoke+re-add cycles in group churn watcher (#1847) --- pkgs/id/src/commands/serve.rs | 163 ++++++++++++++++++++++++++++++---- 1 file changed, 146 insertions(+), 17 deletions(-) diff --git a/pkgs/id/src/commands/serve.rs b/pkgs/id/src/commands/serve.rs index 8a4d0505c..76dc3fd7a 100644 --- a/pkgs/id/src/commands/serve.rs +++ b/pkgs/id/src/commands/serve.rs @@ -1374,55 +1374,78 @@ const GROUP_WARNING_INTERVAL: std::time::Duration = std::time::Duration::from_se /// every group is observed as client-made. Member counts come from the fold. /// /// Group events carry no timestamps, so churn cannot be reconstructed from -/// the log for time before serve started. Instead the watcher derives re-adds -/// from what it observes between evaluations: a device that is authorized, -/// later unauthorized, and then authorized again is a re-add, stamped with -/// the time of the evaluation that first sees it back. +/// the log for time before serve started. Instead the watcher counts re-adds +/// from the log events folded since its previous evaluation (#1847): a +/// device authorization that takes effect for a device the watcher has seen +/// authorized before, and that is not authorized at that point in the event +/// stream, is a re-add, stamped with the time of the evaluation that folds +/// it. Counting from the event stream — not from the net device set — means +/// a revoke + re-add cycle that completes inside one evaluation interval +/// still counts. The first evaluation only establishes the baseline (the +/// devices the fold already shows), so history from before serve started +/// never counts. struct GroupWarningWatcher { evaluator: Evaluator, - /// The devices authorized per group at the previous evaluation. - devices: std::collections::BTreeMap>, + /// The devices authorized per group at the last event the watcher has + /// folded, tracked through the event stream, not just at evaluations. + authorized: std::collections::BTreeMap>, /// Every device ever seen authorized per group. seen_devices: std::collections::BTreeMap>, /// The re-add times per group, as observed by this watcher. readds: std::collections::BTreeMap>, + /// How many log events the watcher has folded, or `None` before the + /// first evaluation establishes the baseline. + events_seen: Option, } impl GroupWarningWatcher { fn new() -> Self { Self { evaluator: Evaluator::default(), - devices: std::collections::BTreeMap::new(), + authorized: std::collections::BTreeMap::new(), seen_devices: std::collections::BTreeMap::new(), readds: std::collections::BTreeMap::new(), + events_seen: None, } } /// Evaluates every active group in `projection` at `now` (Unix seconds). /// Returns the warnings this evaluation adds, and writes each of them to /// the server log through the warnings module. - fn evaluate(&mut self, projection: &Projection, now: u64) -> Vec<(Hash, Warning)> { + fn evaluate( + &mut self, + projection: &Projection, + events: &[crate::groups::Event], + now: u64, + ) -> Vec<(Hash, Warning)> { + let delta_readds = self.fold_new_events(projection, events); let mut fired = Vec::new(); for (group, view) in projection.groups() { if !view.is_active() { continue; } + // Keep the event-tracked authorization in step with the fold: + // a device can leave or rejoin the active set without a device + // event of its own (its account was removed or re-added). Such + // a change is not a re-add — only a device event counts — but + // the tracked set must match the fold, or a later genuine + // re-add would be missed or counted twice. let current = projection.group_active_devices(group); - let mut new_readds = 0_usize; { + let authorized = self.authorized.entry(*group).or_default(); + authorized.retain(|device| current.contains(device)); let seen = self.seen_devices.entry(*group).or_default(); - let previous = self.devices.entry(*group).or_default(); for device in ¤t { - if !previous.contains(device) && seen.contains(device) { - new_readds += 1; + if !authorized.contains(device) { + authorized.insert(*device); + seen.insert(*device); } } - seen.extend(current.iter().copied()); - *previous = current; } - if new_readds > 0 { + let fresh_readds = delta_readds.get(group).copied().unwrap_or(0); + if fresh_readds > 0 { let times = self.readds.entry(*group).or_default(); - for _ in 0..new_readds { + for _ in 0..fresh_readds { times.push(now); } times.retain(|at| { @@ -1444,6 +1467,79 @@ impl GroupWarningWatcher { } fired } + + /// Folds the log events recorded since the previous evaluation and + /// counts the re-adds among them, per group. Only events the fold + /// applied count: a refused authorization authorizes nothing, and a + /// refused revocation revokes nothing. + /// + /// The first call only establishes the baseline — it adopts the fold's + /// current devices and counts nothing — because events carry no + /// timestamps and churn from before serve started must not be + /// reconstructed. A log that shrank since the previous evaluation (it + /// was replaced) likewise re-baselines instead of counting. + fn fold_new_events( + &mut self, + projection: &Projection, + events: &[crate::groups::Event], + ) -> std::collections::BTreeMap { + let mut counts = std::collections::BTreeMap::new(); + let Some(cursor) = self.events_seen else { + self.baseline(projection); + self.events_seen = Some(events.len()); + return counts; + }; + if cursor > events.len() { + self.baseline(projection); + self.events_seen = Some(events.len()); + return counts; + } + for event in &events[cursor..] { + let Some(group) = event.group else { + continue; + }; + let crate::groups::Body::Device(op) = &event.body else { + continue; + }; + if projection.outcome(&event.id) != Some(&crate::groups::Outcome::Applied) { + continue; + } + match op { + crate::groups::DeviceOp::Add { device, .. } => { + let seen = self.seen_devices.entry(group).or_default(); + let was_seen = seen.contains(device); + seen.insert(*device); + let authorized = self.authorized.entry(group).or_default(); + if !authorized.contains(device) { + authorized.insert(*device); + if was_seen { + *counts.entry(group).or_default() += 1; + } + } + } + crate::groups::DeviceOp::Revoke { device } => { + if let Some(authorized) = self.authorized.get_mut(&group) { + authorized.remove(device); + } + } + } + } + self.events_seen = Some(events.len()); + counts + } + + /// Adopts the fold's current devices as the watcher's tracked state, + /// counting nothing: the state before the baseline is history the + /// watcher did not observe. + fn baseline(&mut self, projection: &Projection) { + self.authorized.clear(); + self.seen_devices.clear(); + for (group, _view) in projection.groups() { + let current = projection.group_active_devices(group); + self.seen_devices.insert(*group, current.clone()); + self.authorized.insert(*group, current); + } + } } /// One warning evaluation pass over the group log at `path`. @@ -1472,7 +1568,7 @@ fn evaluate_group_warnings( return Vec::new(); } }; - watcher.evaluate(&projection, now) + watcher.evaluate(&projection, log.events(), now) } /// The current time as Unix seconds, for the warning evaluator's clock. @@ -1861,6 +1957,39 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn serve_group_warnings_fire_on_intra_interval_readd_churn() { + use crate::groups::Role; + + // #1847 regression: revoke + re-add cycles that complete inside + // one evaluation interval are invisible to a net-set comparison. + // Four cycles written to the group log with no evaluation in + // between must still count four re-adds at the next evaluation. + let dir = serve_test_dir("churn-intra-interval"); + let path = dir.join(GROUPS_FILE_NAME); + let group = group_log_with_members(&dir, 2); + let author: GroupKey = [1; 32]; + let device: GroupKey = [200; 32]; + let mut log = GroupLog::open(&path).unwrap(); + let mut watcher = GroupWarningWatcher::new(); + + // The first authorization is not a re-add, and warns about nothing. + log.device_add(author, group, device, Role::Read).unwrap(); + assert!(evaluate_group_warnings(&mut watcher, &path, 1_000).is_empty()); + + // Four revoke + re-authorize cycles, all inside one interval: + // no evaluation runs until every cycle is already in the log. + for _ in 0..4 { + log.device_revoke(author, group, device).unwrap(); + log.device_add(author, group, device, Role::Read).unwrap(); + } + let fired = evaluate_group_warnings(&mut watcher, &path, 1_001); + assert_eq!(fired.len(), 1); + assert_eq!(fired[0].0, group); + assert!(matches!(fired[0].1, Warning::Churn { readds: 4 })); + let _ = std::fs::remove_dir_all(&dir); + } + #[cfg(feature = "world")] #[test] fn the_server_ceiling_is_the_named_list_or_the_whole_catalog() { From 87c31e071b8da656bf329fa1a449973cd0638f7d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 2 Nov 2026 08:24:13 -0600 Subject: [PATCH 2/3] fix(id): replay revokes account-scoped in the group churn watcher Codex P2 on PR #4035: a device revocation ends only the revoking account's grant in the fold, but the watcher removed the device from the whole group set, so another account's later re-add was counted as churn even though the device stayed authorized throughout. The watcher now tracks the authorizing accounts per device (from device events, and from the fold at baseline) and removes a device only when its last grant ends. Adds a regression test: four revoke+re-add cycles by a second account while the first account's grant stands produce no churn warning. For #1847. --- pkgs/id/src/commands/serve.rs | 93 ++++++++++++++++++++++++++++++----- 1 file changed, 80 insertions(+), 13 deletions(-) diff --git a/pkgs/id/src/commands/serve.rs b/pkgs/id/src/commands/serve.rs index 76dc3fd7a..4e985c11d 100644 --- a/pkgs/id/src/commands/serve.rs +++ b/pkgs/id/src/commands/serve.rs @@ -1387,8 +1387,17 @@ const GROUP_WARNING_INTERVAL: std::time::Duration = std::time::Duration::from_se struct GroupWarningWatcher { evaluator: Evaluator, /// The devices authorized per group at the last event the watcher has - /// folded, tracked through the event stream, not just at evaluations. - authorized: std::collections::BTreeMap>, + /// folded, tracked through the event stream, not just at evaluations, + /// with the accounts whose grants authorize each device: a revocation + /// is account-scoped in the fold (it ends only the revoking account's + /// grant), so a device stays authorized while any account's grant for + /// it remains. An empty account set means the fold shows the device + /// authorized but the watcher has not observed a grant for it (the + /// device was adopted in the fold sync in `evaluate`). + authorized: std::collections::BTreeMap< + Hash, + std::collections::BTreeMap>, + >, /// Every device ever seen authorized per group. seen_devices: std::collections::BTreeMap>, /// The re-add times per group, as observed by this watcher. @@ -1433,11 +1442,11 @@ impl GroupWarningWatcher { let current = projection.group_active_devices(group); { let authorized = self.authorized.entry(*group).or_default(); - authorized.retain(|device| current.contains(device)); + authorized.retain(|device, _accounts| current.contains(device)); let seen = self.seen_devices.entry(*group).or_default(); for device in ¤t { - if !authorized.contains(device) { - authorized.insert(*device); + if !authorized.contains_key(device) { + authorized.insert(*device, std::collections::BTreeSet::new()); seen.insert(*device); } } @@ -1510,16 +1519,26 @@ impl GroupWarningWatcher { let was_seen = seen.contains(device); seen.insert(*device); let authorized = self.authorized.entry(group).or_default(); - if !authorized.contains(device) { - authorized.insert(*device); - if was_seen { - *counts.entry(group).or_default() += 1; - } + if !authorized.contains_key(device) && was_seen { + *counts.entry(group).or_default() += 1; } + authorized.entry(*device).or_default().insert(event.author); } crate::groups::DeviceOp::Revoke { device } => { + // A revocation is account-scoped in the fold: it ends + // only the revoking account's grant, so the device + // stays authorized while another account's grant for + // it remains (Codex review on PR #4035). Removing the + // device outright would count the other account's + // later re-add as churn that never happened. if let Some(authorized) = self.authorized.get_mut(&group) { - authorized.remove(device); + let mut ended = false; + if let Some(accounts) = authorized.get_mut(device) { + ended = accounts.remove(&event.author) && accounts.is_empty(); + } + if ended { + authorized.remove(device); + } } } } @@ -1534,10 +1553,25 @@ impl GroupWarningWatcher { fn baseline(&mut self, projection: &Projection) { self.authorized.clear(); self.seen_devices.clear(); - for (group, _view) in projection.groups() { + for (group, view) in projection.groups() { let current = projection.group_active_devices(group); self.seen_devices.insert(*group, current.clone()); - self.authorized.insert(*group, current); + // Record which accounts' grants authorize each device, so a + // later account-scoped revocation replays correctly against + // the baseline too. + let mut devices: std::collections::BTreeMap< + GroupKey, + std::collections::BTreeSet, + > = current + .iter() + .map(|device| (*device, std::collections::BTreeSet::new())) + .collect(); + for account in view.members.keys() { + for device in projection.active_devices(group, account) { + devices.entry(device).or_default().insert(*account); + } + } + self.authorized.insert(*group, devices); } } } @@ -1990,6 +2024,39 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn serve_group_warnings_ignore_other_accounts_revoke_readd_cycles() { + use crate::groups::Role; + + // Codex review on PR #4035: a revocation is account-scoped in the + // fold - it ends only the revoking account's grant. When account A + // has authorized a device, revoke + re-add cycles by account B + // never leave the device unauthorized (A's grant stands + // throughout), so they are not re-adds and must not fire the churn + // warning. + let dir = serve_test_dir("churn-other-account"); + let path = dir.join(GROUPS_FILE_NAME); + let group = group_log_with_members(&dir, 2); + let author: GroupKey = [1; 32]; + let other: GroupKey = [2; 32]; + let device: GroupKey = [200; 32]; + let mut log = GroupLog::open(&path).unwrap(); + let mut watcher = GroupWarningWatcher::new(); + + // Account A authorizes the device; the first evaluation adopts it. + log.device_add(author, group, device, Role::Read).unwrap(); + assert!(evaluate_group_warnings(&mut watcher, &path, 1_000).is_empty()); + + // Four revoke + re-add cycles by account B inside one interval: + // B's revokes do not touch A's grant, so nothing here is a re-add. + for _ in 0..4 { + log.device_revoke(other, group, device).unwrap(); + log.device_add(other, group, device, Role::Read).unwrap(); + } + assert!(evaluate_group_warnings(&mut watcher, &path, 1_001).is_empty()); + let _ = std::fs::remove_dir_all(&dir); + } + #[cfg(feature = "world")] #[test] fn the_server_ceiling_is_the_named_list_or_the_whole_catalog() { From aa5acd3a67cc7c5c7cc9f3efe5028a3ea3c5cc5a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 2 Nov 2026 08:54:11 -0600 Subject: [PATCH 3/3] fix(id): reconcile grant owners in the group churn watcher The evaluation reconciliation kept the device keys in step with the fold but preserved the tracked authorizing-account sets untouched. When an account that had authorized a device was removed from the group, its stale entry kept the device authorized through every later revoke by the remaining accounts, so genuine revoke+re-add cycles never counted as churn (Codex review on PR #4035). Refresh each active device's authorizing accounts from the fold (Projection::active_devices per member) during reconciliation, and pin it with serve_group_warnings_count_churn_after_a_grant_owner_is_removed: both accounts authorize, one is removed, then four cycles by the remaining account inside one interval fire the churn warning. --- pkgs/id/src/commands/serve.rs | 67 ++++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/pkgs/id/src/commands/serve.rs b/pkgs/id/src/commands/serve.rs index 4e985c11d..b04e6650a 100644 --- a/pkgs/id/src/commands/serve.rs +++ b/pkgs/id/src/commands/serve.rs @@ -1441,12 +1441,33 @@ impl GroupWarningWatcher { // re-add would be missed or counted twice. let current = projection.group_active_devices(group); { + // Refresh the authorizing accounts from the fold as well + // as the device keys: an account can stop authorizing a + // device without a device event of its own (its membership + // was removed), and a stale account left in the tracked + // set would keep the device authorized through every + // later revoke by the remaining accounts, hiding genuine + // churn (Codex review on PR #4035). + let mut fold_accounts: std::collections::BTreeMap< + GroupKey, + std::collections::BTreeSet, + > = std::collections::BTreeMap::new(); + for account in view.members.keys() { + for device in projection.active_devices(group, account) { + fold_accounts.entry(device).or_default().insert(*account); + } + } let authorized = self.authorized.entry(*group).or_default(); authorized.retain(|device, _accounts| current.contains(device)); let seen = self.seen_devices.entry(*group).or_default(); for device in ¤t { - if !authorized.contains_key(device) { + let is_new = !authorized.contains_key(device); + if let Some(accounts) = fold_accounts.get(device) { + authorized.insert(*device, accounts.clone()); + } else if is_new { authorized.insert(*device, std::collections::BTreeSet::new()); + } + if is_new { seen.insert(*device); } } @@ -2057,6 +2078,50 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn serve_group_warnings_count_churn_after_a_grant_owner_is_removed() { + use crate::groups::Role; + + // Codex review on PR #4035 (second round): when accounts A and B + // both authorize a device and A is then removed from the group, + // the device stays active through B, but the watcher's tracked + // account set must drop A too. A stale A would keep the device + // authorized through every later revoke by B, so genuine + // revoke + re-add cycles by B would never count as churn. + let dir = serve_test_dir("churn-grant-owner-removed"); + let path = dir.join(GROUPS_FILE_NAME); + let group = group_log_with_members(&dir, 2); + let author: GroupKey = [1; 32]; + let other: GroupKey = [2; 32]; + let device: GroupKey = [200; 32]; + let mut log = GroupLog::open(&path).unwrap(); + let mut watcher = GroupWarningWatcher::new(); + + // Both accounts authorize the device; the first evaluation + // adopts it with both grant owners tracked. + log.device_add(author, group, device, Role::Read).unwrap(); + log.device_add(other, group, device, Role::Read).unwrap(); + assert!(evaluate_group_warnings(&mut watcher, &path, 1_000).is_empty()); + + // Removing the other account leaves the device authorized + // through the author alone; the evaluation reconciles the + // tracked grant owners with the fold. Not itself a re-add. + log.remove(author, group, other, None).unwrap(); + assert!(evaluate_group_warnings(&mut watcher, &path, 1_001).is_empty()); + + // Four genuine revoke + re-add cycles by the remaining account, + // all inside one interval, must count four re-adds and warn. + for _ in 0..4 { + log.device_revoke(author, group, device).unwrap(); + log.device_add(author, group, device, Role::Read).unwrap(); + } + let fired = evaluate_group_warnings(&mut watcher, &path, 1_002); + assert_eq!(fired.len(), 1); + assert_eq!(fired[0].0, group); + assert!(matches!(fired[0].1, Warning::Churn { readds: 4 })); + let _ = std::fs::remove_dir_all(&dir); + } + #[cfg(feature = "world")] #[test] fn the_server_ceiling_is_the_named_list_or_the_whole_catalog() {