Skip to content

Commit eababd7

Browse files
committed
fix(turn,benchmark): retry remediation for Todo turns and offline tiktoken staging
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent 27ff837 commit eababd7

7 files changed

Lines changed: 468 additions & 18 deletions

File tree

‎benchmark/runtime/codex_offline.py‎

Lines changed: 90 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,21 @@
11
"""Offline Codex staging shared by Harbor benchmark adapters."""
22

3+
import hashlib
34
import os
45
import shlex
56
from pathlib import Path
67

78
from harbor.agents.installed.codex import Codex
89
from harbor.environments.base import BaseEnvironment
910

11+
_TIKTOKEN_ENCODING_URLS = {
12+
"o200k_base": "https://openaipublic.blob.core.windows.net/encodings/o200k_base.tiktoken",
13+
"cl100k_base": "https://openaipublic.blob.core.windows.net/encodings/cl100k_base.tiktoken",
14+
"o200k_harmony": "https://openaipublic.blob.core.windows.net/encodings/o200k_harmony.tiktoken",
15+
"p50k_base": "https://openaipublic.blob.core.windows.net/encodings/p50k_base.tiktoken",
16+
"r50k_base": "https://openaipublic.blob.core.windows.net/encodings/r50k_base.tiktoken",
17+
}
18+
1019
_DEFAULT_OFFLINE_DIR = str(
1120
Path(__file__).resolve().parents[1] / "swe-marathon" / "codex"
1221
)
@@ -26,10 +35,89 @@
2635
)
2736

2837

29-
async def stage_portable_python(environment: BaseEnvironment, destination: str) -> None:
30-
"""Stage the configured runner interpreter without using the task PATH."""
38+
def tiktoken_cache_filename(encoding_name: str) -> str:
39+
"""Return tiktoken's deterministic SHA-1 cache filename for a supported encoding."""
40+
url = _TIKTOKEN_ENCODING_URLS.get(encoding_name)
41+
if url is None:
42+
raise ValueError(f"Unsupported tiktoken encoding: {encoding_name}")
43+
return hashlib.sha1(url.encode("utf-8")).hexdigest()
44+
45+
46+
def portable_python_has_tiktoken(portable_python: Path) -> bool:
47+
"""Return True if the staged portable Python distribution includes tiktoken."""
48+
lib_dir = portable_python / "lib"
49+
if not lib_dir.is_dir():
50+
return False
51+
return any(lib_dir.glob("python*/site-packages/tiktoken/__init__.py"))
52+
53+
54+
def resolve_tiktoken_cache_dir(
55+
portable_python: Path | None = None,
56+
*,
57+
encoding_name: str = "o200k_base",
58+
) -> Path | None:
59+
"""Locate an offline tiktoken BPE cache dir containing `encoding_name`."""
60+
target_name = tiktoken_cache_filename(encoding_name)
61+
candidates: list[Path] = []
62+
if portable_python is not None:
63+
candidates.extend(
64+
[
65+
portable_python / "tiktoken-cache",
66+
portable_python / "share" / "tiktoken-cache",
67+
]
68+
)
69+
for env_key in ("LOOPX_TIKTOKEN_CACHE_DIR", "TIKTOKEN_CACHE_DIR", "DATA_GYM_CACHE_DIR"):
70+
raw = os.environ.get(env_key)
71+
if raw:
72+
candidates.append(Path(raw))
73+
candidates.append(Path("/tmp/data-gym-cache"))
74+
for candidate in candidates:
75+
try:
76+
resolved = candidate.resolve()
77+
if (resolved / target_name).is_file():
78+
return resolved
79+
except OSError:
80+
continue
81+
return None
82+
83+
84+
def verify_portable_python_tokenizer(
85+
portable_python: Path,
86+
*,
87+
encoding_name: str = "o200k_base",
88+
) -> Path:
89+
"""Ensure offline portable Python has both `tiktoken` and cached `encoding_name`."""
90+
resolved = portable_python.resolve()
91+
if not portable_python_has_tiktoken(resolved):
92+
raise RuntimeError(
93+
f"Portable Python at {resolved} lacks tiktoken; install tiktoken into its "
94+
"site-packages for offline token metering."
95+
)
96+
cache_dir = resolve_tiktoken_cache_dir(resolved, encoding_name=encoding_name)
97+
if cache_dir is None:
98+
raise RuntimeError(
99+
f"Offline tiktoken cache for {encoding_name} is missing under {resolved}/tiktoken-cache "
100+
"or TIKTOKEN_CACHE_DIR / LOOPX_TIKTOKEN_CACHE_DIR."
101+
)
102+
return cache_dir
103+
104+
105+
async def stage_portable_python(environment: BaseEnvironment, destination: str) -> bool:
106+
"""Stage the configured runner interpreter without using the task PATH.
107+
108+
Returns True when an offline tiktoken BPE cache directory is present at
109+
`<destination>/tiktoken-cache`.
110+
"""
31111
source = Path(os.environ["LOOPX_PORTABLE_PYTHON"]).resolve()
32112
await environment.upload_dir(source, destination)
113+
bundled = source / "tiktoken-cache"
114+
if bundled.is_dir() and any(bundled.iterdir()):
115+
return True
116+
fallback_cache = resolve_tiktoken_cache_dir(source)
117+
if fallback_cache is not None and not fallback_cache.is_relative_to(source):
118+
await environment.upload_dir(fallback_cache, f"{destination}/tiktoken-cache")
119+
return True
120+
return False
33121

