A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
Fix print-mode goal wakeup after empty-turn backoff (#3408)
Sebastian Müller561274fb2461
diff --git a/.changes/fix-print-goal-empty-turn-wakeup.md b/.changes/fix-print-goal-empty-turn-wakeup.mdnew file mode 100644index 0000000000..7e42c80d53--- /dev/null+++ b/.changes/fix-print-goal-empty-turn-wakeup.md@@ -0,0 +1 @@+- Print-mode goals consume eligible empty-turn backoff wakeups and report the no-progress continuation cap rather than silently losing further progress.diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex acde36c2d1..463bcec19e 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -330,15 +330,57 @@ jobs:- name: Bootstrap the kernel venv (ready before the kernel e2e units)if: steps.selection.outputs.units != '0'run: ./target/debug/prime-agent --prime-agent-bootstrap+ # The targeted lifecycle comparisons use the recognized, pinned TS release+ # and only synthetic loopback providers/state. One leg avoids 8 downloads.+ - name: Compare the lifecycle binaries (pinned TS reference)+ id: lifecycle_parity+ if: matrix.shard == 1 && steps.selection.outputs.units != '0' && (hashFiles('scripts/review_graceful_shutdown_parity.py') != '' || hashFiles('scripts/review_goal_backoff_parity.py') != '' || hashFiles('scripts/review_draft_disconnect_parity.py') != '')+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ set -euo pipefail+ reference="${RUNNER_TEMP}/lifecycle-ts-reference"+ mkdir -p "${reference}"+ gh release download v0.9.8 --repo "${GITHUB_REPOSITORY}" \+ --pattern prime-agent-0.9.8-linux-x64.tar.gz --dir "${reference}"+ archive="${reference}/prime-agent-0.9.8-linux-x64.tar.gz"+ echo "83fb09129bf78e3e60268212cd70932166591b15188caa70c1b0efbcc76235e2 ${archive}" | sha256sum --check+ mkdir -p "${reference}/package"+ tar -xzf "${archive}" -C "${reference}/package"+ export PA_TS_ARCHIVE="${archive}"+ export PA_TS_BINARY="${reference}/package/prime-agent"+ export PA_RUST_BINARY="${GITHUB_WORKSPACE}/target/debug/prime-agent"+ export PI_PACKAGE_DIR="${reference}/package"+ export PRIME_AGENT_KERNEL_PYTHON="${HOME}/.prime/agent/kernel-venv/bin/python"+ export PA_E2E_KERNEL_PYTHON="${PRIME_AGENT_KERNEL_PYTHON}"+ export PYTHONPATH="${reference}/package/skills/goal/src"+ test -x "${PRIME_AGENT_KERNEL_PYTHON}"+ mkdir -p "${RUNNER_TEMP}/lifecycle-parity-receipts"+ comparison_status=0+ for scenario in graceful_shutdown goal_backoff draft_disconnect; do+ verifier="scripts/review_${scenario}_parity.py"+ if [ -f "${verifier}" ]; then+ python3 "${verifier}" --receipt "${RUNNER_TEMP}/lifecycle-parity-receipts/${scenario}.json" || comparison_status=1+ fi+ done+ exit "${comparison_status}"+ - name: Upload the binary comparison receipts+ if: always() && matrix.shard == 1 && steps.selection.outputs.units != '0' && (hashFiles('scripts/review_graceful_shutdown_parity.py') != '' || hashFiles('scripts/review_goal_backoff_parity.py') != '' || hashFiles('scripts/review_draft_disconnect_parity.py') != '')+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2+ with:+ name: lifecycle-parity-receipts-attempt-${{ github.run_attempt }}+ path: ${{ runner.temp }}/lifecycle-parity-receipts/*.json+ if-no-files-found: error- name: Run this shard's test subset+ if: ${{ !cancelled() && (success() || steps.lifecycle_parity.outcome == 'failure') }}run: |- python3 scripts/ci_test_shard.py --shard ${{ matrix.shard }} --total ${{ env.SHARD_COUNT }} --crates "${{ needs.changes.outputs.crates }}" --manifest "$RUNNER_TEMP/shard-manifest-${{ matrix.shard }}.json"+ python3 scripts/ci_test_shard.py --shard ${{ matrix.shard }} --total ${{ env.SHARD_COUNT }} --crates "${{ needs.changes.outputs.crates }}" --manifest "$RUNNER_TEMP/shard-manifest-${{ matrix.shard }}-attempt-${{ github.run_attempt }}.json"- name: Upload the shard manifest (always — the summary audits it)if: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2with:- name: shard-manifest-${{ matrix.shard }}- path: ${{ runner.temp }}/shard-manifest-${{ matrix.shard }}.json+ name: shard-manifest-${{ matrix.shard }}-attempt-${{ github.run_attempt }}+ path: ${{ runner.temp }}/shard-manifest-${{ matrix.shard }}-attempt-${{ github.run_attempt }}.json# The aggregate: audits the partition (same enumeration everywhere,# disjoint shards, every assigned unit executed — coverage can never@@ -360,7 +402,11 @@ jobs:merge-multiple: truepath: manifests- name: Audit the shards and merge their failure reports- run: python3 scripts/ci_test_shard_summary.py --total ${{ env.SHARD_COUNT }} --dir manifests+ run: |+ python3 scripts/test_ci_test_shard.py+ python3 scripts/test_ci_pr_crates.py+ python3 scripts/test_ci_test_shard_summary.py+ python3 scripts/ci_test_shard_summary.py --total ${{ env.SHARD_COUNT }} --dir manifests# The Windows job set + the supply-chain deny gate:#diff --git a/crates/pa-cli/Cargo.toml b/crates/pa-cli/Cargo.tomlindex f507a6090d..1349b59c41 100644--- a/crates/pa-cli/Cargo.toml+++ b/crates/pa-cli/Cargo.toml@@ -41,6 +41,9 @@ futures = { workspace = true }crossterm = "0.28"nix = { version = "0.29", features = ["term", "signal", "fs"] }url = "2"+# `test-util` (tokio time pause) is test-only: the goal backoff-wake tests+# drive the 10s/20s windows through the paused clock.+tokio = { workspace = true, features = ["test-util"] }[lints.clippy]# pa-cli keeps its OWN lints table (not `workspace = true`): thediff --git a/crates/pa-cli/src/print_goal.rs b/crates/pa-cli/src/print_goal.rsindex 1274524e57..2b639747b7 100644--- a/crates/pa-cli/src/print_goal.rs+++ b/crates/pa-cli/src/print_goal.rs@@ -541,6 +541,22 @@ impl PrintGoalSurface {.map_err(|error| format!("{error:#}"))?;self.publish_goal_update(engine).await;}+ if let Some(wake_at) = engine.take_goal_backoff_wake_at().await {+ tokio::time::sleep(std::time::Duration::from_millis(+ wake_at.saturating_sub(pa_core::autonomous::now_millis()),+ ))+ .await;+ boundary+ .admit_continuation(+ engine,+ model,+ api_key.clone(),+ pa_core::session_engine::goal_driver::GOAL_BACKOFF_WAKE_MARKER_TEXT,+ global_harness_dir.clone(),+ )+ .await?;+ continue;+ }return Ok(engine.goal_state().await.status == pa_types::goal::GoalStatus::Active);}}@@ -690,6 +706,27 @@ mod tests {.collect()}+ /// The wake-marker user rows the goal arm's backoff wake admitted, in any turn.+ async fn wake_marker_rows(engine: &SessionEngine) -> usize {+ engine+ .session+ .entries()+ .await+ .into_iter()+ .filter(|entry| {+ let pa_types::session::FileEntry::Message {+ message: pa_types::session::AgentMessage::User(user),+ ..+ } = entry+ else {+ return false;+ };+ user.content.text()+ == pa_core::session_engine::goal_driver::GOAL_BACKOFF_WAKE_MARKER_TEXT+ })+ .count()+ }+/// The transcript's assistant turn texts in order.async fn assistant_texts(engine: &SessionEngine) -> Vec<String> {engine@@ -1054,6 +1091,90 @@ mod tests {);}+ /// An empty goal turn arms the backoff window: the wake marker runs as the next turn at+ /// the deadline, the recovered reply lands, and the in-loop continuation resumes inside+ /// the wake run.+ #[tokio::test(start_paused = true)]+ async fn backoff_wake_runs_the_marker_turn_and_recovers_the_reply() {+ let _guard = FAUX_TEST_LOCK.lock().await;+ let bed = goal_bed(+ script(&json!([{}, "recovered reply"]), 128_000),+ no_compaction(),+ Some(("finish the work", None)),+ )+ .await;+ let (counter, subscription) = agent_run_counter(&bed.engine).await;+ let owns = bed.prompt("work").await;+ subscription.unsubscribe().await;+ assert_eq!(+ counter.load(Ordering::SeqCst),+ 2,+ "the initial run plus the wake turn's run"+ );+ assert!(!owns, "the exhausted faux queue fails the resumed goal");+ assert_eq!(+ wake_marker_rows(&bed.engine).await,+ 1,+ "exactly one wake marker turn ran"+ );+ assert_eq!(+ assistant_texts(&bed.engine).await,+ [String::new(), "recovered reply".to_string()],+ "the empty turn, then the wake turn's recovered reply"+ );+ assert_eq!(+ bed.engine.goal_state().await.status,+ pa_types::goal::GoalStatus::Error+ );+ }++ /// Three consecutive empty turns end the goal at the cap after exactly three model+ /// calls — the third wake never runs.+ #[tokio::test(start_paused = true)]+ async fn three_empty_turns_hit_the_cap_with_exactly_three_model_calls() {+ let _guard = FAUX_TEST_LOCK.lock().await;+ let bed = goal_bed(+ script(&json!([{}, {}, {}]), 128_000),+ no_compaction(),+ Some(("finish the work", None)),+ )+ .await;+ let (counter, subscription) = agent_run_counter(&bed.engine).await;+ let owns = bed.prompt("work").await;+ subscription.unsubscribe().await;+ assert_eq!(+ counter.load(Ordering::SeqCst),+ 3,+ "the prompt turn plus the two wake turns"+ );+ assert!(!owns, "the capped goal no longer owns the boundary");+ assert_eq!(wake_marker_rows(&bed.engine).await, 2);+ let goal = bed.engine.goal_state().await;+ assert_eq!(goal.status, pa_types::goal::GoalStatus::Error);+ assert_eq!(+ goal.last_error.as_deref(),+ Some(pa_core::session_engine::goal_driver::CONTINUATION_NO_PROGRESS_CAP_REASON)+ );+ assert_eq!(goal.no_progress_streak, Some(3));+ }++ /// A non-goal empty turn never wakes: no marker turn, the boundary returns at once.+ #[tokio::test(start_paused = true)]+ async fn non_goal_empty_turn_returns_without_a_wake() {+ let _guard = FAUX_TEST_LOCK.lock().await;+ let bed = goal_bed(script(&json!([{}]), 128_000), no_compaction(), None).await;+ let (counter, subscription) = agent_run_counter(&bed.engine).await;+ let owns = bed.prompt("work").await;+ subscription.unsubscribe().await;+ assert!(!owns, "no goal owns the boundary");+ assert_eq!(counter.load(Ordering::SeqCst), 1, "no wake turn ran");+ assert_eq!(wake_marker_rows(&bed.engine).await, 0);+ assert_eq!(+ bed.engine.goal_state().await.status,+ pa_types::goal::GoalStatus::Idle+ );+ }+/// The crossing turn's usage flips the goal to `budget_limited`, the run ends, and the/// steer drains as its own run.#[tokio::test]diff --git a/crates/pa-cli/src/print_runtime.rs b/crates/pa-cli/src/print_runtime.rsindex 6b44fd3943..6bad142b0a 100644--- a/crates/pa-cli/src/print_runtime.rs+++ b/crates/pa-cli/src/print_runtime.rs@@ -1215,6 +1215,7 @@ async fn run_prompts_and_emit(// only silently.let goal = std::sync::Arc::new(crate::print_goal::PrintGoalSurface::new(json_mode));goal.seed_publish_baseline(engine).await;+ let goal_updated_at_start = engine.goal_state().await.updated_at;let goal_accounting = goal.wire_accounting(engine, engine.session.agent()).await;// The autonomous run: the CLI flags enable it, a no-flag session starts disabled and// `/autonomous` rewrites it live.@@ -1355,6 +1356,15 @@ async fn run_prompts_and_emit(// the primary message (error to stderr with exit 1, settled answer to stdout).let mut exit_code = 0;if !json_mode {+ let goal = engine.goal_state().await;+ let cap_reason = pa_core::session_engine::goal_driver::CONTINUATION_NO_PROGRESS_CAP_REASON;+ if goal.status == pa_types::goal::GoalStatus::Error+ && goal.last_error.as_deref() == Some(cap_reason)+ && goal.updated_at != goal_updated_at_start+ {+ eprintln!("{cap_reason}");+ exit_code = 1;+ }if let Some(primary) = result.primary {if let Some(stderr) = primary.stderr_text(&mut exit_code) {eprintln!("{stderr}");diff --git a/crates/pa-cli/tests/print_runtime_e2e.rs b/crates/pa-cli/tests/print_runtime_e2e.rsindex 6a6f80a655..c71ad9e0b5 100644--- a/crates/pa-cli/tests/print_runtime_e2e.rs+++ b/crates/pa-cli/tests/print_runtime_e2e.rs@@ -154,6 +154,35 @@ fn read_entries(path: &std::path::Path) -> Vec<serde_json::Value> {.unwrap()}+/// The goal cap's text-mode end state: the capped run exits 1 with the reason, and a later+/// resume of the capped session answers normally — the persisted cap never swallows a run.+#[test]+fn print_mode_goal_cap_reports_the_reason_and_exits_one() {+ let home = isolated_home();+ let script = serde_json::json!({ "responses": [{}, {}, {}] });+ let (stdout, stderr, code) = run_in_home(+ home.path(),+ &["--goal", "finish the work", "-p", "work"],+ &script,+ );+ assert_eq!(code, 1);+ assert!(stderr.ends_with("Goal continuation cap reached: consecutive turns made no progress\n"));+ assert!(stdout.is_empty());++ let session_id = read_entries(&session_files(home.path())[0])[0]["id"]+ .as_str()+ .unwrap()+ .to_string();+ let script = serde_json::json!({ "responses": ["follow-up answer"] });+ let (stdout, stderr, code) = run_in_home(+ home.path(),+ &["--resume", &session_id[..8], "-p", "next"],+ &script,+ );+ assert_eq!(code, 0, "stderr: {stderr}");+ assert_eq!(stdout, "follow-up answer\n");+}+/// The session files holding a runtime lease right now (the owner records/// under the agent dir's `session-leases`).fn leased_session_files(home: &std::path::Path) -> Vec<String> {diff --git a/crates/pa-core/src/session_engine/goal_boundary.rs b/crates/pa-core/src/session_engine/goal_boundary.rsindex 8eff982761..d93f9ac367 100644--- a/crates/pa-core/src/session_engine/goal_boundary.rs+++ b/crates/pa-core/src/session_engine/goal_boundary.rs@@ -159,6 +159,13 @@ impl SessionEngine {self.goal_driver.lock().await.state_with_creation_elapsed()}+ /// Take the armed no-progress backoff window's deadline while the goal+ /// is Active: the settled boundary may outlast the window, so an overdue+ /// deadline still yields, and the take consumes it — one wake per strike.+ pub async fn take_goal_backoff_wake_at(&self) -> Option<u64> {+ self.goal_driver.lock().await.take_backoff_wake_at()+ }+/// Release the pending-continuation guard: the surface admitted (or/// withdrew) the minted continuation, so the next boundary mints again.pub async fn clear_pending_goal_continuation(&self) {diff --git a/crates/pa-core/src/session_engine/goal_driver.rs b/crates/pa-core/src/session_engine/goal_driver.rsindex 42289f433e..b6b78dcb18 100644--- a/crates/pa-core/src/session_engine/goal_driver.rs+++ b/crates/pa-core/src/session_engine/goal_driver.rs@@ -75,7 +75,10 @@ mod progress;use progress::CONTINUATION_NO_PROGRESS_CAP;pub use progress::{terminal_provider_failure, turn_produced_no_output};-pub use progress::{GOAL_BACKOFF_WAKE_CRON_LABEL, GOAL_BACKOFF_WAKE_MARKER_TEXT};+pub use progress::{+ CONTINUATION_NO_PROGRESS_CAP_REASON, GOAL_BACKOFF_WAKE_CRON_LABEL,+ GOAL_BACKOFF_WAKE_MARKER_TEXT,+};impl GoalDriver {#[must_use]@@ -522,8 +525,7 @@ impl GoalDriver {if self.state.status == GoalStatus::Active&& self.no_progress_streak >= CONTINUATION_NO_PROGRESS_CAP{- let reason =- "Goal continuation cap reached: consecutive turns made no progress".to_string();+ let reason = progress::CONTINUATION_NO_PROGRESS_CAP_REASON.to_string();self.set_state(session,GoalState {@@ -689,6 +691,20 @@ impl GoalDriver {(self.state.status == GoalStatus::Active && until > now_millis()).then_some(until)}+ /// Take the armed backoff window's deadline: the print surface's settled+ /// boundary reads it after its run, so an overdue window still yields+ /// (the caller's sleep saturates to zero) and the take consumes it —+ /// one wake per strike.+ #[must_use]+ pub fn take_backoff_wake_at(&mut self) -> Option<u64> {+ let until = self.no_progress_backoff_until_ms;+ if self.state.status != GoalStatus::Active || until == 0 {+ return None;+ }+ self.no_progress_backoff_until_ms = 0;+ Some(until)+ }+#[must_use]pub fn owns_continuation_wakeup(&self) -> bool {self.state.status == GoalStatus::Active && self.state.objective.is_some()diff --git a/crates/pa-core/src/session_engine/goal_driver/progress.rs b/crates/pa-core/src/session_engine/goal_driver/progress.rsindex bb65a23914..459f45a841 100644--- a/crates/pa-core/src/session_engine/goal_driver/progress.rs+++ b/crates/pa-core/src/session_engine/goal_driver/progress.rs@@ -16,6 +16,10 @@ pub(crate) const CONTINUATION_NO_PROGRESS_CAP: u32 = 3;/// each retry of a no-progress continuation waits twice as long.pub(crate) const CONTINUATION_NO_PROGRESS_BACKOFF_BASE_MS: u64 = 10_000;+/// The goal's terminal reason when the no-progress streak reaches the cap.+pub const CONTINUATION_NO_PROGRESS_CAP_REASON: &str =+ "Goal continuation cap reached: consecutive turns made no progress";+/// The durable one-shot wake's cron label: the daemon's boundary sites arm a/// one-shot cron at [`GoalDriver::backoff_wake_at`], so the backoff retry actually runs.pub const GOAL_BACKOFF_WAKE_CRON_LABEL: &str = "goal-backoff-wake";@@ -126,9 +130,7 @@ impl GoalDriver {},)?;if self.no_progress_streak >= CONTINUATION_NO_PROGRESS_CAP {- let reason =- "Goal continuation cap reached: consecutive turns made no progress"- .to_string();+ let reason = CONTINUATION_NO_PROGRESS_CAP_REASON.to_string();self.set_state(session,GoalState {diff --git a/crates/pa-core/src/session_engine/goal_driver/tests.rs b/crates/pa-core/src/session_engine/goal_driver/tests.rsindex d83d164ed0..02b2507d40 100644--- a/crates/pa-core/src/session_engine/goal_driver/tests.rs+++ b/crates/pa-core/src/session_engine/goal_driver/tests.rs@@ -723,6 +723,34 @@ fn a_parked_refusal_clears_an_earlier_strikes_window() {assert_eq!(driver.no_progress_streak(), 1, "the strike stays durable");}+/// The print surface's wake take owns an armed window even after its+/// deadline passed during the settled run: the take still yields the+/// overdue deadline once — the sleep saturates to zero — and consuming+/// it admits exactly one wake per strike.+#[test]+fn the_print_wake_take_yields_an_overdue_window_once() {+ let mut session = persisted_session();+ let mut driver = GoalDriver::new();+ driver.start(&mut session, "work", None).unwrap();+ let created_at = driver.state().created_at.unwrap();++ // Strike one: the backoff window arms.+ let empty = test_empty_turn(created_at as i64 + 1);+ assert!(driver+ .next_continuation_message(&mut session, Some(&empty))+ .unwrap()+ .is_none());++ // The settled boundary outlasted the window: the armed deadline sits+ // in the past, still non-zero.+ let overdue = now_millis().saturating_sub(1);+ driver.no_progress_backoff_until_ms = overdue;++ // The take yields the overdue deadline once, and consumes it.+ assert_eq!(driver.take_backoff_wake_at(), Some(overdue));+ assert_eq!(driver.take_backoff_wake_at(), None);+}+#[test]fn the_rate_limit_refusal_sticks_across_reconsults() {let mut session = persisted_session();diff --git a/scripts/ci_test_shard.py b/scripts/ci_test_shard.pyindex 6193767452..bc43d2707a 100644--- a/scripts/ci_test_shard.py+++ b/scripts/ci_test_shard.py@@ -193,13 +193,22 @@ def _failed_tests(lines: list[str]) -> list[str]:def write_manifest(path: Path, shard: int, total: int, all_ids: list[str],- results: list[dict], crates: list[str] | None = None) -> None:+ results: list[dict], crates: list[str] | None = None,+ run_attempt: int | None = None, run_id: str | None = None,+ commit_sha: str | None = None) -> None:selection_ids = [i for i in all_idsif crates is None or _unit_package(i) in set(crates)]+ if commit_sha is None:+ commit_sha = os.environ.get("GITHUB_SHA") or subprocess.run(+ ["git", "rev-parse", "HEAD"], cwd=REPO_ROOT, capture_output=True,+ text=True, check=True).stdout.strip()manifest = {"schema": 1,"shard": shard,"total": total,+ "run_attempt": run_attempt if run_attempt is not None else int(os.environ.get("GITHUB_RUN_ATTEMPT", "1")),+ "run_id": run_id if run_id is not None else os.environ.get("GITHUB_RUN_ID", "local"),+ "commit_sha": commit_sha,"all_unit_ids": all_ids,"digest": hashlib.sha256("\n".join(all_ids).encode("utf-8")).hexdigest(),"scope": scope_manifest(crates),diff --git a/scripts/ci_test_shard_summary.py b/scripts/ci_test_shard_summary.pyindex 2cb23bd274..00ae4b0865 100644--- a/scripts/ci_test_shard_summary.py+++ b/scripts/ci_test_shard_summary.py@@ -22,6 +22,10 @@ It then prints ONE merged report: the scope, which binaries failed, in whichshard, with their failing test names — the single place a lane looks when aPR run goes red, instead of crawling the job logs.+Artifact selection uses the latest *available* manifest per shard. A rerun+that crashes before uploading a manifest cannot be inferred from artifacts;+the matrix job's own failure remains a separate required CI gate.+Usage (from the repo root, in ci.yml's test summary job):python3 scripts/ci_test_shard_summary.py --total 4 --dir manifests@@ -30,8 +34,10 @@ Usage (from the repo root, in ci.yml's test summary job):from __future__ import annotationsimport argparse+import hashlibimport jsonimport os+import reimport sysfrom pathlib import Path@@ -43,11 +49,50 @@ def shard_of(unit_id: str, total: int) -> int:def load_manifests(manifest_dir: Path, total: int):- manifests = {}+ """Choose the newest numeric attempt independently for each shard."""+ candidates = {}+ problems = []+ pattern = re.compile(r"shard-manifest-(\d+)(?:-attempt-(\d+))?\.json")for path in sorted(manifest_dir.glob("shard-manifest-*.json")):- shard = json.loads(path.read_text(encoding="utf-8"))- manifests[shard["shard"]] = shard- return manifests+ match = pattern.fullmatch(path.name)+ if not match:+ problems.append(f"unrecognized manifest filename: {path.name}")+ continue+ shard_number, attempt = int(match[1]), int(match[2] or 1)+ if not 1 <= shard_number <= total or attempt < 1:+ problems.append(f"invalid shard/attempt in {path.name}")+ continue+ try:+ manifest = json.loads(path.read_text(encoding="utf-8"))+ if not isinstance(manifest, dict):+ raise ValueError("JSON root must be an object")+ recorded_attempt = manifest.get("run_attempt", 1)+ if (type(manifest["shard"]) is not int or manifest["shard"] != shard_number+ or type(manifest["total"]) is not int or manifest["total"] != total+ or type(recorded_attempt) is not int or recorded_attempt != attempt):+ raise ValueError("filename, shard, total, or attempt metadata disagree")+ if ((os.environ.get("GITHUB_RUN_ID") and+ manifest.get("run_id") != os.environ["GITHUB_RUN_ID"]) or+ (os.environ.get("GITHUB_SHA") and+ manifest.get("commit_sha") != os.environ["GITHUB_SHA"])):+ raise ValueError("run/commit identity mismatch")+ except (OSError, ValueError, KeyError, TypeError) as error:+ problems.append(f"{path.name}: invalid manifest: {error}")+ continue+ key = (shard_number, attempt)+ if key in candidates:+ problems.append(f"shard {shard_number} attempt {attempt}: duplicate manifests "+ f"({candidates[key][0].name}, {path.name})")+ else:+ candidates[key] = (path, manifest)+ manifests = {}+ retained = {}+ for shard in range(1, total + 1):+ attempts = sorted(attempt for number, attempt in candidates if number == shard)+ if attempts:+ manifests[shard] = candidates[(shard, attempts[-1])][1]+ retained[shard] = attempts[:-1]+ return manifests, retained, problemsdef run_scope(manifests: dict) -> tuple[str, list[str] | None]:@@ -87,13 +132,54 @@ def audit(manifests: dict, total: int) -> tuple[list[str], set[str]]:"finishing (see that job's log)")if problems:return problems, failed_units+ incomplete = []+ for shard, manifest in sorted(manifests.items()):+ if not isinstance(manifest.get("all_unit_ids"), list) or not isinstance(manifest.get("units"), list):+ problems.append(f"shard {shard}: missing enumeration or unit results")+ elif (any(not isinstance(uid, str) for uid in manifest["all_unit_ids"])+ or any(not isinstance(unit, dict) or not isinstance(unit.get("id"), str)+ or type(unit.get("rc")) is not int+ for unit in manifest["units"])):+ problems.append(f"shard {shard}: malformed enumeration or unit results")+ if "selected_unit_ids" in manifest and (+ not isinstance(manifest["selected_unit_ids"], list)+ or any(not isinstance(uid, str) for uid in manifest["selected_unit_ids"])):+ problems.append(f"shard {shard}: malformed selected unit ids")+ if manifest.get("complete") is not True:+ incomplete.append(f"shard {shard} is incomplete: complete must be literal true")+ scope = manifest.get("scope", {"kind": "all"})+ if (not isinstance(scope, dict) or scope.get("kind") not in ("all", "crates")+ or (scope.get("kind") == "all" and "crates" in scope)+ or (scope.get("kind") == "crates" and+ (not isinstance(scope.get("crates"), list) or+ any(not isinstance(crate, str) for crate in scope["crates"])))):+ problems.append(f"shard {shard}: invalid selection scope")+ if problems:+ return problems + incomplete, failed_units++ identities = {(m.get("run_id"), m.get("commit_sha")) for m in manifests.values()}+ if (len(identities) != 1 or any(not run_id or not sha for run_id, sha in identities)+ or (os.environ.get("GITHUB_RUN_ID") and+ any(run_id != os.environ["GITHUB_RUN_ID"] for run_id, _ in identities))+ or (os.environ.get("GITHUB_SHA") and+ any(sha != os.environ["GITHUB_SHA"] for _, sha in identities))):+ problems.append("selected shards have mismatched or missing run/commit identity")+ return problems + incomplete, failed_unitsid_lists = {tuple(m["all_unit_ids"]) for m in manifests.values()}if len(id_lists) != 1:problems.append("shards enumerated different unit sets — the merge ""ref changed mid-run or a manifest is stale; rerun CI")- return problems, failed_units+ return problems + incomplete, failed_unitsall_ids = manifests[1]["all_unit_ids"]+ if len(all_ids) != len(set(all_ids)):+ problems.append("enumeration contains duplicate unit ids")+ expected_digest = hashlib.sha256("\n".join(all_ids).encode("utf-8")).hexdigest()+ for shard, manifest in sorted(manifests.items()):+ if manifest.get("digest") != expected_digest:+ problems.append(f"shard {shard}: enumeration digest mismatch")+ if problems:+ return problems + incomplete, failed_unitskind, crates = run_scope(manifests)if kind == "MIXED":@@ -102,9 +188,15 @@ def audit(manifests: dict, total: int) -> tuple[list[str], set[str]]:problems.append("shards recorded different selection scopes — a ""mixed-scope wave is a broken partition: " +", ".join(described))- return problems, failed_units+ return problems + incomplete, failed_unitsselection = selected_ids(manifests[1], crates)selection_set = set(selection)+ expected_selection = [uid for uid in all_ids if crates is None or _unit_package(uid) in set(crates)]+ for shard, manifest in sorted(manifests.items()):+ if selected_ids(manifest, crates) != expected_selection:+ problems.append(f"shard {shard}: selected unit ids disagree with scope/enumeration")+ if problems:+ return problems + incomplete, failed_unitsexecuted: dict[str, str] = {} # unit id -> shard that ran itfor shard, manifest in sorted(manifests.items()):@@ -113,6 +205,8 @@ def audit(manifests: dict, total: int) -> tuple[list[str], set[str]]:if uid not in all_ids:problems.append(f"shard {shard}: executed unknown unit {uid}")continue+ if shard_of(uid, total) != shard - 1:+ problems.append(f"shard {shard}: unit {uid} belongs to shard {shard_of(uid, total) + 1}")if uid in executed:problems.append(f"unit {uid} ran in shards {executed[uid]} "f"and {shard} — assignments must be disjoint")@@ -132,23 +226,42 @@ def audit(manifests: dict, total: int) -> tuple[list[str], set[str]]:problems.append(f"assigned outside the enumeration: {outside}")for shard, manifest in sorted(manifests.items()):- if not manifest.get("complete", False):+ if manifest.get("complete") is not True:assigned = [i for i in selection if shard_of(i, total) == shard - 1]unfinished = sorted(set(assigned) - {u["id"] for u in manifest["units"]})problems.append(f"shard {shard} is incomplete; units it never "f"reported: {unfinished}")- return problems, failed_units+ return problems + incomplete, failed_unitsdef merged_report(manifests: dict, total: int, problems: list[str],- failed_units: set[str]) -> str:- kind, crates = run_scope(manifests)+ failed_units: set[str], retained: dict | None = None) -> str:+ if problems:+ lines = [f"### test summary ({total} shards)",+ "- attempt selection: latest available manifest per shard; the matrix job "+ "separately reports reruns that uploaded no manifest"]+ for shard in sorted(manifests):+ older = (retained or {}).get(shard, [])+ lines.append(f"- shard {shard}: selected attempt "+ f"{manifests[shard].get('run_attempt', 1)}; retained prior attempts: "+ f"{', '.join(map(str, older)) if older else 'none'}")+ lines.extend(["", "**partition audit FAILED**", *(f"- {problem}" for problem in problems)])+ return "\n".join(lines)+ kind, crates = run_scope(manifests) if manifests else ("all", None)scope = ("full selection" if kind == "all"else f"crate selection: {', '.join(crates or [])}")selected = selected_ids(manifests.get(1, {"all_unit_ids": []}), crates)union_size = len(manifests.get(1, {}).get("all_unit_ids", []))lines = [f"### test summary ({total} shards)",- f"- scope: {scope} — {len(selected)} of {union_size} units selected"]+ f"- scope: {scope} — {len(selected)} of {union_size} units selected",+ "- attempt selection: latest available manifest per shard; the matrix job "+ "separately reports reruns that uploaded no manifest"]+ for shard in range(1, total + 1):+ if shard in manifests:+ attempt = manifests[shard].get("run_attempt", 1)+ older = (retained or {}).get(shard, [])+ lines.append(f"- shard {shard}: selected attempt {attempt}; retained prior attempts: "+ f"{', '.join(map(str, older)) if older else 'none'}")for shard in sorted(manifests):manifest = manifests[shard]units = manifest["units"]@@ -182,9 +295,10 @@ def main() -> int:help="directory with shard-manifest-*.json files")args = parser.parse_args()- manifests = load_manifests(args.dir, args.total)- problems, failed_units = audit(manifests, args.total)- report = merged_report(manifests, args.total, problems, failed_units)+ manifests, retained, load_problems = load_manifests(args.dir, args.total)+ audit_problems, failed_units = audit(manifests, args.total)+ problems = load_problems + audit_problems+ report = merged_report(manifests, args.total, problems, failed_units, retained)print(report)step_summary = os.environ.get("GITHUB_STEP_SUMMARY")if step_summary:diff --git a/scripts/review_goal_backoff_parity.py b/scripts/review_goal_backoff_parity.pynew file mode 100755index 0000000000..fe5abbd638--- /dev/null+++ b/scripts/review_goal_backoff_parity.py@@ -0,0 +1,356 @@+#!/usr/bin/env python3+"""Binary-level, offline observation of goal continuation in TS and Rust.++Requires PA_TS_BINARY and PA_RUST_BINARY. The TS binary is the official 0.9.8+Linux release extracted by CI. All model traffic goes to this process's+loopback HTTP server; each invocation gets a disposable home and session tree.+Behavioral differences are evidence in --receipt, not silently normalized.+"""++import argparse+import hashlib+import http.server+import json+import os+import pathlib+import signal+import subprocess+import sys+import tempfile+import threading+import time+++TS_ARCHIVE_SHA256 = "83fb09129bf78e3e60268212cd70932166591b15188caa70c1b0efbcc76235e2"+TIMEOUT_SECONDS = 35+MAX_REQUESTS = 6+++def sha256(path):+ digest = hashlib.sha256()+ with open(path, "rb") as stream:+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):+ digest.update(chunk)+ return digest.hexdigest()+++class MockServer(http.server.ThreadingHTTPServer):+ daemon_threads = True++ def __init__(self, scenario):+ super().__init__(("127.0.0.1", 0), MockHandler)+ self.scenario = scenario+ self.requests = []+ self.changed = threading.Condition()+ self.process = None+ self.limit_hit = False+++class MockHandler(http.server.BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_POST(self):+ if self.path != "/v1/chat/completions":+ self.send_error(404)+ return+ try:+ length = int(self.headers.get("Content-Length", "0"))+ body = json.loads(self.rfile.read(length))+ except (ValueError, json.JSONDecodeError):+ self.send_error(400)+ return+ server = self.server+ with server.changed:+ number = len(server.requests) + 1+ server.requests.append({+ "number": number,+ "elapsed_ms": round((time.monotonic() - server.started) * 1000),+ "path": self.path,+ "model": body.get("model"),+ "stream": body.get("stream"),+ "roles": [m.get("role") for m in body.get("messages", [])],+ "wake_marker": "<goal_backoff_wake>" in json.dumps(body),+ "goal_context": "goal_context" in json.dumps(body),+ })+ if number >= MAX_REQUESTS:+ server.limit_hit = True+ if server.process is not None:+ os.killpg(server.process.pid, signal.SIGTERM)+ server.changed.notify_all()++ if server.scenario == "recover" and number == 2:+ delta = {"tool_calls": [{"index": 0, "id": "call_complete", "type": "function",+ "function": {"name": "ipython", "arguments": json.dumps({"code": "await goal.complete()"})}}]}+ finish = "tool_calls"+ elif server.scenario == "recover" and number >= 3:+ delta = {"content": "Goal completed."}+ finish = "stop"+ else:+ delta = {}+ finish = "stop"++ def chunk(value, reason=None):+ return {"id": "mock-goal", "object": "chat.completion.chunk", "created": 1,+ "model": "goal-fixture", "choices": [{"index": 0, "delta": value, "finish_reason": reason}]}++ usage = {"id": "mock-goal", "object": "chat.completion.chunk", "created": 1,+ "model": "goal-fixture", "choices": [],+ "usage": {"prompt_tokens": 10, "completion_tokens": 1,+ "total_tokens": 11, "prompt_tokens_details": {"cached_tokens": 0}}}+ payload = "".join("data: " + json.dumps(item, separators=(",", ":")) + "\n\n"+ for item in (chunk({"role": "assistant", **delta}),+ chunk({}, finish), usage))+ payload += "data: [DONE]\n\n"+ wire = payload.encode()+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.send_header("Cache-Control", "no-cache")+ self.send_header("Content-Length", str(len(wire)))+ self.end_headers()+ try:+ self.wfile.write(wire)+ self.wfile.flush()+ except (BrokenPipeError, ConnectionResetError):+ pass+++def run_case(binary, label, scenario, base_dir):+ home = base_dir / (label + "-" + scenario)+ home.mkdir()+ agent = home / "agent"+ sessions = home / "sessions"+ cwd = home / "work"+ for path in (agent, sessions, cwd):+ path.mkdir()+ server = MockServer(scenario)+ server.started = time.monotonic()+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ base_url = "http://127.0.0.1:%d/v1" % server.server_address[1]+ models = {"providers": {"fixture": {"api": "openai-completions", "baseUrl": base_url,+ "apiKey": "offline-fixture-token", "models": [{+ "id": "goal-fixture", "name": "Goal Fixture",+ "reasoning": False, "contextWindow": 128000,+ "maxTokens": 4096}]}}}+ (agent / "models.json").write_text(json.dumps(models))+ (agent / "settings.json").write_text(json.dumps({"defaultProvider": "fixture",+ "defaultModel": "goal-fixture"}))+ # An explicit environment prevents inherited tokens, proxies, or a user's+ # package/session paths from reaching either binary or a spawned kernel.+ env = {key: os.environ[key] for key in ("PATH", "LANG", "LC_ALL", "TZ", "PYTHONPATH",+ "PRIME_AGENT_KERNEL_PYTHON", "PA_E2E_KERNEL_PYTHON")+ if key in os.environ}+ env.update({"HOME": str(home), "XDG_CONFIG_HOME": str(home / "config"),+ "XDG_CACHE_HOME": str(home / "cache"), "XDG_DATA_HOME": str(home / "data"),+ "TMPDIR": str(home / "tmp"), "DO_NOT_TRACK": "1", "PI_OFFLINE": "1",+ "PI_CODING_AGENT_DIR": str(agent), "PI_SESSION_DIR": str(sessions),+ "PRIME_AGENT_CODING_AGENT_DIR": str(agent),+ "PRIME_AGENT_SESSION_DIR": str(sessions)})+ (home / "tmp").mkdir()+ goal_module = next((pathlib.Path(part) / "goal" / "__init__.py"+ for part in env.get("PYTHONPATH", "").split(os.pathsep)+ if part and (pathlib.Path(part) / "goal" / "__init__.py").is_file()), None)+ kernel_provenance = {+ "kernel_python": env.get("PRIME_AGENT_KERNEL_PYTHON"),+ "e2e_kernel_python": env.get("PA_E2E_KERNEL_PYTHON"),+ "pythonpath": env.get("PYTHONPATH"),+ "goal_module_path": str(goal_module) if goal_module else None,+ "goal_module_sha256": sha256(goal_module) if goal_module else None,+ }+ version = None+ if scenario == "control":+ probe = subprocess.run([str(binary), "--version"], cwd=cwd, env=env,+ text=True, capture_output=True, timeout=10, check=False)+ version = {"exit_code": probe.returncode, "stdout": probe.stdout.strip(),+ "stderr": probe.stderr.strip()}+ if probe.returncode != 0 or not probe.stdout.strip():+ raise RuntimeError("--version failed: " + json.dumps(version))+ command = [str(binary), "--mode", "json", "--provider", "fixture", "--model",+ "goal-fixture", "--no-session"]+ if scenario != "control":+ command += ["--goal", "Finish the offline fixture objective"]+ if scenario == "budget":+ command += ["--goal-token-budget", "1"]+ command += ["Complete the fixture task."]+ stdout_path = home / "stdout.jsonl"+ stderr_path = home / "stderr.txt"+ started = time.monotonic()+ with stdout_path.open("wb") as stdout, stderr_path.open("wb") as stderr:+ process = subprocess.Popen(command, cwd=cwd, env=env, stdout=stdout, stderr=stderr,+ start_new_session=True)+ server.process = process+ stopped = None+ try:+ while True:+ try:+ exit_code = process.wait(timeout=0.15)+ if server.limit_hit:+ stopped = "request_observation_limit"+ break+ except subprocess.TimeoutExpired:+ pass+ with server.changed:+ count = len(server.requests)+ if time.monotonic() - started > TIMEOUT_SECONDS:+ stopped = "timeout"+ elif count >= MAX_REQUESTS:+ stopped = "request_observation_limit"+ if stopped:+ os.killpg(process.pid, signal.SIGTERM)+ try:+ exit_code = process.wait(timeout=2)+ except subprocess.TimeoutExpired:+ os.killpg(process.pid, signal.SIGKILL)+ exit_code = process.wait(timeout=2)+ break+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=2)++ raw = stdout_path.read_text(errors="replace")+ errors = stderr_path.read_text(errors="replace")+ events = []+ for line in raw.splitlines():+ try:+ event = json.loads(line)+ if isinstance(event, dict):+ events.append(event)+ except json.JSONDecodeError:+ pass+ combined = raw + "\n" + errors+ goal_updates = [event["goal"] for event in events+ if event.get("type") == "goal_update"+ and isinstance(event.get("goal"), dict)]+ goal_statuses = [goal.get("status") for goal in goal_updates]+ final_goal_status = goal_statuses[-1] if goal_statuses else None+ tool_events = []+ for event in events:+ if event.get("type") == "tool_execution_end":+ tool_events.append({key: event.get(key) for key in+ ("toolName", "toolCallId", "isError", "result") if key in event})+ turn_tool_results = [event.get("toolResults") for event in events+ if event.get("type") == "turn_end" and event.get("toolResults")]+ model_completion_text = False+ for event in events:+ message = event.get("message")+ if event.get("type") != "message_end" or not isinstance(message, dict):+ continue+ if message.get("role") != "assistant":+ continue+ content = message.get("content")+ if isinstance(content, list):+ model_completion_text |= any(+ isinstance(block, dict) and block.get("type") == "text"+ and "Goal completed." in block.get("text", "") for block in content+ )+ return {+ "version_probe": version,+ "kernel_provenance": kernel_provenance if scenario == "control" else None,+ "exit_code": exit_code,+ "stopped": stopped,+ "elapsed_ms": round((time.monotonic() - started) * 1000),+ "requests": server.requests,+ "wake_request_numbers": [row["number"] for row in server.requests if row["wake_marker"]],+ "goal_context_request_numbers": [row["number"] for row in server.requests if row["goal_context"]],+ "request_count": len(server.requests),+ "event_types": [event.get("type") for event in events],+ "tool_execution_end": tool_events,+ "turn_end_tool_results": turn_tool_results,+ "goal_statuses": goal_statuses,+ "final_goal_status": final_goal_status,+ "confirmed_goal_complete": final_goal_status == "complete",+ "model_completion_text_seen": model_completion_text,+ "goal_context_count": combined.count("goal_context"),+ "wake_marker_count": combined.count("<goal_backoff_wake>"),+ "cap_reason_seen": "Goal continuation cap reached: consecutive turns made no progress" in combined,+ "stderr_tail": errors[-2500:],+ "stdout_tail": raw[-3500:],+ }+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--receipt", type=pathlib.Path, required=True)+ args = parser.parse_args()+ paths = {}+ for label in ("TS", "RUST"):+ value = os.environ.get("PA_" + label + "_BINARY")+ if not value or not pathlib.Path(value).is_file() or not os.access(value, os.X_OK):+ parser.error("PA_" + label + "_BINARY must name an executable file")+ paths[label.lower()] = pathlib.Path(value).resolve()+ if sys.platform != "linux":+ parser.error("this fixture runs only in Linux CI")+ args.receipt.parent.mkdir(parents=True, exist_ok=True)+ if args.receipt.resolve().is_relative_to(pathlib.Path.cwd().resolve()):+ parser.error("--receipt must be outside the repository")+ archive = os.environ.get("PA_TS_ARCHIVE")+ if not archive or not pathlib.Path(archive).is_file():+ parser.error("PA_TS_ARCHIVE must name the downloaded official TS 0.9.8 archive")+ archive_hash = sha256(archive)+ if archive_hash != TS_ARCHIVE_SHA256:+ parser.error("PA_TS_ARCHIVE SHA-256 mismatch: " + archive_hash)+ result = {"ts_release_archive_sha256": archive_hash,+ "binaries": {key: {"path": str(path), "sha256": sha256(path)}+ for key, path in paths.items()},+ "scenarios": {}, "differences": {}, "fixture_error": None}+ with tempfile.TemporaryDirectory(prefix="goal-backoff-parity-") as temp:+ base_dir = pathlib.Path(temp)+ for scenario in ("control", "empty", "recover", "budget"):+ result["scenarios"][scenario] = {}+ for label, binary in paths.items():+ try:+ result["scenarios"][scenario][label] = run_case(binary, label, scenario, base_dir)+ except Exception as exc:+ result["fixture_error"] = "%s/%s: %s" % (scenario, label, exc)+ break+ if result["fixture_error"]:+ break+ ts = result["scenarios"][scenario]["ts"]+ rust = result["scenarios"][scenario]["rust"]+ if scenario == "control":+ for label in paths:+ result["binaries"][label]["version_probe"] = result["scenarios"][scenario][label]["version_probe"]+ result["binaries"][label]["kernel_provenance"] = result["scenarios"][scenario][label]["kernel_provenance"]+ result["differences"][scenario] = {+ field: {"ts": ts[field], "rust": rust[field]}+ for field in ("request_count", "wake_marker_count", "wake_request_numbers",+ "goal_context_request_numbers", "cap_reason_seen",+ "final_goal_status", "confirmed_goal_complete",+ "model_completion_text_seen", "exit_code", "stopped")+ if ts[field] != rust[field]+ }+ all_runs = [run for versions in result["scenarios"].values() for run in versions.values()]+ result["observed_fields_equal"] = not any(result["differences"].values())+ result["validation_complete"] = (not result["fixture_error"] and len(all_runs) == 8+ and all(run["request_count"] > 0 and run["stopped"] is None+ for run in all_runs))+ recovery = result["scenarios"].get("recover", {})+ result["recovery_confirmed"] = (len(recovery) == 2 and+ all(run["confirmed_goal_complete"] for run in recovery.values()))+ result["parity"] = (result["observed_fields_equal"] and result["validation_complete"]+ and result["recovery_confirmed"])+ result["requires_behavior_decision"] = not result["parity"]+ args.receipt.write_text(json.dumps(result, indent=2) + "\n")+ print("goal parity receipt: %s" % args.receipt)+ for scenario, versions in result["scenarios"].items():+ print(scenario + ": " + ", ".join("%s requests=%s exit=%s stopped=%s" %+ (label, run["request_count"], run["exit_code"], run["stopped"])+ for label, run in versions.items()))+ if result["requires_behavior_decision"]:+ print("PARITY NOT CONFIRMED: inspect differences and incomplete observations in receipt")+ if result["binaries"].get("ts", {}).get("kernel_provenance"):+ print("kernel/goal provenance: " + json.dumps(result["binaries"]["ts"]["kernel_provenance"]))+ if result["fixture_error"]:+ print(result["fixture_error"], file=sys.stderr)+ return 1+ if any(run["request_count"] == 0 for versions in result["scenarios"].values()+ for run in versions.values()):+ print("a binary made no mock-provider request; inspect receipt", file=sys.stderr)+ return 1+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/test_ci_test_shard.py b/scripts/test_ci_test_shard.pyindex e1fe8aa1cc..f5473807f9 100644--- a/scripts/test_ci_test_shard.py+++ b/scripts/test_ci_test_shard.py@@ -31,6 +31,7 @@ import sysimport tempfileimport unittestfrom pathlib import Path+from unittest.mock import patchSCRIPTS_DIR = Path(__file__).resolve().parentREPO = SCRIPTS_DIR.parent@@ -77,7 +78,8 @@ class EnumerationTestCase(unittest.TestCase):failed_tests=[]) for u in mine]SHARD.write_manifest(directory / f"shard-manifest-{shard}.json", shard, TOTAL,- self.all_ids, results, scope_by_shard(shard) if scope_by_shard else crates)+ self.all_ids, results, scope_by_shard(shard) if scope_by_shard else crates,+ run_attempt=1)return selectiondef test_the_assignment_is_stable_under_the_selection(self):@@ -136,13 +138,16 @@ class AuditTestCase(unittest.TestCase):use_crates = scope_by_shard(shard) if scope_by_shard else cratesSHARD.write_manifest(directory / f"shard-manifest-{shard}.json", shard, TOTAL,- self.all_ids, results, use_crates)+ self.all_ids, results, use_crates, run_attempt=1)def test_a_full_wave_audits_green(self):with tempfile.TemporaryDirectory() as tmp:directory = Path(tmp)- self.green_wave(directory, None)- result = run_summary(directory)+ # Legacy fixture names imply attempt 1 even when this battery runs+ # inside a GitHub Actions rerun (GITHUB_RUN_ATTEMPT=2 or later).+ with patch.dict(os.environ, {"GITHUB_RUN_ATTEMPT": "2"}):+ self.green_wave(directory, None)+ result = run_summary(directory)self.assertEqual(result.returncode, 0, result.stdout)self.assertIn("full selection", result.stdout)diff --git a/scripts/test_ci_test_shard_summary.py b/scripts/test_ci_test_shard_summary.pynew file mode 100644index 0000000000..8cc3fa43a1--- /dev/null+++ b/scripts/test_ci_test_shard_summary.py@@ -0,0 +1,218 @@+#!/usr/bin/env python3+"""Offline regression cases for selecting rerun shard manifests."""++import importlib.util+import json+import os+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++HERE = Path(__file__).resolve().parent+spec = importlib.util.spec_from_file_location("ci_test_shard", HERE / "ci_test_shard.py")+shards = importlib.util.module_from_spec(spec)+spec.loader.exec_module(shards)+++class AttemptAudit(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.directory = Path(self.temp.name)+ self.ids = [next(f"pkg#test:unit-{n}" for n in range(100)+ if shards.shard_of(f"pkg#test:unit-{n}", 2) == shard)+ for shard in range(2)]++ def write(self, shard, attempt=1, rc=0, complete=True, legacy=False):+ suffix = "" if legacy else f"-attempt-{attempt}"+ path = self.directory / f"shard-manifest-{shard}{suffix}.json"+ unit = {"id": self.ids[shard - 1], "rc": rc, "seconds": 1.0,+ "failed_tests": ["failure"] if rc else []}+ shards.write_manifest(path, shard, 2, self.ids, [unit] if complete else [],+ run_attempt=attempt, run_id="12345", commit_sha="a" * 40)+ if legacy:+ data = json.loads(path.read_text())+ data.pop("run_attempt")+ path.write_text(json.dumps(data))+ return path++ def run_summary(self, sha="a" * 40):+ env = dict(os.environ, GITHUB_RUN_ID="12345", GITHUB_SHA=sha)+ return subprocess.run([sys.executable, str(HERE / "ci_test_shard_summary.py"),+ "--total", "2", "--dir", str(self.directory)],+ capture_output=True, text=True, env=env, check=False)++ @staticmethod+ def rewrite(path, change):+ data = json.loads(path.read_text())+ change(data)+ path.write_text(json.dumps(data))++ def test_old_failed_new_pass_keeps_other_shard_original(self):+ self.write(1, 1, rc=1)+ self.write(2, 1)+ self.write(1, 2)+ result = self.run_summary()+ self.assertEqual(result.returncode, 0, result.stdout)+ self.assertIn("shard 1: selected attempt 2; retained prior attempts: 1", result.stdout)+ self.assertIn("shard 2: selected attempt 1; retained prior attempts: none", result.stdout)++ def test_new_failure_never_falls_back_to_old_green(self):+ self.write(1, 1)+ self.write(2, 1)+ self.write(1, 2, rc=1)+ result = self.run_summary()+ self.assertEqual(result.returncode, 1)+ self.assertIn("1 failing test binaries", result.stdout)++ def test_attempt_ten_outranks_nine_numerically(self):+ self.write(1, 9)+ self.write(2, 9)+ self.write(1, 10, rc=1)+ result = self.run_summary()+ self.assertEqual(result.returncode, 1)+ self.assertIn("selected attempt 10; retained prior attempts: 9", result.stdout)+ self.assertIn("1 failing test binaries", result.stdout)++ def test_new_partial_never_falls_back(self):+ self.write(1, 1)+ self.write(2, 1)+ self.write(1, 2, complete=False)+ result = self.run_summary()+ self.assertEqual(result.returncode, 1)+ self.assertIn("shard 1 is incomplete", result.stdout)++ def test_incomplete_latest_attempt_still_reports_mixed_scope(self):+ self.write(1, 1)+ self.write(2, 1)+ path = self.write(1, 2, complete=False)+ self.rewrite(path, lambda data: data.update(scope={"kind": "crates", "crates": ["pkg"]}))+ result = self.run_summary()+ self.assertEqual(result.returncode, 1)+ self.assertIn("different selection scopes", result.stdout)+ self.assertIn("shard 1 is incomplete", result.stdout)++ def test_duplicate_same_attempt_is_ambiguous(self):+ self.write(1, 1, legacy=True)+ self.write(1, 1)+ self.write(2, 1)+ result = self.run_summary()+ self.assertEqual(result.returncode, 1)+ self.assertIn("duplicate manifests", result.stdout)++ def test_identity_mismatch_is_refused(self):+ self.write(1)+ self.write(2)+ result = self.run_summary(sha="b" * 40)+ self.assertEqual(result.returncode, 1)+ self.assertIn("identity", result.stdout)++ def test_retained_prior_attempt_with_wrong_identity_is_refused(self):+ prior = self.write(1, 1)+ self.write(1, 2)+ self.write(2, 1)+ data = json.loads(prior.read_text())+ data["run_id"] = "another-run"+ prior.write_text(json.dumps(data))+ result = self.run_summary()+ self.assertEqual(result.returncode, 1)+ self.assertIn("identity mismatch", result.stdout)++ def test_malformed_json_root_is_diagnostic(self):+ self.write(1)+ path = self.write(2)+ path.write_text("[]")+ result = self.run_summary()+ self.assertEqual(result.returncode, 1)+ self.assertIn("JSON root must be an object", result.stdout)+ self.assertNotIn("Traceback", result.stderr)++ def test_selected_manifest_missing_units_is_diagnostic(self):+ self.write(1)+ path = self.write(2)+ self.rewrite(path, lambda data: data.pop("units"))+ result = self.run_summary()+ self.assertEqual(result.returncode, 1)+ self.assertIn("missing enumeration or unit results", result.stdout)+ self.assertNotIn("Traceback", result.stderr)++ def test_falseish_string_complete_is_refused(self):+ path = self.write(1)+ self.write(2)+ self.rewrite(path, lambda data: data.update(complete="false"))+ result = self.run_summary()+ self.assertEqual(result.returncode, 1)+ self.assertIn("complete must be literal true", result.stdout)++ def test_boolean_rc_is_refused(self):+ path = self.write(1)+ self.write(2)+ self.rewrite(path, lambda data: data["units"][0].update(rc=False))+ result = self.run_summary()+ self.assertEqual(result.returncode, 1)+ self.assertIn("malformed enumeration or unit results", result.stdout)++ def test_non_string_unit_id_is_refused(self):+ path = self.write(1)+ self.write(2)+ self.rewrite(path, lambda data: data["units"][0].update(id=7))+ result = self.run_summary()+ self.assertEqual(result.returncode, 1)+ self.assertIn("malformed enumeration or unit results", result.stdout)++ def test_non_string_selected_id_is_refused(self):+ path = self.write(1)+ self.write(2)+ self.rewrite(path, lambda data: data["selected_unit_ids"].append(7))+ result = self.run_summary()+ self.assertEqual(result.returncode, 1)+ self.assertIn("malformed selected unit ids", result.stdout)++ def test_all_scope_cannot_carry_crates(self):+ path = self.write(1)+ self.write(2)+ self.rewrite(path, lambda data: data["scope"].update(crates=["pkg"]))+ result = self.run_summary()+ self.assertEqual(result.returncode, 1)+ self.assertIn("invalid selection scope", result.stdout)++ def test_malformed_scope_is_diagnostic(self):+ path = self.write(1)+ self.write(2)+ self.rewrite(path, lambda data: data.update(scope=[]))+ result = self.run_summary()+ self.assertEqual(result.returncode, 1)+ self.assertIn("invalid selection scope", result.stdout)+ self.assertNotIn("Traceback", result.stderr)++ def test_legacy_attempt_one_with_identity_is_accepted(self):+ self.write(1, legacy=True)+ self.write(2, legacy=True)+ result = self.run_summary()+ self.assertEqual(result.returncode, 0, result.stdout)++ def test_digest_mismatch_is_refused(self):+ path = self.write(1)+ self.write(2)+ data = json.loads(path.read_text())+ data["digest"] = "bad"+ path.write_text(json.dumps(data))+ result = self.run_summary()+ self.assertEqual(result.returncode, 1)+ self.assertIn("digest mismatch", result.stdout)++ def test_wrong_shard_assignment_is_refused(self):+ path = self.write(1)+ self.write(2)+ data = json.loads(path.read_text())+ data["units"][0]["id"] = self.ids[1]+ path.write_text(json.dumps(data))+ result = self.run_summary()+ self.assertEqual(result.returncode, 1)+ self.assertIn("belongs to shard 2", result.stdout)+++if __name__ == "__main__":+ unittest.main(verbosity=2)