Skip to content

Official Codebase of 3DCodeVerse

Python

tests: 175 s to 27 s, and the wall-clock waits were nearly all accidental

gaoypengab6a72a80916
diff --git a/harness/codeverse/agents/cli_common.py b/harness/codeverse/agents/cli_common.py
index 08930f9d..ae6ae691 100644
--- a/harness/codeverse/agents/cli_common.py
+++ b/harness/codeverse/agents/cli_common.py
@@ -586,6 +586,12 @@ def deliver_prompt(s: Session, prompt: str, *, max_bytes: int = MAX_ARGV_PROMPT_
#: read at call time by :func:`invoke` so a test can monkeypatch it here.
IDLE_GRACE_S = 300.0
+#: watchdog poll period. A real vendor CLI runs for minutes, so 1 s of latency on
+#: noticing it exited is free — but a FAKE cli in a test exits in milliseconds and then
+#: waits out the poll, which was ~1 s on every agent.run() in the suite. Same shape as
+#: IDLE_GRACE_S: read at call time so tests can turn it down (tests/agents/conftest.py).
+POLL_S = 1.0
+
def invoke(
s: Session,
@@ -632,7 +638,7 @@ def invoke(
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=soft, hard_timeout_s=soft + 300.0,
- idle_grace_s=IDLE_GRACE_S if idle_grace_s is None else idle_grace_s,
+ idle_grace_s=IDLE_GRACE_S if idle_grace_s is None else idle_grace_s, poll_s=POLL_S,
on_line=on_line, stdin=stdin, activity_dirs=[s.ws.src, s.ws.public],
)
suffix = "" if attempt == 1 else f".{attempt}"
diff --git a/harness/tests/agents/conftest.py b/harness/tests/agents/conftest.py
index e7e9ed4f..8fe8ac0c 100644
--- a/harness/tests/agents/conftest.py
+++ b/harness/tests/agents/conftest.py
@@ -46,3 +46,11 @@ def _clean_agent_env(monkeypatch):
"""Make sure host secrets in the test process do not leak assumptions into tests."""
monkeypatch.setenv("FAKE_SERVICE_API_KEY", "leak-me")
yield
+
+
[email protected](autouse=True)
+def _fast_watchdog_poll(monkeypatch):
+ """A fake CLI exits in milliseconds; the watchdog's 1 s poll then dominated every
+ agent.run() in this directory (~13 s across the suite). Production keeps 1 s —
+ a real vendor CLI runs for minutes and does not care."""
+ monkeypatch.setattr("codeverse.agents.cli_common.POLL_S", 0.02)
diff --git a/harness/tests/agents/test_gemini_cli.py b/harness/tests/agents/test_gemini_cli.py
index 7496ffce..384349e3 100644
--- a/harness/tests/agents/test_gemini_cli.py
+++ b/harness/tests/agents/test_gemini_cli.py
@@ -50,6 +50,13 @@ def agent(fake_bin, monkeypatch):
monkeypatch.setattr(s, "gemini_api_keys", ["k1", "k2"])
monkeypatch.setattr(s, "cache_dir", Path(binary).parent / "cache")
monkeypatch.delenv("GEMINI_API_KEYS", raising=False)
+ # shared_pool caches per (keys, quota) for the life of the PROCESS, so an earlier
+ # test in this worker can leave k1 spent or cooling and the next invoke starts on
+ # k2 — which broke `keys == ["k1", "k2"]` once the suite went parallel and test
+ # grouping changed. Every test here starts from a fresh pool.
+ from codeverse.models import gemini as gm
+ for sig in [x for x in list(gm._pools) if x and x[0] in ("k1", "only")]: # noqa: SLF001
+ gm._pools.pop(sig, None) # noqa: SLF001
return GeminiCliAgent("gemini-3.7-flash", binary=binary)
diff --git a/harness/tests/conftest.py b/harness/tests/conftest.py
index 656225c8..8e247cfd 100644
--- a/harness/tests/conftest.py
+++ b/harness/tests/conftest.py
@@ -36,3 +36,15 @@ def assert_pid_gone(pid: int, *, group: bool = False, timeout_s: float = 10.0) -
return
time.sleep(0.05)
raise AssertionError(f"{'process group' if group else 'pid'} {pid} survived the kill")
+
+
+#: how many tests this session collected. tests/install/test_hermetic.py needs a
+#: ceiling for the counts docs/INSTALL.md quotes, and used to get it by spawning a
+#: nested `pytest tests --collect-only` — 8-10 s of the suite's wall clock to learn a
+#: number this process already knows. Under xdist every worker collects the whole
+#: suite before running its share, so this is the full count in each of them.
+COLLECTED: dict[str, int] = {}
+
+
+def pytest_collection_modifyitems(session, config, items): # noqa: ARG001
+ COLLECTED["n"] = len(items)
diff --git a/harness/tests/flywheel_cli/test_cli.py b/harness/tests/flywheel_cli/test_cli.py
index 19dbf339..244ae005 100644
--- a/harness/tests/flywheel_cli/test_cli.py
+++ b/harness/tests/flywheel_cli/test_cli.py
@@ -118,7 +118,13 @@ def test_lazy_import_message():
C.lazy("codeverse.definitely_missing_module")
-def test_doctor_json(tmp_path: Path):
+def test_doctor_json(tmp_path: Path, monkeypatch):
+ # run_doctor shells out to gemini/agy/codex/claude/blender/node/git for version
+ # strings — 1.6 s for `gemini --version` alone, and what they answer depends on
+ # which binaries this particular box has. The assertion below is about the JSON's
+ # SHAPE, so the probes' answers are irrelevant; their cost is not.
+ import codeverse.doctor as doc
+ monkeypatch.setattr(doc, "_ver", lambda *a, **k: (True, "stub 0.0"))
r = runner.invoke(app, ["doctor", "--no-gpu", "--json"])
assert r.exit_code in (0, 1), r.output
rows = json.loads(r.output[r.output.index("["):])
diff --git a/harness/tests/install/test_hermetic.py b/harness/tests/install/test_hermetic.py
index cd036e0b..c835f877 100644
--- a/harness/tests/install/test_hermetic.py
+++ b/harness/tests/install/test_hermetic.py
@@ -19,6 +19,8 @@ from pathlib import Path
import pytest
+from tests.conftest import COLLECTED
+
HARNESS = Path(__file__).resolve().parents[2]
KEY_ENVS = ("GEMINI_API_KEYS", "GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_GENAI_API_KEY")
@@ -29,17 +31,18 @@ CREDENTIAL_FREE = (
)
[email protected]("nodeid", CREDENTIAL_FREE)
-def test_passes_with_no_api_keys_in_the_environment(nodeid: str, tmp_path: Path) -> None:
+def test_passes_with_no_api_keys_in_the_environment(tmp_path: Path) -> None:
+ """ONE subprocess for both node ids — it was parametrized, which paid the ~2 s
+ interpreter + import cost twice to prove one property about the same stripped env."""
env = {k: v for k, v in os.environ.items() if k not in KEY_ENVS}
env["HOME"] = str(tmp_path) # no ~/.config/astra3d/gemini_keys.env either
env["PYTHONPATH"] = str(HARNESS)
# -n0: the suite's addopts turn xdist ON, and a nested run must not fork 24 more workers
- r = subprocess.run([sys.executable, "-m", "pytest", nodeid, "-q", "-n0", "-p", "no:cacheprovider"],
+ r = subprocess.run([sys.executable, "-m", "pytest", *CREDENTIAL_FREE, "-q", "-n0", "-p", "no:cacheprovider"],
cwd=HARNESS, env=env, capture_output=True, text=True, timeout=300)
- assert r.returncode == 0, f"{nodeid} needs credentials:\n{r.stdout[-3000:]}\n{r.stderr[-2000:]}"
+ assert r.returncode == 0, f"needs credentials:\n{r.stdout[-3000:]}\n{r.stderr[-2000:]}"
# --------------------------------------------------------------------------- PORT-8
@@ -48,13 +51,23 @@ INSTALL = HARNESS / "docs" / "INSTALL.md"
_COUNT = re.compile(r"(\d{3,6})\s+(?:passed|selected)|out of the (\d{3,6})")
+#: below this, the run was narrowed (one file, -k, a single directory) and cannot bound
+#: the suite. The full offline suite is ~2 800.
+_FULL_RUN_FLOOR = 1000
+
+
def _collected() -> int:
- """How many tests the suite actually has (the ceiling for any quoted count)."""
- r = subprocess.run([sys.executable, "-m", "pytest", "tests", "--collect-only", "-q", "-n0",
- "-p", "no:cacheprovider"], cwd=HARNESS, capture_output=True, text=True, timeout=300)
- m = re.search(r"(\d+)\s*/\s*(\d+) tests collected", r.stdout) or re.search(r"(\d+) tests collected", r.stdout)
- assert m, r.stdout[-2000:]
- return int(m.group(m.lastindex))
+ """How many tests the suite has (the ceiling for any quoted count).
+
+ This used to spawn `pytest tests --collect-only` — 8-10 s to learn a number the
+ running process already knows. tests/conftest.py stashes it at collection; under
+ xdist every worker collects the whole suite before running its share, so the count
+ is the full one wherever this lands.
+ """
+ n = COLLECTED.get("n", 0)
+ if n < _FULL_RUN_FLOOR:
+ pytest.skip(f"only {n} tests collected — a narrowed run cannot bound the suite")
+ return n
@pytest.mark.parametrize("doc", [INSTALL], ids=["INSTALL.md"])
diff --git a/harness/tests/models/test_gemini.py b/harness/tests/models/test_gemini.py
index 0a342854..0df944ad 100644
--- a/harness/tests/models/test_gemini.py
+++ b/harness/tests/models/test_gemini.py
@@ -287,10 +287,20 @@ def test_429_on_every_key_waits_for_cooldown_then_counts_against_budget():
def test_no_single_wait_exceeds_the_house_limit():
"""Every backoff path — 429 cooldown, provider retryDelay, 5xx, capacity
storm — sleeps at most MAX_WAIT_S at a time (owner rule, 2026-08-24)."""
+ # the sleep must ADVANCE the clock, like the neighbour test's: with a recording
+ # sleep and the real monotonic clock the cooldown loop never gets past "still
+ # cooling" and busy-spins — it logged 1.9 M naps over 3 s of wall time, of which
+ # 4 were real waits, so `max(naps)` was sampling the spin, not the backoff.
+ clock = {"t": 1000.0}
naps: list[float] = []
- pool = KeyPool(["k1", "k2"], sleep=naps.append)
+
+ def nap(s: float) -> None:
+ naps.append(s)
+ clock["t"] += s
+
+ pool = KeyPool(["k1", "k2"], clock=lambda: clock["t"], sleep=nap)
m, _log, _ = _keyed_model(["k1", "k2"], {k: THROTTLED for k in ("k1", "k2")}, pool=pool, max_attempts=3)
- m._sleep = naps.append
+ m._sleep = nap
with pytest.raises(ModelError):
m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
assert naps, "expected the throttled path to sleep at least once"
diff --git a/harness/tests/orchestrator_tracks/test_plan_features.py b/harness/tests/orchestrator_tracks/test_plan_features.py
index bdccd73e..1d9df910 100644
--- a/harness/tests/orchestrator_tracks/test_plan_features.py
+++ b/harness/tests/orchestrator_tracks/test_plan_features.py
@@ -3,6 +3,7 @@ which env switches any code actually reads (CQ-5)."""
from __future__ import annotations
+from functools import cache
from pathlib import Path
import pytest
@@ -13,13 +14,27 @@ from codeverse.tracks import plan_features as F
HARNESS = Path(__file__).resolve().parents[2]
-def _sources() -> list[Path]:
- return [p for d in ("codeverse", "bench") for p in (HARNESS / d).rglob("*.py")
- if p.name != "plan_features.py"]
+@cache
+def _sources() -> tuple[tuple[str, str], ...]:
+ """(relpath, text) for every harness source, read ONCE per session.
+
+ ``bench/out`` is excluded on purpose: it is gitignored battery output (5 781 of the
+ 5 978 .py files this used to walk, all LLM-authored ``model.py``). Reading it cost
+ ~0.65 s per parametrized case × 13, and it was also WRONG — a generated model.py
+ that happens to contain a switch name would satisfy _readers() or fail the
+ dead-switch guard, from a file that is not part of the harness at all.
+ """
+ out = []
+ for d in ("codeverse", "bench"):
+ for p in (HARNESS / d).rglob("*.py"):
+ if p.name == "plan_features.py" or "out" in p.relative_to(HARNESS).parts:
+ continue
+ out.append((str(p.relative_to(HARNESS)), p.read_text(errors="replace")))
+ return tuple(out)
def _readers(name: str) -> list[str]:
- return [str(p.relative_to(HARNESS)) for p in _sources() if name in p.read_text(errors="replace")]
+ return [rel for rel, text in _sources() if name in text]
@pytest.mark.parametrize("name", sorted(F.LIVE_SWITCHES))
diff --git a/harness/tests/skills/test_freshness.py b/harness/tests/skills/test_freshness.py
index a1d4e887..394df831 100644
--- a/harness/tests/skills/test_freshness.py
+++ b/harness/tests/skills/test_freshness.py
@@ -105,7 +105,10 @@ def _live_vocabulary() -> set[str]:
if not root.is_dir():
continue
for p in root.rglob("*"):
- if (not p.is_file() or p.suffix not in exts
+ # bench/out is live battery output — 5 781 of the 6 128 files this used to
+ # read, 35 MB of 39 MB, and it grows with every run. The only thing wanted
+ # from it is battery NAMES, collected by iterdir() below.
+ if (not p.is_file() or p.suffix not in exts or "out" in p.parts
or "node_modules" in p.parts or "__pycache__" in p.parts
or p.parent.name.startswith("cv3d-") or "_claims" in p.parts
or p.parent.parent.name.startswith("cv3d-")):