From 1bef46ae6a11a33684f5e8118a6e88ea5dda2f12 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 7 Nov 2026 12:44:57 -0500 Subject: [PATCH] Settings sweeps read by key, and the runs sweeps reach every run The settings table holds analytics, markers and every team's settings together, well over 100,000 items on a busy install. Two sweeps found their records by scanning all of it: the hourly automatic-fix sweep and the 15-minute name check. A shared index partition (INDEX#) now names each record; writers add to it, readers get each record by key, drop members whose record is gone, and rebuild the index from one full scan at most once a day. The PR-outcome sweeps scanned the runs table from the first page each tick with a 20-page cap, so runs past the cap were never reached once the table grew. They now save where the cap stopped and carry on from there. The install's only-team lookup read one 50-item page of the teams table, which also holds ticket locks; it now reads every page. --- services/common/src/hybrid/name_check.rs | 4 + services/common/src/lib.rs | 1 + services/common/src/log_findings.rs | 80 ++++-- services/common/src/settings_index.rs | 246 ++++++++++++++++++ services/gateway/src/routes/hybrid.rs | 12 + services/gateway/src/routes/hybrid_install.rs | 67 +++-- services/gateway/src/routes/log_findings.rs | 12 + .../worker/src/passes/hybrid_name_check.rs | 73 +++++- services/worker/src/passes/pr_outcomes.rs | 184 ++++++++++++- 9 files changed, 629 insertions(+), 50 deletions(-) create mode 100644 services/common/src/settings_index.rs diff --git a/services/common/src/hybrid/name_check.rs b/services/common/src/hybrid/name_check.rs index bc2a8202f..80743ffb9 100644 --- a/services/common/src/hybrid/name_check.rs +++ b/services/common/src/hybrid/name_check.rs @@ -22,6 +22,10 @@ use super::names::{self, NameRecord}; +/// The settings index naming every reserved name (`crate::settings_index`): +/// the gateway adds a name when it is claimed, the name check reads it. +pub const NAME_INDEX: &str = "HYBRIDNAME"; + /// Wrong answers in a row before a name is parked (15 minutes apart: about /// 45 minutes). pub const PARK_AFTER: u32 = 3; diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 266d68144..82a699f3a 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -63,6 +63,7 @@ pub mod github_wait; pub mod live; /// Log findings and the fix runs started from them. pub mod log_findings; +pub mod settings_index; // Which repo a log group's or alarm's code lives in, from evidence. pub mod log_reader; pub mod log_repo; diff --git a/services/common/src/log_findings.rs b/services/common/src/log_findings.rs index 9496b0594..20d7a4cb3 100644 --- a/services/common/src/log_findings.rs +++ b/services/common/src/log_findings.rs @@ -1244,33 +1244,52 @@ pub async fn load_ticket( }) } -/// Teams whose automatic fixes are on. +/// The settings index naming every team with an automatic-fix setting +/// ([`crate::settings_index`]); the gateway adds the team when it saves one. +pub const AUTOFIX_INDEX: &str = "LOG_AUTOFIX"; + +fn autofix_team(i: &Item) -> Option { + let team = s(i, "pk"); + (s(i, "sk") == AUTOFIX_SK && !team.is_empty()).then_some(team) +} + +/// How a full scan finds the automatic-fix settings (the index's rebuild). +pub fn autofix_index() -> crate::settings_index::Spec<'static> { + crate::settings_index::Spec { + name: AUTOFIX_INDEX, + filter: "sk = :sk", + values: vec![(":sk", attr(AUTOFIX_SK))], + member_of: autofix_team, + } +} + +/// Teams whose automatic fixes are on: each indexed team's setting, read by +/// key. This ran hourly as a scan of the whole settings table before. pub async fn teams_with_autofix( dynamo: &DynamoClient, settings_table: &str, ) -> Result, String> { + let teams = crate::settings_index::members(dynamo, settings_table, &autofix_index()).await?; let mut out = Vec::new(); - let mut start: Option = None; - loop { - let page = dynamo - .scan() + for team in teams { + let got = dynamo + .get_item() .table_name(settings_table) - .filter_expression("sk = :sk") - .expression_attribute_values(":sk", attr(AUTOFIX_SK)) - .set_exclusive_start_key(start.take()) + .key("pk", attr(&team)) + .key("sk", attr(AUTOFIX_SK)) .send() .await .map_err(|e| e.to_string())?; - for i in page.items() { - let cfg = AutoFix::from_item(Some(i)); - let team = s(i, "pk"); - if cfg.enabled && !team.is_empty() { - out.push((team, cfg)); + match got.item() { + None => { + crate::settings_index::remove(dynamo, settings_table, AUTOFIX_INDEX, &team).await + } + Some(i) => { + let cfg = AutoFix::from_item(Some(i)); + if cfg.enabled { + out.push((team, cfg)); + } } - } - match page.last_evaluated_key() { - Some(k) if !k.is_empty() => start = Some(k.clone()), - _ => break, } } Ok(out) @@ -2505,3 +2524,30 @@ mod tests { assert_eq!(daily_sk(t(NOW)), "LOG_AUTOFIX_RUNS#2026-10-21"); } } + +#[cfg(test)] +mod autofix_index_tests { + use super::*; + + fn item(pk: &str, sk: &str) -> Item { + HashMap::from([("pk".to_string(), attr(pk)), ("sk".to_string(), attr(sk))]) + } + + #[test] + fn only_automatic_fix_settings_become_index_members() { + assert_eq!( + autofix_team(&item("TEAM#a", AUTOFIX_SK)), + Some("TEAM#a".into()) + ); + assert_eq!(autofix_team(&item("TEAM#a", "ANALYTICS#x")), None); + assert_eq!(autofix_team(&item("", AUTOFIX_SK)), None); + } + + #[test] + fn the_rebuild_scan_matches_the_setting_key() { + let spec = autofix_index(); + assert_eq!(spec.name, AUTOFIX_INDEX); + assert_eq!(spec.filter, "sk = :sk"); + assert_eq!(spec.values[0].1, attr(AUTOFIX_SK)); + } +} diff --git a/services/common/src/settings_index.rs b/services/common/src/settings_index.rs new file mode 100644 index 000000000..7d334aade --- /dev/null +++ b/services/common/src/settings_index.rs @@ -0,0 +1,246 @@ +//! A small index partition in the settings table that names every record of +//! one kind, so a sweep reads those records by key instead of scanning the +//! whole table. +//! +//! The settings table holds analytics, markers and every team's settings +//! together; on a busy install it is well over 100,000 items. A sweep that +//! found its records with a filtered scan read all of it on every tick, and a +//! scan with a page cap stopped before reaching them at all. +//! +//! Layout (settings table): +//! - `pk = INDEX#`, `sk = `: one item per member (a team id, a +//! name). Writers add the member when they save the record. +//! - `pk = INDEX#`, `sk = #BUILT`: when the index was last rebuilt +//! from a full scan (`at`, RFC 3339). +//! +//! Readers rebuild the index from one full scan when it was never built or +//! the last rebuild is older than [`REBUILD_AFTER_HOURS`], so records saved +//! before the index existed, or by a writer that failed to add itself, are +//! found within a day. Readers check each member's record by key and drop +//! members whose record is gone. + +use std::collections::{BTreeSet, HashMap}; + +use aws_sdk_dynamodb::types::{AttributeValue, PutRequest, WriteRequest}; +use aws_sdk_dynamodb::Client as DynamoClient; +use chrono::{DateTime, Duration, Utc}; +use tracing::{info, warn}; + +pub type Item = HashMap; + +/// How old a rebuild may be before the next reader rebuilds again. +pub const REBUILD_AFTER_HOURS: i64 = 24; +const BUILT_SK: &str = "#BUILT"; + +/// One index: its name and how a full scan recognises its members. +pub struct Spec<'a> { + /// `INDEX#`. + pub name: &'a str, + /// The scan filter that matches the indexed records. + pub filter: &'a str, + pub values: Vec<(&'a str, AttributeValue)>, + /// The member a matching record stands for (`None` skips it). + pub member_of: fn(&Item) -> Option, +} + +fn s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +pub fn partition(name: &str) -> String { + format!("INDEX#{name}") +} + +/// Pure: whether a reader must rebuild, from the last rebuild time. +pub fn needs_rebuild(built_at: Option<&str>, now: DateTime) -> bool { + match built_at.and_then(|t| DateTime::parse_from_rfc3339(t).ok()) { + Some(t) => now - t.with_timezone(&Utc) >= Duration::hours(REBUILD_AFTER_HOURS), + None => true, + } +} + +/// Adds `member` to the index (writers call this when they save a record). +pub async fn add( + dynamo: &DynamoClient, + table: &str, + name: &str, + member: &str, +) -> Result<(), String> { + dynamo + .put_item() + .table_name(table) + .item("pk", s(&partition(name))) + .item("sk", s(member)) + .send() + .await + .map(|_| ()) + .map_err(|e| format!("index {name}: {e}")) +} + +/// Drops `member` from the index (its record is gone). +pub async fn remove(dynamo: &DynamoClient, table: &str, name: &str, member: &str) { + if let Err(e) = dynamo + .delete_item() + .table_name(table) + .key("pk", s(&partition(name))) + .key("sk", s(member)) + .send() + .await + { + warn!(index = name, member, error = %e, "Could not drop a stale index member"); + } +} + +/// Every member, rebuilding the index from one full scan when it is due. +pub async fn members( + dynamo: &DynamoClient, + table: &str, + spec: &Spec<'_>, +) -> Result, String> { + let pk = partition(spec.name); + let built = dynamo + .get_item() + .table_name(table) + .key("pk", s(&pk)) + .key("sk", s(BUILT_SK)) + .send() + .await + .map_err(|e| format!("index {}: {e}", spec.name))?; + let built_at = built + .item() + .and_then(|i| i.get("at")) + .and_then(|v| v.as_s().ok()) + .cloned(); + if needs_rebuild(built_at.as_deref(), Utc::now()) { + rebuild(dynamo, table, spec).await?; + } + let mut out = BTreeSet::new(); + let mut start: Option = None; + loop { + let page = dynamo + .query() + .table_name(table) + .key_condition_expression("pk = :p") + .expression_attribute_values(":p", s(&pk)) + .projection_expression("sk") + .set_exclusive_start_key(start.take()) + .send() + .await + .map_err(|e| format!("index {}: {e}", spec.name))?; + for i in page.items() { + if let Some(m) = i.get("sk").and_then(|v| v.as_s().ok()) { + if m != BUILT_SK { + out.insert(m.clone()); + } + } + } + match page.last_evaluated_key() { + Some(k) if !k.is_empty() => start = Some(k.clone()), + _ => break, + } + } + Ok(out.into_iter().collect()) +} + +/// One full scan for the indexed records, written as members, then the +/// rebuild time. Every page is read: a cap would leave members out. +async fn rebuild(dynamo: &DynamoClient, table: &str, spec: &Spec<'_>) -> Result<(), String> { + let pk = partition(spec.name); + let mut found = BTreeSet::new(); + let (mut start, mut pages): (Option, usize) = (None, 0); + loop { + let mut scan = dynamo + .scan() + .table_name(table) + .filter_expression(spec.filter) + .set_exclusive_start_key(start.take()); + for (k, v) in &spec.values { + scan = scan.expression_attribute_values(*k, v.clone()); + } + let page = scan + .send() + .await + .map_err(|e| format!("index {} rebuild: {e}", spec.name))?; + pages += 1; + found.extend(page.items().iter().filter_map(spec.member_of)); + match page.last_evaluated_key() { + Some(k) if !k.is_empty() => start = Some(k.clone()), + _ => break, + } + } + let members: Vec = found.into_iter().collect(); + for chunk in members.chunks(25) { + let writes = chunk + .iter() + .filter_map(|m| { + PutRequest::builder() + .item("pk", s(&pk)) + .item("sk", s(m)) + .build() + .ok() + .map(|p| WriteRequest::builder().put_request(p).build()) + }) + .collect::>(); + let mut pending = Some(HashMap::from([(table.to_string(), writes)])); + for _ in 0..5 { + let Some(req) = pending.take().filter(|r| r.values().any(|w| !w.is_empty())) else { + break; + }; + let r = dynamo + .batch_write_item() + .set_request_items(Some(req)) + .send() + .await + .map_err(|e| format!("index {} rebuild write: {e}", spec.name))?; + pending = r.unprocessed_items().cloned(); + } + if pending.is_some_and(|r| r.values().any(|w| !w.is_empty())) { + return Err(format!( + "index {} rebuild: some members were not written", + spec.name + )); + } + } + dynamo + .put_item() + .table_name(table) + .item("pk", s(&pk)) + .item("sk", s(BUILT_SK)) + .item("at", s(&Utc::now().to_rfc3339())) + .item("members", AttributeValue::N(members.len().to_string())) + .send() + .await + .map_err(|e| format!("index {} rebuild mark: {e}", spec.name))?; + info!( + index = spec.name, + pages, + members = members.len(), + "Rebuilt a settings index from a full scan" + ); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_never_built_index_is_rebuilt() { + assert!(needs_rebuild(None, Utc::now())); + assert!(needs_rebuild(Some("not a time"), Utc::now())); + } + + #[test] + fn a_recent_rebuild_is_kept_and_an_old_one_is_redone() { + let now = DateTime::parse_from_rfc3339("2026-11-07T12:00:00Z") + .unwrap() + .with_timezone(&Utc); + assert!(!needs_rebuild(Some("2026-11-07T00:00:01Z"), now)); + assert!(needs_rebuild(Some("2026-11-06T12:00:00Z"), now)); + } + + #[test] + fn the_index_lives_in_its_own_partition() { + assert_eq!(partition("LOG_AUTOFIX"), "INDEX#LOG_AUTOFIX"); + } +} diff --git a/services/gateway/src/routes/hybrid.rs b/services/gateway/src/routes/hybrid.rs index e1289226d..5978604d5 100644 --- a/services/gateway/src/routes/hybrid.rs +++ b/services/gateway/src/routes/hybrid.rs @@ -740,6 +740,18 @@ pub async fn claim_name( ) }); } + // The 15-minute name check reads reservations from this index, not a + // table scan. A failed add is found by the index's daily rebuild. + if let Err(e) = common::settings_index::add( + &state.dynamo, + &state.config.settings_table_name, + common::hybrid::name_check::NAME_INDEX, + &name, + ) + .await + { + tracing::warn!(name = %name, error = %e, "Could not index the name reservation"); + } // The setup page for the name. CREATE: a name with any record already // in the zone (made outside this API) is refused, never overwritten. if let Err(e) = apply_dns(&name, &names::plan_claim(&name)).await { diff --git a/services/gateway/src/routes/hybrid_install.rs b/services/gateway/src/routes/hybrid_install.rs index b6eab18d9..a080d5106 100644 --- a/services/gateway/src/routes/hybrid_install.rs +++ b/services/gateway/src/routes/hybrid_install.rs @@ -1999,24 +1999,57 @@ fn intake_claim_message(code: &str) -> &'static str { } /// The install's team, when it has exactly one (the usual self-hosted case). +/// +/// Every page is read: the teams table also holds each team's ticket locks, +/// so one 50-item page could hold no team record at all, or only one of +/// several teams (and that one was then taken as the only team). async fn only_team(state: &AppState) -> Option { - let r = state - .dynamo - .scan() - .table_name(&state.config.teams_table_name) - .filter_expression("sk = :m") - .expression_attribute_values(":m", AttributeValue::S("META".into())) - .projection_expression("team_id") - .limit(50) - .send() - .await - .ok()?; - let ids: Vec = r - .items() - .iter() - .filter_map(|i| i.get("team_id")?.as_s().ok().cloned()) - .collect(); - (ids.len() == 1).then(|| ids[0].clone()) + let mut ids: Vec = Vec::new(); + let mut start = None; + loop { + let r = state + .dynamo + .scan() + .table_name(&state.config.teams_table_name) + .filter_expression("sk = :m") + .expression_attribute_values(":m", AttributeValue::S("META".into())) + .projection_expression("team_id") + .set_exclusive_start_key(start) + .send() + .await + .ok()?; + ids.extend( + r.items() + .iter() + .filter_map(|i| i.get("team_id")?.as_s().ok().cloned()), + ); + if ids.len() > 1 { + return None; + } + start = r.last_evaluated_key().filter(|k| !k.is_empty()).cloned(); + if start.is_none() { + break; + } + } + sole(ids) +} + +/// Pure: the one team, when there is exactly one. +fn sole(mut ids: Vec) -> Option { + ids.dedup(); + (ids.len() == 1).then(|| ids.remove(0)) +} + +#[cfg(test)] +mod only_team_tests { + use super::sole; + + #[test] + fn exactly_one_team_is_the_install_team() { + assert_eq!(sole(vec!["TEAM#a".into()]), Some("TEAM#a".into())); + assert_eq!(sole(vec![]), None); + assert_eq!(sole(vec!["TEAM#a".into(), "TEAM#b".into()]), None); + } } #[derive(Deserialize, Default)] diff --git a/services/gateway/src/routes/log_findings.rs b/services/gateway/src/routes/log_findings.rs index 4fbb293a2..e536e029d 100644 --- a/services/gateway/src/routes/log_findings.rs +++ b/services/gateway/src/routes/log_findings.rs @@ -749,6 +749,18 @@ async fn save_autofix(state: &AppState, team: &str, cfg: &AutoFix, by: &str) -> .send() .await .map_err(|e| internal("Could not save the automatic-fix setting", e))?; + // The hourly sweep reads teams from this index, not a table scan. A + // failed add is found by the index's daily rebuild. + if let Err(e) = common::settings_index::add( + &state.dynamo, + &state.config.settings_table_name, + lf::AUTOFIX_INDEX, + team, + ) + .await + { + tracing::warn!(team, error = %e, "Could not index the automatic-fix setting"); + } Ok(()) } diff --git a/services/worker/src/passes/hybrid_name_check.rs b/services/worker/src/passes/hybrid_name_check.rs index ca8710cf8..82c363a77 100644 --- a/services/worker/src/passes/hybrid_name_check.rs +++ b/services/worker/src/passes/hybrid_name_check.rs @@ -84,27 +84,47 @@ fn claim_from(i: &std::collections::HashMap) -> Option` / `NAME`). +/// The reservation's name, for the index rebuild's full scan. +fn reserved_name(i: &std::collections::HashMap) -> Option { + let sk = i.get("sk").and_then(|v| v.as_s().ok())?; + let pk = i.get("pk").and_then(|v| v.as_s().ok())?; + (sk == "NAME").then(|| pk.strip_prefix("HYBRIDNAME#").map(String::from))? +} + +fn name_index() -> common::settings_index::Spec<'static> { + common::settings_index::Spec { + name: name_check::NAME_INDEX, + filter: "begins_with(pk, :p) AND sk = :s", + values: vec![(":p", s("HYBRIDNAME#")), (":s", s("NAME"))], + member_of: reserved_name, + } +} + +/// Every name reservation (`HYBRIDNAME#` / `NAME`), read by key from +/// the names index. This was a scan of the whole settings table every 15 +/// minutes before. async fn claims(state: &WorkerState) -> Result, Error> { + let table = &state.config.settings_table_name; + let names = common::settings_index::members(&state.dynamo, table, &name_index()).await?; let mut out = vec![]; - let mut start = None; - loop { + for name in names { let r = state .dynamo - .scan() - .table_name(&state.config.settings_table_name) - .filter_expression("begins_with(pk, :p) AND sk = :s") - .expression_attribute_values(":p", s("HYBRIDNAME#")) - .expression_attribute_values(":s", s("NAME")) - .set_exclusive_start_key(start) + .get_item() + .table_name(table) + .key("pk", s(&format!("HYBRIDNAME#{name}"))) + .key("sk", s("NAME")) .send() .await?; - out.extend(r.items().iter().filter_map(claim_from)); - start = r.last_evaluated_key().cloned(); - if start.is_none() { - return Ok(out); + match r.item() { + None => { + common::settings_index::remove(&state.dynamo, table, name_check::NAME_INDEX, &name) + .await + } + Some(i) => out.extend(claim_from(i)), } } + Ok(out) } /// The install's recorded CloudFront address, when it is active, verified, @@ -563,3 +583,30 @@ mod tests { assert!(claim_from(&i).is_none()); } } + +#[cfg(test)] +mod name_index_tests { + use super::*; + use std::collections::HashMap; + + fn item(pk: &str, sk: &str) -> HashMap { + HashMap::from([("pk".to_string(), s(pk)), ("sk".to_string(), s(sk))]) + } + + #[test] + fn only_name_reservations_become_index_members() { + assert_eq!( + reserved_name(&item("HYBRIDNAME#acme", "NAME")), + Some("acme".into()) + ); + assert_eq!(reserved_name(&item("HYBRIDNAME#acme", "AUDIT#1")), None); + assert_eq!(reserved_name(&item("TEAM#x", "NAME")), None); + } + + #[test] + fn the_rebuild_scan_matches_what_the_old_scan_matched() { + let spec = name_index(); + assert_eq!(spec.name, name_check::NAME_INDEX); + assert_eq!(spec.filter, "begins_with(pk, :p) AND sk = :s"); + } +} diff --git a/services/worker/src/passes/pr_outcomes.rs b/services/worker/src/passes/pr_outcomes.rs index e6d6e002d..c9e68cbbc 100644 --- a/services/worker/src/passes/pr_outcomes.rs +++ b/services/worker/src/passes/pr_outcomes.rs @@ -150,6 +150,7 @@ async fn reconcile_finished( let cutoff = (now - chrono::Duration::hours(RECHECK_OPEN_AFTER_HOURS)).to_rfc3339(); let pending = find_runs( state, + "finished_outcomes", "#s IN (:s0, :s1, :s2, :s3) AND attribute_exists(pr_url) AND attribute_not_exists(pr_outcome) \ AND attribute_not_exists(pr_backfill) \ AND (attribute_not_exists(pr_outcome_checked_at) OR pr_outcome_checked_at < :cut)", @@ -247,20 +248,115 @@ async fn find_pending( ) -> Result, Box> { find_runs( state, + "merged_backfill", "#s = :merged AND attribute_not_exists(merged_at) AND attribute_not_exists(pr_backfill) AND attribute_exists(pr_url)", vec![(":merged", attr_s("merged"))], ) .await } +type Key = HashMap; + +/// The settings item holding where a sweep's scan stopped (`SYSTEM` / +/// `SCAN_CURSOR#`). +fn cursor_sk(sweep: &str) -> String { + format!("SCAN_CURSOR#{sweep}") +} + +/// What to do with the saved cursor after a tick's scan. +#[derive(Debug, PartialEq)] +enum CursorStep { + /// The tick filled up mid-scan: start from the same place next tick + /// (what it found is settled meanwhile and drops out of the filter). + Keep, + /// The page cap ran out: carry on from here next tick. + Save(Key), + /// The scan reached the end of the table: start over next tick. + Clear, +} + +/// Pure: the cursor step, from how the scan ended. +fn cursor_step(filled: bool, pages_left: bool, last: Option<&Key>) -> CursorStep { + match (filled, last.filter(|k| !k.is_empty())) { + (true, _) => CursorStep::Keep, + (false, Some(k)) if !pages_left => CursorStep::Save(k.clone()), + _ => CursorStep::Clear, + } +} + +fn key_from(item: Option<&Key>) -> Option { + let i = item?; + let team = i.get("team_id")?.clone(); + let run = i.get("run_id")?.clone(); + Some(HashMap::from([ + ("team_id".to_string(), team), + ("run_id".to_string(), run), + ])) +} + +async fn load_cursor(state: &WorkerState, sweep: &str) -> Option { + let r = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s("SYSTEM")) + .key("sk", attr_s(&cursor_sk(sweep))) + .send() + .await + .ok()?; + key_from(r.item()) +} + +async fn store_cursor(state: &WorkerState, sweep: &str, step: CursorStep) { + let table = &state.config.settings_table_name; + let r = match step { + CursorStep::Keep => return, + CursorStep::Clear => state + .dynamo + .delete_item() + .table_name(table) + .key("pk", attr_s("SYSTEM")) + .key("sk", attr_s(&cursor_sk(sweep))) + .send() + .await + .map(|_| ()) + .map_err(|e| e.to_string()), + CursorStep::Save(k) => { + let mut req = state + .dynamo + .put_item() + .table_name(table) + .item("pk", attr_s("SYSTEM")) + .item("sk", attr_s(&cursor_sk(sweep))) + .item("at", attr_s(&chrono::Utc::now().to_rfc3339())); + for (name, v) in k { + req = req.item(name, v); + } + req.send().await.map(|_| ()).map_err(|e| e.to_string()) + } + }; + if let Err(e) = r { + warn!(sweep, error = %e, "Could not save where the runs scan stopped"); + } +} + /// Scan for runs matching `filter` (`#s` = status), up to PER_TICK of them. +/// Each tick reads at most MAX_PAGES pages, starting where the last tick's +/// page cap stopped, so every run is reached however large the table grows +/// (a cap that restarted from the first page never reached later runs). async fn find_runs( state: &WorkerState, + sweep: &str, filter: &str, values: Vec<(&str, AttributeValue)>, ) -> Result, Box> { let mut out = Vec::new(); - let mut start: Option> = None; + let resumed = load_cursor(state, sweep).await; + let from_middle = resumed.is_some(); + let mut start: Option = resumed; + let mut pages = 0usize; + let mut last: Option = None; + let mut filled = false; for _ in 0..MAX_PAGES { let mut scan = state .dynamo @@ -276,6 +372,8 @@ async fn find_runs( .set_exclusive_start_key(start.take()) .send() .await?; + pages += 1; + last = resp.last_evaluated_key().cloned(); for i in resp.items() { let s = |k: &str| { i.get(k) @@ -298,14 +396,28 @@ async fn find_runs( installation_id, }); if out.len() >= PER_TICK { - return Ok(out); + filled = true; + break; } } - match resp.last_evaluated_key() { + if filled { + break; + } + match last.as_ref().filter(|k| !k.is_empty()) { Some(k) => start = Some(k.clone()), None => break, } } + let step = cursor_step(filled, pages < MAX_PAGES, last.as_ref()); + info!( + sweep, + pages, + found = out.len(), + from_middle, + reached_end = step == CursorStep::Clear, + "Runs scan" + ); + store_cursor(state, sweep, step).await; Ok(out) } @@ -355,6 +467,72 @@ async fn mark_unknown(state: &WorkerState, p: &Pending, why: &str) { mod tests { use super::*; + fn key(run: &str) -> Key { + HashMap::from([ + ("team_id".to_string(), attr_s("TEAM#a")), + ("run_id".to_string(), attr_s(run)), + ]) + } + + #[test] + fn a_tick_that_runs_out_of_pages_carries_on_from_there() { + assert_eq!( + cursor_step(false, false, Some(&key("r20"))), + CursorStep::Save(key("r20")) + ); + } + + #[test] + fn a_tick_that_reaches_the_end_starts_over_next_time() { + assert_eq!(cursor_step(false, true, None), CursorStep::Clear); + assert_eq!(cursor_step(false, false, None), CursorStep::Clear); + assert_eq!( + cursor_step(false, true, Some(&HashMap::new())), + CursorStep::Clear + ); + } + + #[test] + fn a_tick_that_fills_up_keeps_its_starting_point() { + assert_eq!(cursor_step(true, false, Some(&key("r9"))), CursorStep::Keep); + assert_eq!(cursor_step(true, true, None), CursorStep::Keep); + } + + /// Ticks over a table larger than the page cap: every page is reached, + /// which the old restart-from-the-first-page scan never did. + #[test] + fn every_page_is_reached_across_ticks() { + let total_pages = MAX_PAGES * 3 + 7; + let mut cursor: Option = None; + let mut seen = std::collections::BTreeSet::new(); + for _ in 0..10 { + let from = cursor.unwrap_or(0); + let mut pages = 0; + let mut page = from; + while pages < MAX_PAGES && page < total_pages { + seen.insert(page); + page += 1; + pages += 1; + } + let last = (page < total_pages).then(|| key(&format!("r{page}"))); + match cursor_step(false, pages < MAX_PAGES, last.as_ref()) { + CursorStep::Save(_) => cursor = Some(page), + CursorStep::Clear => cursor = None, + CursorStep::Keep => {} + } + } + assert_eq!(seen.len(), total_pages); + } + + #[test] + fn a_saved_cursor_is_read_back_as_the_table_key() { + let mut item = key("r5"); + item.insert("pk".into(), attr_s("SYSTEM")); + item.insert("at".into(), attr_s("2026-11-07T00:00:00Z")); + assert_eq!(key_from(Some(&item)), Some(key("r5"))); + assert_eq!(key_from(None), None); + } + #[test] fn merged_and_closed_prs_map_to_outcome_fields() { let merged = Outcome::Merged {