diff --git a/docs/coder-loop.md b/docs/coder-loop.md index 36978cff1..694c0a93a 100644 --- a/docs/coder-loop.md +++ b/docs/coder-loop.md @@ -120,7 +120,58 @@ The causes were in the loop, not only in prompt wording: run) is judged again with what it found, even when it wrote no code (`proof::round_answered`, `incidents::cn_proof_answer_judged`). -7. **Rounds agree.** +7. **Commit and push.** + Each gate runs where the commit is made, not as a line in the prompt + (`common::push_gate`, `passes/push_checks.rs`). + + - **The checks come from the repository.** `run_checks` adds the scripts + of each package that owns a touched file: its test script, its type + check (`check-types`, `typecheck`) and its lint. When a non-test file + changed, the package's whole unit suite runs, because a shared helper + breaks callers outside the diff. Only a change to nothing but test + files runs just those files. This step replaces the test line taken + from the first workflow that had one. On one pull request that line was + another package's `npm test --passWithNoTests`: it reported "2 of 2 + checks passed" while `vitest` on the touched files exited 1. + - **Checks before every push** (`push_checks::before_push`, in the CI fix + round before `round::land`). If the checks ran on the fix's last edit + and passed, the fix is pushed and the commit records what ran. If they + failed, or never ran on the last edit, the fix is not pushed: the next + attempt continues on the same edits with the failing output. If the + sandbox couldn't run them (the install failed, or there is no sandbox), + the fix is pushed with an `Unverified:` line saying why and what ran. + - **The message matches the diff** (`round::land`, + `push_gate::true_message`). A message is rewritten from the diff when + it says revert, remove or drop while the diff adds test lines or more + than it removes, when it says add while the diff only removes, or when + it names a file the commit doesn't touch. + - **A revert takes its tests with it** (`push_gate::removed_symbols`, + `still_expected`). A commit that removes a definition a test still + names is held until that test is reverted or updated in the same + commit. + - **Two fixes per failing test** (`push_gate::FixLedger`, kept on the run + as `ci_test_fixes`). The failing tests are read from the failure report + or the log (vitest, jest, Playwright, pytest, cargo, go), or, when they + can't be, the failing checks are used. After two pushed fixes a test that + is still red stops the rounds: the pull request and the run name the + test and its error, and nothing more is pushed. The branch is never + rolled back to an older green head, and a planned task is never taken + out to turn CI green. Only a dependency run's newest set of bumps comes + out (`resume::take_out_failing_bumps`). Five of 53 runs had rolled back, + two of them with tests left behind that expected the reverted code. + - **No log is no reason to stop** (`push_gate::logs_unread_brief`, + `hold_no_logs`). When CI's job log can't be read, the fix brief gives + the owning package's commands so the fixer reproduces the failure in the + sandbox. Any sentence that blames the missing log is replaced. + - **Fixtures use looked-up ids, and tests are sized to the behaviour** + (`minimal_change::made_up_ids`, `repeated_cases`, in the habits check). + Ids like `sport-a` or `id-1` are sent back when the run's lookups + returned real ids. Three or more added cases that differ only in their + values are sent back as one case per behaviour. The size check (test + lines against code lines) runs too; it fires on the roughly 415 test + lines one run added for 50 lines of code. + +8. **Rounds agree.** Planned work that a review commit on the pull request took out is not built again by a planned-work round, and the run says which commit took it out. When an acceptance criterion of the ticket asks for it, the ticket diff --git a/docs/incidents/ga_fix_pushed_unchecked.md b/docs/incidents/ga_fix_pushed_unchecked.md new file mode 100644 index 000000000..1cccb0381 --- /dev/null +++ b/docs/incidents/ga_fix_pushed_unchecked.md @@ -0,0 +1,5 @@ +# ga. `ga_fix_pushed_unchecked` + +**What happened:** A pull request that removed a duplicated filter chip changed a shared slug helper and added about 415 lines of unit tests for about 50 lines of code, with fixture ids `sport-a` and `sport-b` although the run had looked up the two real records. CI went red on a test outside the diff. Every CI fix round's sandbox said "2 of 2 checks passed": its test step was another package's `npm test` with `--passWithNoTests`, so no touched test ran, while the coder's own `vitest run` of the touched files exited 1 four times. The fixes were pushed anyway. After four attempts the supervisor put a source file back to an older green head in a commit titled "Revert the change that broke CI" and left the tests that expected the reverted helper in place. + +**The guarantee:** The sandbox runs the owning package's own scripts: its whole unit suite when a non-test file changed, only the touched test files when nothing but tests changed, and its type check and lint (`common::push_gate::package_steps`). A CI fix is pushed only when those ran on its last edit and passed; one the sandbox couldn't check is pushed with `Unverified:` and what ran (`push_checks::before_push`). A commit message that disagrees with its diff is rewritten from it (`round::land`). A commit that removes a definition a test still names is held until the test goes with it. A failing test gets two pushed fixes; then the rounds stop with the test and its error named, and nothing is rolled back. Invented fixture ids and three or more test cases that differ only in their values go back to the coder (`minimal_change`). diff --git a/docs/incidents/gb_red_ci_stops_named.md b/docs/incidents/gb_red_ci_stops_named.md new file mode 100644 index 000000000..fadd8219e --- /dev/null +++ b/docs/incidents/gb_red_ci_stops_named.md @@ -0,0 +1,5 @@ +# gb. `gb_red_ci_stops_named` + +**What happened:** A pull request's end-to-end check failed on "selecting a camp adds it to the cart while registration is open" with `Subtotal$0`. After three fix attempts the supervisor rolled seven of the pull request's files back to an older green head. The test failed the same way on the result: the vendor portal had opened registration, so it was red on every branch. Five of the last 53 runs rolled their branch back the same way. + +**The guarantee:** Red checks never roll a ticket run's branch back to an older head or take a planned task out; only a dependency run's newest set of bumps comes out (`resume::take_out_failing_bumps`). A failing test gets at most two pushed fixes (`common::push_gate::FixLedger`, kept on the run as `ci_test_fixes`). Then the rounds stop, nothing more is pushed, and the pull request and the run name the test and its error. When CI's job log can't be read, the fixer reproduces the failure with the owning package's own commands in the sandbox, and a sentence that blames the unreadable log is replaced. diff --git a/services/common/src/fixture_ids.rs b/services/common/src/fixture_ids.rs new file mode 100644 index 000000000..63b806ebf --- /dev/null +++ b/services/common/src/fixture_ids.rs @@ -0,0 +1,126 @@ +//! A test fixture uses the ids the run looked up, not made-up ones. +//! +//! A run queried the production database, found the two records behind a +//! duplicated filter and quoted their ids in its evidence, then wrote test +//! fixtures with `sport-a` and `sport-b`. The test passed on data that +//! doesn't exist, and nobody could tell from it which records the bug was +//! about. +//! +//! [`looked_up_ids`] reads the ids out of the run's lookups (UUIDs, their +//! eight-character prefixes, long hex and numeric ids); [`made_up`] finds an +//! id-like value in a test's added lines that looks invented (`sport-a`, +//! `id-1`, `test-id`, `fake_user`) while real ids are on record. The check +//! of the change against the plan (`habits_check`) sends each one back. + +/// Ids a run's lookups returned, in order, each once. +pub fn looked_up_ids(lines: &[String]) -> Vec { + let re = regex::Regex::new( + r"\b(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{8}(?:…|\.\.\.)|[0-9a-f]{24,40})", + ) + .expect("valid regex"); + let mut out: Vec = Vec::new(); + for l in lines { + // Only what came back: the question may hold ids typed by hand. + let got = l.split("Came back:").nth(1).unwrap_or(""); + for m in re.find_iter(got) { + let id = m.as_str().trim_end_matches('…').trim_end_matches("..."); + if id.chars().any(|c| c.is_ascii_digit()) && !out.iter().any(|o| o == id) { + out.push(id.to_string()); + } + } + } + out +} + +/// Whether a fixture value looks invented rather than read. +pub fn looks_made_up(value: &str) -> bool { + let v = value.to_lowercase(); + let letter_or_digit = regex::Regex::new(r"^[a-z]+[-_][a-z0-9]$").expect("valid regex"); + let numbered = regex::Regex::new(r"^(?:id|item|row|rec)[-_]?\d{1,3}$").expect("valid regex"); + let filler = regex::Regex::new( + r"^(?:test|fake|mock|dummy|placeholder|sample|some|foo|bar)(?:[-_][a-z0-9-_]*)?$", + ) + .expect("valid regex"); + letter_or_digit.is_match(&v) || numbered.is_match(&v) || filler.is_match(&v) +} + +/// One invented fixture id. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MadeUp { + pub path: String, + pub value: String, +} + +/// Invented id values on the added lines of test files (`diff`: path, +/// status, patch), when the run looked up real ids (`looked`). An id-like +/// key: `id`, `…Id`, `…_id`, `ids`. +pub fn made_up(diff: &[(String, String, String)], looked: &[String]) -> Vec { + if looked.is_empty() { + return Vec::new(); + } + let key = + regex::Regex::new(r#"(?i)\b[a-z_]*(?:id|ids)\s*[:=]\s*\[?\s*["'`]([^"'`]{1,40})["'`]"#) + .expect("valid regex"); + let mut out: Vec = Vec::new(); + for (path, _, patch) in diff + .iter() + .filter(|(p, _, _)| crate::push_gate::is_test_file(p)) + { + for line in patch + .lines() + .filter(|l| l.starts_with('+') && !l.starts_with("+++")) + { + for c in key.captures_iter(line) { + let value = c[1].to_string(); + if looks_made_up(&value) + && !looked.iter().any(|l| l == &value) + && !out.iter().any(|m| m.path == *path && m.value == value) + { + out.push(MadeUp { + path: path.clone(), + value, + }); + } + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn made_up_ids_are_found_only_when_real_ones_were_looked_up() { + let lines = vec![ + "- [L1] Asked Production database: SELECT id FROM sport WHERE ... Came back: 4c2d9e10-1111-4a2b-8c3d-0a2b3c4d5e6f 'Multi-sport'; b7f3a2c8… 'Multi-Sport'".to_string(), + "- [L2] Asked it: SELECT 9f8e7d6c-0000-0000-0000-000000000000 Came back EMPTY".to_string(), + ]; + let ids = looked_up_ids(&lines); + assert_eq!( + ids, + vec!["4c2d9e10-1111-4a2b-8c3d-0a2b3c4d5e6f", "b7f3a2c8"] + ); + let diff = vec![ + ( + "src/test/filters.test.ts".to_string(), + "modified".to_string(), + "+ { id: 'sport-a', name: 'Multi-sport' },\n+ { id: \"sport-b\", name: 'Multi-Sport' },\n+ { sportId: '4c2d9e10-1111-4a2b-8c3d-0a2b3c4d5e6f' },\n- { id: 'old-1' }".to_string(), + ), + ( + "src/utils/filters.ts".to_string(), + "modified".to_string(), + "+const id = 'sport-a';".to_string(), + ), + ]; + let found = made_up(&diff, &ids); + assert_eq!( + found.iter().map(|m| m.value.as_str()).collect::>(), + vec!["sport-a", "sport-b"] + ); + assert!(made_up(&diff, &[]).is_empty()); + assert!(looks_made_up("id-1") && looks_made_up("test-id") && looks_made_up("fake_user")); + assert!(!looks_made_up("multi-sport") && !looks_made_up("4c2d9e10")); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 8c35553cb..92fe5244e 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -168,6 +168,8 @@ pub mod ci_repro; /// The last check on a pull request description: no section twice, no /// deploy maps, no empty "who this affects". pub mod description_lint; +/// A test fixture uses the ids the run looked up, not made-up ones. +pub mod fixture_ids; // A diff holds the lines the change needs: formatting-only hunks are told // apart and put back. pub mod diff_shape; @@ -204,6 +206,8 @@ pub mod pr_steps; /// A repository's pull request template as the description's structure. pub mod pr_template; pub mod preview; +/// What a fix must show before it is committed and pushed. +pub mod push_gate; pub mod run_prs; pub mod waiting_line; // review_stats: time-ordered review records for analytics diff --git a/services/common/src/push_gate.rs b/services/common/src/push_gate.rs new file mode 100644 index 000000000..689dec2ea --- /dev/null +++ b/services/common/src/push_gate.rs @@ -0,0 +1,999 @@ +//! What a fix must show before it is committed and pushed, read from the +//! commit itself, never from what the coder says about it. +//! +//! Three pull requests went wrong the same way. A CI fix round pushed while +//! the coder's own run of the touched tests failed: the sandbox's test step +//! ran another package's suite with `--passWithNoTests`, so "2 of 2 checks +//! passed" while `vitest` on the changed files exited 1, four times. A commit +//! titled "Revert the change that broke CI" put a source file back and left +//! the tests that expected the reverted behaviour in place. Twice the branch +//! was rolled back to an older green head as the "fix". +//! +//! The gates, each a function here and each called where the commit is made: +//! +//! - **Checks before every push** ([`verdict`], [`package_steps`]): the +//! commands come from the repository itself, the scripts of the package +//! that owns each touched test file and the steps its CI runs. A red +//! result holds the push; a fix nothing ran on is not pushed; a sandbox +//! that could not install pushes with an `Unverified:` line in the commit. +//! - **A commit message matches its diff** ([`message_problems`], +//! [`true_message`]): a message that says revert, remove or drop and adds +//! test lines, one that says add and only deletes, or one that names a +//! file the commit doesn't touch, is rewritten from the diff. +//! - **A revert takes its tests with it** ([`removed_symbols`], +//! [`still_expected`]): a definition the commit removes that a test still +//! names holds the push until the test goes in the same commit. +//! - **Two fixes per failing test** ([`FixLedger`]): a test still red after +//! two pushed fixes stops the fix rounds with the test and its error named. +//! Never a rollback to an older head. +//! - **No logs is no reason to stop** ([`logs_unread_brief`], +//! [`hold_no_logs`]): when CI's job log can't be read, the fixer is given +//! the repository's own commands to reproduce the failure locally, and a +//! sentence that blames the missing log is replaced. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +// ── Checks before every push ─────────────────────────────────────────────── + +/// What the sandbox's last check run on the commit's tree came to. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Checked { + /// A sandbox can run the repository's checks for this run. + pub sandbox: bool, + /// The commit touches test files. + pub touched_tests: bool, + pub tests_ran: bool, + pub tests_passed: bool, + pub types_ran: bool, + pub types_passed: bool, + /// Why the last attempt gave no result (the install failed, the build + /// had no result). + pub failure: Option, + /// The tree changed after the last check run, or none ran. + pub owed: bool, +} + +/// Whether a fix may be pushed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Verdict { + /// The checks ran on this tree and passed. + Verified, + /// The checks ran on this tree and failed: never pushed. + Red(String), + /// The checks could not run (no sandbox, the install failed): pushed + /// with an `Unverified:` line in the commit saying why. + Unverified(String), + /// The tree changed after the last check run: the checks run first. + Owed, +} + +/// The push verdict for a fix, from its last check run. +pub fn verdict(c: &Checked) -> Verdict { + if !c.sandbox { + return Verdict::Unverified("no sandbox could run the repository's checks".into()); + } + if let Some(why) = c.failure.as_deref().filter(|w| !w.trim().is_empty()) { + return Verdict::Unverified(format!("the sandbox gave no result ({})", why.trim())); + } + if c.owed { + return Verdict::Owed; + } + let mut red = Vec::new(); + if c.types_ran && !c.types_passed { + red.push("the type check"); + } + if c.tests_ran && !c.tests_passed { + red.push("the touched tests"); + } + if !red.is_empty() { + return Verdict::Red(format!("{} failed in the sandbox", red.join(" and "))); + } + if c.touched_tests && !c.tests_ran { + return Verdict::Unverified( + "no unit suite of the repository ran for this change (no test script covers the \ + changed package)" + .into(), + ); + } + Verdict::Verified +} + +/// The line an unverified commit carries. +pub fn unverified_line(why: &str) -> String { + format!( + "Unverified: {}. CI is the first run of this change.", + why.trim() + ) +} + +/// A check the sandbox runs before a push, from the repository's own files. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PkgStep { + /// `tests`, `types` or `lint`. + pub kind: &'static str, + /// The package folder ("" for the root). + pub dir: String, + pub cmd: String, +} + +/// A unit or component test file, by its name. +pub fn is_test_file(path: &str) -> bool { + let p = path.to_lowercase(); + let base = p.rsplit('/').next().unwrap_or(&p); + base.contains(".test.") || base.contains(".spec.") || p.contains("__tests__/") +} + +/// A test that needs a browser or deployed services: never a sandbox step. +fn is_browser_test(path: &str, script: &str) -> bool { + let p = path.to_lowercase(); + let s = script.to_lowercase(); + p.starts_with("e2e/") + || p.contains("/e2e/") + || ["playwright", "cypress", "e2e"] + .iter() + .any(|w| s.contains(w)) +} + +/// A source file a unit suite can cover (not a doc, an asset or a config). +pub fn is_code_file(path: &str) -> bool { + let p = path.to_lowercase(); + [ + ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".vue", ".svelte", + ] + .iter() + .any(|e| p.ends_with(e)) +} + +/// The package manager the repository's lockfiles name. +pub fn package_manager(root_files: &[String]) -> &'static str { + let has = |f: &str| root_files.iter().any(|p| p == f); + if has("pnpm-lock.yaml") { + "pnpm" + } else if has("yarn.lock") { + "yarn" + } else if has("bun.lockb") || has("bun.lock") { + "bun" + } else { + "npm" + } +} + +/// `run