34122

35123
class CodexOffline(Codex):

‎benchmark/runtime/harbor.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,7 @@ async def install(self, environment: BaseEnvironment) -> None:
347347
timeout_sec=180,
348348
)
349349
actual_commit = await self._stage_source(environment, loopx_src)
350-
await stage_portable_python(environment, _PYTHON)
350+
self._tiktoken_cache_staged = await stage_portable_python(environment, _PYTHON)
351351
if self.execution.uses_loopx:
352352
await environment.upload_dir(node_root, _NODE)
353353
await self.exec_as_root(
@@ -733,6 +733,11 @@ def _worker_env(self, *, cwd: str) -> dict[str, str]:
733733
"LOOPX_MODEL_CATALOG": (
734734
MODEL_CATALOG_REMOTE if self._model_catalog_staged else ""
735735
),
736+
**(
737+
{"TIKTOKEN_CACHE_DIR": f"{_PYTHON}/tiktoken-cache"}
738+
if getattr(self, "_tiktoken_cache_staged", False)
739+
else {}
740+
),
736741
}
737742
)
738743
return env
Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
"""Tests for offline tiktoken staging, preflight verification, and bundled cache discovery."""
2+
3+
from __future__ import annotations
4+
5+
import asyncio
6+
import sys
7+
from pathlib import Path
8+
9+
import pytest
10+
11+
from loopx.control_plane.turn_driver.epoch_prefetch import (
12+
_resolve_bundled_tiktoken_cache_dir,
13+
count_verifiable_tokens,
14+
)
15+
16+
17+
def _import_codex_offline():
18+
pytest.importorskip("harbor")
19+
from benchmark.runtime.codex_offline import (
20+
portable_python_has_tiktoken,
21+
resolve_tiktoken_cache_dir,
22+
stage_portable_python,
23+
tiktoken_cache_filename,
24+
verify_portable_python_tokenizer,
25+
)
26+
27+
return (
28+
portable_python_has_tiktoken,
29+
resolve_tiktoken_cache_dir,
30+
stage_portable_python,
31+
tiktoken_cache_filename,
32+
verify_portable_python_tokenizer,
33+
)
34+
35+
36+
def _make_fake_portable_python(root: Path, *, with_tiktoken: bool = True) -> Path:
37+
py_root = root / "portable-python"
38+
if with_tiktoken:
39+
pkg = py_root / "lib" / "python3.12" / "site-packages" / "tiktoken"
40+
pkg.mkdir(parents=True, exist_ok=True)
41+
(pkg / "__init__.py").write_text("", encoding="utf-8")
42+
else:
43+
(py_root / "lib" / "python3.12" / "site-packages").mkdir(parents=True, exist_ok=True)
44+
return py_root
45+
46+
47+
class _FakeUploadEnv:
48+
def __init__(self) -> None:
49+
self.uploads: list[tuple[Path, str]] = []
50+
51+
async def upload_dir(self, source_dir: Path, target_dir: str) -> None:
52+
self.uploads.append((Path(source_dir), target_dir))
53+
54+
55+
def test_tiktoken_cache_filename_and_portable_python_has_tiktoken(tmp_path: Path) -> None:
56+
(
57+
portable_python_has_tiktoken,
58+
_resolve_tiktoken_cache_dir,
59+
_stage_portable_python,
60+
tiktoken_cache_filename,
61+
_verify_portable_python_tokenizer,
62+
) = _import_codex_offline()
63+
o200k = tiktoken_cache_filename("o200k_base")
64+
cl100k = tiktoken_cache_filename("cl100k_base")
65+
assert len(o200k) == 40
66+
assert int(o200k, 16) >= 0
67+
assert o200k != cl100k
68+
69+
with_pkg = _make_fake_portable_python(tmp_path / "with", with_tiktoken=True)
70+
without_pkg = _make_fake_portable_python(tmp_path / "without", with_tiktoken=False)
71+
assert portable_python_has_tiktoken(with_pkg) is True
72+
assert portable_python_has_tiktoken(without_pkg) is False
73+
assert portable_python_has_tiktoken(tmp_path / "missing") is False
74+
75+
76+
def test_resolve_and_verify_portable_python_tokenizer(
77+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
78+
) -> None:
79+
(
80+
_portable_python_has_tiktoken,
81+
resolve_tiktoken_cache_dir,
82+
_stage_portable_python,
83+
tiktoken_cache_filename,
84+
verify_portable_python_tokenizer,
85+
) = _import_codex_offline()
86+
for key in ("LOOPX_TIKTOKEN_CACHE_DIR", "TIKTOKEN_CACHE_DIR", "DATA_GYM_CACHE_DIR"):
87+
monkeypatch.delenv(key, raising=False)
88+
89+
py_root = _make_fake_portable_python(tmp_path / "dist", with_tiktoken=False)
90+
with pytest.raises(RuntimeError, match="lacks tiktoken"):
91+
verify_portable_python_tokenizer(py_root)
92+
93+
py_root = _make_fake_portable_python(tmp_path / "dist-ok", with_tiktoken=True)
94+
external_cache = tmp_path / "external-cache"
95+
external_cache.mkdir()
96+
(external_cache / tiktoken_cache_filename("o200k_base")).write_text("bpe", encoding="utf-8")
97+
monkeypatch.setenv("LOOPX_TIKTOKEN_CACHE_DIR", str(external_cache))
98+
assert resolve_tiktoken_cache_dir(py_root) == external_cache.resolve()
99+
assert verify_portable_python_tokenizer(py_root) == external_cache.resolve()
100+
101+
bundled_cache = py_root / "tiktoken-cache"
102+
bundled_cache.mkdir()
103+
(bundled_cache / tiktoken_cache_filename("o200k_base")).write_text("bpe", encoding="utf-8")
104+
assert resolve_tiktoken_cache_dir(py_root) == bundled_cache.resolve()
105+
106+
monkeypatch.delenv("LOOPX_TIKTOKEN_CACHE_DIR", raising=False)
107+
missing_py = _make_fake_portable_python(tmp_path / "dist-nocache", with_tiktoken=True)
108+
monkeypatch.setattr(
109+
"benchmark.runtime.codex_offline.Path",
110+
lambda p: (tmp_path / "no-tmp-cache") if p == "/tmp/data-gym-cache" else Path(p),
111+
)
112+
with pytest.raises(RuntimeError, match="Offline tiktoken cache"):
113+
verify_portable_python_tokenizer(missing_py)
114+
115+
116+
def test_stage_portable_python_uploads_bundled_or_fallback_cache(
117+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
118+
) -> None:
119+
(
120+
_portable_python_has_tiktoken,
121+
_resolve_tiktoken_cache_dir,
122+
stage_portable_python,
123+
tiktoken_cache_filename,
124+
_verify_portable_python_tokenizer,
125+
) = _import_codex_offline()
126+
for key in ("LOOPX_TIKTOKEN_CACHE_DIR", "TIKTOKEN_CACHE_DIR", "DATA_GYM_CACHE_DIR"):
127+
monkeypatch.delenv(key, raising=False)
128+
129+
py_bundled = _make_fake_portable_python(tmp_path / "bundled", with_tiktoken=True)
130+
(py_bundled / "tiktoken-cache").mkdir()
131+
(py_bundled / "tiktoken-cache" / tiktoken_cache_filename("o200k_base")).write_text(
132+
"bpe", encoding="utf-8",
133+
)
134+
monkeypatch.setenv("LOOPX_PORTABLE_PYTHON", str(py_bundled))
135+
env1 = _FakeUploadEnv()
136+
assert asyncio.run(stage_portable_python(env1, "/opt/python")) is True
137+
assert env1.uploads == [(py_bundled.resolve(), "/opt/python")]
138+
139+
py_plain = _make_fake_portable_python(tmp_path / "plain", with_tiktoken=True)
140+
fallback = tmp_path / "fallback-cache"
141+
fallback.mkdir()
142+
(fallback / tiktoken_cache_filename("o200k_base")).write_text("bpe", encoding="utf-8")
143+
monkeypatch.setenv("LOOPX_PORTABLE_PYTHON", str(py_plain))
144+
monkeypatch.setenv("TIKTOKEN_CACHE_DIR", str(fallback))
145+
env2 = _FakeUploadEnv()
146+
assert asyncio.run(stage_portable_python(env2, "/opt/python")) is True
147+
assert env2.uploads == [
148+
(py_plain.resolve(), "/opt/python"),
149+
(fallback.resolve(), "/opt/python/tiktoken-cache"),
150+
]
151+
152+
153+
def test_benchmark_codex_worker_env_exports_tiktoken_cache_dir_when_staged(
154+
tmp_path: Path,
155+
) -> None:
156+
pytest.importorskip("harbor")
157+
from benchmark.runtime.harbor import BenchmarkCodex, _PYTHON
158+
159+
agent = BenchmarkCodex(logs_dir=tmp_path, model_name="fixture")
160+
env_without = agent._worker_env(cwd="/app")
161+
assert "TIKTOKEN_CACHE_DIR" not in env_without
162+
163+
agent._tiktoken_cache_staged = True
164+
env_with = agent._worker_env(cwd="/app")
165+
assert env_with["TIKTOKEN_CACHE_DIR"] == f"{_PYTHON}/tiktoken-cache"
166+
167+
168+
def test_epoch_prefetch_resolves_bundled_tiktoken_cache_dir(
169+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
170+
) -> None:
171+
monkeypatch.delenv("TIKTOKEN_CACHE_DIR", raising=False)
172+
monkeypatch.delenv("DATA_GYM_CACHE_DIR", raising=False)
173+
174+
prefix_direct = tmp_path / "prefix-direct"
175+
cache_direct = prefix_direct / "tiktoken-cache"
176+
cache_direct.mkdir(parents=True)
177+
monkeypatch.setattr(sys, "prefix", str(prefix_direct))
178+
assert _resolve_bundled_tiktoken_cache_dir() is None
179+
(cache_direct / "bpe.tiktoken").write_text("bpe", encoding="utf-8")
180+
assert _resolve_bundled_tiktoken_cache_dir() == cache_direct.resolve()
181+
182+
prefix_share = tmp_path / "prefix-share"
183+
cache_share = prefix_share / "share" / "tiktoken-cache"
184+
cache_share.mkdir(parents=True)
185+
(cache_share / "bpe.tiktoken").write_text("bpe", encoding="utf-8")
186+
monkeypatch.setattr(sys, "prefix", str(prefix_share))
187+
assert _resolve_bundled_tiktoken_cache_dir() == cache_share.resolve()
188+
189+
tokens, meta = count_verifiable_tokens(
190+
"hello offline fold world",
191+
token_counter=lambda text: len(text.split()),
192+
) or (None, None)
193+
assert tokens == 4
194+
assert isinstance(meta, dict)
195+
assert meta["encoding"] == "o200k_base"

‎loopx/control_plane/turn_driver/epoch_prefetch.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import signal
1717
import sqlite3
1818
import subprocess
19+
import sys
1920
import time
2021
from typing import Any, cast
2122

@@ -49,6 +50,20 @@
4950
DEFAULT_TOKENIZER_ENCODING = "o200k_base"
5051

5152

53+
def _resolve_bundled_tiktoken_cache_dir() -> Path | None:
54+
"""Return a bundled tiktoken cache directory under `sys.prefix`, if present."""
55+
for candidate in (
56+
Path(sys.prefix) / "tiktoken-cache",
57+
Path(sys.prefix) / "share" / "tiktoken-cache",
58+
):
59+
try:
60+
if candidate.is_dir() and any(candidate.iterdir()):
61+
return candidate
62+
except OSError:
63+
continue
64+
return None
65+
66+
5267
def count_verifiable_tokens(
5368
text: str,
5469
*,
@@ -66,6 +81,10 @@ def count_verifiable_tokens(
6681
return count, {"name": "configured_tokenizer", "encoding": encoding_name}
6782
try:
6883
from importlib.metadata import version
84+
if not os.environ.get("TIKTOKEN_CACHE_DIR") and not os.environ.get("DATA_GYM_CACHE_DIR"):
85+
bundled_cache = _resolve_bundled_tiktoken_cache_dir()
86+
if bundled_cache is not None:
87+
os.environ["TIKTOKEN_CACHE_DIR"] = str(bundled_cache)
6988
import tiktoken
7089

7190
encoding = tiktoken.get_encoding(encoding_name)

0 commit comments

Comments
 (0)