Official Codebase of 3DCodeVerse
Python
cost: the run binding is a context token, not a process global
gaoypeng9f0f621bc9e9
diff --git a/harness/codeverse/cost/context.py b/harness/codeverse/cost/context.pyindex 03965f77..9bf8f616 100644--- a/harness/codeverse/cost/context.py+++ b/harness/codeverse/cost/context.py@@ -22,16 +22,17 @@ role" for the call that is about to happen. Precedence:A label that names nothing (:data:`~codeverse.cost.types.Stage.OTHER`) statesnothing and never displaces anything.-The **run binding** (:func:`bind_run`, the run slug) is a ``ContextVar`` with a-process-wide fallback: a nested run (a bench worker that opens its own ledger in-its own thread) gets its own binding, while a plain worker thread that inherits-nothing — ``codeverse.proc`` does not copy context — still sees the process's-one run.+The **run binding** (:func:`bound_run`, the run slug) is a plain ``ContextVar``.+A bench worker that opens its own run in its own thread gets its own binding, and a+worker thread inherits its caller's because ``codeverse.proc.fan_out`` copies the+context (bb6179c). There is deliberately no process-wide fallback: restoring one by+value republished a sibling's run the moment the first parallel run exited, and rows+written afterwards landed in that finished run's file (2026-08-30 — the interleave+1756866 deleted the ``_active_ledgers`` global for, left standing on this half)."""from __future__ import annotations-import threadingfrom collections.abc import Callable, Iteratorfrom contextlib import contextmanagerfrom contextvars import ContextVar@@ -75,30 +76,24 @@ _ctx: ContextVar[CallContext] = ContextVar("cv3d_cost_ctx", default=_EMPTY)#: the run this execution context belongs to ("" = nothing bound here)_run_var: ContextVar[str] = ContextVar("cv3d_cost_run", default="")-_binding_lock = threading.Lock()-_run_binding: CallContext = _EMPTY+@contextmanager+def bound_run(run: str) -> Iterator[None]:+ """Name the run every row written inside the block belongs to.-def bind_run(run: str) -> None:- """Name the run every subsequent row belongs to.-- Sets both the context-local binding (so a bench worker that runs its own- prompt in its own thread cannot have its rows stolen by a sibling) and the- process-wide fallback (so a worker thread that inherited no context — the- fan-out pools — still finds the run)."""- global _run_binding- _run_var.set(run or "")- with _binding_lock:- _run_binding = CallContext(run=run)+ Unwinds with the ``ContextVar`` token instead of re-setting the previous value:+ two of these open at once (``bench.run_bench``'s pool) must undo independently+ — see the module docstring."""+ token = _run_var.set(run or "")+ try:+ yield+ finally:+ _run_var.reset(token)def run_binding() -> CallContext:- """The context-local run if this thread bound one, else the process's."""- local = _run_var.get()- if local:- return CallContext(run=local)- with _binding_lock:- return _run_binding+ """The run bound in this execution context (``run=""`` when none is)."""+ return CallContext(run=_run_var.get())def current() -> CallContext:@@ -264,5 +259,5 @@ def attempt_recording(sink: AttemptSink) -> Iterator[None]:__all__ = ["AttemptRecord", "AttemptSink", "CallContext", "attempt_recording", "attempt_sink",- "attribute", "bind_run", "call_context", "context_from_label", "current",+ "attribute", "bound_run", "call_context", "context_from_label", "current","run_binding"]diff --git a/harness/codeverse/cost/instrument.py b/harness/codeverse/cost/instrument.pyindex 4da013cb..c5459c36 100644--- a/harness/codeverse/cost/instrument.py+++ b/harness/codeverse/cost/instrument.py@@ -37,18 +37,17 @@ from codeverse.contracts.common import Usagefrom codeverse.cost.context import (AttemptRecord,attempt_recording,- bind_run,+ bound_run,call_context,run_binding,)from codeverse.cost.ledger import (CostLedger,+ bound_ledger,default_ledger,- default_ledger_path,existing_ledger_path,open_run_ledger,record_call,- set_default_ledger,)from codeverse.cost.types import Role, Stage, stage_for_label@@ -102,12 +101,13 @@ class MeteredChatModel:def generate(self, request: ChatRequest) -> ChatResponse:call_id = uuid4().hex # joins the per-attempt rows to the call's logical row# captured NOW: a hedge loser lands after this call returned, in a thread- # with no context, and its row must still reach THIS run's ledger+ # with no context, so neither the run's ledger nor its name is reachable thereledger = default_ledger()+ run = run_binding().runbooked: list[int] = [] # round-trips that already billed themselves as "extra"def attempt_row(rec: AttemptRecord) -> None:- if self._record_attempt(request, call_id, rec, ledger):+ if self._record_attempt(request, call_id, rec, ledger, run):booked.append(rec.attempt)t0 = time.perf_counter()@@ -146,7 +146,7 @@ class MeteredChatModel:log.debug("cost: could not record %s: %s", request.label, e)def _record_attempt(self, request: ChatRequest, call_id: str, rec: AttemptRecord,- ledger: CostLedger | None) -> bool:+ ledger: CostLedger | None, run: str = "") -> bool:"""One row per round-trip. A round-trip that was DISCARDED and still cost money(a billed-but-invalid reply, a hedge loser that landed) is money nothing elserecords, so it goes in as ``source="extra"`` and counts in every total; the rest@@ -154,7 +154,7 @@ class MeteredChatModel:already carries their tokens. Returns True when it billed an ``extra``."""extra = bool(rec.discarded and rec.usage.cost_usd)try:- record_call(rec.usage, label=request.label,+ record_call(rec.usage, run=run, label=request.label,backend=rec.usage.backend or self.provider,model=rec.usage.model or self.model,outcome="discarded" if rec.discarded else "ok",@@ -262,8 +262,7 @@ def run_ledger(workspace: str | Path, *, run: str = "", create: bool = True) ->"""Meter one run into ``<workspace>/telemetry/cost.jsonl``.Binds the run name and points :func:`~codeverse.cost.ledger.record_call` at the- run's ledger; restores the previous default on the way out so a second run in- the same process is not mixed in.+ run's ledger for the duration of the block.``create=False`` is for work done *after* a run finished (``3dcv judge``,a post-hoc texture pass): it appends only when the run already keeps a@@ -271,32 +270,22 @@ def run_ledger(workspace: str | Path, *, run: str = "", create: bool = True) ->the whole run's cost and hide everything the run really spent. Without onethe rows go to the per-process log instead.- **Nests and parallelises.** The previous ledger and run binding are restored- on the way out rather than cleared, so a bench cell that opens a ledger for- the cell and then a second one for the harness run inside it keeps both; and- both are context-local first (see :func:`codeverse.cost.context.bind_run`), so- ``bench.run_bench`` can run N prompts in N threads without their rows mixing."""+ **Nests and parallelises.** Both bindings unwind by ``ContextVar`` token, so a+ bench cell that opens a ledger for the cell and then a second one for the+ harness run inside it keeps both, and ``bench.run_bench`` can run N prompts in+ N threads without their rows mixing — a save-and-restore by value could not,+ because a fresh worker saved whatever a sibling had published last."""if not metering_enabled():yield Nonereturnws = Path(workspace)- prev_run = run_binding().run- prev_path = default_ledger_path()if not create and existing_ledger_path(ws) is None:- bind_run(run or ws.name)- try:+ with bound_run(run or ws.name):yield None- finally:- bind_run(prev_run)returnledger = open_run_ledger(ws)- set_default_ledger(ledger.path)- bind_run(run or ws.name)- try:+ with bound_run(run or ws.name), bound_ledger(ledger.path):yield ledger- finally:- set_default_ledger(prev_path)- bind_run(prev_run)__all__ = ["MeteredAgent", "MeteredChatModel", "metered_agent", "metered_chat_model",diff --git a/harness/codeverse/cost/ledger.py b/harness/codeverse/cost/ledger.pyindex 21b39b67..1fd9f75f 100644--- a/harness/codeverse/cost/ledger.py+++ b/harness/codeverse/cost/ledger.py@@ -19,7 +19,8 @@ import loggingimport osimport threadingimport time-from collections.abc import Iterable, Sequence+from collections.abc import Iterable, Iterator, Sequence+from contextlib import contextmanagerfrom contextvars import ContextVarfrom pathlib import Pathfrom typing import Any@@ -49,10 +50,10 @@ log = logging.getLogger(__name__)TELEMETRY_DIR = "telemetry"TELEMETRY_LEDGER = f"{TELEMETRY_DIR}/cost.jsonl"-#: legacy/alias name at the run root. ``flywheel.telemetry.live_ledger_path`` looks-#: here for "does this run have a live ledger", and runs recorded before the-#: telemetry bucket existed have the real file here — so it stays readable, and-#: :func:`open_run_ledger` leaves a symlink pointing at the telemetry copy.+#: alias name at the run root: a relative symlink :func:`open_run_ledger` leaves+#: pointing at the telemetry copy, so ``flywheel.telemetry.live_ledger_path`` and+#: anything that learned this path before the telemetry bucket existed still reads+#: the one physical file.LEDGER_NAME = "cost_ledger.jsonl"#: env var that points ``record_call`` at a ledger when no path is passed@@ -94,50 +95,36 @@ class CostLedger:return summarise(self.read(), **kw)-_default_lock = threading.Lock()-_default: CostLedger | None = None+_fallback_lock = threading.Lock()_fallback: CostLedger | None = None_fallback_read = False#: sentinel: "this execution context did not state a ledger"_UNSET: Any = object()-#: context-local override of the default ledger. Mirrors-#: ``codeverse.cost.context.bind_run``: a bench worker running its own prompt in-#: its own thread must not have its rows land in a sibling run's file, while a-#: plain worker thread that inherited no context still finds the process's ledger.+#: context-local override of the default ledger. Context-local ONLY, like+#: ``codeverse.cost.context._run_var``: a bench worker running its own prompt in its+#: own thread must not have its rows land in a sibling run's file, and a process-wide+#: copy of it could not unwind correctly when two runs overlap (2026-08-30)._default_var: ContextVar[Any] = ContextVar("cv3d_cost_default_ledger", default=_UNSET)-def set_default_ledger(path: str | Path | None) -> CostLedger | None:- """Point the module-level :func:`record_call` at ``path``.+@contextmanager+def bound_ledger(path: str | Path) -> Iterator[CostLedger]:+ """Point :func:`record_call` at ``path`` for the duration of the block.- ``None`` clears the override (back to ``$CV3D_COST_LEDGER`` / the per-process- log). Sets both the context-local override and the process-wide one, so a- nested or parallel run is attributed correctly and an uninstrumented worker- thread still writes somewhere sensible."""- global _default, _fallback_read- led = CostLedger(path) if path is not None else None- _default_var.set(led if led is not None else _UNSET)- with _default_lock:- _default = led- if led is None:- _fallback_read = False # re-read $CV3D_COST_LEDGER next time- return led---def default_ledger_path() -> Path | None:- """The path :func:`set_default_ledger` last set here (``None`` = no override).- Used to save/restore around a nested :func:`~codeverse.cost.instrument.run_ledger`."""- led = _default_var.get()- if led is not _UNSET:- return led.path if led is not None else None- with _default_lock:- return _default.path if _default is not None else None+ Unwinds with the ``ContextVar`` token, so nested and parallel blocks each undo+ exactly their own binding."""+ led = CostLedger(path)+ token = _default_var.set(led)+ try:+ yield led+ finally:+ _default_var.reset(token)def default_ledger() -> CostLedger | None:"""The ledger :func:`record_call` writes to when no ``ledger=`` is given:- whatever :func:`set_default_ledger` set, else ``$CV3D_COST_LEDGER``, else the+ whatever :func:`bound_ledger` bound here, else ``$CV3D_COST_LEDGER``, else theper-process fallback log (:func:`process_ledger_path`) so a call made outsideany run — ``3dcv judge``, a bench script, a notebook — is still accounted for.``CV3D_COST_LEDGER=off`` turns writing off entirely."""@@ -145,9 +132,7 @@ def default_ledger() -> CostLedger | None:led = _default_var.get()if led is not _UNSET:return led- with _default_lock:- if _default is not None:- return _default+ with _fallback_lock:if _fallback_read:return _fallbackenv = os.environ.get(LEDGER_ENV, "").strip()@@ -171,14 +156,13 @@ def process_ledger_path() -> Path:def existing_ledger_path(workspace: str | Path) -> Path | None:- """The ledger file a run actually has — the telemetry one, else the legacy- root file — or ``None``."""- root = Path(workspace)- for name in (TELEMETRY_LEDGER, LEDGER_NAME):- p = root / name- if p.is_file():- return p- return None+ """The ledger file a run actually has, or ``None``.++ Only ``telemetry/cost.jsonl``: the root :data:`LEDGER_NAME` is the symlink+ :func:`open_run_ledger` leaves pointing at it, and a walk of every run under+ ``$HOME`` on 2026-08-30 found 677 such symlinks and not one real file there."""+ p = Path(workspace) / TELEMETRY_LEDGER+ return p if p.is_file() else Nonedef open_run_ledger(workspace: str | Path) -> CostLedger:@@ -335,9 +319,9 @@ def record_call(def load_ledger(path: str | Path, *, include_attempts: bool = False) -> list[CallCost]:- """Read a ledger file (or a run directory containing one: ``telemetry/cost.jsonl``- first, then the legacy root ``cost_ledger.jsonl``). Bad lines are skipped with a- debug log — a truncated last line never loses the rest of the file.+ """Read a ledger file, or a run directory holding one (``telemetry/cost.jsonl``).+ Bad lines are skipped with a debug log — a truncated last line never loses the+ rest of the file.``source="attempt"`` rows (one per round-trip, ``instrument.MeteredChatModel``)are left out unless ``include_attempts=True``: their tokens are already on thediff --git a/harness/codeverse/cost/types.py b/harness/codeverse/cost/types.pyindex 955fbcd9..574c2484 100644--- a/harness/codeverse/cost/types.py+++ b/harness/codeverse/cost/types.py@@ -20,9 +20,10 @@ class Stage(StrEnum):of ``events.jsonl`` (``stage.start``/``generate.done`` labels)."""PLAN = "plan"- #: SKELETON / ASSEMBLE / GATES / RENDER are *deterministic harness work* (no- #: model call at all); kept in the enum so latency can be attributed to them- #: from events (``report.STAGE_ORDER``, ``audit.stage_latency``).+ #: SKELETON / GATES / RENDER are *deterministic harness work* (no model call at+ #: all); kept in the enum so latency can be attributed to them from events+ #: (``report.STAGE_ORDER``, ``audit.stage_latency``). ASSEMBLE is NOT one of+ #: them — the scene track's ``compose`` task is an agent session that bills.SKELETON = "skeleton"ASSETS = "assets"ENV = "env"@@ -73,6 +74,10 @@ _LABEL_STAGES: tuple[tuple[str, Stage], ...] = (("env", Stage.ENV),("baseline", Stage.BASELINE),("refine", Stage.REFINE),+ # the static track's surface-detail round (labels "detail" / "detail_<scope>",+ # lifecycle.DEFAULT_DETAIL_ROUNDS=1 so it runs by default) is a refine pass under+ # another name; without this its ledger row AND generation.task_stage said "other"+ ("detail", Stage.REFINE),("candidate", Stage.CANDIDATE),("cand", Stage.CANDIDATE),("plan", Stage.PLAN),@@ -107,8 +112,8 @@ def role_for_stage(stage: Stage) -> Role:return Role.JUDGEif stage is Stage.CAPTION:return Role.CAPTIONER- if stage in (Stage.ASSETS, Stage.ENV, Stage.ZONES, Stage.BASELINE, Stage.REFINE,- Stage.REPAIR, Stage.CANDIDATE):+ if stage in (Stage.ASSETS, Stage.ENV, Stage.ZONES, Stage.ASSEMBLE, Stage.BASELINE,+ Stage.REFINE, Stage.REPAIR, Stage.CANDIDATE):return Role.GENERATORreturn Role.OTHERdiff --git a/harness/codeverse/texturing/generate.py b/harness/codeverse/texturing/generate.pyindex 12860ca1..7fd01536 100644--- a/harness/codeverse/texturing/generate.py+++ b/harness/codeverse/texturing/generate.py@@ -14,10 +14,8 @@ from __future__ import annotationsimport hashlibimport loggingimport shutil-import threadingimport timefrom collections.abc import Callable, Sequence-from concurrent.futures import ThreadPoolExecutorfrom pathlib import Pathfrom typing import Any@@ -33,6 +31,7 @@ from codeverse.contracts.spec import Specfrom codeverse.conventions import OBJECT_VIEWS_QUICK, ViewPresetfrom codeverse.judges.base import JudgeInput, plan_digestfrom codeverse.judges.rubrics import is_degraded+from codeverse.proc import fan_out#: seam score above which a texture is considered NOT tileable (after make_tileable)SEAM_MAX = 0.08@@ -157,58 +156,6 @@ def prompt_key(prompt: str, model_id: str, size: int) -> str:return hashlib.sha256(f"v{CACHE_VERSION}|{model_id}|{size}|{prompt.strip()}".encode()).hexdigest()[:24]-# --------------------------------------------------------------------------- fake model-class FakeImageModel:- """Deterministic procedural textures (seeded by the prompt) for offline tests.- Records every prompt it was asked for in ``calls``."""-- provider = "fake"-- def __init__(self, model: str = "fake-image", *, latency_s: float = 0.0, fail_on: Sequence[str] = (),- usd_per_image: float = 0.001) -> None:- self.model = model- self.latency_s = latency_s- self.fail_on = tuple(fail_on)- self.usd_per_image = usd_per_image- self.calls: list[str] = []- self._lock = threading.Lock()-- @property- def id(self) -> str:- return f"fake-image:{self.model}"-- def generate_with_usage(self, prompt: str, *, size: int = 1024, n: int = 1, seed: int | None = None,- reference_images: Sequence[Any] = ()) -> tuple[list[Image.Image], Usage]:- with self._lock:- self.calls.append(prompt)- if any(s in prompt for s in self.fail_on):- from codeverse.models.base import ModelError-- raise ModelError(f"fake image model refused: {prompt[:40]}", retryable=False)- if self.latency_s:- time.sleep(self.latency_s)- images = [procedural_texture(prompt, size=size, seed=(seed or 0) + i) for i in range(n)]- usage = Usage(backend="fake-image", model=self.model, input_tokens=len(prompt.split()), output_tokens=1290 * n,- cost_usd=self.usd_per_image * n, latency_ms=int(self.latency_s * 1000))- return images, usage---def procedural_texture(prompt: str, *, size: int = 256, seed: int = 0) -> Image.Image:- """Prompt-seeded noise + stripes in a prompt-derived colour. NOT tileable on- purpose (so tests exercise ``make_tileable``): a linear gradient is added."""- h = int(hashlib.sha256(prompt.encode()).hexdigest()[:8], 16)- rng = np.random.default_rng(h + seed)- base = np.array([(h >> 16) & 255, (h >> 8) & 255, h & 255], dtype=np.float32) / 255.0- base = 0.25 + 0.6 * base- y, x = np.mgrid[0:size, 0:size].astype(np.float32) / size- stripes = 0.08 * np.sin(2 * np.pi * (8 * x + 3 * np.sin(2 * np.pi * y)))- noise = 0.06 * rng.standard_normal((size, size)).astype(np.float32)- grad = 0.25 * x # seam-breaking gradient- lum = (stripes + noise + grad)[:, :, None]- img = np.clip(base[None, None, :] + lum, 0.0, 1.0)- return Image.fromarray((img * 255).astype(np.uint8), "RGB")--# --------------------------------------------------------------------------- generationdef _cache_dir(cache_dir: Path | None) -> Path:d = (cache_dir or get_settings().cache_dir) / "textures"@@ -296,8 +243,12 @@ def generate_textures(size=size, error=f"{type(e).__name__}: {e}")ids = list(leaders.values())- with ThreadPoolExecutor(max_workers=max(1, min(max_workers, len(ids)))) as pool:- assets = list(pool.map(_job, ids))+ # fan_out, not a bare pool: its workers inherit the caller's context, so the image+ # model's spend is billed to the run's ledger instead of the per-process log+ # (codeverse.cost.context). ``_job`` swallows its own failures, so nothing here+ # comes back as an Exception.+ assets = [a for a in fan_out(ids, _job, max_workers=max_workers, label="texture", item_name=str)+ if isinstance(a, TextureAsset)]for a in assets:result.textures[a.texture_id] = aresult.usage = result.usage + a.usagediff --git a/harness/tests/cost/test_context.py b/harness/tests/cost/test_context.pyindex c3ff6535..c5d0e769 100644--- a/harness/tests/cost/test_context.py+++ b/harness/tests/cost/test_context.py@@ -5,7 +5,7 @@ from __future__ import annotationsfrom codeverse.cost.context import (CallContext,attribute,- bind_run,+ bound_run,call_context,context_from_label,current,@@ -58,8 +58,7 @@ def test_a_call_that_names_its_own_job_beats_the_session_it_runs_inside():def test_nested_contexts_merge_and_unwind():- try:- bind_run("run-a")+ with bound_run("run-a"):assert current().run == "run-a"with call_context(stage=Stage.BASELINE, round=0):with call_context(label="inner"):@@ -67,10 +66,41 @@ def test_nested_contexts_merge_and_unwind():assert inner.stage is Stage.BASELINE and inner.round == 0 and inner.label == "inner"assert current().label == ""assert current().stage is None and current().run == "run-a"- finally:- bind_run("")+ assert current().run == ""+++def test_a_run_bound_in_a_thread_is_never_published_to_the_others():+ """The 2026-08-30 leak: the binding also lived in a process global, so once the+ first parallel run exited it republished ITS name for every later caller."""+ import threading++ ready, seen = threading.Barrier(3), {}++ def one(name: str) -> None:+ with bound_run(name):+ ready.wait(timeout=5)+ seen[name] = current().run++ threads = [threading.Thread(target=one, args=(n,)) for n in ("a", "b")]+ for t in threads:+ t.start()+ ready.wait(timeout=5)+ for t in threads:+ t.join(timeout=5)+ assert seen == {"a": "a", "b": "b"}+ assert current().run == "" # ...and the main thread never inherited either of themdef test_role_is_derived_from_stage_when_unstated():assert attribute(CallContext(stage=Stage.ZONES)).role is Role.GENERATORassert attribute(CallContext(stage=Stage.PAIRWISE)).role is Role.JUDGE+ # the scene track's compose task is an agent session, not deterministic assembly+ assert attribute(CallContext(stage=Stage.ASSEMBLE)).role is Role.GENERATOR+++def test_the_static_track_detail_round_is_a_refine_pass():+ """``DEFAULT_DETAIL_ROUNDS=1``, so every static run bills one of these; until+ 2026-08-30 no prefix matched and the whole round landed under ``other``."""+ for label in ("detail", "detail_seat_edge"):+ got = attribute(label=label)+ assert got.stage is Stage.REFINE and got.role is Role.GENERATOR, labeldiff --git a/harness/tests/cost/test_instrument.py b/harness/tests/cost/test_instrument.pyindex f751f27f..2802bc67 100644--- a/harness/tests/cost/test_instrument.py+++ b/harness/tests/cost/test_instrument.py@@ -9,12 +9,13 @@ import pytestfrom codeverse.contracts.agent import AgentJob, AgentResultfrom codeverse.contracts.chat import ChatMessage, ChatRequest, ChatResponsefrom codeverse.contracts.common import Usage+from codeverse.cost.context import run_bindingfrom codeverse.cost.instrument import (MeteredAgent,MeteredChatModel,run_ledger,)-from codeverse.cost.ledger import load_ledger+from codeverse.cost.ledger import load_ledger, record_callfrom codeverse.cost.types import Role, Stage@@ -223,15 +224,16 @@ def test_a_cli_session_is_recorded_even_when_a_tool_bills_a_model_inside_it(tmp_def test_an_in_process_session_is_never_counted_twice_even_from_another_thread(tmp_path: Path):"""Worker-thread rows from a self-metered agent are not double counted."""- import threading+ from codeverse.proc import fan_outclass ThreadedAgent(FakeAgent):def run(self, job: AgentJob) -> AgentResult:- out: list[AgentResult] = []- t = threading.Thread(target=lambda: out.append(FakeAgent.run(self, job)))- t.start()- t.join()- return out[0]+ # fan_out, not a bare Thread: it is the one helper that copies the caller's+ # context, and since 2026-08-30 nothing else can find the run's ledger from+ # a worker thread (the process-global fallback leaked between parallel runs)+ (out,) = fan_out([job], lambda j: FakeAgent.run(self, j), label="agent")+ assert isinstance(out, AgentResult)+ return outwith run_ledger(tmp_path, run="r1"):MeteredAgent(ThreadedAgent(MeteredChatModel(FakeChat()))).run(@@ -267,10 +269,13 @@ def test_run_ledgers_nest_and_restore_the_outer_one(tmp_path: Path):assert {r.run for r in load_ledger(outer)} == {"cell"}-def test_parallel_runs_in_their_own_threads_keep_their_own_ledgers(tmp_path: Path):+def test_parallel_runs_in_their_own_threads_keep_their_own_ledgers(tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch):"""`bench.run_bench` runs N prompts in N threads; their rows must not mix."""from concurrent.futures import ThreadPoolExecutor+ from codeverse.cost import ledger as ledger_mod+def one(name: str) -> None:with run_ledger(tmp_path / name, run=name):for _ in range(3):@@ -283,6 +288,18 @@ def test_parallel_runs_in_their_own_threads_keep_their_own_ledgers(tmp_path: Patfor name in names:rows = load_ledger(tmp_path / name)assert len(rows) == 3 and {r.run for r in rows} == {name}+ # ...and neither binding leaked out of its worker. Until 2026-08-30 the run name+ # and the default ledger were ALSO process globals that the first thread to exit+ # republished, so this plain main-thread call appended to a finished run's file+ # under that run's name instead of going to the per-process log.+ monkeypatch.setenv("CV3D_COST_LEDGER", str(tmp_path / "process.jsonl"))+ monkeypatch.setattr(ledger_mod, "_fallback", None)+ monkeypatch.setattr(ledger_mod, "_fallback_read", False)+ assert run_binding().run == ""+ record_call(Usage(cost_usd=0.5), label="baseline")+ assert [r.run for r in load_ledger(tmp_path / "process.jsonl")] == [""]+ for name in names:+ assert len(load_ledger(tmp_path / name)) == 3# ------------------------------------------------------- key + attempts on the row (audit 2026-08-26 §4)diff --git a/harness/tests/cost/test_ledger.py b/harness/tests/cost/test_ledger.pyindex d14c7a10..962eb6e7 100644--- a/harness/tests/cost/test_ledger.py+++ b/harness/tests/cost/test_ledger.py@@ -6,7 +6,7 @@ from pathlib import Pathfrom codeverse.contracts.common import Usagefrom codeverse.cost import CostLedger, load_ledger, record_call, summarise-from codeverse.cost.ledger import set_default_ledger+from codeverse.cost.ledger import bound_ledger, existing_ledger_path, open_run_ledgerfrom codeverse.cost.types import Role, Stage@@ -78,10 +78,22 @@ def test_summarise_dimensions(tmp_path: Path):assert s.total.usd_per_1k_tokens > 0-def test_default_ledger_env_and_setter(tmp_path: Path):- try:- set_default_ledger(tmp_path / "default.jsonl")+def test_a_bound_ledger_takes_the_calls_that_name_no_file(tmp_path: Path):+ with bound_ledger(tmp_path / "default.jsonl"):record_call(_usage(), run="r", stage="plan")- assert len(load_ledger(tmp_path / "default.jsonl")) == 1- finally:- set_default_ledger(None)+ assert len(load_ledger(tmp_path / "default.jsonl")) == 1+ record_call(_usage(), run="r", stage="plan", ledger=tmp_path / "after.jsonl")+ assert len(load_ledger(tmp_path / "default.jsonl")) == 1 # the binding is gone with the block+++def test_a_run_has_exactly_one_ledger_file_and_the_root_name_is_its_symlink(tmp_path: Path):+ """``open_run_ledger`` writes only ``telemetry/cost.jsonl``; the root+ ``cost_ledger.jsonl`` others still open by name is a symlink to it, so the reader+ must not treat that name as a second, separate ledger."""+ led = open_run_ledger(tmp_path)+ assert existing_ledger_path(tmp_path) is None # nothing written yet+ record_call(_usage(), run="r", stage="baseline", ledger=led)+ assert existing_ledger_path(tmp_path) == tmp_path / "telemetry" / "cost.jsonl"+ alias = tmp_path / "cost_ledger.jsonl"+ assert alias.is_symlink() and len(load_ledger(alias)) == 1+ assert len(load_ledger(tmp_path)) == 1 # the directory reads the one file, not twodiff --git a/harness/tests/texturing/conftest.py b/harness/tests/texturing/conftest.pyindex e519384b..d3bbadd7 100644--- a/harness/tests/texturing/conftest.py+++ b/harness/tests/texturing/conftest.py@@ -3,7 +3,11 @@ its plan + spec, a fake image model, a fake render function and a fake judge."""from __future__ import annotations+import hashlibimport json+import threading+import time+from collections.abc import Sequencefrom pathlib import Pathfrom typing import Any@@ -134,3 +138,59 @@ class FakePlanModel:self.calls.append(req)return ChatResponse(text=json.dumps(self.payload), parsed=self.payload,usage=Usage(cost_usd=0.002, input_tokens=100))+++# --------------------------------------------------------------------------- fake image model+class FakeImageModel:+ """Deterministic procedural textures (seeded by the prompt) for offline tests.+ Records every prompt it was asked for in ``calls``.++ Lived in ``codeverse.texturing.generate`` until 2026-08-30, where nothing in a+ real run could reach it: no setting, env var or CLI flag selects it, and the+ keyless path raises ``ModelError`` rather than falling back to a fake."""++ provider = "fake"++ def __init__(self, model: str = "fake-image", *, latency_s: float = 0.0, fail_on: Sequence[str] = (),+ usd_per_image: float = 0.001) -> None:+ self.model = model+ self.latency_s = latency_s+ self.fail_on = tuple(fail_on)+ self.usd_per_image = usd_per_image+ self.calls: list[str] = []+ self._lock = threading.Lock()++ @property+ def id(self) -> str:+ return f"fake-image:{self.model}"++ def generate_with_usage(self, prompt: str, *, size: int = 1024, n: int = 1, seed: int | None = None,+ reference_images: Sequence[Any] = ()) -> tuple[list[Image.Image], Usage]:+ with self._lock:+ self.calls.append(prompt)+ if any(s in prompt for s in self.fail_on):+ from codeverse.models.base import ModelError++ raise ModelError(f"fake image model refused: {prompt[:40]}", retryable=False)+ if self.latency_s:+ time.sleep(self.latency_s)+ images = [procedural_texture(prompt, size=size, seed=(seed or 0) + i) for i in range(n)]+ usage = Usage(backend="fake-image", model=self.model, input_tokens=len(prompt.split()), output_tokens=1290 * n,+ cost_usd=self.usd_per_image * n, latency_ms=int(self.latency_s * 1000))+ return images, usage+++def procedural_texture(prompt: str, *, size: int = 256, seed: int = 0) -> Image.Image:+ """Prompt-seeded noise + stripes in a prompt-derived colour. NOT tileable on+ purpose (so tests exercise ``make_tileable``): a linear gradient is added."""+ h = int(hashlib.sha256(prompt.encode()).hexdigest()[:8], 16)+ rng = np.random.default_rng(h + seed)+ base = np.array([(h >> 16) & 255, (h >> 8) & 255, h & 255], dtype=np.float32) / 255.0+ base = 0.25 + 0.6 * base+ y, x = np.mgrid[0:size, 0:size].astype(np.float32) / size+ stripes = 0.08 * np.sin(2 * np.pi * (8 * x + 3 * np.sin(2 * np.pi * y)))+ noise = 0.06 * rng.standard_normal((size, size)).astype(np.float32)+ grad = 0.25 * x # seam-breaking gradient+ lum = (stripes + noise + grad)[:, :, None]+ img = np.clip(base[None, None, :] + lum, 0.0, 1.0)+ return Image.fromarray((img * 255).astype(np.uint8), "RGB")diff --git a/harness/tests/texturing/test_apply.py b/harness/tests/texturing/test_apply.pyindex ca0b1ef0..926dddb2 100644--- a/harness/tests/texturing/test_apply.py+++ b/harness/tests/texturing/test_apply.py@@ -9,8 +9,9 @@ import trimeshfrom codeverse.spatial.measure import measure_glbfrom codeverse.texturing.apply import apply_textures, node_part_lookup-from codeverse.texturing.generate import FakeImageModel, generate_textures+from codeverse.texturing.generate import generate_texturesfrom codeverse.texturing.plan import default_plan+from tests.texturing.conftest import FakeImageModeldef test_node_part_lookup_instances_and_links(chair_plan):diff --git a/harness/tests/texturing/test_generate.py b/harness/tests/texturing/test_generate.pyindex 7671efd9..e1d23888 100644--- a/harness/tests/texturing/test_generate.py+++ b/harness/tests/texturing/test_generate.py@@ -6,7 +6,8 @@ from pathlib import Pathfrom PIL import Image-from codeverse.texturing.generate import SEAM_MAX, FakeImageModel, generate_textures, prompt_key+from codeverse.texturing.generate import SEAM_MAX, generate_textures, prompt_key+from tests.texturing.conftest import FakeImageModeldef test_generate_dedupes_caches_and_accounts(tmp_path: Path):diff --git a/harness/tests/texturing/test_run.py b/harness/tests/texturing/test_run.pyindex f0058dcc..25edc0eb 100644--- a/harness/tests/texturing/test_run.py+++ b/harness/tests/texturing/test_run.py@@ -7,7 +7,6 @@ import shutilfrom pathlib import Pathfrom codeverse.contracts.run import RunRecord-from codeverse.texturing.generate import FakeImageModelfrom codeverse.texturing.run import (TextureReport,TextureServices,@@ -16,7 +15,7 @@ from codeverse.texturing.run import (texture_pass,)from codeverse.workspace import Workspace-from tests.texturing.conftest import FakeJudge, fake_render+from tests.texturing.conftest import FakeImageModel, FakeJudge, fake_renderdef _ws(tmp_path: Path, chair_glb: Path, chair_spec, chair_plan) -> Workspace:diff --git a/harness/tests/texturing/test_scene_pack.py b/harness/tests/texturing/test_scene_pack.pyindex 4d400e54..011c3d82 100644--- a/harness/tests/texturing/test_scene_pack.py+++ b/harness/tests/texturing/test_scene_pack.py@@ -8,7 +8,6 @@ from pathlib import Pathimport pytestfrom codeverse.contracts.plan import AssetPlan, BBox, CameraPlan, ScenePlan, ZonePlan-from codeverse.texturing.generate import FakeImageModelfrom codeverse.texturing.plan import (default_scene_pack_plan,load_manifest,@@ -16,6 +15,7 @@ from codeverse.texturing.plan import (scene_texture_pack,texture_pack_prompt,)+from tests.texturing.conftest import FakeImageModelfrom tests.texturing.test_plan import _FakeChatdiff --git a/harness/tests/texturing/test_tile.py b/harness/tests/texturing/test_tile.pyindex ee9ed570..dbb9e92e 100644--- a/harness/tests/texturing/test_tile.py+++ b/harness/tests/texturing/test_tile.py@@ -9,10 +9,10 @@ from codeverse.texturing.generate import (SEAM_MAX,fit_size,make_tileable,- procedural_texture,save_texture,seam_score,)+from tests.texturing.conftest import procedural_texturedef _tileable(size: int = 64) -> Image.Image:diff --git a/harness/tests/texturing/test_tools_cli.py b/harness/tests/texturing/test_tools_cli.pyindex 517f6234..b3930b44 100644--- a/harness/tests/texturing/test_tools_cli.py+++ b/harness/tests/texturing/test_tools_cli.py@@ -8,10 +8,9 @@ from pathlib import Pathfrom typer.testing import CliRunnerfrom codeverse.spatial.registry import ToolContext, get_tool-from codeverse.texturing.generate import FakeImageModelfrom codeverse.texturing.run import TextureServicesfrom codeverse.workspace import Workspace-from tests.texturing.conftest import FakeJudge, FakePlanModel, fake_render+from tests.texturing.conftest import FakeImageModel, FakeJudge, FakePlanModel, fake_renderdef _ws(tmp_path: Path, chair_glb, chair_spec, chair_plan, *, texture: bool = True) -> Workspace: