Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions services/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
83 changes: 83 additions & 0 deletions services/common/src/review_config_index.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
//! The teams that have a per-repository reviewer config
//! (`pk = <team>`, `sk = REVIEW_CONFIG#REPO#<owner/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<String> {
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"
);
}
}
12 changes: 12 additions & 0 deletions services/gateway/src/routes/reviewer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions services/worker/src/passes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
261 changes: 261 additions & 0 deletions services/worker/src/passes/review_configs.rs
Original file line number Diff line number Diff line change
@@ -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 = <team>`, `sk = REVIEW_CONFIG#REPO#<owner/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<String, AttributeValue>;

/// 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<T, F, Fut>(what: &str, limit: usize, mut fetch: F) -> Option<Vec<T>>
where
F: FnMut(Option<Item>) -> Fut,
Fut: Future<Output = Result<(Vec<T>, Option<Item>), String>>,
{
let mut out = vec![];
let mut next: Option<Item> = 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<RepoConfig>,
pub failed: usize,
pub empty: Vec<String>,
}

/// 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<F, Fut>(teams: &[String], mut team_configs: F) -> Collected
where
F: FnMut(String) -> Fut,
Fut: Future<Output = Option<Vec<RepoConfig>>>,
{
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<Vec<RepoConfig>> {
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::<Vec<_>>();
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<RepoConfig> {
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<Item>) -> 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");
}
}
Loading
Loading