Skip to content

Commit afa9829

Browse files
authored
Bind context-strategy usage to one native Codex rollout (#9946)
Exact-head review and 81 targeted Python tests passed. The proposed integration tree passed 83 targeted Python tests, control-plane type checking, and standard local premerge (6 direct and 14 selected checks). The older CI gate failed on the Lark transport lint. The current base has the transport-owner fix. The maintainer authorized admin bypass for the up-to-date branch rule and this CI hold. Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com> Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent cb628c5 commit afa9829

5 files changed

Lines changed: 163 additions & 48 deletions

File tree

‎docs/reference/protocols/loopx-turn-v0.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1451,6 +1451,17 @@ binding under the native session lock only if the persisted binding is still
14511451
that candidate. The backup belongs to the Turn that staged it and is retired
14521452
after rollback. A later explicit `fresh` Turn owns its observed native binding.
14531453

1454+
Context-strategy telemetry reports the last cumulative provider token snapshot
1455+
from the same complete rollout capture used to measure source size. A matching
1456+
native session header and a unique source file establish the binding. Duplicate
1457+
requests or repeated equal snapshots do not add usage. Missing or inconsistent
1458+
counters remain unknown. A changed, ambiguous or unreadable source invalidates
1459+
a staged handoff when the native source is checked before dispatch.
1460+
1461+
上下文策略从同一份完整的原生 rollout 读取体积和最后一条累计 token 快照。文件需唯一,
1462+
且会话头与已绑定的原生会话一致。重复的请求记录和同值快照不会重复计入用量。用量缺失
1463+
或计数不一致时保留未知。投递前发现原生来源已变更、不唯一或不可读时,暂存交接失效。
1464+
14541465
中文:显式启用 `--context-strategy-mode auto`(默认 `off`,且 CLI 或 benchmark worker
14551466
显式传入的 `off` 优先于 Goal 级配置)时,接续/结算回合会在既有宿主返回结构上顺带承载可选的
14561467
`context_strategy_proposal_json`,不增加独立模型调用;只读规划预览(`turn plan

‎loopx/capabilities/context_strategy/turn_hooks.py‎

Lines changed: 38 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from collections.abc import Callable, Mapping
1212
from contextlib import closing
1313
from datetime import datetime, timezone
14+
from glob import escape as escape_glob
1415
import hashlib
1516
import json
1617
import os
@@ -20,13 +21,18 @@
2021

2122
from ...control_plane.capability_hooks import TurnContextHookRegistration
2223
from ...control_plane.projects.registry_codec import ProjectRegistryProtocolError, load_registry
24+
from ...control_plane.quota.codex_session_usage import (
25+
CodexSessionUsageError,
26+
read_captured_codex_session_usage,
27+
)
2328
from ...control_plane.quota.turn_envelope import (
2429
adjudicate_context_strategy_adoption,
2530
parse_context_strategy_proposal,
2631
resolve_host_context_strategy_execution,
2732
)
2833
from ...control_plane.runtime.document_io import atomic_write_private_json
2934
from ...paths import validate_goal_id_path_segment
35+
from ...control_plane.turn_driver.codex_input_trace import read_native_trace_file
3036
from ...control_plane.turn_driver.codex_sessions import (
3137
_read_codex_cli_session_document,
3238
_session_path,
@@ -294,50 +300,40 @@ def _save_context_strategy_state(
294300
_write_sqlite_state(sqlite_path, scope_key, payload)
295301

296302

297-
def _find_codex_rollout_metrics(session_id: str | None) -> dict[str, Any] | None:
298-
"""Inspect native Codex rollout JSONL for actual UTF-8 size, tokens, and cache counters."""
303+
def _find_codex_rollout_metrics(
304+
session_id: str | None, *, estimate_tokens: bool = True,
305+
) -> dict[str, Any] | None:
306+
"""Read one bounded rollout owned by the selected native session."""
299307
if not session_id:
300308
return None
301309
codex_home = Path(os.environ.get("CODEX_HOME", "~/.codex")).expanduser()
302-
sessions_dir = codex_home / "sessions"
310+
sessions_dir = (codex_home / "sessions").resolve()
303311
if not sessions_dir.is_dir():
304312
return None
305-
matches = sorted(sessions_dir.rglob(f"*{session_id}*.jsonl"))
306-
if not matches:
307-
return None
308-
rollout_path = matches[-1]
309-
try:
310-
if rollout_path.stat().st_size > _MAX_ROLLOUT_INSPECT_BYTES:
311-
return None
312-
raw_bytes = rollout_path.read_bytes()
313-
except OSError:
313+
suffix = f"-{session_id}.jsonl"
314+
matches = (
315+
path for path in sessions_dir.rglob(f"rollout-*{escape_glob(session_id)}.jsonl")
316+
if path.name.endswith(suffix)
317+
)
318+
rollout_path = next(matches, None)
319+
if rollout_path is None:
314320
return None
315-
text = raw_bytes.decode("utf-8", errors="replace")
316-
counted = count_verifiable_tokens(text, encoding_name=DEFAULT_TOKENIZER_ENCODING)
317-
input_tokens_total = 0
318-
cached_tokens_total = 0
319-
saw_usage = False
320-
for line in text.splitlines():
321-
if "token_count" not in line and "usage" not in line:
322-
continue
323-
try:
324-
row = json.loads(line)
325-
except ValueError:
326-
continue
327-
payload = _as_dict(row.get("payload"))
328-
info = _as_dict(payload.get("info"))
329-
last_usage = _as_dict(info.get("last_token_usage") or payload.get("usage") or row.get("usage"))
330-
if isinstance(last_usage.get("input_tokens"), int):
331-
input_tokens_total += int(last_usage["input_tokens"])
332-
cached_tokens_total += int(last_usage.get("cached_input_tokens") or 0)
333-
saw_usage = True
321+
if next(matches, None) is not None or not rollout_path.resolve(strict=True).is_relative_to(sessions_dir):
322+
raise CodexSessionUsageError("Native rollout source is ambiguous or outside its session store")
323+
raw_bytes = read_native_trace_file(rollout_path)
324+
usage = read_captured_codex_session_usage(
325+
rollout_path, raw_bytes, expected_session_id=session_id,
326+
) or {}
327+
counted = count_verifiable_tokens(
328+
raw_bytes.decode("utf-8"), encoding_name=DEFAULT_TOKENIZER_ENCODING,
329+
) if estimate_tokens else None
334330
return {
335331
"rollout_path": str(rollout_path),
336332
"rollout_sha256": hashlib.sha256(raw_bytes).hexdigest(),
337333
"rollout_bytes": len(raw_bytes),
338334
"rollout_tokens": counted[0] if counted is not None else None,
339-
"provider_input_tokens": input_tokens_total if saw_usage else None,
340-
"provider_cached_input_tokens": cached_tokens_total if saw_usage else None,
335+
"provider_input_tokens": usage.get("input_tokens"),
336+
"provider_cached_input_tokens": usage.get("cache_tokens"),
341337
}
342338

343339

@@ -453,7 +449,10 @@ def verify_staged_handoff_provenance(
453449
if current_session_id != prov.get("native_session_id"):
454450
return False, "native_session_binding_changed"
455451
if host_id == "codex-cli" and current_session_id is not None:
456-
live_rollout = _find_codex_rollout_metrics(current_session_id)
452+
try:
453+
live_rollout = _find_codex_rollout_metrics(current_session_id, estimate_tokens=False)
454+
except (OSError, ValueError, RuntimeError):
455+
return False, "native_rollout_changed"
457456
if prov.get("native_rollout_present") is False and live_rollout is not None:
458457
return False, "unexpected_native_rollout_appeared"
459458
if prov.get("native_rollout_present") is True:
@@ -921,7 +920,11 @@ def _append_epoch_ledger_and_measure_baseline(
921920
)
922921
ledger_tokens = counted_ledger[0] if counted_ledger is not None else None
923922

924-
rollout_meta = _find_codex_rollout_metrics(active_session_id)
923+
try:
924+
rollout_meta = _find_codex_rollout_metrics(active_session_id)
925+
except (OSError, ValueError, RuntimeError):
926+
# The ledger remains a bound source when the optional native one fails.
927+
rollout_meta = None
925928
baseline_tokens = ledger_tokens
926929
if rollout_meta is not None and isinstance(rollout_meta.get("rollout_tokens"), int):
927930
# Prefer the larger verified native rollout token count when Codex CLI rollout is present.

‎loopx/control_plane/quota/codex_session_usage.py‎

Lines changed: 66 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
import os
3434
from collections.abc import Iterator
3535
from datetime import datetime
36+
from io import BytesIO
3637
from pathlib import Path
3738
from typing import Any, Mapping, MutableMapping, cast
3839

@@ -52,6 +53,10 @@ class CodexSessionUsageError(UsageRowError):
5253
"""Fail-closed diagnostic for unreadable or unusable Codex rollouts."""
5354

5455

56+
class _UnobservedCodexUsage(CodexSessionUsageError):
57+
"""A bound source lacks a token snapshot or the snapshot's model."""
58+
59+
5560
def _parse_timestamp(value: Any) -> datetime | None:
5661
text = str(value or "").strip()
5762
if not text:
@@ -76,7 +81,40 @@ def read_codex_session_usage(rollout_path: Path) -> dict[str, Any]:
7681
return _read_codex_session_usage(rollout_path)[0]
7782

7883

79-
def _rollout_records(path: Path) -> Iterator[dict[str, Any]]:
84+
def read_captured_codex_session_usage(
85+
rollout_path: Path, capture: bytes, *, expected_session_id: str,
86+
) -> dict[str, Any] | None:
87+
"""Read the same complete bytes that backed an exact native source receipt.
88+
89+
Bad session provenance raises. A bound capture without usable usage can
90+
still back source-size estimates.
91+
"""
92+
try:
93+
usage, _ = _read_codex_session_usage(
94+
rollout_path, capture=capture, expected_session_id=expected_session_id,
95+
)
96+
except _UnobservedCodexUsage:
97+
return None
98+
return usage
99+
100+
101+
def _captured_counters_are_consistent(
102+
totals: Mapping[str, Any], previous: Mapping[str, Any] | None,
103+
) -> bool:
104+
prior = previous or {}
105+
for key in ("input_tokens", "output_tokens", "cached_input_tokens"):
106+
count = totals.get(key)
107+
before = prior.get(key)
108+
if key == "cached_input_tokens" and count is None and before is None:
109+
continue
110+
if type(count) is not int or not 0 <= count <= 2**53 - 1:
111+
return False
112+
if before is not None and count < before:
113+
return False
114+
return (totals.get("cached_input_tokens") or 0) <= totals["input_tokens"]
115+
116+
117+
def _rollout_records(path: Path, *, capture: bytes | None = None) -> Iterator[dict[str, Any]]:
80118
"""Scan the opening byte extent, without sampling or retaining transcripts.
81119
82120
Accounting needs every record, unlike discovery's bounded head sample.
@@ -85,8 +123,8 @@ def _rollout_records(path: Path) -> Iterator[dict[str, Any]]:
85123
a later observation sees appended usage under its usual snapshot identity.
86124
"""
87125
try:
88-
with path.open("rb") as stream:
89-
remaining = os.fstat(stream.fileno()).st_size
126+
with (path.open("rb") if capture is None else BytesIO(capture)) as stream:
127+
remaining = os.fstat(stream.fileno()).st_size if capture is None else len(capture)
90128
line_number = 0
91129
pending_corrupt_line: int | None = None
92130
while remaining:
@@ -97,6 +135,8 @@ def _rollout_records(path: Path) -> Iterator[dict[str, Any]]:
97135
)
98136
remaining -= len(line)
99137
line_number += 1
138+
if capture is not None and not line.endswith(b"\n"):
139+
raise CodexSessionUsageError(f"captured rollout has an incomplete record: {path}")
100140
if not line.strip():
101141
continue
102142
if pending_corrupt_line is not None:
@@ -106,7 +146,7 @@ def _rollout_records(path: Path) -> Iterator[dict[str, Any]]:
106146
try:
107147
text = line.decode("utf-8")
108148
except UnicodeDecodeError as exc:
109-
if remaining == 0 and exc.reason == "unexpected end of data":
149+
if capture is None and remaining == 0 and exc.reason == "unexpected end of data":
110150
# A writer may be partway through a final UTF-8 codepoint.
111151
# Other encoding damage, including a terminated record,
112152
# must never be mistaken for an incomplete append.
@@ -116,21 +156,29 @@ def _rollout_records(path: Path) -> Iterator[dict[str, Any]]:
116156
) from exc
117157
try:
118158
item = json.loads(text)
119-
except json.JSONDecodeError:
159+
except json.JSONDecodeError as exc:
160+
if capture is not None:
161+
raise CodexSessionUsageError(
162+
f"captured rollout line {line_number} is corrupt: {path}"
163+
) from exc
120164
# Defer until the next nonblank line: only malformed final
121165
# JSON is tolerated. No later event may hide interior damage.
122166
pending_corrupt_line = line_number
123167
continue
124168
if isinstance(item, dict):
125169
yield item
170+
elif capture is not None:
171+
raise CodexSessionUsageError(
172+
f"captured rollout line {line_number} is not an object: {path}"
173+
)
126174
except OSError as exc:
127175
raise CodexSessionUsageError(
128176
f"cannot read codex session rollout: {exc}"
129177
) from exc
130178

131179

132180
def _read_codex_session_usage(
133-
rollout_path: Path,
181+
rollout_path: Path, *, capture: bytes | None = None, expected_session_id: str | None = None,
134182
) -> tuple[dict[str, Any], list[tuple[str, str]]]:
135183
path = Path(rollout_path).expanduser()
136184
session_id = ""
@@ -139,11 +187,14 @@ def _read_codex_session_usage(
139187
last_totals: Mapping[str, Any] | None = None
140188
last_totals_at = ""
141189
last_totals_model = ""
190+
consistent_capture = True
142191
trailing_models: list[tuple[str, str]] = []
143-
for item in _rollout_records(path):
192+
for item in _rollout_records(path, capture=capture):
144193
kind = str(item.get("type") or "")
145194
raw_payload = item.get("payload")
146195
payload = raw_payload if isinstance(raw_payload, dict) else {}
196+
if expected_session_id is not None and not session_id and kind != "session_meta":
197+
raise CodexSessionUsageError(f"captured rollout must start with session_meta: {path}")
147198
if kind == "session_meta":
148199
metadata_session_id = str(
149200
payload.get("session_id") or payload.get("id") or ""
@@ -152,6 +203,8 @@ def _read_codex_session_usage(
152203
raise CodexSessionUsageError(
153204
f"codex session rollout has no session_meta id: {path}"
154205
)
206+
if expected_session_id is not None and metadata_session_id != expected_session_id:
207+
raise CodexSessionUsageError(f"captured rollout belongs to a different session: {path}")
155208
if session_id and metadata_session_id != session_id:
156209
raise CodexSessionUsageError(
157210
f"codex session rollout has conflicting session_meta ids: {path}"
@@ -176,6 +229,8 @@ def _read_codex_session_usage(
176229
raise CodexSessionUsageError(
177230
f"codex session rollout has usage before session_meta: {path}"
178231
)
232+
if capture is not None and consistent_capture:
233+
consistent_capture = _captured_counters_are_consistent(totals, last_totals)
179234
last_totals = totals
180235
last_totals_at = str(item.get("timestamp") or "").strip()
181236
# The model labels this cumulative snapshot only if it was
@@ -188,12 +243,14 @@ def _read_codex_session_usage(
188243
raise CodexSessionUsageError(
189244
f"codex session rollout has no session_meta id: {path}"
190245
)
246+
if not consistent_capture:
247+
raise _UnobservedCodexUsage(f"captured rollout has inconsistent token counters: {path}")
191248
if last_totals is None:
192-
raise CodexSessionUsageError(
249+
raise _UnobservedCodexUsage(
193250
f"codex session rollout has no token_count usage events: {path}"
194251
)
195252
if not last_totals_model:
196-
raise CodexSessionUsageError(
253+
raise _UnobservedCodexUsage(
197254
f"codex session rollout has no turn_context model id: {path}"
198255
)
199256

‎tests/control_plane/test_autonomous_context_strategy.py‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,8 @@ def run_three_turn_arm(arm_root: Path, mode: str) -> list[dict[str, object]]:
527527
528528
rollout_path = codex_home / "sessions" / f"rollout-{{session_id}}.jsonl"
529529
prior_rollout = rollout_path.read_text(encoding="utf-8") if (is_resume and rollout_path.exists()) else ""
530+
if not prior_rollout:
531+
prior_rollout = json.dumps({{"type": "session_meta", "payload": {{"id": session_id}}}}) + "\\n"
530532
531533
# Extract turn_key from prompt JSON payload
532534
turn_key = ""
@@ -762,10 +764,12 @@ def test_turn_plan_detail_does_not_initialize_legacy_prefetch_sqlite_table(
762764

763765

764766
@pytest.mark.parametrize("provider", ["file", "sqlite"])
767+
@pytest.mark.parametrize("source_change", ["append", "ambiguous"])
765768
def test_stale_rollout_rejects_staged_epoch_reset_and_omits_handoff(
766769
tmp_path: Path,
767770
monkeypatch: pytest.MonkeyPatch,
768771
provider: str,
772+
source_change: str,
769773
) -> None:
770774
"""Out-of-band native rollout changes must retain `resume` and omit rejected handoffs."""
771775
import contextlib
@@ -803,6 +807,8 @@ def test_stale_rollout_rejects_staged_epoch_reset_and_omits_handoff(
803807
804808
rollout_path = codex_home / "sessions" / f"rollout-{{session_id}}.jsonl"
805809
prior = rollout_path.read_text(encoding="utf-8") if rollout_path.exists() else ""
810+
if not prior:
811+
prior = json.dumps({{"type": "session_meta", "payload": {{"id": session_id}}}}) + "\\n"
806812
blob = ("probe_trace: dense exploration line for epoch reset gate. " * 260) if turn_idx == 1 else "done"
807813
rollout_path.write_text(prior + json.dumps({{"type": "event_msg", "payload": {{"text": blob}}}}) + "\\n", encoding="utf-8")
808814
@@ -910,10 +916,12 @@ def _run_turn(instance_id: str) -> dict[str, object]:
910916
)
911917
assert staged_state["pending_handoff"]["status"] == "staged_for_next_turn"
912918

913-
# Mutate native rollout out-of-band before Turn 2 dispatches!
914919
rollout_1 = codex_home / "sessions" / "rollout-sess-native-1.jsonl"
915-
with rollout_1.open("a", encoding="utf-8") as fh:
916-
fh.write('{"type":"event_msg","payload":{"text":"out-of-band manual turn"}}\n')
920+
if source_change == "append":
921+
with rollout_1.open("a", encoding="utf-8") as fh:
922+
fh.write('{"type":"event_msg","payload":{"text":"out-of-band manual turn"}}\n')
923+
else:
924+
rollout_1.with_name("rollout-copy-sess-native-1.jsonl").write_bytes(rollout_1.read_bytes())
917925

918926
# Both `turn plan` and `turn run-once` must reject the invalidated EpochReset, keep `resume`, and omit handoff.
919927
plan_buf = io.StringIO()
@@ -1000,7 +1008,9 @@ def test_failed_epoch_reset_rollback_does_not_adopt_another_session(
10001008
10011009
rollout_path = codex_home / "sessions" / f"rollout-{{session_id}}.jsonl"
10021010
blob = ("probe_trace: dense exploration line for epoch reset gate. " * 260) if turn_idx == 1 else "candidate"
1003-
rollout_path.write_text(json.dumps({{"type": "event_msg", "payload": {{"text": blob}}}}) + "\\n", encoding="utf-8")
1011+
header = {{"type": "session_meta", "payload": {{"id": session_id}}}}
1012+
line = {{"type": "event_msg", "payload": {{"text": blob}}}}
1013+
rollout_path.write_text(json.dumps(header) + "\\n" + json.dumps(line) + "\\n", encoding="utf-8")
10041014
10051015
turn_key = ""
10061016
for line in prompt.splitlines():
@@ -1172,6 +1182,8 @@ def test_late_rollout_append_after_fresh_planning_falls_back_to_resume_and_rejec
11721182
11731183
rollout_path = codex_home / "sessions" / f"rollout-{{session_id}}.jsonl"
11741184
prior = rollout_path.read_text(encoding="utf-8") if rollout_path.exists() else ""
1185+
if not prior:
1186+
prior = json.dumps({{"type": "session_meta", "payload": {{"id": session_id}}}}) + "\\n"
11751187
blob = ("probe_trace: dense exploration line for epoch reset gate. " * 260) if turn_idx in (1, 2) else "done"
11761188
rollout_path.write_text(prior + json.dumps({{"type": "event_msg", "payload": {{"text": blob}}}}) + "\\n", encoding="utf-8")
11771189

0 commit comments

Comments
 (0)