Official Codebase of 3DCodeVerse
Python
workspace: multi-command git methods are one transaction
gaoypengefe29393d007
diff --git a/harness/codeverse/workspace.py b/harness/codeverse/workspace.pyindex 10f21a93..55a5bbdc 100644--- a/harness/codeverse/workspace.py+++ b/harness/codeverse/workspace.py@@ -15,7 +15,7 @@ import shutilimport subprocessimport threadingimport time-from collections.abc import Sequence+from collections.abc import Iterator, Sequencefrom pathlib import Pathfrom typing import Any@@ -334,13 +334,14 @@ class Workspace:self._cfg_mtime = cfg.stat().st_mtime_ns if cfg.is_file() else 0def _git_init(self) -> None:- if (self.root / ".git").exists():- self._sanitise_git_config() # a resumed run: the agent has had the repo since- return- self._git("init", "-q")- self.ensure_gitignore()- self._git("add", "-A")- self._git("commit", "-q", "-m", "init", "--allow-empty")+ with self._lock: # init + config + first commit are one unit+ if (self.root / ".git").exists():+ self._sanitise_git_config() # a resumed run: the agent has had the repo since+ return+ self._git("init", "-q")+ self.ensure_gitignore()+ self._git("add", "-A")+ self._git("commit", "-q", "-m", "init", "--allow-empty")def ensure_gitignore(self, *, dry_run: bool = False) -> bool:"""Make sure every harness-owned path is ignored by the run's git repo.@@ -357,11 +358,25 @@ class Workspace:return Truedef commit(self, message: str) -> str:- """Commit everything tracked (src/, public/, plan, ...) and return the sha."""- self._sanitise_git_config()- self._git("add", "-A")- self._git("commit", "-q", "-m", message, "--allow-empty")- return self._git("rev-parse", "HEAD").stdout.strip()+ """Commit everything tracked (src/, public/, plan, ...) and return the sha.++ ONE transaction: ``_git`` locks per command, so a sibling thread that committed+ between the commit and the ``rev-parse`` made this return ITS sha — the round+ journal then named a commit this task never made (repro'd 2026-08-27)."""+ with self._lock:+ self._sanitise_git_config()+ self._git("add", "-A")+ self._git("commit", "-q", "-m", message, "--allow-empty")+ return self._git("rev-parse", "HEAD").stdout.strip()++ @contextlib.contextmanager+ def git_transaction(self) -> Iterator[None]:+ """Hold this workspace's git lock across SEVERAL calls (re-entrant).++ For a caller whose unit spans methods — read the diff, then restore from it —+ where a sibling commit in between would make the second act on stale facts."""+ with self._lock:+ yielddef head(self) -> str:return self._git("rev-parse", "HEAD").stdout.strip()@@ -375,40 +390,42 @@ class Workspace:def changed_files(self, since: str | None = None) -> list[FileChange]:"""Files changed vs ``since`` (a commit) or vs HEAD (uncommitted work)."""- self._sanitise_git_config() # `add`/`diff` apply clean + textconv drivers- self._git("add", "-A", "-N") # register untracked so they show up in diff- args = ["diff", "--numstat", "--diff-filter=ADM"] + ([since] if since else ["HEAD"])- out = self._git(*args).stdout- status = {}- for line in self._git("diff", "--name-status", since or "HEAD").stdout.splitlines():- if "\t" in line:- st, path = line.split("\t", 1)- status[path] = {"A": "added", "D": "deleted"}.get(st[0], "modified")- changes = []- for line in out.splitlines():- parts = line.split("\t")- if len(parts) != 3:- continue- add, rem, path = parts- changes.append(FileChange(path=path, status=status.get(path, "modified"),- lines_added=int(add) if add.isdigit() else 0,- lines_removed=int(rem) if rem.isdigit() else 0))- return changes+ with self._lock: # add -N + two diffs are one unit: a sibling commit between them mislabels a status+ self._sanitise_git_config() # `add`/`diff` apply clean + textconv drivers+ self._git("add", "-A", "-N") # register untracked so they show up in diff+ args = ["diff", "--numstat", "--diff-filter=ADM"] + ([since] if since else ["HEAD"])+ out = self._git(*args).stdout+ status = {}+ for line in self._git("diff", "--name-status", since or "HEAD").stdout.splitlines():+ if "\t" in line:+ st, path = line.split("\t", 1)+ status[path] = {"A": "added", "D": "deleted"}.get(st[0], "modified")+ changes = []+ for line in out.splitlines():+ parts = line.split("\t")+ if len(parts) != 3:+ continue+ add, rem, path = parts+ changes.append(FileChange(path=path, status=status.get(path, "modified"),+ lines_added=int(add) if add.isdigit() else 0,+ lines_removed=int(rem) if rem.isdigit() else 0))+ return changesdef restore(self, commit: str) -> None:"""Make src/ + public/ exactly match ``commit`` (artifacts untouched)."""- tracked = self._git("ls-tree", "--name-only", commit).stdout.split()- roots = [r for r in ("src", "public") if r in tracked]- # remove current tracked+untracked content of the roots, then check out the target- self._git("rm", "-r", "-q", "--cached", "--ignore-unmatch", "--", "src", "public")- for r in ("src", "public"):- d = self.root / r- if d.exists():- shutil.rmtree(d)- d.mkdir(parents=True, exist_ok=True)- if roots:- self._git("checkout", "-q", commit, "--", *roots)- self._git("add", "-A")+ with self._lock: # rm + rmtree + checkout + add: a sibling must never see the half-removed tree+ tracked = self._git("ls-tree", "--name-only", commit).stdout.split()+ roots = [r for r in ("src", "public") if r in tracked]+ # remove current tracked+untracked content of the roots, then check out the target+ self._git("rm", "-r", "-q", "--cached", "--ignore-unmatch", "--", "src", "public")+ for r in ("src", "public"):+ d = self.root / r+ if d.exists():+ shutil.rmtree(d)+ d.mkdir(parents=True, exist_ok=True)+ if roots:+ self._git("checkout", "-q", commit, "--", *roots)+ self._git("add", "-A")def restore_paths(self, commit: str, paths: Sequence[str]) -> None:"""Make just ``paths`` match ``commit`` (worktree + index; everything else untouched).diff --git a/harness/tests/orchestrator_tracks/test_resume_reconcile.py b/harness/tests/orchestrator_tracks/test_resume_reconcile.pyindex b43d4fd9..552cf679 100644--- a/harness/tests/orchestrator_tracks/test_resume_reconcile.py+++ b/harness/tests/orchestrator_tracks/test_resume_reconcile.py@@ -1,22 +1,15 @@"""reconcile_resume: on resume, the durable round journal is the truth.-Covers the audited failure modes:--* the crash window between the round-journal write and the state save — a stale- best used to be restored and DELIVERED although a newer PAID round was on disk;-* a planner outage on resume serializing record.json with ``rounds=[]`` (the- flywheel-visible history wipe);-* ``resume --force`` after a spec edit pairing old rounds with the new spec/plan- (fake prompt→code provenance) — the old rounds are archived under- ``rounds/pre_force/`` instead;-* a spec edit WITHOUT ``--force`` → typed :class:`SpecChanged` refusal, before- any model call and without damaging the run;-* judge-failure notes lost to ``_run_round``'s local notes list.+One test per audited failure mode — the two crash windows between a round write and the+state save, a planner outage wiping ``record.rounds``, ``--force``/no-``--force`` after a+spec edit, judge notes lost to a local list, and spend the budget snapshot missed."""from __future__ import annotationsimport json+from functools import partial+from types import SimpleNamespaceimport pytest@@ -42,7 +35,7 @@ def _planner(plan_dict):def _writer(job, ws):- return {"src/model.py": f"import bpy # {job.label} r{job.extra.get('round', 0)}\n"}+ return {"src/model.py": f"import bpy # {job.label} r{job.round}\n"}def _track(planner, settings, *, judge=None, policy=None):@@ -51,17 +44,38 @@ def _track(planner, settings, *, judge=None, policy=None):runtime=FakeRuntime(Language.BLENDER), policy=policy)+def completed_run(tmp_path, chair_plan, settings):+ """A finished StaticObjectTrack run — the starting point of every resume test below.++ ``.rerun(...)`` replays the same track over the same workspace (``resume=``/``force=``)+ with a FRESH planner, so a test that passes its own ``planner=`` sees in ``.requests``+ only what the resume asked for; ``policy=`` / ``spec=`` override the rest.+ """+ plan = chair_plan.model_dump(mode="json")++ def rerun(r, *, planner=None, policy=None, spec=None, **kw):+ return _track(planner or _planner(plan), settings, policy=policy or r.policy).run(+ spec or r.spec, r.ws, **kw)++ def build(max_rounds: int = 1, **spec_kw) -> SimpleNamespace:+ r = SimpleNamespace(plan=plan, ws=Workspace(tmp_path / "runs" / "r"),+ spec=make_spec(language=Language.BLENDER, max_rounds=max_rounds, **spec_kw),+ policy=RoundPolicy(max_rounds=max_rounds, target=0.9))+ r.rerun = partial(rerun, r)+ r.record = r.rerun()+ return r++ return build++# --------------------------------------------------------------------- (a) crash window-def test_crash_between_round_write_and_state_save_delivers_the_newer_round(tmp_path, chair_plan, settings):- """rNN.json + its commit are durable; mark_round_done/update_best used to live only- in memory until _save_budget — with a possible PAID pairwise call in between. A- crash in that window plus an immediate stop on resume restored and delivered a- STALE best although the newer paid round was on disk."""- spec = make_spec(language=Language.BLENDER, max_rounds=1)- ws = Workspace(tmp_path / "runs" / "r")- planner = _planner(chair_plan.model_dump(mode="json"))- pol = RoundPolicy(max_rounds=1, target=0.9)- rec1 = _track(planner, settings, policy=pol).run(spec, ws)+def test_crash_between_round_write_and_state_save_delivers_the_newer_round(completed_run):+ """rNN.json + its commit are durable but mark_round_done/update_best lived only in+ memory until _save_budget — with a possible PAID pairwise call in between. A crash in+ that window plus an immediate stop on resume delivered the STALE best."""+ run = completed_run(max_rounds=1)+ rec1, ws = run.record, run.wsassert rec1.best_round == 1 and len(rec1.rounds) == 2# rewind state.json to what a crash between the r01 write and the state save leavesstate = json.loads(ws.state_path.read_text())@@ -72,7 +86,7 @@ def test_crash_between_round_write_and_state_save_delivers_the_newer_round(tmp_pws.restore(rec1.rounds[0].commit) # ...and the tree at the stale best, as deliveredws.commit("stale delivery")- rec2 = _track(planner, settings, policy=pol).run(spec, ws, resume=True)+ rec2 = run.rerun(resume=True)# the immediate stop (max_rounds) now delivers the NEWER paid roundassert rec2.best_round == 1 and rec2.final_score == pytest.approx(0.7)assert [r.index for r in rec2.rounds] == [0, 1]@@ -84,47 +98,66 @@ def test_crash_between_round_write_and_state_save_delivers_the_newer_round(tmp_passert ev and ev[-1]["state_was_stale"] is True and ev[-1]["best_changed"] is True+def test_a_self_consistent_state_with_an_unranked_round_still_re_ranks(completed_run):+ """The sharper crash shape (reproduced by review, 2026-08-27): the round was saved+ BEFORE best selection, so completed_rounds/round_commits matched the journal exactly+ while best_round still pointed at the older round — nothing looked stale, reconcile+ believed it, and the run DELIVERED r0=0.5 over the paid r1=0.7. ``best_considered_+ through`` makes the repair independent of write ordering."""+ run = completed_run(max_rounds=1)+ rec1, ws = run.record, run.ws+ assert rec1.best_round == 1 and rec1.rounds[1].score == pytest.approx(0.7)++ state = json.loads(ws.state_path.read_text()) # journal-consistent, best stale+ assert state["completed_rounds"] == [0, 1]+ state["best_round"], state["best_commit"], state["best_score"] = 0, rec1.rounds[0].commit, 0.5+ state["best_considered_through"] = 0 # r1 was written but never ranked+ ws.state_path.write_text(json.dumps(state))+ ws.restore(rec1.rounds[0].commit)+ ws.commit("stale delivery")++ rec2 = run.rerun(resume=True)+ assert rec2.best_round == 1 and rec2.final_score == pytest.approx(0.7)+ ev = [e for e in EventLog(ws.events_path).read() if e["event"] == "resume.reconciled"][-1]+ assert ev["state_was_stale"] is False and ev["unranked_rounds"] is True and ev["best_changed"] is True++# --------------------------------------------------------------------- (b) history wipe-def test_a_planner_outage_on_resume_keeps_the_recorded_history(tmp_path, chair_plan, settings):- """The FAILED handler used to serialize record.json with rounds=[] because the- journal was only loaded AFTER plan/prepare — one planner outage on resume wiped- record.rounds (and with it the flywheel's rounds_summary)."""- spec = make_spec(language=Language.BLENDER, max_rounds=0)- ws = Workspace(tmp_path / "runs" / "r")- rec1 = _track(_planner(chair_plan.model_dump(mode="json")), settings,- policy=RoundPolicy(max_rounds=0, target=0.9)).run(spec, ws)- assert len(rec1.rounds) == 1+def test_a_planner_outage_on_resume_keeps_the_recorded_history(completed_run):+ """The FAILED handler serialized record.json with rounds=[] because the journal was+ loaded only AFTER plan/prepare — one planner outage on resume wiped record.rounds+ (and with it the flywheel's rounds_summary)."""+ run = completed_run(max_rounds=0)+ ws = run.ws+ assert len(run.record.rounds) == 1(ws.root / "stages" / "plan.json").unlink() # clobbered cache → the resume re-plansdef _boom(req):raise RuntimeError("planner 503 storm")with pytest.raises(RuntimeError, match="503 storm"):- _track(FakeChatModel(_boom), settings,- policy=RoundPolicy(max_rounds=1, target=0.9)).run(spec, ws, resume=True)+ run.rerun(planner=FakeChatModel(_boom), policy=RoundPolicy(max_rounds=1, target=0.9), resume=True)saved = json.loads(ws.record_path.read_text())assert saved["status"] == "failed" and "503 storm" in saved["error"]assert [r["index"] for r in saved["rounds"]] == [0], "a planner outage must not wipe the history"- assert saved["rounds"][0]["commit"] == rec1.rounds[0].commit+ assert saved["rounds"][0]["commit"] == run.record.rounds[0].commitassert RunState.load(ws).completed_rounds == [0]# --------------------------------------------------------------------- (d) force provenance-def test_force_resume_with_an_edited_prompt_archives_the_old_rounds(tmp_path, chair_plan, settings):- """`resume --force` after a prompt edit used to re-plan and then pair the OLD- rounds with the NEW spec/plan in record.json — fake prompt→code provenance.- The old journal + record are archived under rounds/pre_force/ instead."""- spec = make_spec(language=Language.BLENDER, max_rounds=0)- ws = Workspace(tmp_path / "runs" / "r")- pol = RoundPolicy(max_rounds=0, target=0.9)- rec1 = _track(_planner(chair_plan.model_dump(mode="json")), settings, policy=pol).run(spec, ws)- old_commit = rec1.rounds[0].commit+def test_force_resume_with_an_edited_prompt_archives_the_old_rounds(completed_run):+ """`resume --force` after a prompt edit re-planned and then paired the OLD rounds with+ the NEW spec/plan in record.json — fake prompt→code provenance. The old journal ++ record are archived under rounds/pre_force/ instead."""+ run = completed_run(max_rounds=0)+ ws = run.ws+ old_commit = run.record.rounds[0].commitspec2 = make_spec(language=Language.BLENDER, max_rounds=0,prompt="a completely different bar stool")ws.write_json(ws.spec_path, spec2) # the user edited the prompt- p2 = _planner(chair_plan.model_dump(mode="json"))- rec2 = _track(p2, settings, policy=pol).run(spec2, ws, resume=True, force=True)+ p2 = _planner(run.plan)+ rec2 = run.rerun(planner=p2, spec=spec2, resume=True, force=True)# the old journal + record are ARCHIVED, never paired with the new specassert (ws.root / "rounds" / "pre_force" / "r00.json").is_file()@@ -142,18 +175,16 @@ def test_force_resume_with_an_edited_prompt_archives_the_old_rounds(tmp_path, chassert "resume.spec_changed" in kinds and "resume.reconciled" in kinds-def test_a_spec_edit_without_force_is_refused_before_anything_runs(tmp_path, chair_plan, settings):- spec = make_spec(language=Language.BLENDER, max_rounds=0)- ws = Workspace(tmp_path / "runs" / "r")- pol = RoundPolicy(max_rounds=0, target=0.9)- _track(_planner(chair_plan.model_dump(mode="json")), settings, policy=pol).run(spec, ws)+def test_a_spec_edit_without_force_is_refused_before_anything_runs(completed_run):+ run = completed_run(max_rounds=0)+ ws = run.wsspec2 = make_spec(language=Language.BLENDER, max_rounds=0,prompt="a completely different bar stool")ws.write_json(ws.spec_path, spec2)- p2 = _planner(chair_plan.model_dump(mode="json"))+ p2 = _planner(run.plan)with pytest.raises(SpecChanged, match="--force"):- _track(p2, settings, policy=pol).run(spec2, ws, resume=True)+ run.rerun(planner=p2, spec=spec2, resume=True)# refused cleanly: nothing archived, nothing spent, nothing overwrittenassert p2.requests == [], "no model call before the refusal"assert not (ws.root / "rounds" / "pre_force").exists()@@ -165,15 +196,14 @@ def test_a_spec_edit_without_force_is_refused_before_anything_runs(tmp_path, cha# the sanctioned budget raise (outside the fingerprint) still resumes plainlyspec3 = make_spec(language=Language.BLENDER, max_rounds=0, max_usd=50.0)ws.write_json(ws.spec_path, spec3)- rec3 = _track(_planner(chair_plan.model_dump(mode="json")), settings, policy=pol).run(- spec3, ws, resume=True)+ rec3 = run.rerun(spec=spec3, resume=True)assert [r.index for r in rec3.rounds] == [0]# --------------------------------------------------------------------- (f3) notes survivedef test_notes_survive_a_judge_crash(tmp_path, chair_plan, settings):- """_judge used to append 'judge failed: ...' to rec.notes, which _run_round then- overwrote with its own local notes list — the note never reached rNN.json."""+ """_judge appended 'judge failed: ...' to rec.notes, which _run_round then overwrote+ with its own local notes list — the note never reached rNN.json."""class BoomJudge(FakeJudge):def judge(self, inp):if inp.round_index >= 1:@@ -192,41 +222,10 @@ def test_notes_survive_a_judge_crash(tmp_path, chair_plan, settings):assert "judge failed: RuntimeError: vlm 500" in saved["notes"]-def test_a_self_consistent_state_with_an_unranked_round_still_re_ranks(tmp_path, chair_plan, settings):- """The OTHER crash shape, and the sharper one (reproduced by review, 2026-08-27).-- While the round was saved BEFORE best selection, a crash in between left a state- that looked perfectly consistent — completed_rounds and round_commits matched the- journal exactly — while best_round still pointed at the older, worse round. Nothing- was 'stale', so reconcile kept it and the run DELIVERED r0=0.5 over the paid r1=0.7.- The writer now saves once, after ranking; `best_considered_through` makes the repair- independent of write ordering, so even such a state (an older run dir, a partial- write) is re-ranked rather than believed."""- spec = make_spec(language=Language.BLENDER, max_rounds=1)- ws = Workspace(tmp_path / "runs" / "r")- planner = _planner(chair_plan.model_dump(mode="json"))- pol = RoundPolicy(max_rounds=1, target=0.9)- rec1 = _track(planner, settings, policy=pol).run(spec, ws)- assert rec1.best_round == 1 and rec1.rounds[1].score == pytest.approx(0.7)-- state = json.loads(ws.state_path.read_text()) # journal-consistent, best stale- assert state["completed_rounds"] == [0, 1]- state["best_round"], state["best_commit"], state["best_score"] = 0, rec1.rounds[0].commit, 0.5- state["best_considered_through"] = 0 # r1 was written but never ranked- ws.state_path.write_text(json.dumps(state))- ws.restore(rec1.rounds[0].commit)- ws.commit("stale delivery")-- rec2 = _track(planner, settings, policy=pol).run(spec, ws, resume=True)- assert rec2.best_round == 1 and rec2.final_score == pytest.approx(0.7)- ev = [e for e in EventLog(ws.events_path).read() if e["event"] == "resume.reconciled"][-1]- assert ev["state_was_stale"] is False and ev["unranked_rounds"] is True and ev["best_changed"] is True--def test_resume_charges_for_spend_the_snapshot_missed(tmp_path, chair_plan, settings):- """The ledger is appended per CALL; the snapshot is saved at boundaries. A crash- between a round's spend and its save used to hand the resumed run that money back —- silently under-counting is how a resumed run walks past its ceiling."""+ """The ledger is appended per CALL, the snapshot saved at boundaries: a crash between+ a round's spend and its save handed the resumed run that money back — silently+ under-counting is how a resumed run walks past its ceiling."""from codeverse.cost.ledger import open_run_ledgerfrom codeverse.cost.types import CallCostfrom codeverse.orchestrator.budget import BudgetGuard, BudgetSnapshotdiff --git a/harness/tests/orchestrator_tracks/test_tracks.py b/harness/tests/orchestrator_tracks/test_tracks.pyindex 4b5a10c3..5c1975c0 100644--- a/harness/tests/orchestrator_tracks/test_tracks.py+++ b/harness/tests/orchestrator_tracks/test_tracks.py@@ -42,9 +42,9 @@ def _agent_writer(job, ws):if name:from codeverse.conventions import to_snake- files[f"src/parts/{to_snake(name)}.js"] = f"export function build{name}(THREE) {{ /* {job.label} r{job.extra.get('round', 0)} */ return new THREE.Group(); }}\n"+ files[f"src/parts/{to_snake(name)}.js"] = f"export function build{name}(THREE) {{ /* {job.label} r{job.round} */ return new THREE.Group(); }}\n"# every round edits something (a real refine agent changes code; identical output = plateau)- files["src/object.js"] = f"// {job.label} r{job.extra.get('round', 0)}\nexport function build(THREE) {{ return new THREE.Group(); }}\n"+ files["src/object.js"] = f"// {job.label} r{job.round}\nexport function build(THREE) {{ return new THREE.Group(); }}\n"return files