diff --git a/docs/incidents/xt_contract_change_reaches_every_consumer.md b/docs/incidents/xt_contract_change_reaches_every_consumer.md index 32a2dc24..3603a59d 100644 --- a/docs/incidents/xt_contract_change_reaches_every_consumer.md +++ b/docs/incidents/xt_contract_change_reaches_every_consumer.md @@ -6,7 +6,7 @@ **The guarantee (invariants, enforced in code):** -- **An installation index, cheap and current.** For every repository of the installation, the contracts it exposes and the ones it uses: HTTP endpoints, GraphQL root fields, events and queue messages, packages and the symbols other repositories import from them, and environment variables (`common::contracts`). It is extracted with plain patterns by the code graph's index pass, which already reads the repository: a first build reads every file, a push replaces only the changed files' entries. All of a team's records sit in one partition and are read in one query, kept in memory for ten minutes. Every bound is a constant: file size, files per pass, entries per file and per repository, the stored record's size, links per answer, excerpts and characters per prompt. A repository with no record yet, whatever its graph's state, is queued for a contracts-only read (its graph and build status untouched), a few per step, each at most once an hour; so are the dependents of a package a pass newly exposes. +- **An installation index, cheap and current.** For every repository of the installation, the contracts it exposes and the ones it uses: HTTP endpoints, GraphQL root fields, events and queue messages, packages and the symbols other repositories import from them, and environment variables (`common::contracts`). It is extracted with plain patterns by the code graph's index pass, which already reads the repository: a first build reads every file, a push replaces only the changed files' entries. Each write is conditioned on the record's version: a pass that loses the race to another reads the newer record and merges its own files onto it, a few times at most, so overlapping passes never drop each other's entries. The branch's current head is the authority: before it writes, a pass reads the head again, and a pass whose commit isn't it never writes its view; it reads the files that changed between the two, either way, and writes at the head, whether the branch moved forward or was reset back. Each file's entries record the head they were read at. Turning the graph off empties the record with no commit, so turning it on reads every file again; one that keeps losing writes nothing, leaves the other's record intact and says so. All of a team's records sit in one partition and are read in one query, kept in memory for ten minutes. Every bound is a constant: file size, files per pass, entries per file and per repository, the stored record's size, links per answer, excerpts and characters per prompt. A repository with no record yet, whatever its graph's state, is queued for a contracts-only read (its graph and build status untouched), a few per step, each at most once an hour; so are the dependents of a package a pass newly exposes. - **Planning.** The planner's first message lists what the ticket's likely files expose to other repositories and use from them. A plan whose files carry a contract another repository uses goes back once unless it changes every such repository (a group per repository, the multi-repository plan the run builds and links in merge order) or says how it stays compatible under `## Compatibility`. - **Coding, fix rounds and CI rounds.** The coder's first message carries the consumers' own lines, read from each repository's default branch, so every round through the coder starts knowing its callers. A round a person asks for loads the same index. - **Review.** The reviewer is shown each contract the change touches that another repository uses, and every contract the change removes or renames while a consumer still uses it is a required, blocking finding citing that consumer, whatever the model said. A removal is found by the patch's text, not by line numbers: a route moved to another method, a package renamed, a field or topic gone are each one. A rewrite that keeps the contract is not one. The reviewer's code graph covers the installation's other repositories too. diff --git a/services/common/src/app_map.rs b/services/common/src/app_map.rs index 31be49fb..a0b5559b 100644 --- a/services/common/src/app_map.rs +++ b/services/common/src/app_map.rs @@ -463,16 +463,50 @@ where P: Fn(Status, Option) -> PF, PF: std::future::Future>, { - for _ in 0..5 { + match write_versioned(5, read, put, change).await? { + Some(Versioned::Written(next)) => Ok(Updated::Written(next)), + Some(Versioned::Kept(cur)) => Ok(Updated::Kept(cur)), + None => Err("the map's build status kept changing; try again".into()), + } +} + +/// What a versioned write came to. +pub(crate) enum Versioned { + /// The new value was written. + Written(T), + /// The change didn't apply to the value as it is, which is kept. + Kept(Option), +} + +/// The one versioned-write loop in `common`: `read` gives the value and +/// its version, `change` the next value (or `None` to keep it), and `put` +/// writes it conditioned on the version read (`Ok(false)` when another +/// write came first, which reads again and asks `change` again). `Ok(None)` +/// when every one of `tries` lost the race: nothing was written, and the +/// stored value is the other writer's. +pub(crate) async fn write_versioned( + tries: usize, + read: R, + put: P, + change: impl Fn(Option<&T>) -> Option, +) -> Result>, String> +where + T: Clone, + R: Fn() -> RF, + RF: std::future::Future, Option), String>>, + P: Fn(T, Option) -> PF, + PF: std::future::Future>, +{ + for _ in 0..tries { let (cur, version) = read().await?; let Some(next) = change(cur.as_ref()) else { - return Ok(Updated::Kept(cur)); + return Ok(Some(Versioned::Kept(cur))); }; if put(next.clone(), version).await? { - return Ok(Updated::Written(next)); + return Ok(Some(Versioned::Written(next))); } } - Err("the map's build status kept changing; try again".into()) + Ok(None) } /// Writes `next` if the status is still at `version` (`Ok(false)` if not). diff --git a/services/common/src/contracts.rs b/services/common/src/contracts.rs index f7168dc0..0333703c 100644 --- a/services/common/src/contracts.rs +++ b/services/common/src/contracts.rs @@ -40,7 +40,7 @@ //! packages some repository of the installation exposes, so a repository's //! imports of public libraries cost nothing. -use std::collections::{BTreeSet, HashMap}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::sync::{Arc, LazyLock, Mutex}; use std::time::{Duration, Instant}; @@ -879,6 +879,10 @@ pub struct Record { pub commit: String, #[serde(default)] pub entries: Vec, + /// The head commit each file's entries were read at (only files that + /// have entries, so it stays within the record's own bound). + #[serde(default, rename = "h", skip_serializing_if = "BTreeMap::is_empty")] + pub heads: BTreeMap, } impl Record { @@ -1437,40 +1441,323 @@ pub async fn load_record( Record::from_body(body.as_ref()) } -/// Writes one repository's record; the team's index in memory is dropped -/// so the next read has it. -pub async fn save_record( - dynamo: &DynamoClient, - table: &str, +/// Versioned writes a pass of the index makes: one more try per lost race. +pub const WRITE_TRIES: usize = 5; + +/// A store call's future. +pub type StoreFut<'a, T> = std::pin::Pin + Send + 'a>>; + +/// The files that differ between two commits, each with its content at +/// the later one (`None`: gone there). +pub type Changed = Vec<(String, Option)>; + +/// A stored record and its version, as one read gives them. +pub type Versioned = (Option, Option); + +/// Where records are kept, each with a version every write moves on. +pub trait RecordStore: Send + Sync { + /// The repository's record and its version (`None`, `None` when it has + /// none; a version of `0` for a record written before versions). + fn read<'a>( + &'a self, + team_id: &'a str, + repo: &'a str, + ) -> StoreFut<'a, Result>; + /// Writes `record` as the next version if the stored one is still at + /// `version`; `Ok(false)` when another write came first. + fn put<'a>( + &'a self, + team_id: &'a str, + record: Record, + version: Option, + ) -> StoreFut<'a, Result>; +} + +/// What one index pass contributes to its repository's record. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Pass { + pub repo: String, + /// The head commit this pass read. + pub commit: String, + /// The files this pass read: their entries are replaced by `fresh`. + pub replaced: Vec, + pub fresh: Vec, + /// A full pass's tree: entries of files no longer in it go. `None` for + /// a push, which touches only its own files. + pub tree: Option>, +} + +impl Pass { + /// The record as this pass leaves it over `cur`, the newest stored. + /// Only a pass at the branch's current head is applied + /// ([`write_pass`]), so what it read is the truth: the files it read + /// take its entries, and a full pass removes every file its tree no + /// longer has, whichever commit wrote it. Other files' entries are + /// kept as they are. + pub fn apply(&self, cur: Option<&Record>) -> Record { + let mut r = cur.cloned().unwrap_or_else(|| Record { + repo: self.repo.clone(), + ..Default::default() + }); + let mut owned: BTreeSet = self.replaced.iter().cloned().collect(); + if let Some(tree) = &self.tree { + owned.extend( + r.entries + .iter() + .map(|e| e.file.clone()) + .filter(|f| !tree.contains(f)), + ); + } + let owned: Vec = owned.into_iter().collect(); + r.replace_files(&owned, self.fresh.clone()); + for f in &owned { + r.heads.remove(f); + } + for e in &self.fresh { + r.heads.insert(e.file.clone(), self.commit.clone()); + } + let files: BTreeSet<&str> = r.entries.iter().map(|e| e.file.as_str()).collect(); + r.heads.retain(|f, _| files.contains(f.as_str())); + r.commit = self.commit.clone(); + r + } + + /// The same pass moved to `head`: each file `changed` between the + /// commit it read and `head` is read again there (`Some` content) or + /// is gone (`None`). Imported symbols are kept as [`extract`] keeps them. + pub fn moved_to( + &mut self, + head: &str, + changed: &[(String, Option)], + keep: &dyn Fn(&str) -> bool, + ) { + for (path, src) in changed.iter().filter(|(p, _)| scans(p)) { + self.fresh.retain(|e| &e.file != path); + if !self.replaced.contains(path) { + self.replaced.push(path.clone()); + } + if let Some(src) = src { + self.fresh.extend(extract(path, src, keep)); + } + if let Some(tree) = &mut self.tree { + if src.is_some() { + tree.insert(path.clone()); + } else { + tree.remove(path); + } + } + } + self.commit = head.to_string(); + } +} + +/// Every path a GitHub comparison (`compare/{base}...{head}`) touches: +/// each file's own path, and for a file `renamed` or `copied` the path it +/// came from (`previous_filename`), so a rename is its old path removed and +/// its new one added. `None` when the comparison may be cut (300 files or +/// more): what changed can't be told in full. +pub fn compare_paths(compare: &Value) -> Option> { + let files = compare["files"] + .as_array() + .map(Vec::as_slice) + .unwrap_or(&[]); + if files.len() >= 300 { + return None; + } + let mut out: BTreeSet = BTreeSet::new(); + for f in files { + if let Some(p) = f["filename"].as_str() { + out.insert(p.to_string()); + } + if let Some(p) = f["previous_filename"].as_str() { + out.insert(p.to_string()); + } + } + Some(out.into_iter().collect()) +} + +/// The branch a repository's record follows: its current head, and what +/// changed between two commits of it. +pub trait BranchHead: Send + Sync { + /// The branch's head commit now. + fn head(&self) -> StoreFut<'_, Result>; + /// The files that differ between `from` and `to`, either way (a branch + /// moved forward or reset back), each with its content at `to`, or + /// `None` when `to` doesn't have it. `Err` when it can't be told in + /// full (a comparison too large): the caller reads the repository again. + fn changed<'a>(&'a self, from: &'a str, to: &'a str) -> StoreFut<'a, Result>; +} + +/// How a pass's write ended. +#[derive(Debug, Clone, PartialEq)] +pub enum Wrote { + /// The record as stored now. + Saved(Record), + /// Every try lost the race to other writes or a moving branch: nothing + /// was written, and the stored record is theirs, intact. The caller + /// says so. + Conflict, +} + +/// Writes `pass` onto the newest stored record. The branch's current +/// head is the authority: before each write the head is read again, and a +/// pass whose commit isn't it never writes its view; it reads the files +/// that changed between the two ([`Pass::moved_to`]) and tries again at +/// the head, whether the branch moved forward or was reset back. The write +/// itself is conditioned on the record's version, so two writers at the +/// same head never drop each other's entries. At most [`WRITE_TRIES`] +/// tries in all. +pub async fn write_pass( + store: &dyn RecordStore, + branch: &dyn BranchHead, team_id: &str, - record: &Record, -) -> Result<(), String> { - use aws_sdk_dynamodb::primitives::Blob; - use aws_sdk_dynamodb::types::AttributeValue; - dynamo - .put_item() - .table_name(table) - .item("pk", AttributeValue::S(pk(team_id))) - .item("sk", AttributeValue::S(sk(&record.repo))) - .item("repo", AttributeValue::S(record.repo.clone())) - .item("commit", AttributeValue::S(record.commit.clone())) - .item( - "entries", - AttributeValue::N(record.entries.len().to_string()), - ) - .item("body", AttributeValue::B(Blob::new(record.to_body()))) - .item( - "updated_at", - AttributeValue::S(chrono::Utc::now().to_rfc3339()), + pass: &mut Pass, + keep: &dyn Fn(&str) -> bool, +) -> Result { + for _ in 0..WRITE_TRIES { + let head = branch.head().await?; + if head != pass.commit { + let changed = branch.changed(&pass.commit, &head).await?; + pass.moved_to(&head, &changed, keep); + continue; + } + let p: &Pass = pass; + let out = crate::app_map::write_versioned( + 1, + || store.read(team_id, &p.repo), + |next: Record, version| store.put(team_id, next, version), + |cur| Some(p.apply(cur)), ) - .send() - .await - .map_err(|e| format!("{}", aws_sdk_dynamodb::error::DisplayErrorContext(e)))?; - CACHE - .lock() - .unwrap_or_else(|e| e.into_inner()) - .remove(team_id); - Ok(()) + .await?; + if let Some(crate::app_map::Versioned::Written(r)) = out { + CACHE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(team_id); + return Ok(Wrote::Saved(r)); + } + } + Ok(Wrote::Conflict) +} + +/// Empties a repository's record when its graph is turned off: no commit +/// and no stamp, so the next full read, once it is on again, writes every +/// file as the head has it. +pub async fn write_off( + store: &dyn RecordStore, + team_id: &str, + repo: &str, +) -> Result { + let out = crate::app_map::write_versioned( + WRITE_TRIES, + || store.read(team_id, repo), + |next: Record, version| store.put(team_id, next, version), + |_| { + Some(Record { + repo: repo.to_string(), + ..Default::default() + }) + }, + ) + .await?; + match out { + Some(crate::app_map::Versioned::Written(r)) => { + CACHE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(team_id); + Ok(Wrote::Saved(r)) + } + _ => Ok(Wrote::Conflict), + } +} + +/// The records on DynamoDB, versioned in `v`. +pub struct DynamoRecords<'a> { + pub dynamo: &'a DynamoClient, + pub table: &'a str, +} + +impl RecordStore for DynamoRecords<'_> { + fn read<'a>( + &'a self, + team_id: &'a str, + repo: &'a str, + ) -> StoreFut<'a, Result> { + Box::pin(async move { + use aws_sdk_dynamodb::types::AttributeValue; + let out = self + .dynamo + .get_item() + .table_name(self.table) + .key("pk", AttributeValue::S(pk(team_id))) + .key("sk", AttributeValue::S(sk(repo))) + .consistent_read(true) + .send() + .await + .map_err(|e| format!("{}", aws_sdk_dynamodb::error::DisplayErrorContext(e)))?; + let Some(item) = out.item() else { + return Ok((None, None)); + }; + let version = item + .get("v") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0); + let record = item + .get("body") + .and_then(|b| b.as_b().ok()) + .and_then(|b| Record::from_body(b.as_ref())); + Ok((record, Some(version))) + }) + } + + fn put<'a>( + &'a self, + team_id: &'a str, + record: Record, + version: Option, + ) -> StoreFut<'a, Result> { + Box::pin(async move { + use aws_sdk_dynamodb::primitives::Blob; + use aws_sdk_dynamodb::types::AttributeValue as A; + let mut put = self + .dynamo + .put_item() + .table_name(self.table) + .item("pk", A::S(pk(team_id))) + .item("sk", A::S(sk(&record.repo))) + .item("repo", A::S(record.repo.clone())) + .item("commit", A::S(record.commit.clone())) + .item("entries", A::N(record.entries.len().to_string())) + .item("body", A::B(Blob::new(record.to_body()))) + .item("updated_at", A::S(chrono::Utc::now().to_rfc3339())) + .item("v", A::N((version.unwrap_or(0) + 1).to_string())); + put = match version { + None => put.condition_expression("attribute_not_exists(pk)"), + Some(0) => put + .condition_expression("attribute_not_exists(#v)") + .expression_attribute_names("#v", "v"), + Some(v) => put + .condition_expression("#v = :v") + .expression_attribute_names("#v", "v") + .expression_attribute_values(":v", A::N(v.to_string())), + }; + match put.send().await { + Ok(_) => Ok(true), + Err(e) + if e.as_service_error() + .is_some_and(|se| se.is_conditional_check_failed_exception()) => + { + Ok(false) + } + Err(e) => Err(format!( + "{}", + aws_sdk_dynamodb::error::DisplayErrorContext(e) + )), + } + }) + } } async fn read_index(dynamo: &DynamoClient, table: &str, team_id: &str) -> Result { @@ -1875,6 +2162,7 @@ mod tests { repo: repo.into(), commit: "c".into(), entries, + ..Default::default() } } @@ -2032,6 +2320,378 @@ mod tests { assert!(dependents_of_new(&idx, &types, &none, &had, 10).is_empty()); } + /// Records in memory, versioned as DynamoDB keeps them. `race` runs + /// once, just before the first conditional write, as another pass + /// writing in between; `stubborn` makes every write lose. + #[derive(Default)] + struct Mem { + kept: std::sync::Mutex<(Option, i64)>, + race: std::sync::Mutex>, + stubborn: bool, + } + + impl RecordStore for Mem { + fn read<'a>(&'a self, _: &'a str, _: &'a str) -> StoreFut<'a, Result> { + let (r, v) = self.kept.lock().unwrap().clone(); + Box::pin(async move { Ok((r.clone(), r.map(|_| v))) }) + } + fn put<'a>( + &'a self, + _: &'a str, + record: Record, + version: Option, + ) -> StoreFut<'a, Result> { + if let Some(other) = self.race.lock().unwrap().take() { + let mut k = self.kept.lock().unwrap(); + let next = other.apply(k.0.as_ref()); + *k = (Some(next), k.1 + 1); + } + let mut k = self.kept.lock().unwrap(); + let current = k.0.as_ref().map(|_| k.1); + let ok = !self.stubborn && current == version; + if ok { + *k = (Some(record), k.1 + 1); + } + Box::pin(async move { Ok(ok) }) + } + } + + fn push(repo: &str, file: &str, src: &str) -> Pass { + Pass { + repo: repo.into(), + commit: "h2".into(), + replaced: vec![file.into()], + fresh: extract(file, src, &all), + tree: None, + } + } + + /// A branch in memory: its head, and per commit pair what changed. + struct Branch { + head: std::sync::Mutex, + changes: BTreeMap<(String, String), Changed>, + asked: std::sync::Mutex>, + } + + impl Branch { + fn at(head: &str) -> Self { + Branch { + head: std::sync::Mutex::new(head.into()), + changes: BTreeMap::new(), + asked: Default::default(), + } + } + } + + impl BranchHead for Branch { + fn head(&self) -> StoreFut<'_, Result> { + let h = self.head.lock().unwrap().clone(); + Box::pin(async move { Ok(h) }) + } + fn changed<'a>( + &'a self, + from: &'a str, + to: &'a str, + ) -> StoreFut<'a, Result> { + self.asked.lock().unwrap().push((from.into(), to.into())); + let got = self + .changes + .get(&(from.to_string(), to.to_string())) + .cloned() + .ok_or_else(|| "too large to compare".to_string()); + Box::pin(async move { got }) + } + } + + fn keys(r: &Record) -> BTreeSet { + r.entries.iter().map(|e| e.key.clone()).collect() + } + + fn set(k: &[&str]) -> BTreeSet { + k.iter().map(|s| s.to_string()).collect() + } + + fn stored(r: Record, v: i64) -> Mem { + Mem { + kept: std::sync::Mutex::new((Some(r), v)), + race: std::sync::Mutex::new(None), + stubborn: false, + } + } + + /// The record at commit h1: src/a.ts and src/old.ts. + fn at_h1() -> Record { + let mut base = rec("acme/orders-api", Vec::new()); + base.replace_files(&[], extract("src/a.ts", "app.get('/a/one', h);", &all)); + base.replace_files( + &[], + extract("src/old.ts", "app.get('/old/route', h);", &all), + ); + base.commit = "h1".into(); + base + } + + /// A full pass that read h1 overlaps a push at h2, which added src/new.ts + /// and rewrote src/a.ts. The full pass never writes its h1 view: it reads + /// what changed up to h2 and writes at h2, so the push's entries stay. + #[tokio::test] + async fn an_older_pass_overlapping_a_newer_push_keeps_the_pushs_entries() { + let mut newer = push("acme/orders-api", "src/new.ts", "app.get('/new/route', h);"); + newer.replaced.push("src/a.ts".into()); + newer + .fresh + .extend(extract("src/a.ts", "app.get('/a/two', h);", &all)); + let store = stored(at_h1(), 1); + *store.race.lock().unwrap() = Some(newer); + let mut branch = Branch::at("h2"); + branch.changes.insert( + ("h1".into(), "h2".into()), + vec![ + ( + "src/new.ts".into(), + Some("app.get('/new/route', h);".into()), + ), + ("src/a.ts".into(), Some("app.get('/a/two', h);".into())), + ], + ); + // The full pass read h1, where src/old.ts was already gone. + let mut full = Pass { + repo: "acme/orders-api".into(), + commit: "h1".into(), + replaced: vec!["src/a.ts".into()], + fresh: extract("src/a.ts", "app.get('/a/one', h);", &all), + tree: Some(set(&["src/a.ts"])), + }; + let Wrote::Saved(r) = write_pass(&store, &branch, "t", &mut full, &all) + .await + .unwrap() + else { + panic!("the full pass should have written at the head"); + }; + assert_eq!(keys(&r), set(&["/a/two", "/new/route"])); + assert_eq!(r.commit, "h2"); + assert_eq!(r.heads.get("src/new.ts").map(String::as_str), Some("h2")); + } + + /// The branch is reset from h2 back to h1: a pass at h1 is the head's + /// truth and replaces what the discarded commit wrote. + #[tokio::test] + async fn a_reset_to_an_older_commit_replaces_newer_entries() { + let mut h2 = at_h1(); + h2.replace_files( + &["src/a.ts".into()], + extract("src/a.ts", "app.get('/a/two', h);", &all), + ); + h2.replace_files( + &[], + extract("src/new.ts", "app.get('/new/route', h);", &all), + ); + h2.commit = "h2".into(); + let store = stored(h2, 3); + let branch = Branch::at("h1"); + let mut full = Pass { + repo: "acme/orders-api".into(), + commit: "h1".into(), + replaced: vec!["src/a.ts".into(), "src/old.ts".into()], + fresh: [ + extract("src/a.ts", "app.get('/a/one', h);", &all), + extract("src/old.ts", "app.get('/old/route', h);", &all), + ] + .concat(), + tree: Some(set(&["src/a.ts", "src/old.ts"])), + }; + let Wrote::Saved(r) = write_pass(&store, &branch, "t", &mut full, &all) + .await + .unwrap() + else { + panic!("a pass at the head always writes"); + }; + assert_eq!(keys(&r), set(&["/a/one", "/old/route"])); + assert_eq!(r.commit, "h1"); + assert!(branch.asked.lock().unwrap().is_empty()); + } + + /// Turned off, then on: the off record has no commit and no stamps, and + /// the first full read after it writes every file. + #[tokio::test] + async fn off_then_on_rebuilds_every_file() { + let store = stored(at_h1(), 2); + let Wrote::Saved(off) = write_off(&store, "t", "acme/orders-api").await.unwrap() else { + panic!("off is written"); + }; + assert!(off.entries.is_empty() && off.commit.is_empty() && off.heads.is_empty()); + let branch = Branch::at("h1"); + let mut on = Pass { + repo: "acme/orders-api".into(), + commit: "h1".into(), + replaced: vec!["src/a.ts".into(), "src/old.ts".into()], + fresh: [ + extract("src/a.ts", "app.get('/a/one', h);", &all), + extract("src/old.ts", "app.get('/old/route', h);", &all), + ] + .concat(), + tree: Some(set(&["src/a.ts", "src/old.ts"])), + }; + let Wrote::Saved(r) = write_pass(&store, &branch, "t", &mut on, &all) + .await + .unwrap() + else { + panic!("on is written"); + }; + assert_eq!(keys(&r), set(&["/a/one", "/old/route"])); + } + + /// The head moves while a pass runs: the pass reads what changed and + /// writes at the new head; no write ever carries its stale view. A move + /// it can't compare writes nothing and says so. + #[tokio::test] + async fn a_moved_head_triggers_a_reread_not_a_stale_write() { + let store = stored(at_h1(), 1); + let mut branch = Branch::at("h3"); + branch.changes.insert( + ("h1".into(), "h3".into()), + vec![("src/old.ts".into(), None)], + ); + let mut push1 = push("acme/orders-api", "src/a.ts", "app.get('/a/two', h);"); + push1.commit = "h1".into(); + let Wrote::Saved(r) = write_pass(&store, &branch, "t", &mut push1, &all) + .await + .unwrap() + else { + panic!("written at the head"); + }; + assert_eq!( + branch.asked.lock().unwrap().clone(), + vec![("h1".to_string(), "h3".to_string())] + ); + assert_eq!(r.commit, "h3"); + assert_eq!(keys(&r), set(&["/a/two"])); + // Nothing stored ever carried the h1 view after the move. + assert_eq!(store.kept.lock().unwrap().0.as_ref().unwrap().commit, "h3"); + // A move that can't be compared: an error, and nothing written. + let before = store.kept.lock().unwrap().clone(); + let mut stale = push("acme/orders-api", "src/a.ts", "app.get('/a/three', h);"); + stale.commit = "h0".into(); + assert!(write_pass(&store, &branch, "t", &mut stale, &all) + .await + .is_err()); + assert_eq!(store.kept.lock().unwrap().clone(), before); + } + + /// Renamed, copied and removed files in a comparison: a rename is its + /// old path and its new one. + #[test] + fn a_comparison_names_both_paths_of_a_rename() { + let cmp = json!({"files": [ + {"filename": "src/routes/titles.ts", "status": "renamed", "previous_filename": "src/routes/books.ts"}, + {"filename": "src/copy.ts", "status": "copied", "previous_filename": "src/orig.ts"}, + {"filename": "src/gone.ts", "status": "removed"}, + {"filename": "src/a.ts", "status": "modified"} + ]}); + assert_eq!( + compare_paths(&cmp).unwrap(), + [ + "src/a.ts", + "src/copy.ts", + "src/gone.ts", + "src/orig.ts", + "src/routes/books.ts", + "src/routes/titles.ts" + ] + .map(String::from) + .to_vec() + ); + let many: Vec = (0..300) + .map(|i| json!({"filename": format!("f{i}.ts")})) + .collect(); + assert_eq!(compare_paths(&json!({"files": many})), None); + } + + /// A file renamed while a pass runs: once the pass moves to the head, + /// nothing is left under the old path, and the new path has its entries. + #[tokio::test] + async fn a_rename_during_a_pass_leaves_no_entries_under_the_old_path() { + let mut base = at_h1(); + base.replace_files( + &[], + extract("src/routes/books.ts", "app.get('/books/:id', show);", &all), + ); + let store = stored(base, 1); + let cmp = json!({"files": [{"filename": "src/routes/titles.ts", "status": "renamed", "previous_filename": "src/routes/books.ts"}]}); + let at_h2: BTreeMap<&str, &str> = + [("src/routes/titles.ts", "app.get('/books/:id', show);")].into(); + let changed: Changed = compare_paths(&cmp) + .unwrap() + .into_iter() + .map(|p| { + let src = at_h2.get(p.as_str()).map(|s| s.to_string()); + (p, src) + }) + .collect(); + let mut branch = Branch::at("h2"); + branch.changes.insert(("h1".into(), "h2".into()), changed); + let mut pass = push("acme/orders-api", "src/a.ts", "app.get('/a/one', h);"); + pass.commit = "h1".into(); + let Wrote::Saved(r) = write_pass(&store, &branch, "t", &mut pass, &all) + .await + .unwrap() + else { + panic!("written at the head"); + }; + assert!(r.entries.iter().all(|e| e.file != "src/routes/books.ts")); + assert!(r + .entries + .iter() + .any(|e| e.file == "src/routes/titles.ts" && e.key == "/books/{}")); + assert!(!r.heads.contains_key("src/routes/books.ts")); + } + + /// Two passes at the head overlap: each keeps the other's entries. + #[tokio::test] + async fn interleaved_passes_keep_both_passes_entries() { + let mut base = rec( + "acme/orders-api", + extract("src/a.ts", "app.get('/a/one', h);", &all), + ); + base.commit = "h2".into(); + let store = stored(base, 1); + *store.race.lock().unwrap() = + Some(push("acme/orders-api", "src/b.ts", "app.get('/b/two', h);")); + let branch = Branch::at("h2"); + let mut ours = push("acme/orders-api", "src/c.ts", "app.get('/c/three', h);"); + let Wrote::Saved(r) = write_pass(&store, &branch, "t", &mut ours, &all) + .await + .unwrap() + else { + panic!("the pass should have been written after one retry"); + }; + assert_eq!(keys(&r), set(&["/a/one", "/b/two", "/c/three"])); + let kept = store.kept.lock().unwrap().clone(); + assert_eq!((kept.0.unwrap(), kept.1), (r, 3)); + } + + /// A conflict that outlasts the tries writes nothing: the stored record + /// is the other writer's, intact, and the caller is told. + #[tokio::test] + async fn a_conflict_past_the_tries_leaves_the_stored_record_intact() { + let mut base = rec( + "acme/orders-api", + extract("src/a.ts", "app.get('/a/one', h);", &all), + ); + base.commit = "h2".into(); + let mut store = stored(base.clone(), 4); + store.stubborn = true; + let branch = Branch::at("h2"); + let mut ours = push("acme/orders-api", "src/c.ts", "app.get('/c/three', h);"); + assert_eq!( + write_pass(&store, &branch, "t", &mut ours, &all) + .await + .unwrap(), + Wrote::Conflict + ); + assert_eq!(store.kept.lock().unwrap().clone(), (Some(base), 4)); + } + #[test] fn records_are_incremental_bounded_and_round_trip() { let mut r = rec("acme/a", extract("src/a.ts", "app.get('/a/b', h);", &all)); diff --git a/services/worker/src/passes/code_graph.rs b/services/worker/src/passes/code_graph.rs index 90f7fc4d..c832081f 100644 --- a/services/worker/src/passes/code_graph.rs +++ b/services/worker/src/passes/code_graph.rs @@ -703,7 +703,13 @@ async fn index_pass( // The installation's contract index follows the same pass // (`common::contracts`): a first build reads every file, a push only // the changed ones. - refresh_contracts(state, &msg, &snapshot, &all_paths, &head).await; + let branch_head = GithubBranch { + github: &github, + owner, + repo, + branch: &branch, + }; + refresh_contracts(state, &msg, &snapshot, &all_paths, &head, &branch_head).await; // Which files to (re)extract this pass. let targets: Vec = match &msg.changed_files { @@ -957,6 +963,7 @@ async fn refresh_contracts( snapshot: &crate::clients::repo_snapshot::RepoSnapshot, all_paths: &[String], head: &str, + branch: &dyn common::contracts::BranchHead, ) { use common::contracts as xc; let table = &state.config.settings_table_name; @@ -970,16 +977,21 @@ async fn refresh_contracts( Some(_) => xc::load_record(&state.dynamo, table, &msg.team_id, &repo).await, None => None, }; - let (mut record, files): (xc::Record, Vec) = match (stored, &msg.changed_files) { - (Some(r), Some(changed)) => (r, changed.clone()), - _ => ( - xc::Record { - repo: repo.clone(), - ..Default::default() - }, - all_paths.to_vec(), - ), - }; + // A push onto a record read at some commit touches only its files; + // anything else (no record, or one emptied when the graph was turned + // off) is a full read, whose tree also says which files are gone. + let (record, files, tree): (xc::Record, Vec, Option<_>) = + match (stored, &msg.changed_files) { + (Some(r), Some(changed)) if !r.commit.is_empty() => (r, changed.clone(), None), + _ => ( + xc::Record { + repo: repo.clone(), + ..Default::default() + }, + all_paths.to_vec(), + Some(all_paths.iter().cloned().collect()), + ), + }; let before: std::collections::BTreeSet = record.packages().into_iter().map(|(p, _)| p).collect(); let mut scanned: Vec = Vec::new(); @@ -995,12 +1007,37 @@ async fn refresh_contracts( }; fresh.extend(xc::extract(path, &src, &|p| exposed.contains(p))); } - record.commit = head.to_string(); - record.replace_files(&scanned, fresh); - if let Err(e) = xc::save_record(&state.dynamo, table, &msg.team_id, &record).await { - warn!(repo = %repo, error = %e, "Contract index: the record could not be written"); - return; - } + // Written only at the branch's current head: a pass whose head moved + // (forward, or reset back) reads what changed and writes there, and the + // write is conditioned on the record's version, so a pass on the same + // repository that wrote in between keeps its entries + // (`common::contracts::write_pass`). + let mut pass = xc::Pass { + repo: repo.clone(), + commit: head.to_string(), + replaced: scanned.clone(), + fresh, + tree, + }; + let store = xc::DynamoRecords { + dynamo: &state.dynamo, + table, + }; + let keep = |p: &str| exposed.contains(p); + let record = match xc::write_pass(&store, branch, &msg.team_id, &mut pass, &keep).await { + Ok(xc::Wrote::Saved(r)) => r, + Ok(xc::Wrote::Conflict) => { + warn!(repo = %repo, tries = xc::WRITE_TRIES, "Contract index: other passes or a moving branch kept this pass from writing; it wrote nothing and the stored record is intact"); + return; + } + Err(e) => { + // What changed since this pass's head couldn't be told: the + // repository is read again in full at its head. + warn!(repo = %repo, error = %e, "Contract index: the record could not be written; a full read is queued"); + queue_contract_read(state, &msg.team_id, &repo, msg.installation_id).await; + return; + } + }; info!(repo = %repo, files = scanned.len(), entries = record.entries.len(), "Contract index: repository brought to its head"); let Some(team) = team else { return; @@ -1087,12 +1124,17 @@ async fn contracts_pass( let table = &state.config.settings_table_name; let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); if !common::code_graph::is_enabled(&state.dynamo, table, &msg.team_id, &repo).await { - let empty = common::contracts::Record { - repo: repo.clone(), - commit: "off".into(), - entries: Vec::new(), + // Emptied, with no commit: once the graph is on again, its first + // read writes every file as the head has it. + let store = common::contracts::DynamoRecords { + dynamo: &state.dynamo, + table, }; - common::contracts::save_record(&state.dynamo, table, &msg.team_id, &empty).await?; + if let common::contracts::Wrote::Conflict = + common::contracts::write_off(&store, &msg.team_id, &repo).await? + { + warn!(repo = %repo, "Contract index: another pass kept writing this record; it is left as it is"); + } return Ok(()); } let github = GitHubClient::new( @@ -1120,10 +1162,72 @@ async fn contracts_pass( changed_files: None, ..msg }; - refresh_contracts(state, &full, &snapshot, &all_paths, &head).await; + let branch_head = GithubBranch { + github: &github, + owner: &full.repo_owner, + repo: &full.repo_name, + branch: &branch, + }; + refresh_contracts(state, &full, &snapshot, &all_paths, &head, &branch_head).await; Ok(()) } +/// A repository's branch on GitHub, as the contract index follows it. +struct GithubBranch<'a> { + github: &'a GitHubClient, + owner: &'a str, + repo: &'a str, + branch: &'a str, +} + +impl common::contracts::BranchHead for GithubBranch<'_> { + fn head(&self) -> common::contracts::StoreFut<'_, Result> { + Box::pin(async move { + self.github + .get_ref(self.owner, self.repo, self.branch) + .await + .map_err(|e| e.to_string()) + }) + } + + fn changed<'a>( + &'a self, + from: &'a str, + to: &'a str, + ) -> common::contracts::StoreFut<'a, Result> { + Box::pin(async move { + // Both ways: a branch moved forward, reset back, or both. A + // rename or copy names its old path too, so a renamed file's + // old entries go (`common::contracts::compare_paths`). + let mut paths: std::collections::BTreeSet = Default::default(); + for (a, b) in [(from, to), (to, from)] { + let compare = self + .github + .get_diff(self.owner, self.repo, a, b) + .await + .map_err(|e| e.to_string())?; + let files = common::contracts::compare_paths(&compare) + .ok_or("too many files changed to compare")?; + paths.extend(files); + } + let mut out = Vec::new(); + for p in paths + .into_iter() + .filter(|p| common::contracts::scans(p)) + .take(common::contracts::MAX_SCAN_FILES) + { + let src = self + .github + .read_file_if_exists(self.owner, self.repo, &p, to) + .await + .map_err(|e| e.to_string())?; + out.push((p, src)); + } + Ok(out) + }) + } +} + /// Repositories read again at most when one pass newly exposes a package. const REQUEUE_CAP: usize = 10; diff --git a/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs b/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs index d845fd05..d23cb6e0 100644 --- a/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs +++ b/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs @@ -44,6 +44,7 @@ fn record(repo: &str, files: &[(&str, &str)]) -> Record { repo: repo.into(), commit: "c0ffee".into(), entries: Vec::new(), + ..Default::default() }; for (path, src) in files { r.replace_files(&[], xc::extract(path, src, &all)); @@ -279,9 +280,17 @@ fn the_index_is_used_not_bypassed() { assert!( super::fixture::fn_src(graph, "pub async fn run(").contains("contracts_pass(state, msg)") ); + // Every pass writes onto the newest record, conditioned on its version, + // and says so when other passes kept winning; no unconditioned write. + let refresh = super::fixture::fn_src(graph, "async fn refresh_contracts("); + assert!(refresh.contains("xc::write_pass(&store, branch, &msg.team_id, &mut pass, &keep)")); + assert!(refresh.contains("Ok(xc::Wrote::Conflict)") && refresh.contains("it wrote nothing")); + assert!(!graph.contains("save_record(")); // The index follows every push: the code graph's pass refreshes it. let pass = super::fixture::fn_src(graph, "async fn index_pass("); - assert!(pass.contains("refresh_contracts(state, &msg, &snapshot, &all_paths, &head)")); + assert!( + pass.contains("refresh_contracts(state, &msg, &snapshot, &all_paths, &head, &branch_head)") + ); // Every loop is offered find_consumers and told to ask it first. let provider = include_str!("../../agent/provider.rs"); let loop_ = super::fixture::fn_src(provider, "async fn converse_as(");