Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions _llmrig/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).",
Expand Down Expand Up @@ -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)
Expand All @@ -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:
Expand Down Expand Up @@ -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


Expand Down
81 changes: 78 additions & 3 deletions _llmrig/rescue.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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):
Expand All @@ -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"
Expand Down Expand Up @@ -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"
Expand All @@ -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"])
Expand Down Expand Up @@ -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.")
Expand Down
9 changes: 6 additions & 3 deletions _llmrig/rescue_ab.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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")
Expand Down
165 changes: 165 additions & 0 deletions _llmrig/rescue_compaction_ab.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading