From e88c4e4fee0d4e5dd06d69f5046a61e3e3ee3718 Mon Sep 17 00:00:00 2001 From: Sunil Kumar Vadlamani Date: Sun, 18 Oct 2026 12:47:36 -0700 Subject: [PATCH 1/6] feat(rescue): allow compaction setting as one isolated variable in A/B fixtures --- _llmrig/rescue_ab.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/_llmrig/rescue_ab.py b/_llmrig/rescue_ab.py index 3ddf3e1..1f48bc6 100644 --- a/_llmrig/rescue_ab.py +++ b/_llmrig/rescue_ab.py @@ -127,12 +127,13 @@ def _grade_events(raw: bytes, task: Task, workspace: Path }, count -def _trial(model: str, context: int, task: Task, seconds: int - ) -> Dict[str, Any]: +def _trial(model: str, context: int, task: Task, seconds: int, + disable_auto_compaction: bool = False) -> Dict[str, Any]: """Run a single fixed task with a fresh project and fresh HOME.""" outcome: Dict[str, Any] = { "task_id": task.task_id, "context_tokens": context, + "auto_compaction_disabled": disable_auto_compaction, "status": "failed", "checks": {}, "events_seen": 0, @@ -151,7 +152,9 @@ def _trial(model: str, context: int, task: Task, seconds: int (home / "empty-opencode").mkdir() fixture = workspace / task.filename fixture.write_text(task.source, encoding="utf-8") - config = _configuration(model, context) + config = _configuration( + model, context, disable_auto_compaction=disable_auto_compaction + ) (workspace / "opencode.json").write_text(json.dumps(config), encoding="utf-8") original = _sha(fixture.read_bytes()) opencode = shutil.which("opencode") From 06853e939856c032062062ac1e6650e1119064fc Mon Sep 17 00:00:00 2001 From: Sunil Kumar Vadlamani Date: Sun, 18 Oct 2026 12:48:31 -0700 Subject: [PATCH 2/6] feat(rescue): paired controlled compaction A/B evaluator over 3 read-only fixtures --- _llmrig/rescue_compaction_ab.py | 165 ++++++++++++++++++++++++++++++++ 1 file changed, 165 insertions(+) create mode 100644 _llmrig/rescue_compaction_ab.py diff --git a/_llmrig/rescue_compaction_ab.py b/_llmrig/rescue_compaction_ab.py new file mode 100644 index 0000000..b903371 --- /dev/null +++ b/_llmrig/rescue_compaction_ab.py @@ -0,0 +1,165 @@ +"""Opt-in controlled compaction on/off OpenCode A/B experiment. + +Only compaction.auto differs within paired disposable fixture sessions. +No outside user project or persistent OpenCode configuration is modified. +This remains exploratory and not a statistically verified repair. +""" +from __future__ import annotations + +import shutil +import time +from typing import Any, Dict, List + +from . import rescue_ab + + +def _summary(trials: List[Dict[str, Any]]) -> Dict[str, Any]: + checks = [t.get("checks") or {} for t in trials] + n = len(trials) + successes = sum(t.get("status") == "passed" for t in trials) + return { + "trials": n, + "strict_passes": successes, + "strict_pass_rate": round(successes / n, 4) if n else None, + "fix_evidence": sum(all(c.get(k) is True for k in ( + "read_tool_completed", "correct_return_proposed", + "valid_event_stream", "no_disallowed_tool_observed", + "fixture_unchanged", + )) for c in checks), + "process_exits": sum(c.get("process_exit_zero") is True for c in checks), + "timeouts": sum(t.get("failure_category") == "agent_timeout" for t in trials), + "timeouts_with_fix": sum( + t.get("failure_category") == "agent_timeout" + and all(c.get(k) is True for k in ( + "read_tool_completed", "correct_return_proposed", + "valid_event_stream", "no_disallowed_tool_observed", "fixture_unchanged" + )) + for t, c in zip(trials, checks) + ), + "explanation_only_rubric_misses": sum( + t.get("failure_category") == "task_requirements_not_met" + and c.get("bug_explained") is False + and all(c.get(k) is True for k in ( + "read_tool_completed", "correct_return_proposed", "process_exit_zero", + "no_disallowed_tool_observed", "no_error_event", + "valid_event_stream", "fixture_unchanged", + )) + for t, c in zip(trials, checks) + ), + } + + +def compare_compaction(model: str, context: int, repeats: int = 1, + seconds: int = 90, budget_seconds: int = 600 + ) -> Dict[str, Any]: + """Run paired tasks, reversing condition order across tasks and repeats. + + Budget reserves full per-run timeout for BOTH sides before launching a + pair. If a full pair cannot fit, stop rather than truncate one side. + Failure of an individual agent task is recorded, not hidden as success. + """ + if type(repeats) is not int or not 1 <= repeats <= 3: + raise ValueError("--compaction-repeats must be between 1 and 3") + if type(seconds) is not int or not 20 <= seconds <= 180: + raise ValueError("--agent-timeout must be between 20 and 180 seconds") + if type(budget_seconds) is not int or not 120 <= budget_seconds <= 1200: + raise ValueError("--ab-budget must be between 120 and 1200 seconds") + if not shutil.which("opencode"): + raise ValueError("OpenCode executable was not found") + + tasks = rescue_ab.TASKS + result: Dict[str, Any] = { + "schema_version": "rescue-compaction-ab-v1", + "status": "incomplete", + "agent": "opencode", + "model": model, + "declared_context_tokens": context, + "task_suite_version": "rescue-readonly-fixed-v1", + "task_ids": [t.task_id for t in tasks], + "condition_variable": "opencode_compaction_auto", + "baseline_policy": "unspecified_default", + "candidate_policy": "explicit_auto_false", + "repeats_per_task": repeats, + "timeout_seconds_per_run": seconds, + "total_budget_seconds": budget_seconds, + "planned_agent_sessions": len(tasks) * repeats * 2, + "executed_agent_sessions": 0, + "trials": [], + "groups": None, + "observed_comparison": None, + "recommendation": "no_automatic_or_global_compaction_change", + "limitations": [ + "Task suite is tiny and synthetic, not representative of coding agents.", + "Reported context is an OpenCode declaration; per-request Ollama context is unverified.", + "Equal timeouts and alternating order reduce some confounds but do not prove causality.", + "Compaction disabled can cause context exhaustion on larger real tasks.", + "This executes third-party OpenCode under current OS user; not a kernel-enforced sandbox.", + "No user project opened and no persistent user configuration intentionally changed.", + "Raw agent messages, paths and arguments are not retained in evidence.", + ], + } + deadline = time.monotonic() + budget_seconds + halted = False + stopped_for_budget = False + pair_number = 0 + for repetition in range(repeats): + for task_index, task in enumerate(tasks): + # Do not penalize one condition by giving it less time than the other. + if deadline - time.monotonic() < (2 * seconds + 2): + stopped_for_budget = True + break + pair_number += 1 + order = (False, True) + if (repetition + task_index) % 2: + order = (True, False) + for disabled in order: + trial = rescue_ab._trial( + model, context, task, seconds, + disable_auto_compaction=disabled, + ) + trial["pair_number"] = pair_number + trial["repeat_index"] = repetition + 1 + trial["condition"] = ( + "compaction_disabled" if disabled else "compaction_default" + ) + result["trials"].append(trial) + if (trial.get("failure_category") == "test_boundary_violation" + or not (trial.get("checks") or {}).get("fixture_unchanged", True) + or not (trial.get("checks") or {}).get("no_disallowed_tool_observed", True)): + halted = True + break + if halted: + break + if halted or stopped_for_budget: + break + + trials = result["trials"] + result["executed_agent_sessions"] = len(trials) + full = not halted and not stopped_for_budget and len(trials) == result["planned_agent_sessions"] + result["status"] = ( + "completed" if full else + "stopped_on_boundary_violation" if halted else + "budget_exhausted" + ) + baseline = [t for t in trials if t.get("condition") == "compaction_default"] + candidate = [t for t in trials if t.get("condition") == "compaction_disabled"] + base, modified = _summary(baseline), _summary(candidate) + result["groups"] = {"baseline": base, "candidate": modified} + + # Only complete, equally-timed paired schedules can have a comparison. + if full: + rate = round(modified["strict_pass_rate"] - base["strict_pass_rate"], 4) + result["observed_comparison"] = { + "candidate_minus_baseline_strict_pass_rate": rate, + "candidate_minus_baseline_successful_exits": + modified["process_exits"] - base["process_exits"], + "candidate_minus_baseline_fix_evidence": + modified["fix_evidence"] - base["fix_evidence"], + "direction": ( + "compaction_disabled_observed_more_passes" if rate > 0 + else "compaction_disabled_observed_fewer_passes" if rate < 0 + else "no_observed_strict_pass_difference" + ), + "evidence_strength": "exploratory_small_sample_not_causally_verified", + } + return result From b5a706b301195b33b352cc97325e40d68760b321 Mon Sep 17 00:00:00 2001 From: Sunil Kumar Vadlamani Date: Sun, 18 Oct 2026 12:49:17 -0700 Subject: [PATCH 3/6] feat(rescue): expose paired compaction A/B task mode and guarded interpretation --- _llmrig/rescue.py | 81 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 78 insertions(+), 3 deletions(-) diff --git a/_llmrig/rescue.py b/_llmrig/rescue.py index b61bb52..43d447e 100644 --- a/_llmrig/rescue.py +++ b/_llmrig/rescue.py @@ -239,7 +239,9 @@ def rescue(agent: str, model: str, context: int, runs: int, agent_timeout: int = 120, ab_test: bool = False, ab_repeats: int = 2, ab_budget: int = 600, agent_steps: Optional[int] = None, - agent_no_auto_compact: bool = False) -> Dict[str, Any]: + agent_no_auto_compact: bool = False, + compaction_ab: bool = False, + compaction_repeats: int = 1) -> Dict[str, Any]: if agent != "opencode": raise RescueError("only the opencode preflight adapter is supported") model = validate_model(model) @@ -252,6 +254,17 @@ def rescue(agent: str, model: str, context: int, runs: int, or not 256 <= compare_context <= 262144 or compare_context == context ): raise RescueError("--compare-context must differ and be between 256 and 262144") + if compaction_ab: + if (probe or ab_test or agent_test or compare_context is not None + or agent_steps is not None or agent_no_auto_compact): + raise RescueError( + "--compaction-ab is independent of --probe, --ab-test, " + "--compare-context, --agent-test and agent-specific flags" + ) + if type(compaction_repeats) is not int or not 1 <= compaction_repeats <= 3: + raise RescueError("--compaction-repeats must be between 1 and 3") + elif compaction_repeats != 1: + raise RescueError("--compaction-repeats requires --compaction-ab") if ab_test and (probe or agent_test or compare_context is None): raise RescueError("--ab-test requires --compare-context and cannot combine with --probe or --agent-test") if compare_context is not None and not (probe or ab_test): @@ -272,6 +285,42 @@ def rescue(agent: str, model: str, context: int, runs: int, report = preflight(agent, model, context, base) if report["status"] != "ready_for_probe": return report + if compaction_ab: + if not report["agent_executable_detected"]: + report["status"] = "blocked" + report["blockers"].append("OpenCode executable not detected; no compaction A/B attempted") + return report + from .rescue_compaction_ab import compare_compaction + try: + compaction = compare_compaction( + model, context, repeats=compaction_repeats, + seconds=agent_timeout, budget_seconds=ab_budget, + ) + except ValueError as exc: + raise RescueError(str(exc)) + report["mode"] = "measured_compaction_ab" + report["scope"] = ( + "Controlled alternating compaction-policy comparison on three " + "disposable read-only OpenCode fixtures; not a verified repair" + ) + report["unknowns"] = [ + x for x in report["unknowns"] + if x != "OpenCode tool execution and task completion have not been tested" + ] + report["compaction_ab_evaluation"] = compaction + report["status"] = ( + "compaction_ab_completed" if compaction["status"] == "completed" + else "compaction_ab_incomplete" + ) + report["local_changes"] = ( + "Only temporary disposable OpenCode test configuration and agent state; " + "no persistent user settings deliberately changed" + ) + report["unknowns"].append( + "No direct compaction events or per-request Ollama context were verified; " + "tiny tests cannot establish a causal or broadly safe mitigation" + ) + return report if ab_test: if not report["agent_executable_detected"]: report["status"] = "blocked" @@ -379,7 +428,9 @@ def rescue(agent: str, model: str, context: int, runs: int, def format_terminal(report: Dict[str, Any]) -> str: mode = report.get("mode") - if mode == "measured_agent_ab": + if mode == "measured_compaction_ab": + heading = "LLMRig Rescue | Controlled compaction A/B experiment" + elif mode == "measured_agent_ab": heading = "LLMRig Rescue | Exploratory OpenCode A/B evaluation" elif mode == "measured_agent_task": heading = "LLMRig Rescue | OpenCode coding-task evaluation" @@ -405,6 +456,29 @@ def format_terminal(report: Dict[str, Any]) -> str: " synthetic tool calls passed" ) lines.append("Outcomes: " + ", ".join(item["outcomes"])) + if report.get("compaction_ab_evaluation"): + experiment = report["compaction_ab_evaluation"] + lines.append("Compaction A/B: " + experiment["status"]) + for name in ("baseline", "candidate"): + stats = experiment["groups"][name] + policy = "default" if name == "baseline" else "disabled" + lines.append( + " Compaction " + policy + ": " + str(stats["strict_passes"]) + + "/" + str(stats["trials"]) + " strict task passes; " + + str(stats["process_exits"]) + " successful exits; " + + str(stats["timeouts"]) + " timeouts" + ) + lines.append( + " Correct-fix evidence: " + str(stats["fix_evidence"]) + + "; explanation-only rubric misses: " + + str(stats["explanation_only_rubric_misses"]) + ) + if experiment["observed_comparison"]: + lines.append( + "Observed A/B: " + experiment["observed_comparison"]["direction"] + ) + lines.append("Evidence: exploratory, not causal or statistically validated") + lines.append("No automatic or global compaction changes were made.") if report.get("agent_ab_evaluation"): comparison = report["agent_ab_evaluation"] lines.append("A/B suite: " + comparison["status"]) @@ -471,7 +545,8 @@ def format_terminal(report: Dict[str, Any]) -> str: lines.append("Confidence: insufficient to establish agent improvement") for item in report["unknowns"]: lines.append("Unknown: " + item) - if report.get("agent_evaluation") or report.get("agent_ab_evaluation"): + if (report.get("agent_evaluation") or report.get("agent_ab_evaluation") + or report.get("compaction_ab_evaluation")): lines.append("OpenCode ran in disposable projects; this is not an OS sandbox.") else: lines.append("No OpenCode configuration was read or changed.") From 5d8b0d368cefc527d8afc61aedc6a781a338584e Mon Sep 17 00:00:00 2001 From: Sunil Kumar Vadlamani Date: Sun, 18 Oct 2026 12:49:34 -0700 Subject: [PATCH 4/6] feat(cli): explicit controlled --compaction-ab runner with bounded repeats --- _llmrig/cli.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/_llmrig/cli.py b/_llmrig/cli.py index aefff18..87a2b45 100644 --- a/_llmrig/cli.py +++ b/_llmrig/cli.py @@ -258,6 +258,14 @@ def _rescue_parser() -> argparse.ArgumentParser: help="Compare a second context; requires --probe or --ab-test.", ) parser.add_argument("--runs", type=int, default=3, help="Canary trials per context (1-5).") + parser.add_argument( + "--compaction-ab", action="store_true", + help="Opt in to paired, alternating default-versus-disabled compaction tasks.", + ) + parser.add_argument( + "--compaction-repeats", type=int, default=1, + help="Repeat each compaction on/off task pair (1-3, default 1).", + ) parser.add_argument( "--ab-test", action="store_true", help="Opt into a fixed 3-task OpenCode A/B comparison (no config changes).", @@ -308,6 +316,8 @@ def command_rescue(args: argparse.Namespace) -> int: ab_test=args.ab_test, ab_repeats=args.ab_repeats, ab_budget=args.ab_budget, agent_steps=args.agent_steps, agent_no_auto_compact=args.agent_no_auto_compact, + compaction_ab=args.compaction_ab, + compaction_repeats=args.compaction_repeats, ) except RescueError as exc: print("llmrig rescue: " + str(exc), file=sys.stderr) @@ -330,9 +340,9 @@ def command_rescue(args: argparse.Namespace) -> int: print("Rescue report saved locally. No report was uploaded.") else: print(payload, end="") if args.json else print(format_terminal(report), end="") - if report["status"] in ("agent_task_failed", "agent_ab_incomplete"): + if report["status"] in ("agent_task_failed", "agent_ab_incomplete", "compaction_ab_incomplete"): return 1 - return 0 if report["status"] in ("ready_for_probe", "measured", "agent_task_passed", "agent_ab_completed") else 2 + return 0 if report["status"] in ("ready_for_probe", "measured", "agent_task_passed", "agent_ab_completed", "compaction_ab_completed") else 2 def _build_plan(model: str, context: Optional[int], legacy: object) -> AutopilotExecutionPlan: @@ -723,6 +733,7 @@ def _print_augmented_help() -> int: print(" --agent-test opts into one disposable OpenCode task.") print(" --ab-test compares fixed tasks at two contexts.") print(" rescue-evidence Offline assessment of existing mitigation receipts.") + print(" rescue --compaction-ab Alternate compaction on/off in disposable agent tasks.") return 0 From e8ccb22e77ea350cb6d2974c2bf9b22751ef6ba5 Mon Sep 17 00:00:00 2001 From: Sunil Kumar Vadlamani Date: Sun, 18 Oct 2026 12:50:39 -0700 Subject: [PATCH 5/6] test(rescue): paired compaction order, isolated configs, budget safety and CLI guards --- tests/test_rescue_compaction_ab.py | 228 +++++++++++++++++++++++++++++ 1 file changed, 228 insertions(+) create mode 100644 tests/test_rescue_compaction_ab.py diff --git a/tests/test_rescue_compaction_ab.py b/tests/test_rescue_compaction_ab.py new file mode 100644 index 0000000..8d7bc09 --- /dev/null +++ b/tests/test_rescue_compaction_ab.py @@ -0,0 +1,228 @@ +"""Controls for paired OpenCode compaction A/B experiments (no live inference).""" +import contextlib +import io +import json +import unittest +from unittest import mock + +from _llmrig import cli, rescue, rescue_ab, rescue_compaction_ab + + +def trial(model, context, task, seconds, disable_auto_compaction=False): + assert model == "qwen3.8:27b-mlx" + assert context == 4096 + assert seconds == 90 + checks = { + "read_tool_completed": True, + "bug_explained": True, + "correct_return_proposed": True, + "no_disallowed_tool_observed": True, + "no_error_event": True, + "valid_event_stream": True, + "process_exit_zero": disable_auto_compaction, + "fixture_unchanged": True, + } + return { + "task_id": task.task_id, + "context_tokens": context, + "auto_compaction_disabled": disable_auto_compaction, + "status": "passed" if disable_auto_compaction else "failed", + "checks": checks, + "failure_category": None if disable_auto_compaction else "agent_timeout", + } + + +class ControlledCompactionAbTests(unittest.TestCase): + def test_alternating_order_and_matching_task_pairs(self): + seen = [] + def measure(model, context, task, seconds, disable_auto_compaction=False): + seen.append((task.task_id, disable_auto_compaction, context, seconds)) + return trial(model, context, task, seconds, disable_auto_compaction) + with mock.patch.object(rescue_compaction_ab.shutil, "which", + return_value="/usr/bin/opencode"), \ + mock.patch.object(rescue_ab, "_trial", side_effect=measure): + report = rescue_compaction_ab.compare_compaction( + "qwen3.8:27b-mlx", 4096, repeats=2, seconds=90, budget_seconds=1200 + ) + self.assertEqual(report["status"], "completed") + self.assertEqual(report["executed_agent_sessions"], 12) + self.assertEqual(report["planned_agent_sessions"], 12) + self.assertEqual( + [(t["condition"], t["pair_number"]) for t in report["trials"][:6]], + [("compaction_default", 1), ("compaction_disabled", 1), + ("compaction_disabled", 2), ("compaction_default", 2), + ("compaction_default", 3), ("compaction_disabled", 3)], + ) + self.assertEqual( + [(t["condition"], t["pair_number"]) for t in report["trials"][6:12]], + [("compaction_disabled", 4), ("compaction_default", 4), + ("compaction_default", 5), ("compaction_disabled", 5), + ("compaction_disabled", 6), ("compaction_default", 6)], + ) + self.assertEqual({x[2] for x in seen}, {4096}) + self.assertEqual({x[3] for x in seen}, {90}) + b, c = report["groups"]["baseline"], report["groups"]["candidate"] + self.assertEqual(b["strict_passes"], 0) + self.assertEqual(b["timeouts_with_fix"], 6) + self.assertEqual(c["strict_passes"], 6) + self.assertEqual(c["timeouts"], 0) + self.assertEqual( + report["observed_comparison"]["candidate_minus_baseline_strict_pass_rate"], 1.0 + ) + self.assertEqual(report["recommendation"], "no_automatic_or_global_compaction_change") + self.assertNotIn("Users/", json.dumps(report)) + + def test_abort_safely_on_tool_boundary_violation(self): + calls = [] + def violation(model, context, task, seconds, disable_auto_compaction=False): + calls.append(task.task_id) + result = trial(model, context, task, seconds, disable_auto_compaction) + result["status"] = "failed" + result["failure_category"] = "test_boundary_violation" + result["checks"]["no_disallowed_tool_observed"] = False + return result + with mock.patch.object(rescue_compaction_ab.shutil, "which", + return_value="/usr/bin/opencode"), \ + mock.patch.object(rescue_ab, "_trial", side_effect=violation): + result = rescue_compaction_ab.compare_compaction( + "qwen3.8:27b-mlx", 4096, repeats=2, seconds=90, budget_seconds=1200 + ) + self.assertEqual(result["executed_agent_sessions"], 1) + self.assertEqual(len(calls), 1) + self.assertEqual(result["status"], "stopped_on_boundary_violation") + self.assertIsNone(result["observed_comparison"]) + + def test_budget_never_runs_a_truncated_pair(self): + with mock.patch.object(rescue_compaction_ab.shutil, "which", + return_value="/usr/bin/opencode"), \ + mock.patch.object(rescue_ab, "_trial") as run: + result = rescue_compaction_ab.compare_compaction( + "qwen3.8:27b-mlx", 4096, repeats=1, seconds=90, budget_seconds=180 + ) + self.assertEqual(result["status"], "budget_exhausted") + self.assertEqual(result["executed_agent_sessions"], 0) + self.assertIsNone(result["observed_comparison"]) + run.assert_not_called() + + def test_refuse_bad_bounds_and_missing_agent(self): + with mock.patch.object(rescue_compaction_ab.shutil, "which", + return_value="/usr/bin/opencode"): + for settings in ({"repeats": 0}, {"repeats": 4}, {"seconds": 19}, + {"seconds": 181}, {"budget_seconds": 119}, + {"budget_seconds": 1201}): + with self.subTest(settings=settings), self.assertRaises(ValueError): + rescue_compaction_ab.compare_compaction( + "qwen3.8:27b-mlx", 4096, **settings + ) + with mock.patch.object(rescue_compaction_ab.shutil, "which", return_value=None): + with self.assertRaisesRegex(ValueError, "not found"): + rescue_compaction_ab.compare_compaction("qwen3.8:27b-mlx", 4096) + + def test_real_trial_config_only_differs_by_compaction(self): + calls = [] + def invoke(command, cwd, env, seconds): + cfg = json.loads((cwd / "opencode.json").read_text(encoding="utf-8")) + calls.append(cfg) + self.assertEqual(cfg["provider"]["ollama"]["models"] + ["qwen3.8:27b-mlx"]["limit"]["context"], 4096) + self.assertEqual(cfg["permission"]["bash"], "deny") + self.assertEqual(cfg["permission"]["edit"], "deny") + self.assertEqual(seconds, 90) + self.assertNotIn("OPENAI_API_KEY", env) + fixture = next(x for x in rescue_ab.TASKS if (cwd / x.filename).exists()) + stream = ( + json.dumps({"type": "tool_use", "part": { + "tool": "read", "state": { + "status": "completed", + "input": {"filePath": str(cwd / fixture.filename)} + } + }}) + "\n" + + json.dumps({"type": "text", "part": {"text": { + "parity-v1": "n % 2 == 1 checks odd numbers; return n % 2 == 0", + "nonnegative-clamp-v1": "max(0, -n) negates sign; return max(0, n)", + "prefix-v1": "endswith checks the end; return text.startswith('a')", + }[fixture.task_id]}}) + "\n" + ).encode("utf-8") + return ("exited", 0, stream, False) + with mock.patch.object(rescue_ab.shutil, "which", return_value="/usr/bin/opencode"), \ + mock.patch.object(rescue_ab, "_invoke", side_effect=invoke): + first = rescue_ab._trial("qwen3.8:27b-mlx", 4096, rescue_ab.TASKS[0], 90) + second = rescue_ab._trial( + "qwen3.8:27b-mlx", 4096, rescue_ab.TASKS[0], 90, + disable_auto_compaction=True, + ) + self.assertEqual(first["status"], "passed") + self.assertEqual(second["status"], "passed") + self.assertEqual(first["auto_compaction_disabled"], False) + self.assertEqual(second["auto_compaction_disabled"], True) + self.assertNotIn("compaction", calls[0]) + self.assertEqual(calls[1]["compaction"], {"auto": False}) + without = dict(calls[1]); without.pop("compaction") + self.assertEqual(without, calls[0]) + + def test_cli_explicit_opt_in_and_report_display(self): + preflight = { + "status": "ready_for_probe", + "agent_executable_detected": True, + "agent": "opencode", "model": "qwen3.8:27b-mlx", + "context_tokens": 4096, "unknowns": [ + "OpenCode tool execution and task completion have not been tested" + ], "blockers": [], "probes": [], "comparison": None, + } + run_result = { + "status": "completed", + "groups": { + "baseline": {"strict_passes": 0, "trials": 3, "process_exits": 0, + "timeouts": 3, "fix_evidence": 3, + "explanation_only_rubric_misses": 0}, + "candidate": {"strict_passes": 3, "trials": 3, "process_exits": 3, + "timeouts": 0, "fix_evidence": 3, + "explanation_only_rubric_misses": 0}, + }, + "observed_comparison": { + "direction": "compaction_disabled_observed_more_passes" + }, + } + with mock.patch.object(rescue, "preflight", return_value=preflight), \ + mock.patch.object(rescue, "local_host", + return_value="http://127.0.0.1:11434"), \ + mock.patch.object(rescue_compaction_ab, "compare_compaction", + return_value=run_result) as run, \ + contextlib.redirect_stdout(io.StringIO()) as output: + code = cli.main([ + "rescue", "--agent", "opencode", "--model", "qwen3.8:27b-mlx", + "--context", "4096", "--compaction-ab", "--compaction-repeats", + "1", "--agent-timeout", "90", "--ab-budget", "600", + ]) + self.assertEqual(code, 0) + run.assert_called_once_with( + "qwen3.8:27b-mlx", 4096, repeats=1, + seconds=90, budget_seconds=600 + ) + self.assertIn("Compaction default: 0/3", output.getvalue()) + self.assertIn("Compaction disabled: 3/3", output.getvalue()) + self.assertIn("not causal", output.getvalue()) + self.assertNotIn("have not been tested", output.getvalue()) + + def test_compaction_ab_mutually_exclusive_with_other_modes(self): + for options in [ + {"probe": True}, + {"agent_test": True}, + {"ab_test": True}, + {"compare_context": 8192}, + {"agent_steps": 4}, + {"agent_no_auto_compact": True}, + ]: + with self.subTest(options=options), self.assertRaises(rescue.RescueError): + rescue.rescue( + "opencode", "qwen3.8:27b-mlx", 4096, 3, + options.get("compare_context"), options.get("probe", False), + compaction_ab=True, **{ + k: v for k, v in options.items() + if k not in ("probe", "compare_context") + }, + ) + + +if __name__ == "__main__": + unittest.main() From 51d131721df5678cace40ff58fd15bf76a7327ad Mon Sep 17 00:00:00 2001 From: Sunil Kumar Vadlamani Date: Sun, 18 Oct 2026 12:51:14 -0700 Subject: [PATCH 6/6] docs(rescue): paired compaction A/B run, time budgets and noncausal interpretation --- docs/RESCUE.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/docs/RESCUE.md b/docs/RESCUE.md index 3edea8d..87c80ac 100644 --- a/docs/RESCUE.md +++ b/docs/RESCUE.md @@ -270,6 +270,47 @@ The report recommendation is always criterion is met. To investigate causality, perform independent alternating on/off trials with comparable budgets and multiple workloads. +## Paired compaction A/B experiment (explicit opt-in) + +The next experiment after offline receipt triage is a controlled **on/off** +comparison over the three fixed read-only coding tasks. At the **same** +OpenCode-declared context and model, the tool alternates conditions in an +A/B then B/A schedule, using fresh disposable workspaces and HOME state +per session. The conditions differ solely in whether +`compaction.auto: false` is explicitly set in the local fixture; baseline +uses OpenCode's unspecified default. + +```bash +llmrig rescue --agent opencode --model qwen3.8:27b-mlx \ + --context 4096 --compaction-ab --compaction-repeats 1 \ + --agent-timeout 90 --ab-budget 600 \ + --output rescue-compaction-paired.json +``` + +One repeat means **6 agent sessions**, and two repeats means **12 +sessions**, which can take a long time. If selecting two repeats, increase +`--ab-budget` to at least 1200 seconds when using a 90-second per-session +limit. The runner checks before each pair that the remaining total budget +can accommodate *both* full session timeouts; incomplete experiments are +never reported as complete comparisons. No task is run without explicit +`--compaction-ab`. + +Each outcome records task, compaction setting, pair number, test checks, +process completion, provisional correct-fix evidence, failure category, +and privacy-filtered event counts. The aggregate distinguishes actual +completed passes from explanation-only rubric misses and timeouts. A +single failing test is not silently converted to a success because the +model proposed a correct statement. + +**Interpretation:** Alternating order and equal task budgets reduce simple +confounds but do not independently observe compaction events or establish +a causal root cause, actual Ollama per-request context, statistical +significance, or safe generalization to long coding tasks. Raw model +text and fixture paths are not retained. OpenCode runs with current user +OS permissions; the disposable config and tool policy are *not* an OS +sandbox. Regardless of outcome, LLMRig never applies a persistent +compaction setting or automatically recommends disabling it globally. + ## Experimental A/B coding-task verification LLMRig can run an **opt-in exploratory A/B trial** using three fixed read-only