From 3a6ab7ea2ca7881b7cdb96cffb0113943cf41234 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 7 Nov 2026 12:44:53 -0500 Subject: [PATCH] Review sweeps read reviewer configs by key, so every repository is reached The stuck-review and review-reminder sweeps found their configs with a filtered scan of the whole settings table, capped at 50 pages. That table also holds analytics and rollups (about 137k items, 174 MB), so every tick stopped long before reaching the handful of configs: both sweeps reported no repositories on every run, stuck reviews were never sent again and reminders were never posted. The teams that have a per-repository config are now kept in an index partition (INDEX#REVIEW_CONFIG). Saving a config adds the team; readers rebuild the index from one full scan when it was never built or is a day old, so configs saved before the index existed are found. A member is the config's own partition key, so a team is swept however it is recorded elsewhere, including teams with no teams-table record. Both sweeps share one reader that queries each indexed team's configs by key, reads every page, drops teams with no configs left from the index, and logs how many teams and configs it read. --- services/common/src/lib.rs | 3 + services/common/src/review_config_index.rs | 83 ++++++ services/gateway/src/routes/reviewer.rs | 12 + services/worker/src/passes/mod.rs | 1 + services/worker/src/passes/review_configs.rs | 261 ++++++++++++++++++ services/worker/src/passes/review_reminder.rs | 97 ++----- services/worker/src/passes/review_sweep.rs | 85 +++--- 7 files changed, 421 insertions(+), 121 deletions(-) create mode 100644 services/common/src/review_config_index.rs create mode 100644 services/worker/src/passes/review_configs.rs diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 82a699f3a..d98bdeee7 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -81,6 +81,9 @@ pub mod merge_gate; pub mod messages; /// Retrying model API calls on transient failures, classified by status. pub mod model_retry; +/// The index of teams that have per-repository reviewer configs. +pub mod review_config_index; +/// Index partitions in the settings table, so sweeps read records by key. /// A repository's staging-only CMS write connection (for content the /// end-to-end tests read). pub mod staging_cms; diff --git a/services/common/src/review_config_index.rs b/services/common/src/review_config_index.rs new file mode 100644 index 000000000..9f4d0323a --- /dev/null +++ b/services/common/src/review_config_index.rs @@ -0,0 +1,83 @@ +//! The teams that have a per-repository reviewer config +//! (`pk = `, `sk = REVIEW_CONFIG#REPO#`), kept as a +//! [`settings_index`](crate::settings_index) so the review sweeps read the +//! configs by key. +//! +//! A member is the config's own partition key, so a team is found however +//! it is recorded elsewhere (with or without a record in the teams table). +//! The gateway adds the team when it saves a config; the daily rebuild finds +//! any config saved before the index existed. + +use aws_sdk_dynamodb::types::AttributeValue; + +use crate::settings_index::{Item, Spec}; + +/// `INDEX#REVIEW_CONFIG`. +pub const NAME: &str = "REVIEW_CONFIG"; +pub const CONFIG_PREFIX: &str = "REVIEW_CONFIG#REPO#"; + +/// The repository a config's sort key names, when it is one. +pub fn repo_of(sk: &str) -> Option<&str> { + sk.strip_prefix(CONFIG_PREFIX).filter(|r| r.contains('/')) +} + +/// The team a record stands for in the index: its partition key, when the +/// record is a repository config. +pub fn member_of(item: &Item) -> Option { + let sk = item.get("sk")?.as_s().ok()?; + repo_of(sk)?; + let pk = item.get("pk")?.as_s().ok()?; + (!pk.is_empty() && !pk.starts_with("INDEX#")).then(|| pk.clone()) +} + +/// How the daily rebuild finds every config. +pub fn spec() -> Spec<'static> { + Spec { + name: NAME, + filter: "begins_with(sk, :pfx)", + values: vec![(":pfx", AttributeValue::S(CONFIG_PREFIX.to_string()))], + member_of, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + fn item(pk: &str, sk: &str) -> Item { + HashMap::from([ + ("pk".to_string(), AttributeValue::S(pk.to_string())), + ("sk".to_string(), AttributeValue::S(sk.to_string())), + ]) + } + + #[test] + fn a_repository_config_stands_for_its_own_team() { + // A team known only by its members (no teams-table record) is still + // indexed: the member is the config's partition key. + assert_eq!( + member_of(&item("TEAM#members-only", "REVIEW_CONFIG#REPO#acme/web")).as_deref(), + Some("TEAM#members-only") + ); + } + + #[test] + fn other_records_are_not_members() { + assert_eq!(member_of(&item("TEAM#a", "REVIEW_CONFIG#GLOBAL")), None); + assert_eq!(member_of(&item("TEAM#a", "REVIEW_CONFIG#REPO#nope")), None); + assert_eq!(member_of(&item("TEAM#a", "ANALYTICS#deploys")), None); + assert_eq!( + member_of(&item("INDEX#REVIEW_CONFIG", "REVIEW_CONFIG#REPO#a/b")), + None + ); + } + + #[test] + fn the_index_has_its_own_partition() { + assert_eq!( + crate::settings_index::partition(NAME), + "INDEX#REVIEW_CONFIG" + ); + } +} diff --git a/services/gateway/src/routes/reviewer.rs b/services/gateway/src/routes/reviewer.rs index 7a504d998..1eaeada62 100644 --- a/services/gateway/src/routes/reviewer.rs +++ b/services/gateway/src/routes/reviewer.rs @@ -477,6 +477,18 @@ pub async fn update_config( error!("Failed to update reviewer config: {e}"); StatusCode::INTERNAL_SERVER_ERROR })?; + // The review sweeps find configs through this index; the daily rebuild + // adds the team if this write fails, so the save still succeeds. + if let Err(e) = common::settings_index::add( + &state.dynamo, + &state.config.settings_table_name, + common::review_config_index::NAME, + &claims.team_id, + ) + .await + { + tracing::warn!(error = %e, "Could not add the team to the reviewer config index"); + } // A repo the reviewer is set up for gets its code graph built (once), // unless the graph was turned off for it. diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 5c819ef6f..a0b71d265 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1105,6 +1105,7 @@ pub mod resume; mod review; pub mod review_actions; pub mod review_agent; +pub mod review_configs; #[cfg(test)] mod review_eval; pub(crate) mod review_fingerprint; diff --git a/services/worker/src/passes/review_configs.rs b/services/worker/src/passes/review_configs.rs new file mode 100644 index 000000000..ecd8c8881 --- /dev/null +++ b/services/worker/src/passes/review_configs.rs @@ -0,0 +1,261 @@ +//! Every repository's reviewer config, read by key. +//! +//! The configs live in the shared settings table under each team's partition +//! (`pk = `, `sk = REVIEW_CONFIG#REPO#`). That table also +//! holds analytics, rollups and markers, so a filtered scan of it walks every +//! item to find a handful of configs, and a page cap made the sweeps stop +//! before reaching them. Instead, the teams that have configs are kept in an +//! index partition (`INDEX#REVIEW_CONFIG`, see `common::review_config_index`) +//! and each team's configs are queried by key. Every page is read. + +use crate::passes::attr_s; +use crate::WorkerState; +use aws_sdk_dynamodb::types::AttributeValue; +use common::review_config_index::{self as index, CONFIG_PREFIX}; +use common::settings_index; +use std::collections::HashMap; +use std::future::Future; +use tracing::{info, warn}; + +pub type Item = HashMap; + +/// One reviewer config: the team, the repository and the raw record. +pub struct RepoConfig { + pub team_id: String, + pub repo: String, + pub item: Item, +} + +/// Reads every page `fetch` returns, until it says there are no more. +/// `limit` only guards against a read that never ends; reaching it is logged. +pub async fn drain_pages(what: &str, limit: usize, mut fetch: F) -> Option> +where + F: FnMut(Option) -> Fut, + Fut: Future, Option), String>>, +{ + let mut out = vec![]; + let mut next: Option = None; + for _ in 0..limit { + match fetch(next.take()).await { + Ok((items, more)) => { + out.extend(items); + match more { + Some(k) if !k.is_empty() => next = Some(k), + _ => return Some(out), + } + } + Err(e) => { + warn!(what, error = %e, "Reading reviewer configs failed"); + return None; + } + } + } + warn!( + what, + pages = limit, + read = out.len(), + "Reading reviewer configs stopped at its page guard" + ); + Some(out) +} + +/// Every config of the indexed teams. A team whose read fails is skipped +/// for this tick and counted; a team with no configs left is returned in +/// `empty` so its stale index entry can be dropped. +pub struct Collected { + pub configs: Vec, + pub failed: usize, + pub empty: Vec, +} + +/// Reads each team's configs with `team_configs`. Which teams to read comes +/// only from the index, never from how teams are recorded elsewhere. +pub async fn collect(teams: &[String], mut team_configs: F) -> Collected +where + F: FnMut(String) -> Fut, + Fut: Future>>, +{ + let mut out = Collected { + configs: vec![], + failed: 0, + empty: vec![], + }; + for team in teams { + match team_configs(team.clone()).await { + Some(c) if c.is_empty() => out.empty.push(team.clone()), + Some(c) => out.configs.extend(c), + None => out.failed += 1, + } + } + out +} + +async fn team_configs(state: &WorkerState, team_id: String) -> Option> { + let team = team_id.as_str(); + drain_pages("team configs", 100, |start| async move { + let resp = state + .dynamo + .query() + .table_name(&state.config.settings_table_name) + .key_condition_expression("pk = :p AND begins_with(sk, :pfx)") + .expression_attribute_values(":p", attr_s(team)) + .expression_attribute_values(":pfx", attr_s(CONFIG_PREFIX)) + .set_exclusive_start_key(start) + .send() + .await + .map_err(|e| aws_sdk_dynamodb::error::DisplayErrorContext(&e).to_string())?; + let configs = resp + .items() + .iter() + .filter_map(|item| { + let sk = item.get("sk").and_then(|v| v.as_s().ok())?; + let repo = index::repo_of(sk)?.to_string(); + Some(RepoConfig { + team_id: team.to_string(), + repo, + item: item.clone(), + }) + }) + .collect::>(); + Ok((configs, resp.last_evaluated_key().cloned())) + }) + .await +} + +/// Every reviewer config of every team that has one. +pub async fn all(state: &WorkerState, sweep: &str) -> Vec { + let table = &state.config.settings_table_name; + let teams = match settings_index::members(&state.dynamo, table, &index::spec()).await { + Ok(t) => t, + Err(e) => { + warn!(sweep, error = %e, "Could not read the reviewer config index"); + return vec![]; + } + }; + let got = collect(&teams, |t| team_configs(state, t)).await; + for gone in &got.empty { + settings_index::remove(&state.dynamo, table, index::NAME, gone).await; + } + info!( + sweep, + teams = teams.len(), + teams_failed = got.failed, + teams_dropped = got.empty.len(), + configs = got.configs.len(), + "Reviewer configs read" + ); + got.configs +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + + fn key(n: usize) -> Item { + HashMap::from([("pk".to_string(), AttributeValue::N(n.to_string()))]) + } + fn page_of(k: &Option) -> usize { + k.as_ref() + .and_then(|m| m.get("pk")) + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0) + } + fn cfg(team: &str, repo: &str) -> RepoConfig { + RepoConfig { + team_id: team.to_string(), + repo: repo.to_string(), + item: HashMap::new(), + } + } + + #[tokio::test] + async fn every_page_is_read_however_many_there_are() { + // 120 pages: more than the 50 the old scans stopped at. + let pages = 120; + let calls = RefCell::new(0); + let got = drain_pages("t", 1000, |start| { + *calls.borrow_mut() += 1; + let p = page_of(&start); + async move { + let more = (p + 1 < pages).then(|| key(p + 1)); + Ok::<_, String>((vec![format!("repo-{p}")], more)) + } + }) + .await + .unwrap(); + assert_eq!(got.len(), pages); + assert_eq!(got.last().unwrap(), "repo-119"); + assert_eq!(*calls.borrow(), pages); + } + + #[tokio::test] + async fn a_failed_read_returns_nothing_rather_than_a_partial_list() { + let got = drain_pages("t", 10, |start| { + let p = page_of(&start); + async move { + if p == 2 { + Err("throttled".to_string()) + } else { + Ok((vec![p], Some(key(p + 1)))) + } + } + }) + .await; + assert!(got.is_none()); + } + + #[tokio::test] + async fn the_guard_only_stops_a_read_that_never_ends() { + let got = drain_pages("t", 5, |start| { + let p = page_of(&start); + async move { Ok::<_, String>((vec![p], Some(key(p + 1)))) } + }) + .await + .unwrap(); + assert_eq!(got, vec![0, 1, 2, 3, 4]); + } + + #[tokio::test] + async fn a_team_with_no_teams_table_record_is_still_swept() { + // The index names the team from its config's own partition key, so a + // team that exists only as members (no META record) is read like any + // other. + let teams = vec![ + "TEAM#with-meta".to_string(), + "TEAM#members-only".to_string(), + ]; + let got = collect(&teams, |t| async move { + Some(vec![cfg( + &t, + &format!("{}/web", t.trim_start_matches("TEAM#")), + )]) + }) + .await; + let swept: Vec<_> = got.configs.iter().map(|c| c.team_id.as_str()).collect(); + assert_eq!(swept, vec!["TEAM#with-meta", "TEAM#members-only"]); + assert_eq!(got.failed, 0); + } + + #[tokio::test] + async fn one_failed_team_never_hides_the_others_and_empty_teams_are_dropped() { + let teams = vec![ + "TEAM#a".to_string(), + "TEAM#b".to_string(), + "TEAM#c".to_string(), + ]; + let got = collect(&teams, |t| async move { + match t.as_str() { + "TEAM#a" => None, + "TEAM#b" => Some(vec![]), + _ => Some(vec![cfg(&t, "acme/web")]), + } + }) + .await; + assert_eq!(got.failed, 1); + assert_eq!(got.empty, vec!["TEAM#b".to_string()]); + assert_eq!(got.configs.len(), 1); + assert_eq!(got.configs[0].team_id, "TEAM#c"); + } +} diff --git a/services/worker/src/passes/review_reminder.rs b/services/worker/src/passes/review_reminder.rs index ec42df4bb..5be2efad1 100644 --- a/services/worker/src/passes/review_reminder.rs +++ b/services/worker/src/passes/review_reminder.rs @@ -21,13 +21,11 @@ use crate::clients::github::GitHubClient; use crate::passes::{attr_n, attr_s}; use crate::WorkerState; -use aws_sdk_dynamodb::types::AttributeValue; use common::mcp_credentials::Kms; use common::notify::{self, store, Channels}; use std::collections::HashMap; use tracing::{info, warn}; -const CONFIG_PREFIX: &str = "REVIEW_CONFIG#REPO#"; const DEFAULT_COOLDOWN_HOURS: i64 = 4; /// Minimum quiet time before a head change may re-nudge. Head churn on an /// active PR must not beat this; only the full cooldown re-nudges otherwise. @@ -95,76 +93,41 @@ pub async fn run(state: &WorkerState) -> Result<(), Box Vec { let mut out = vec![]; - let mut last_key: Option> = None; - for page in 0..50 { - let mut req = state - .dynamo - .scan() - .table_name(&state.config.settings_table_name) - .filter_expression("begins_with(sk, :pfx) AND reminders_enabled = :t") - .expression_attribute_values(":pfx", attr_s(CONFIG_PREFIX)) - .expression_attribute_values(":t", AttributeValue::Bool(true)); - if let Some(k) = last_key.take() { - req = req.set_exclusive_start_key(Some(k)); + for cfg in super::review_configs::all(state, "review-reminder").await { + let item = &cfg.item; + let on = item + .get("reminders_enabled") + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(false); + if !on || !store::any_set(item) { + continue; } - let resp = match req.send().await { - Ok(r) => r, - Err(e) => { - warn!(error = %e, "Reminder config scan failed"); - break; - } + let cooldown_hours = item + .get("reminder_cooldown_hours") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .filter(|h| *h > 0) + .unwrap_or(DEFAULT_COOLDOWN_HOURS); + let cipher = Kms { + client: &state.kms, + key_id: "", }; - for item in resp.items() { - if !store::any_set(item) { - continue; - } - let team_id = item - .get("pk") - .and_then(|v| v.as_s().ok()) - .cloned() - .unwrap_or_default(); - let repo = item - .get("sk") - .and_then(|v| v.as_s().ok()) - .and_then(|sk| sk.strip_prefix(CONFIG_PREFIX).map(|s| s.to_string())) - .unwrap_or_default(); - if team_id.is_empty() || repo.is_empty() { - continue; - } - let cooldown_hours = item - .get("reminder_cooldown_hours") - .and_then(|v| v.as_n().ok()) - .and_then(|n| n.parse::().ok()) - .filter(|h| *h > 0) - .unwrap_or(DEFAULT_COOLDOWN_HOURS); - let cipher = Kms { - client: &state.kms, - key_id: "", - }; - let channels = store::open_all(&cipher, &team_id, item).await; - if channels.is_empty() { - warn!(repo = %repo, "Reminder channels could not be opened — skipping"); - continue; - } - out.push(RepoReminder { - team_id, - repo, - channels, - cooldown_secs: cooldown_hours * 3600, - }); - } - match resp.last_evaluated_key() { - Some(k) => last_key = Some(k.clone()), - None => return out, - } - if page == 49 { - warn!("Reminder config scan hit page cap (50) — some repos may be skipped this tick"); + let channels = store::open_all(&cipher, &cfg.team_id, item).await; + if channels.is_empty() { + warn!(repo = %cfg.repo, "Reminder channels could not be opened — skipping"); + continue; } + out.push(RepoReminder { + team_id: cfg.team_id, + repo: cfg.repo, + channels, + cooldown_secs: cooldown_hours * 3600, + }); } out } diff --git a/services/worker/src/passes/review_sweep.rs b/services/worker/src/passes/review_sweep.rs index 04edec738..caa26503c 100644 --- a/services/worker/src/passes/review_sweep.rs +++ b/services/worker/src/passes/review_sweep.rs @@ -28,8 +28,6 @@ pub const STUCK_AFTER_SECS: i64 = 30 * 60; /// How long the sweep won't re-run the same PR head again. const SWEEP_CLAIM_TTL_SECS: u64 = 24 * 3600; -const CONFIG_PREFIX: &str = "REVIEW_CONFIG#REPO#"; - /// One stored CoderHelm review of a PR (a `REVIEW#` record). #[derive(Debug, Clone, Default)] pub struct ReviewRecord { @@ -256,60 +254,39 @@ struct ReviewedRepo { label: String, } -/// Every repo with the reviewer on (and not killed). Paginated and bounded. +/// Every repo with the reviewer on (and not killed), read by key for every +/// team (see `review_configs`). async fn reviewed_repos(state: &WorkerState) -> Vec { - let mut out = vec![]; - let mut last_key: Option> = None; - for page in 0..50 { - let mut req = state - .dynamo - .scan() - .table_name(&state.config.settings_table_name) - .filter_expression("begins_with(sk, :pfx) AND enabled = :t") - .expression_attribute_values(":pfx", attr_s(CONFIG_PREFIX)) - .expression_attribute_values(":t", AttributeValue::Bool(true)); - if let Some(k) = last_key.take() { - req = req.set_exclusive_start_key(Some(k)); - } - let resp = match req.send().await { - Ok(r) => r, - Err(e) => { - warn!(error = %aws_sdk_dynamodb::error::DisplayErrorContext(&e), "Reviewer config scan failed"); - break; - } - }; - for item in resp.items() { - let killed = item - .get("killed") - .and_then(|v| v.as_bool().ok()) - .copied() - .unwrap_or(false); - let team_id = s_of(item, "pk"); - let repo = s_of(item, "sk") - .strip_prefix(CONFIG_PREFIX) - .unwrap_or("") - .to_string(); - if killed || team_id.is_empty() || !repo.contains('/') { - continue; - } - let label = Some(s_of(item, "label")) - .filter(|l| !l.is_empty()) - .unwrap_or_else(|| "ch-review".to_string()); - out.push(ReviewedRepo { - team_id, - repo, - label, - }); - } - match resp.last_evaluated_key() { - Some(k) => last_key = Some(k.clone()), - None => return out, - } - if page == 49 { - warn!("Reviewer config scan hit its page cap; some repos wait for the next sweep"); - } + super::review_configs::all(state, "stuck-review") + .await + .into_iter() + .filter_map(|c| reviewed(c.team_id, c.repo, &c.item)) + .collect() +} + +/// A config the sweep covers: the reviewer on and not killed. +fn reviewed( + team_id: String, + repo: String, + item: &HashMap, +) -> Option { + let flag = |k: &str| { + item.get(k) + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(false) + }; + if !flag("enabled") || flag("killed") || team_id.is_empty() { + return None; } - out + let label = Some(s_of(item, "label")) + .filter(|l| !l.is_empty()) + .unwrap_or_else(|| "ch-review".to_string()); + Some(ReviewedRepo { + team_id, + repo, + label, + }) } /// Runs the sweep over every reviewed repo of every team.