Skip to content

Official Codebase of 3DCodeVerse

Python

codex: a session killed before its turn completed books an estimate (source="estimate"), never $0

gaoypeng1e9fb973edfe
diff --git a/harness/codeverse3d/agents/backends.py b/harness/codeverse3d/agents/backends.py
index b1fd2d99..b15eb4f9 100644
--- a/harness/codeverse3d/agents/backends.py
+++ b/harness/codeverse3d/agents/backends.py
@@ -814,6 +814,20 @@ def effort_overrides(effort: str) -> list[str]:
return ["-c", f"model_reasoning_effort={effort}"] if effort else []
+#: A session killed before its turn completed books no usage (codex reports it per TURN and
+#: ``--ephemeral`` leaves no rollout), so its cost is ESTIMATED from what the stream shows: every
+#: completed item is one more request that re-reads the context, which grows by that item.
+#: Constants fitted on the 356 completed codex sessions on record (2026-09-23): codex's own
+#: system prompt + tool schemas ≈ 20k tokens, ≈ 1k tokens per returned image, 4 chars/token,
+#: output ≈ 1.13 % of input. Estimated input / actual: median 1.01, p10–p90 0.66–1.35;
+#: estimated $ / actual $: median 0.93, p10–p90 0.62–1.34.
+_EST_SYSTEM_TOKENS = 20_000
+_EST_IMAGE_TOKENS = 1_000
+_EST_CHARS_PER_TOKEN = 4.0
+_EST_OUTPUT_SHARE = 0.0113
+_B64_DATA = re.compile(r'"data"\s*:\s*"[A-Za-z0-9+/=]{200,}"')
+
+
class CodexEvents:
"""Folded view over the JSONL event stream."""
@@ -827,6 +841,8 @@ class CodexEvents:
self.thread_id = ""
self.n_events = 0
self.calls: list[ToolCall] = []
+ #: (text tokens, images) each completed item added to the context — the estimate's input
+ self.items: list[tuple[float, int]] = []
def feed(self, line: str) -> None:
line = line.strip()
@@ -843,6 +859,9 @@ class CodexEvents:
elif t == "item.completed":
item = ev.get("item") or {}
it = item.get("type", "")
+ if it != "reasoning":
+ images = len(_B64_DATA.findall(line))
+ self.items.append((len(_B64_DATA.sub('"data":""', line)) / _EST_CHARS_PER_TOKEN, images))
if it == "agent_message":
self.messages.append(str(item.get("text", "")))
elif it in _TOOL_ITEMS:
@@ -865,6 +884,20 @@ class CodexEvents:
completion=r["output_tokens"], reasoning=r["reasoning_output_tokens"],
tool_calls=self.tool_calls)
+ def estimated_usage(self, model: str, prompt_chars: int) -> Usage:
+ """What a session whose turn never completed most likely spent (see ``_EST_*``):
+ one request per completed item plus the one in flight, each reading the whole context
+ so far; everything but each request's new content is a cache hit."""
+ ctx = prompt_chars / _EST_CHARS_PER_TOKEN + _EST_SYSTEM_TOKENS
+ prompt = uncached = ctx
+ for text, images in self.items:
+ grown = text + images * _EST_IMAGE_TOKENS
+ ctx += grown
+ uncached += grown
+ prompt += ctx
+ return openai_usage("codex", model, prompt=int(prompt), cached=int(prompt - uncached),
+ completion=int(prompt * _EST_OUTPUT_SHARE), reasoning=0, tool_calls=self.tool_calls)
+
def parse_codex_jsonl(stdout: str) -> CodexEvents:
ev = CodexEvents()
@@ -899,9 +932,9 @@ class CodexAgent(_CliAgent):
return hardened_env(s.ws, s.job, keep={"OPENAI_API_KEY", "CODEX_API_KEY"})
def run(self, job: AgentJob) -> AgentResult:
- """``usage`` arrives per TURN (``turn.completed``): a session killed mid-turn books
- nothing, and ``--ephemeral`` leaves no rollout to recover it from — 1 of 357 recorded
- codex sessions. ``provider_wait_s`` stays 0.0: codex retries a 5xx inside its HTTP
+ """``usage`` arrives per TURN (``turn.completed``), and ``--ephemeral`` leaves no rollout,
+ so a session killed mid-turn (1 of 357 recorded codex sessions) books an ESTIMATE from its
+ stream (:meth:`CodexEvents.estimated_usage`, ``usage_estimated``). ``provider_wait_s`` stays 0.0: codex retries a 5xx inside its HTTP
client without an event (two fake 503s, 2026-09-22: nothing on the stream)."""
ok, why = self.available()
s = begin_session(job, self.kind)
@@ -909,10 +942,14 @@ class CodexAgent(_CliAgent):
if not ok:
return failed(s, "error", why)
events = CodexEvents()
- proc = invoke(s, self.build_argv(s), self.build_env(s), prompt=_compose_prompt(job),
+ prompt = _compose_prompt(job)
+ proc = invoke(s, self.build_argv(s), self.build_env(s), prompt=prompt,
stdout_name="stdout.jsonl", on_stdout=events.feed)
record_tool_calls(s, events.calls, source="codex exec --json")
- usage = events.usage(self.model)
+ # no turn completed but requests were made (items, or a watchdog kill): an estimate,
+ # flagged on the result and booked as source="estimate" — never a silent $0
+ estimated = events.turns_completed == 0 and (bool(events.items) or proc.timed_out)
+ usage = (events.estimated_usage(self.model, len(prompt)) if estimated else events.usage(self.model))
usage.latency_ms = int(proc.duration_s * 1000)
text = "\n\n".join(m for m in events.messages if m.strip())
errors = list(events.errors)
@@ -932,7 +969,7 @@ class CodexAgent(_CliAgent):
turns=events.turns_completed, errors=errors,
transient=is_transient_failure(*said), quota=is_quota_failure(*said),
rc=proc.rc, killed_reason=proc.killed_reason, thread_id=events.thread_id,
- turns_completed=events.turns_completed, usage_raw=events.usage_raw,
+ turns_completed=events.turns_completed, usage_raw=events.usage_raw, usage_estimated=estimated,
)
finally:
release_session(s)
diff --git a/harness/codeverse3d/agents/cli_common.py b/harness/codeverse3d/agents/cli_common.py
index 9473b4bb..e2a36f07 100644
--- a/harness/codeverse3d/agents/cli_common.py
+++ b/harness/codeverse3d/agents/cli_common.py
@@ -485,6 +485,7 @@ def finish_session(
transient: bool = False,
quota: bool = False,
provider_wait_s: float = 0.0,
+ usage_estimated: bool = False,
**extra: Any,
) -> AgentResult:
"""Commit the agent's work, compute ``files_changed`` via git (attributed to this
@@ -516,6 +517,7 @@ def finish_session(
transcript_path=str(s.traj.transcript_path if s.traj.transcript_path.exists() else s.traj.dir),
usage=usage, duration_s=duration, provider_wait_s=round(min(max(provider_wait_s, 0.0), duration), 3),
tool_calls=tool_calls, turns=turns, errors=errors, transient=transient and not quota, quota=quota,
+ usage_estimated=usage_estimated,
)
s.traj.write_result(res, kind=s.kind, label=s.label, round=s.round_index, attempt=s.attempt, job_label=s.job.label,
head_before=s.head_before, head_after=s.ws.head(), notes=s.notes, **extra)
diff --git a/harness/codeverse3d/contracts/agent.py b/harness/codeverse3d/contracts/agent.py
index 3fdc79e0..0f80a56a 100644
--- a/harness/codeverse3d/contracts/agent.py
+++ b/harness/codeverse3d/contracts/agent.py
@@ -95,6 +95,11 @@ class AgentResult(BaseModel):
"claude-code its stream-json ``api_retry`` events; agy the retry lines of its ``--log-file``; "
"codex none (its HTTP client retries without an event)",
)
+ usage_estimated: bool = Field(
+ default=False, description="``usage`` is an estimate, not the vendor's count: a codex session "
+ "killed before its turn completed reports none (backends.CodexEvents.estimated_usage); its ledger "
+ "row says source=\"estimate\"",
+ )
tool_calls: int = 0
turns: int = Field(
default=0, description="model turns as the backend counts them (claude-code num_turns, codex "
diff --git a/harness/codeverse3d/cost/instrument.py b/harness/codeverse3d/cost/instrument.py
index 571a8c29..69c8b81e 100644
--- a/harness/codeverse3d/cost/instrument.py
+++ b/harness/codeverse3d/cost/instrument.py
@@ -238,7 +238,8 @@ class MeteredAgent(_Proxy):
backend=usage.backend or self.kind, model=usage.model or self.model,
outcome="ok" if result.ok else (result.exit_reason or "error"),
latency_ms=usage.latency_ms or ms,
- n_calls=max(1, int(result.tool_calls or 1)), source="session")
+ n_calls=max(1, int(result.tool_calls or 1)),
+ source="estimate" if result.usage_estimated else "session")
except Exception as e: # pragma: no cover
log.debug("cost: could not record agent session %s: %s", job.label, e)
diff --git a/harness/codeverse3d/cost/types.py b/harness/codeverse3d/cost/types.py
index 9aafa3a0..f673811b 100644
--- a/harness/codeverse3d/cost/types.py
+++ b/harness/codeverse3d/cost/types.py
@@ -214,7 +214,8 @@ class CallCost(BaseModel):
n_calls: int = 1 # >1 when a row aggregates a whole agent session
#: extra = a round-trip that was discarded yet billed (hedge loser, charged-but-invalid
#: reply); nothing else records it, so unlike ``attempt`` it counts in every total
- source: str = "live" # live | record | events | transcript | stdout | residual | session | attempt | extra
+ #: estimate = a session whose vendor reported no usage (a killed codex turn), priced from its stream
+ source: str = "live" # live | record | events | transcript | stdout | residual | session | estimate | attempt | extra
#: which API key served the call, as its last 4 chars ("…ab12") — never the key
#: itself; "" for a failed call, a session row, or a row older than 2026-08-26
key: str = ""
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index a59e352a..7f8ef147 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -568,8 +568,10 @@ the since-deleted in-process `api-agent` and the since-removed pass / plateau st
* threejs: textures are stripped on GLB export (the texture pass re-adds them as a
derived pack); `userData.tick` cannot survive export.
* agy exposes no per-workspace MCP, cost or served model; a killed agy session books no
- usage (its tokens are in the envelope only). A killed codex session neither (usage is
- per turn and `--ephemeral` leaves no rollout); a killed claude-code session books its
+ usage (its tokens are in the envelope only). A killed codex session books an ESTIMATE
+ (usage is per turn and `--ephemeral` leaves no rollout; `CodexEvents.estimated_usage` prices
+ the stream it left, ledger `source="estimate"`, $ within 0.62–1.34× of actual on 356 recorded
+ sessions); a killed claude-code session books its
per-message usage, whose output side is a floor. A killed or given-up gemini-cli
session books its chat record (exact).
* Vendor sessions see only the routed skill bundles, except agy (5 built-ins; no
diff --git a/harness/tests/agents/test_codex.py b/harness/tests/agents/test_codex.py
index ae2bd90f..3baf85aa 100644
--- a/harness/tests/agents/test_codex.py
+++ b/harness/tests/agents/test_codex.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import json
import shutil
+import time
from pathlib import Path
import pytest
@@ -44,8 +45,12 @@ if mode == "usage_limit":
if mode == "storm":
events = events[:2] + [{"type": "error", "message": "stream disconnected before completion: 503 Service Unavailable"},
{"type": "turn.failed", "error": {"message": "exceeded retry limit, last status: 503"}}]
+if mode == "killed": # the turn never completes: the watchdog kills the session mid-turn
+ events = events[:5]
for e in events:
print(json.dumps(e)); sys.stdout.flush()
+if mode == "killed":
+ import time; time.sleep(60)
'''
@@ -108,6 +113,16 @@ def test_fake_run_and_every_failure_is_typed(tmp_ws: Workspace, fake_bin, monkey
monkeypatch.setenv("FAKE_MODE", "storm")
res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="t", timeout_s=30))
assert not res.ok and res.transient and not res.quota and res.provider_wait_s == 0.0 # codex does not say
+ # killed mid-turn: codex reported no usage, so the session books an estimate from its stream
+ # (it used to book $0 — 1 of 357 recorded sessions, a 10-minute baseline among them)
+ monkeypatch.setenv("FAKE_MODE", "killed")
+ res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="k", timeout_s=3,
+ hard_deadline_s=time.monotonic() + 3))
+ assert not res.ok and res.exit_reason == "timeout" and res.usage_estimated
+ # 3 requests (two items + the one in flight), each re-reading a context of ≥ the 20k-token codex system prompt
+ assert 60_000 < res.usage.input_tokens < 61_000 and 0 < res.usage.cached_tokens < res.usage.input_tokens
+ assert res.usage.cost_usd > 0 and res.usage.tool_calls == 2
+ assert json.loads((Path(res.transcript_path).parent / "result.json").read_text())["usage_estimated"] is True
@pytest.mark.live