Official Codebase of 3DCodeVerse
Python
live-wave fixes: a plan may grow to the ceiling, a retry gets only what is left, a stream cannot outrun its wall
gaoypeng0c594012f80a
diff --git a/harness/codeverse/agents/cli_common.py b/harness/codeverse/agents/cli_common.pyindex 05eea1ab..862134c0 100644--- a/harness/codeverse/agents/cli_common.py+++ b/harness/codeverse/agents/cli_common.py@@ -378,6 +378,7 @@ def invoke(stdin: str | None = None,attempt: int = 1,idle_grace_s: float | None = None,+ soft_timeout_s: float | None = None,**invoke_extra: Any,) -> CompletedProc:"""Run one CLI agent process under the watchdog and record it in the trajectory.@@ -404,8 +405,13 @@ def invoke(if on_stdout is not None and stream == "stdout":on_stdout(line)+ # A streaming session must not outlive its window by half of it again: the watchdog's+ # default hard kill is max(1.5x soft, soft+600), and chair_bl (loop_w1, 2026-08-28)+ # streamed straight past a 16-minute window for 37 minutes. Five minutes of grace is+ # what the budget salvage gets; the session gets the same.+ soft = float(s.job.timeout_s if soft_timeout_s is None else soft_timeout_s)proc = run_with_watchdog(- argv, cwd=s.ws.root, env=env, soft_timeout_s=s.job.timeout_s,+ argv, cwd=s.ws.root, env=env, soft_timeout_s=soft, hard_timeout_s=soft + 300.0,idle_grace_s=IDLE_GRACE_S if idle_grace_s is None else idle_grace_s,on_line=on_line, stdin=stdin, activity_dirs=[s.ws.src, s.ws.public],)diff --git a/harness/codeverse/agents/gemini_cli.py b/harness/codeverse/agents/gemini_cli.pyindex 4b1e71f3..d660befb 100644--- a/harness/codeverse/agents/gemini_cli.py+++ b/harness/codeverse/agents/gemini_cli.py@@ -21,6 +21,7 @@ from __future__ import annotationsimport jsonimport logging+import timefrom pathlib import Pathfrom typing import Any@@ -61,6 +62,16 @@ SYSTEM_SETTINGS = {RETRY_KEY_WAIT_S = 10.0+def retry_window_left(timeout_s: float, elapsed_s: float) -> float | None:+ """Seconds of the session window a retry may still use, or ``None`` when too little+ is left to be worth an invoke. A retry never restarts the window: chair_bl+ (loop_w1, 2026-08-28) got a FULL fresh window on attempt 2 and ran 32 more minutes+ against a run wall that had expired before the retry began."""+ min_window = min(120.0, float(timeout_s) * 0.25)+ left = float(timeout_s) - float(elapsed_s)+ return None if left < min_window else left++def _key_pool(keys: list[str]) -> KeyPool:"""THE process-wide pool for these keys — ``models.gemini.shared_pool``, i.e. thesame limiter the API path uses, with quotas from ``Settings.rate``. This module@@ -203,17 +214,24 @@ class GeminiCliAgent:return failed(s, "budget", f"Gemini key pool exhausted before the first attempt: {e}")attempts = 0used: set[str] = set()+ t0 = time.monotonic()+ next_soft: float | None = None # attempt 1 uses the job's own windowusage_total = Usage(backend=self.kind, model=self.model)while True:attempts += 1used.add(key)- proc = self._invoke(s, prompt, key, attempt=attempts)+ proc = self._invoke(s, prompt, key, attempt=attempts, soft_timeout_s=next_soft)outcome = self._interpret(s, proc)usage_total = usage_total + outcome["usage"]pool.report(key, "429" if outcome["quota"] else ("ok" if outcome["ok"] else "5xx"))pool.release() # one acquire per attempt: keep the pool's in-flight gauge honestif outcome["ok"] or outcome["exit_reason"] in ("timeout", "model_substituted") or not outcome["transient"] or attempts >= 2:break+ next_soft = retry_window_left(job.timeout_s, time.monotonic() - t0)+ if next_soft is None:+ s.notes.append(f"attempt {attempts} transient failure ({outcome['exit_reason']}); "+ "no session window left — not retrying past the wall")+ breaknext_key = _retry_key(pool, used)if next_key is None:s.notes.append(f"attempt {attempts} transient failure ({outcome['exit_reason']}); no usable key for a retry")@@ -231,9 +249,10 @@ class GeminiCliAgent:finally:release_session(s)- def _invoke(self, s: Session, prompt: str, key: str, *, attempt: int) -> CompletedProc:+ def _invoke(self, s: Session, prompt: str, key: str, *, attempt: int,+ soft_timeout_s: float | None = None) -> CompletedProc:return invoke(s, self.build_argv(prompt), self.build_env(s, key), prompt=prompt, attempt=attempt,- model=self.model, key_tail=key[-4:])+ soft_timeout_s=soft_timeout_s, model=self.model, key_tail=key[-4:])def _interpret(self, s: Session, proc: CompletedProc) -> dict[str, Any]:parsed = parse_gemini_json(proc.stdout)diff --git a/harness/codeverse/tracks/planner.py b/harness/codeverse/tracks/planner.pyindex 8c2e619c..527a5540 100644--- a/harness/codeverse/tracks/planner.py+++ b/harness/codeverse/tracks/planner.py@@ -204,8 +204,8 @@ def plan_with_usage[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P]try:resp = model.generate(req)except Exception as e: # noqa: BLE001 — a truncated plan is retryable; anything else is not- if not (_truncated(e) and not grown and tokens < PLAN_TOKENS_MAX):- raise+ if not (_truncated(e) and tokens < PLAN_TOKENS_MAX):+ raise # not a truncation, or already at the model ceiling: nothing to growgrown += 1tokens = min(PLAN_TOKENS_MAX, int(tokens * TRUNCATION_GROWTH))if events is not None:diff --git a/harness/tests/agents/test_gemini_cli.py b/harness/tests/agents/test_gemini_cli.pyindex 0cde80a2..234a4a69 100644--- a/harness/tests/agents/test_gemini_cli.py+++ b/harness/tests/agents/test_gemini_cli.py@@ -53,6 +53,16 @@ def agent(fake_bin, monkeypatch):return GeminiCliAgent("gemini-3.7-flash", binary=binary)+def test_retry_window_never_restarts():+ """The retry rule itself: what is LEFT of the window, or None when < min(120, T/4)."""+ from codeverse.agents.gemini_cli import retry_window_left++ assert retry_window_left(1800, 1700) is None # 100s left < 120 floor+ assert retry_window_left(1800, 900) == 900 # half the window remains+ assert retry_window_left(20, 2) == 18 # small test jobs keep retrying+ assert retry_window_left(20, 16) is None # 4s left < 5s (T/4)++def _job(ws: Workspace, **kw) -> AgentJob:base = dict(workspace=str(ws.root), prompt="write hello", model="gemini-3.7-flash", timeout_s=20, label="t")base.update(kw)diff --git a/harness/tests/orchestrator_tracks/test_planner_depth.py b/harness/tests/orchestrator_tracks/test_planner_depth.pyindex 3d833f55..0b08bdea 100644--- a/harness/tests/orchestrator_tracks/test_planner_depth.py+++ b/harness/tests/orchestrator_tracks/test_planner_depth.py@@ -415,6 +415,28 @@ def test_a_truncated_plan_is_retried_with_more_room_instead_of_killing_the_run(tassert len(seen) == 2 and seen[1] > seen[0] and len(plan.parts) == 9+def test_repeated_truncation_keeps_growing_to_the_ceiling(tmp_path, monkeypatch):+ """chest_urdf, loop_w1 (2026-08-28): validation re-asks grew the history and+ 3.6-flash truncated AGAIN at 55,800 — the old single-growth guard killed the run+ one step short of the 65,536 ceiling. Truncation grows until the ceiling."""+ monkeypatch.setenv(BR.BRIEF_ENV, "off")+ from codeverse.models.base import ModelError++ ws = Workspace(tmp_path / "run")+ ws.create()+ good = json.loads(_plan([_part(f"P{i}", desc=_detailed(i), material=f"m{i}") for i in range(9)]).model_dump_json())+ seen: list[int] = []++ def responder(req):+ seen.append(req.max_output_tokens)+ if len(seen) <= 2:+ raise ModelError("structured output unavailable (finish_reason=MAX_TOKENS; raise max_output_tokens)")+ return good++ plan, _u = plan_with_usage(_spec(must=8), "fake:planner", StaticPlan, ws, model=FakeChatModel(responder))+ assert len(seen) == 3 and seen[0] < seen[1] < seen[2] and len(plan.parts) == 9++def test_a_model_error_that_is_not_truncation_still_propagates(tmp_path, monkeypatch):monkeypatch.setenv(BR.BRIEF_ENV, "off")from codeverse.models.base import ModelError