From d0f4c820f9eec7f4682ede79cd4dfc8dc103a18f Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 06:27:41 -0500 Subject: [PATCH 1/4] Index passes write onto the newest record and never drop each other's entries Each repository's record carries a version, and every write is conditioned on it. A pass that loses the race to another reads the newer record, merges its own files onto it and tries again, at most a few times (contracts::write_pass, over the versioned-write loop the app map's status already uses, now shared). A pass that keeps losing writes nothing, leaves the other pass's record intact and logs a warning. --- ..._contract_change_reaches_every_consumer.md | 2 +- services/common/src/app_map.rs | 42 ++- services/common/src/contracts.rs | 316 ++++++++++++++++-- services/worker/src/passes/code_graph.rs | 70 ++-- ..._contract_change_reaches_every_consumer.rs | 8 + 5 files changed, 381 insertions(+), 57 deletions(-) diff --git a/docs/incidents/xt_contract_change_reaches_every_consumer.md b/docs/incidents/xt_contract_change_reaches_every_consumer.md index 32a2dc24..65ba9667 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; 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..dedddf6b 100644 --- a/services/common/src/contracts.rs +++ b/services/common/src/contracts.rs @@ -1437,40 +1437,188 @@ 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>>; + +/// 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, + 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): + /// another pass's entries for other files are always kept. + pub fn apply(&self, cur: Option<&Record>) -> Record { + let mut r = cur.cloned().unwrap_or_else(|| Record { + repo: self.repo.clone(), + ..Default::default() + }); + if let Some(tree) = &self.tree { + r.entries.retain(|e| tree.contains(&e.file)); + } + r.replace_files(&self.replaced, self.fresh.clone()); + r.commit = self.commit.clone(); + r + } +} + +/// 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: nothing was written, and + /// the stored record is theirs, intact. The caller says so. + Conflict, +} + +/// Writes `pass` onto the newest stored record, conditioned on its +/// version: a write that lost the race to another pass reads again and +/// merges onto it, at most [`WRITE_TRIES`] times, so overlapping passes on +/// one repository never drop each other's entries. +pub async fn write_pass( + store: &dyn RecordStore, 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()), - ) - .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(()) + pass: &Pass, +) -> Result { + let out = crate::app_map::write_versioned( + WRITE_TRIES, + || store.read(team_id, &pass.repo), + |next: Record, version| store.put(team_id, next, version), + |cur| Some(pass.apply(cur)), + ) + .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)) + } + Some(crate::app_map::Versioned::Kept(_)) | None => 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 { @@ -2032,6 +2180,108 @@ 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: format!("c-{file}"), + replaced: vec![file.into()], + fresh: extract(file, src, &all), + tree: None, + } + } + + /// Two passes on one repository overlap: each keeps the other's entries. + #[tokio::test] + async fn interleaved_passes_keep_both_passes_entries() { + let base = rec( + "acme/orders-api", + extract("src/a.ts", "app.get('/a/one', h);", &all), + ); + let store = Mem { + kept: std::sync::Mutex::new((Some(base), 1)), + race: std::sync::Mutex::new(Some(push( + "acme/orders-api", + "src/b.ts", + "app.get('/b/two', h);", + ))), + stubborn: false, + }; + let ours = push("acme/orders-api", "src/c.ts", "app.get('/c/three', h);"); + let Wrote::Saved(r) = write_pass(&store, "t", &ours).await.unwrap() else { + panic!("the pass should have been written after one retry"); + }; + let keys: BTreeSet<&str> = r.entries.iter().map(|e| e.key.as_str()).collect(); + assert_eq!(keys, ["/a/one", "/b/two", "/c/three"].into()); + let stored = store.kept.lock().unwrap().clone(); + assert_eq!(stored.0.unwrap(), r); + assert_eq!(stored.1, 3); + // A full pass drops only files no longer in its tree. + let mut full = push("acme/orders-api", "src/c.ts", "app.get('/c/three', h);"); + full.tree = Some(["src/b.ts".to_string(), "src/c.ts".to_string()].into()); + let Wrote::Saved(r) = write_pass(&store, "t", &full).await.unwrap() else { + panic!("no race this time"); + }; + let keys: BTreeSet<&str> = r.entries.iter().map(|e| e.key.as_str()).collect(); + assert_eq!(keys, ["/b/two", "/c/three"].into()); + } + + /// 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 base = rec( + "acme/orders-api", + extract("src/a.ts", "app.get('/a/one', h);", &all), + ); + let store = Mem { + kept: std::sync::Mutex::new((Some(base.clone()), 4)), + race: std::sync::Mutex::new(None), + stubborn: true, + }; + let ours = push("acme/orders-api", "src/c.ts", "app.get('/c/three', h);"); + assert_eq!( + write_pass(&store, "t", &ours).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..90774fcd 100644 --- a/services/worker/src/passes/code_graph.rs +++ b/services/worker/src/passes/code_graph.rs @@ -970,16 +970,20 @@ 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 with a record touches only its files; anything else 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)) => (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 +999,31 @@ 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 onto the newest stored record, conditioned on its version: + // a pass on the same repository that wrote in between keeps its + // entries (`common::contracts::write_pass`). + let pass = xc::Pass { + repo: repo.clone(), + commit: head.to_string(), + replaced: scanned.clone(), + fresh, + tree, + }; + let store = xc::DynamoRecords { + dynamo: &state.dynamo, + table, + }; + let record = match xc::write_pass(&store, &msg.team_id, &pass).await { + Ok(xc::Wrote::Saved(r)) => r, + Ok(xc::Wrote::Conflict) => { + warn!(repo = %repo, tries = xc::WRITE_TRIES, "Contract index: other passes kept writing this repository's record; this pass wrote nothing and the stored record is theirs, intact"); + return; + } + Err(e) => { + warn!(repo = %repo, error = %e, "Contract index: the record could not be written"); + 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 +1110,21 @@ 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 { + let empty = common::contracts::Pass { repo: repo.clone(), commit: "off".into(), - entries: Vec::new(), + tree: Some(Default::default()), + ..Default::default() + }; + 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_pass(&store, &msg.team_id, &empty).await? + { + warn!(repo = %repo, "Contract index: another pass kept writing this record; it is left as it is"); + } return Ok(()); } let github = GitHubClient::new( 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 234d43e5..ee81efba 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 @@ -279,6 +279,14 @@ 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, &msg.team_id, &pass)")); + assert!( + refresh.contains("Ok(xc::Wrote::Conflict)") && refresh.contains("this pass 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)")); From dc3db6928612ac4169b6f2683919efa63e56d938 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 07:23:14 -0500 Subject: [PATCH 2/4] An older index pass never overwrites or removes what a newer commit wrote Each file's entries in a repository's record carry the time of the commit they were read from, and so does a file a pass found gone. A pass merges file by file in that order: it replaces or removes a file's entries only when they came from a commit no newer than its own, and the record's commit moves only forward. A full pass that read an older tree and overlaps a push from a newer one keeps the push's new and rewritten files. --- ..._contract_change_reaches_every_consumer.md | 2 +- services/common/src/contracts.rs | 107 +++++++++++++++++- services/worker/src/passes/code_graph.rs | 26 ++++- ..._contract_change_reaches_every_consumer.rs | 3 +- 4 files changed, 128 insertions(+), 10 deletions(-) diff --git a/docs/incidents/xt_contract_change_reaches_every_consumer.md b/docs/incidents/xt_contract_change_reaches_every_consumer.md index 65ba9667..3a644d99 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. 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; 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. +- **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. Each file's entries carry the time of the commit they were read from, and the merge goes file by file in that order: a pass from an older commit never overwrites, or removes, what a newer one wrote; 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/contracts.rs b/services/common/src/contracts.rs index dedddf6b..e55fae25 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,14 @@ pub struct Record { pub commit: String, #[serde(default)] pub entries: Vec, + /// When the newest commit any pass wrote from was made (epoch seconds). + #[serde(default)] + pub at: i64, + /// Per file read, when the commit its entries (or its absence) came + /// from was made: a pass from an older commit never overwrites or + /// removes what a newer one wrote ([`Pass::apply`]). + #[serde(default, rename = "t", skip_serializing_if = "BTreeMap::is_empty")] + pub stamps: BTreeMap, } impl Record { @@ -1476,21 +1484,58 @@ pub struct Pass { /// 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>, + /// When the commit this pass read was made (epoch seconds): it decides, + /// file by file, which of two overlapping passes is newer. + pub at: i64, } impl Pass { - /// The record as this pass leaves it, over `cur` (the newest stored): - /// another pass's entries for other files are always kept. + /// The record as this pass leaves it, over `cur` (the newest stored), + /// file by file in commit order: a file this pass read replaces the + /// stored one only when the stored one came from a commit no newer than + /// this pass's; a file a full pass's tree no longer has goes only on + /// the same terms. What a newer commit wrote is always kept, and + /// another pass's entries for other files are never touched. pub fn apply(&self, cur: Option<&Record>) -> Record { let mut r = cur.cloned().unwrap_or_else(|| Record { repo: self.repo.clone(), ..Default::default() }); + let ours = |r: &Record, file: &str| r.stamps.get(file).copied().unwrap_or(0) <= self.at; + let mut owned: BTreeSet = self + .replaced + .iter() + .filter(|f| ours(&r, f)) + .cloned() + .collect(); if let Some(tree) = &self.tree { - r.entries.retain(|e| tree.contains(&e.file)); + let files: BTreeSet = r + .entries + .iter() + .map(|e| e.file.clone()) + .chain(r.stamps.keys().cloned()) + .collect(); + owned.extend( + files + .into_iter() + .filter(|f| !tree.contains(f) && ours(&r, f)), + ); + } + let fresh: Vec = self + .fresh + .iter() + .filter(|e| owned.contains(&e.file)) + .cloned() + .collect(); + let owned: Vec = owned.into_iter().collect(); + for f in &owned { + r.stamps.insert(f.clone(), self.at); + } + r.replace_files(&owned, fresh); + if self.at >= r.at { + r.at = self.at; + r.commit = self.commit.clone(); } - r.replace_files(&self.replaced, self.fresh.clone()); - r.commit = self.commit.clone(); r } } @@ -2023,6 +2068,7 @@ mod tests { repo: repo.into(), commit: "c".into(), entries, + ..Default::default() } } @@ -2223,9 +2269,58 @@ mod tests { replaced: vec![file.into()], fresh: extract(file, src, &all), tree: None, + at: 100, } } + /// A full pass that read an older commit overlaps a push from a newer + /// one: the push's new file, and its rewrite of an old one, survive; + /// the full pass still removes what its own commit knew was gone. + #[tokio::test] + async fn an_older_full_pass_never_drops_a_newer_pushs_entries() { + 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.stamps = [("src/a.ts".to_string(), 50), ("src/old.ts".to_string(), 50)].into(); + base.at = 50; + // The newer push (commit at 200) adds src/new.ts and rewrites src/a.ts. + 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)); + newer.at = 200; + // The full pass read commit 100: src/a.ts as it was, src/old.ts gone, + // src/new.ts not there yet. It loses its first race to the push. + let full = Pass { + repo: "acme/orders-api".into(), + commit: "c-100".into(), + replaced: vec!["src/a.ts".into()], + fresh: extract("src/a.ts", "app.get('/a/one', h);", &all), + tree: Some(["src/a.ts".to_string()].into()), + at: 100, + }; + let store = Mem { + kept: std::sync::Mutex::new((Some(base), 1)), + race: std::sync::Mutex::new(Some(newer)), + stubborn: false, + }; + let Wrote::Saved(r) = write_pass(&store, "t", &full).await.unwrap() else { + panic!("the full pass should have merged after one retry"); + }; + let keys: BTreeSet<&str> = r.entries.iter().map(|e| e.key.as_str()).collect(); + assert_eq!(keys, ["/a/two", "/new/route"].into()); + assert_eq!(r.stamps.get("src/new.ts"), Some(&200)); + assert_eq!(r.stamps.get("src/a.ts"), Some(&200)); + // Gone at commit 100, written at 50: removed, and remembered as gone. + assert_eq!(r.stamps.get("src/old.ts"), Some(&100)); + // The record says the newest commit it holds. + assert_eq!((r.commit.as_str(), r.at), ("c-src/new.ts", 200)); + } + /// Two passes on one repository overlap: each keeps the other's entries. #[tokio::test] async fn interleaved_passes_keep_both_passes_entries() { diff --git a/services/worker/src/passes/code_graph.rs b/services/worker/src/passes/code_graph.rs index 90774fcd..2ef04aac 100644 --- a/services/worker/src/passes/code_graph.rs +++ b/services/worker/src/passes/code_graph.rs @@ -703,7 +703,8 @@ 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 at = head_time(&github, owner, repo, &head).await; + refresh_contracts(state, &msg, &snapshot, &all_paths, &head, at).await; // Which files to (re)extract this pass. let targets: Vec = match &msg.changed_files { @@ -957,6 +958,7 @@ async fn refresh_contracts( snapshot: &crate::clients::repo_snapshot::RepoSnapshot, all_paths: &[String], head: &str, + at: i64, ) { use common::contracts as xc; let table = &state.config.settings_table_name; @@ -1008,6 +1010,7 @@ async fn refresh_contracts( replaced: scanned.clone(), fresh, tree, + at, }; let store = xc::DynamoRecords { dynamo: &state.dynamo, @@ -1114,6 +1117,8 @@ async fn contracts_pass( repo: repo.clone(), commit: "off".into(), tree: Some(Default::default()), + // Turned off now: everything written before goes. + at: chrono::Utc::now().timestamp(), ..Default::default() }; let store = common::contracts::DynamoRecords { @@ -1152,10 +1157,27 @@ async fn contracts_pass( changed_files: None, ..msg }; - refresh_contracts(state, &full, &snapshot, &all_paths, &head).await; + let at = head_time(&github, &full.repo_owner, &full.repo_name, &head).await; + refresh_contracts(state, &full, &snapshot, &all_paths, &head, at).await; Ok(()) } +/// When `head` was committed (epoch seconds): the order overlapping index +/// passes are merged in (`common::contracts::Pass::at`). `0` when GitHub +/// doesn't say, so such a pass never overrides or removes what a dated one +/// wrote. +async fn head_time(github: &GitHubClient, owner: &str, repo: &str, head: &str) -> i64 { + match github.commit_time(owner, repo, head).await { + Ok(t) => chrono::DateTime::parse_from_rfc3339(&t) + .map(|d| d.timestamp()) + .unwrap_or(0), + Err(e) => { + warn!(repo = %format!("{owner}/{repo}"), error = %e, "Contract index: the head's commit time couldn't be read; this pass yields to every dated one"); + 0 + } + } +} + /// 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 ee81efba..af9dbfb7 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)); @@ -289,7 +290,7 @@ fn the_index_is_used_not_bypassed() { 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, at)")); // 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("); From 165f32bf0eb8aa5edaa8fe180e7615acb76bd4fd Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 08:01:07 -0500 Subject: [PATCH 3/4] The branch's current head decides what the contract index holds, not commit times A pass writes only at the branch's current head. Before each write it reads the head again; a pass whose commit isn't it never writes its view, but reads the files that changed between the two, either way, and writes at the head, whether the branch moved forward or was reset back. A comparison too large to tell queues a full read instead. The version condition still guards writers at the same head. Each file's entries record the head they were read at, and only files with entries are kept, within the record's bound. Turning the graph off empties the record with no commit, so the first read once it is on again writes every file. Commit times are no longer used. --- ..._contract_change_reaches_every_consumer.md | 2 +- services/common/src/contracts.rs | 460 +++++++++++++----- services/worker/src/passes/code_graph.rs | 125 +++-- ..._contract_change_reaches_every_consumer.rs | 10 +- 4 files changed, 434 insertions(+), 163 deletions(-) diff --git a/docs/incidents/xt_contract_change_reaches_every_consumer.md b/docs/incidents/xt_contract_change_reaches_every_consumer.md index 3a644d99..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. 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. Each file's entries carry the time of the commit they were read from, and the merge goes file by file in that order: a pass from an older commit never overwrites, or removes, what a newer one wrote; 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. +- **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/contracts.rs b/services/common/src/contracts.rs index e55fae25..38beabb7 100644 --- a/services/common/src/contracts.rs +++ b/services/common/src/contracts.rs @@ -879,14 +879,10 @@ pub struct Record { pub commit: String, #[serde(default)] pub entries: Vec, - /// When the newest commit any pass wrote from was made (epoch seconds). - #[serde(default)] - pub at: i64, - /// Per file read, when the commit its entries (or its absence) came - /// from was made: a pass from an older commit never overwrites or - /// removes what a newer one wrote ([`Pass::apply`]). - #[serde(default, rename = "t", skip_serializing_if = "BTreeMap::is_empty")] - pub stamps: BTreeMap, + /// 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 { @@ -1451,6 +1447,10 @@ 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); @@ -1477,6 +1477,7 @@ pub trait RecordStore: Send + Sync { #[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, @@ -1484,60 +1485,82 @@ pub struct Pass { /// 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>, - /// When the commit this pass read was made (epoch seconds): it decides, - /// file by file, which of two overlapping passes is newer. - pub at: i64, } impl Pass { - /// The record as this pass leaves it, over `cur` (the newest stored), - /// file by file in commit order: a file this pass read replaces the - /// stored one only when the stored one came from a commit no newer than - /// this pass's; a file a full pass's tree no longer has goes only on - /// the same terms. What a newer commit wrote is always kept, and - /// another pass's entries for other files are never touched. + /// 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 ours = |r: &Record, file: &str| r.stamps.get(file).copied().unwrap_or(0) <= self.at; - let mut owned: BTreeSet = self - .replaced - .iter() - .filter(|f| ours(&r, f)) - .cloned() - .collect(); + let mut owned: BTreeSet = self.replaced.iter().cloned().collect(); if let Some(tree) = &self.tree { - let files: BTreeSet = r - .entries - .iter() - .map(|e| e.file.clone()) - .chain(r.stamps.keys().cloned()) - .collect(); owned.extend( - files - .into_iter() - .filter(|f| !tree.contains(f) && ours(&r, f)), + r.entries + .iter() + .map(|e| e.file.clone()) + .filter(|f| !tree.contains(f)), ); } - let fresh: Vec = self - .fresh - .iter() - .filter(|e| owned.contains(&e.file)) - .cloned() - .collect(); let owned: Vec = owned.into_iter().collect(); + r.replace_files(&owned, self.fresh.clone()); for f in &owned { - r.stamps.insert(f.clone(), self.at); + r.heads.remove(f); } - r.replace_files(&owned, fresh); - if self.at >= r.at { - r.at = self.at; - r.commit = self.commit.clone(); + 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(); + } +} + +/// 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. @@ -1545,25 +1568,71 @@ impl Pass { pub enum Wrote { /// The record as stored now. Saved(Record), - /// Every try lost the race to other writes: nothing was written, and - /// the stored record is theirs, intact. The caller says so. + /// 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, conditioned on its -/// version: a write that lost the race to another pass reads again and -/// merges onto it, at most [`WRITE_TRIES`] times, so overlapping passes on -/// one repository never drop each other's entries. +/// 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, + 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)), + ) + .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, - pass: &Pass, + repo: &str, ) -> Result { let out = crate::app_map::write_versioned( WRITE_TRIES, - || store.read(team_id, &pass.repo), + || store.read(team_id, repo), |next: Record, version| store.put(team_id, next, version), - |cur| Some(pass.apply(cur)), + |_| { + Some(Record { + repo: repo.to_string(), + ..Default::default() + }) + }, ) .await?; match out { @@ -1574,7 +1643,7 @@ pub async fn write_pass( .remove(team_id); Ok(Wrote::Saved(r)) } - Some(crate::app_map::Versioned::Kept(_)) | None => Ok(Wrote::Conflict), + _ => Ok(Wrote::Conflict), } } @@ -2265,113 +2334,266 @@ mod tests { fn push(repo: &str, file: &str, src: &str) -> Pass { Pass { repo: repo.into(), - commit: format!("c-{file}"), + commit: "h2".into(), replaced: vec![file.into()], fresh: extract(file, src, &all), tree: None, - at: 100, } } - /// A full pass that read an older commit overlaps a push from a newer - /// one: the push's new file, and its rewrite of an old one, survive; - /// the full pass still removes what its own commit knew was gone. - #[tokio::test] - async fn an_older_full_pass_never_drops_a_newer_pushs_entries() { + /// 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.stamps = [("src/a.ts".to_string(), 50), ("src/old.ts".to_string(), 50)].into(); - base.at = 50; - // The newer push (commit at 200) adds src/new.ts and rewrites src/a.ts. + 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)); - newer.at = 200; - // The full pass read commit 100: src/a.ts as it was, src/old.ts gone, - // src/new.ts not there yet. It loses its first race to the push. - let full = Pass { + 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: "c-100".into(), + commit: "h1".into(), replaced: vec!["src/a.ts".into()], fresh: extract("src/a.ts", "app.get('/a/one', h);", &all), - tree: Some(["src/a.ts".to_string()].into()), - at: 100, + tree: Some(set(&["src/a.ts"])), }; - let store = Mem { - kept: std::sync::Mutex::new((Some(base), 1)), - race: std::sync::Mutex::new(Some(newer)), - stubborn: false, + 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"); }; - let Wrote::Saved(r) = write_pass(&store, "t", &full).await.unwrap() else { - panic!("the full pass should have merged after one retry"); + 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"); }; - let keys: BTreeSet<&str> = r.entries.iter().map(|e| e.key.as_str()).collect(); - assert_eq!(keys, ["/a/two", "/new/route"].into()); - assert_eq!(r.stamps.get("src/new.ts"), Some(&200)); - assert_eq!(r.stamps.get("src/a.ts"), Some(&200)); - // Gone at commit 100, written at 50: removed, and remembered as gone. - assert_eq!(r.stamps.get("src/old.ts"), Some(&100)); - // The record says the newest commit it holds. - assert_eq!((r.commit.as_str(), r.at), ("c-src/new.ts", 200)); + 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"])); } - /// Two passes on one repository overlap: each keeps the other's entries. + /// 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); + } + + /// Two passes at the head overlap: each keeps the other's entries. #[tokio::test] async fn interleaved_passes_keep_both_passes_entries() { - let base = rec( + let mut base = rec( "acme/orders-api", extract("src/a.ts", "app.get('/a/one', h);", &all), ); - let store = Mem { - kept: std::sync::Mutex::new((Some(base), 1)), - race: std::sync::Mutex::new(Some(push( - "acme/orders-api", - "src/b.ts", - "app.get('/b/two', h);", - ))), - stubborn: false, - }; - let ours = push("acme/orders-api", "src/c.ts", "app.get('/c/three', h);"); - let Wrote::Saved(r) = write_pass(&store, "t", &ours).await.unwrap() else { + 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"); }; - let keys: BTreeSet<&str> = r.entries.iter().map(|e| e.key.as_str()).collect(); - assert_eq!(keys, ["/a/one", "/b/two", "/c/three"].into()); - let stored = store.kept.lock().unwrap().clone(); - assert_eq!(stored.0.unwrap(), r); - assert_eq!(stored.1, 3); - // A full pass drops only files no longer in its tree. - let mut full = push("acme/orders-api", "src/c.ts", "app.get('/c/three', h);"); - full.tree = Some(["src/b.ts".to_string(), "src/c.ts".to_string()].into()); - let Wrote::Saved(r) = write_pass(&store, "t", &full).await.unwrap() else { - panic!("no race this time"); - }; - let keys: BTreeSet<&str> = r.entries.iter().map(|e| e.key.as_str()).collect(); - assert_eq!(keys, ["/b/two", "/c/three"].into()); + 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 base = rec( + let mut base = rec( "acme/orders-api", extract("src/a.ts", "app.get('/a/one', h);", &all), ); - let store = Mem { - kept: std::sync::Mutex::new((Some(base.clone()), 4)), - race: std::sync::Mutex::new(None), - stubborn: true, - }; - let ours = push("acme/orders-api", "src/c.ts", "app.get('/c/three', h);"); + 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, "t", &ours).await.unwrap(), + write_pass(&store, &branch, "t", &mut ours, &all) + .await + .unwrap(), Wrote::Conflict ); assert_eq!(store.kept.lock().unwrap().clone(), (Some(base), 4)); diff --git a/services/worker/src/passes/code_graph.rs b/services/worker/src/passes/code_graph.rs index 2ef04aac..ee3b552c 100644 --- a/services/worker/src/passes/code_graph.rs +++ b/services/worker/src/passes/code_graph.rs @@ -703,8 +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. - let at = head_time(&github, owner, repo, &head).await; - refresh_contracts(state, &msg, &snapshot, &all_paths, &head, at).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 { @@ -958,7 +963,7 @@ async fn refresh_contracts( snapshot: &crate::clients::repo_snapshot::RepoSnapshot, all_paths: &[String], head: &str, - at: i64, + branch: &dyn common::contracts::BranchHead, ) { use common::contracts as xc; let table = &state.config.settings_table_name; @@ -972,11 +977,12 @@ async fn refresh_contracts( Some(_) => xc::load_record(&state.dynamo, table, &msg.team_id, &repo).await, None => None, }; - // A push with a record touches only its files; anything else is a full - // read, whose tree also says which files are gone. + // 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)) => (r, changed.clone(), None), + (Some(r), Some(changed)) if !r.commit.is_empty() => (r, changed.clone(), None), _ => ( xc::Record { repo: repo.clone(), @@ -1001,29 +1007,34 @@ async fn refresh_contracts( }; fresh.extend(xc::extract(path, &src, &|p| exposed.contains(p))); } - // Written onto the newest stored record, conditioned on its version: - // a pass on the same repository that wrote in between keeps its - // entries (`common::contracts::write_pass`). - let pass = xc::Pass { + // 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, - at, }; let store = xc::DynamoRecords { dynamo: &state.dynamo, table, }; - let record = match xc::write_pass(&store, &msg.team_id, &pass).await { + 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 kept writing this repository's record; this pass wrote nothing and the stored record is theirs, intact"); + 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) => { - warn!(repo = %repo, error = %e, "Contract index: the record could not be written"); + // 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; } }; @@ -1113,20 +1124,14 @@ 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::Pass { - repo: repo.clone(), - commit: "off".into(), - tree: Some(Default::default()), - // Turned off now: everything written before goes. - at: chrono::Utc::now().timestamp(), - ..Default::default() - }; + // 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, }; if let common::contracts::Wrote::Conflict = - common::contracts::write_pass(&store, &msg.team_id, &empty).await? + 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"); } @@ -1157,24 +1162,68 @@ async fn contracts_pass( changed_files: None, ..msg }; - let at = head_time(&github, &full.repo_owner, &full.repo_name, &head).await; - refresh_contracts(state, &full, &snapshot, &all_paths, &head, at).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(()) } -/// When `head` was committed (epoch seconds): the order overlapping index -/// passes are merged in (`common::contracts::Pass::at`). `0` when GitHub -/// doesn't say, so such a pass never overrides or removes what a dated one -/// wrote. -async fn head_time(github: &GitHubClient, owner: &str, repo: &str, head: &str) -> i64 { - match github.commit_time(owner, repo, head).await { - Ok(t) => chrono::DateTime::parse_from_rfc3339(&t) - .map(|d| d.timestamp()) - .unwrap_or(0), - Err(e) => { - warn!(repo = %format!("{owner}/{repo}"), error = %e, "Contract index: the head's commit time couldn't be read; this pass yields to every dated one"); - 0 - } +/// 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. + let mut paths: std::collections::BTreeSet = Default::default(); + for (a, b) in [(from, to), (to, from)] { + let files = self + .github + .compare_changed_files(self.owner, self.repo, a, b) + .await + .map_err(|e| e.to_string())?; + if files.len() >= 300 { + return Err("too many files changed to compare".into()); + } + 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) + }) } } 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 af9dbfb7..6cb51541 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 @@ -283,14 +283,14 @@ fn the_index_is_used_not_bypassed() { // 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, &msg.team_id, &pass)")); - assert!( - refresh.contains("Ok(xc::Wrote::Conflict)") && refresh.contains("this pass wrote nothing") - ); + 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, at)")); + 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("); From a8bbbfceacde09c139d41b4afac44acde4f3644d Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 08:15:28 -0500 Subject: [PATCH 4/4] A renamed or copied file's old path is read again when the head moved What changed between a pass's commit and the head is read from GitHub's comparison, both ways. A file renamed or copied names the path it came from as well (previous_filename), so a rename is its old path removed and its new one added, and no entries stay under the old path. A comparison that may be cut still queues a full read. --- services/common/src/contracts.rs | 93 ++++++++++++++++++++++++ services/worker/src/passes/code_graph.rs | 13 ++-- 2 files changed, 100 insertions(+), 6 deletions(-) diff --git a/services/common/src/contracts.rs b/services/common/src/contracts.rs index 38beabb7..0333703c 100644 --- a/services/common/src/contracts.rs +++ b/services/common/src/contracts.rs @@ -1551,6 +1551,31 @@ impl Pass { } } +/// 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 { @@ -2553,6 +2578,74 @@ mod tests { 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() { diff --git a/services/worker/src/passes/code_graph.rs b/services/worker/src/passes/code_graph.rs index ee3b552c..c832081f 100644 --- a/services/worker/src/passes/code_graph.rs +++ b/services/worker/src/passes/code_graph.rs @@ -1196,17 +1196,18 @@ impl common::contracts::BranchHead for GithubBranch<'_> { to: &'a str, ) -> common::contracts::StoreFut<'a, Result> { Box::pin(async move { - // Both ways: a branch moved forward, reset back, or both. + // 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 files = self + let compare = self .github - .compare_changed_files(self.owner, self.repo, a, b) + .get_diff(self.owner, self.repo, a, b) .await .map_err(|e| e.to_string())?; - if files.len() >= 300 { - return Err("too many files changed to compare".into()); - } + let files = common::contracts::compare_paths(&compare) + .ok_or("too many files changed to compare")?; paths.extend(files); } let mut out = Vec::new();