Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
7ce2299
feat(browsecomp): read-only pack behind the flat search cache
HeyyyyyyG Nov 20, 2026
cd10d65
feat(browsecomp): config-gated masks on the agent's /run, and verify …
HeyyyyyyG Nov 20, 2026
01d54ef
test(browsecomp): with resets off the agent's history only grows (tok…
HeyyyyyyG Nov 20, 2026
154e836
fix(opencode_multimodal_benchmarks): train rollouts cut mid-tool by t…
HeyyyyyyG Nov 21, 2026
96c7e31
test(opencode_multimodal_benchmarks): expect a masked row for an unus…
HeyyyyyyG Nov 21, 2026
ceedc12
fix(browsecomp,opencode_multimodal): mark budget-stop masks with a mo…
HeyyyyyyG Nov 23, 2026
b9ea7d7
docs(browsecomp): describe the /run masks and the timed-out verify
yfw Nov 23, 2026
ad19089
Merge branch 'yifuw/mask-judge-replies-without-verdict' into yifuw/br…
yfw Nov 23, 2026
f854249
fix(browsecomp): keep the timed_out update text that run health greps…
yfw Nov 23, 2026
41536c8
fix(browsecomp): tighten the /run masks after review
yfw Nov 24, 2026
c799edc
fix(browsecomp): make the cache pack safer to operate after review
yfw Nov 24, 2026
32b2054
test(opencode_multimodal_benchmarks): unusable tool evidence wins ove…
yfw Nov 24, 2026
199d45d
Merge branch 'yifuw/mask-judge-replies-without-verdict' into yifuw/br…
yfw Nov 24, 2026
52b9327
Merge branch 'yifuw/mask-judge-replies-without-verdict' into yifuw/br…
yfw Nov 24, 2026
72584a6
docs(browsecomp): say how a recipe keeps masked max_output_tokens row…
yfw Nov 24, 2026
07038fb
fix(browsecomp): say "shards skipped" in the candidates summary
yfw Nov 24, 2026
1ff7c12
perf(browsecomp): read only a prefix of packed entries in the index r…
yfw Nov 24, 2026
c15e959
Merge branch 'yifuw/mask-judge-replies-without-verdict' into yifuw/br…
yfw Nov 24, 2026
f0037b8
Merge branch 'yifuw/mask-judge-replies-without-verdict' into yifuw/br…
yfw Nov 24, 2026
23af177
fix(opencode_multimodal_benchmarks): check the other tool evidence be…
yfw Nov 30, 2026
fa40288
fix(browsecomp): make the cache pack tools safe to rerun
yfw Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion resources_servers/browsecomp_advanced_harness/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,12 +135,41 @@ verbose_phase_log: false # log every cache get and put, not
resources_servers/browsecomp_advanced_harness/build_cache_index.py /shared/browsecomp-cache
```

### Cache pack

A cache of millions of entries is millions of small files. `build_cache_pack.py` packs the same entries into 512
shard file pairs under `<root>/pack/`, on the same filesystem as the cache. Reads try the flat file first and use the
pack only when the flat file does not exist. Writes still go to flat files.

The server turns the pack on at startup when `<root>/pack/MANIFEST.json` exists, so restart running servers after
`finalize`. If the manifest names a missing or wrong-size shard file, the server does not start. The startup line
shows `pack=<generation>`, and the `[cache]` line adds pack hits and pack errors. Run the tool from the Gym root with
this server's venv:

```bash
PY=resources_servers/browsecomp_advanced_harness/.venv/bin/python
$PY -m resources_servers.browsecomp_advanced_harness.build_cache_pack build /shared/browsecomp-cache
$PY -m resources_servers.browsecomp_advanced_harness.build_cache_pack verify /shared/browsecomp-cache
$PY -m resources_servers.browsecomp_advanced_harness.build_cache_pack finalize /shared/browsecomp-cache
```

`build` stages each shard in `$TMPDIR/bcpack-<host>-<pid>/` (or `--tmp-dir`) and leaves it there if it fails. The
pack needs about the compressed size of the cache, on top of the flat files.

`candidates` lists the flat files that match their packed copy byte for byte. Run it only after `finalize` and a
server restart. Right before you delete each file, make sure that it still has the listed size, mtime and sha256.

To roll back, run `unpack`, which recreates the missing flat files. Then move `MANIFEST.json` aside and restart the
servers. Rebuild a finalized pack between runs: stop the servers that read this root first, since they check the
pack's file sizes only at startup. After deleting flat files, run `unpack` before you rebuild. `build` refuses a shard
whose pack holds entries that have no flat file, because a rebuild from the flat files alone would drop them.

## Sessions

Each rollout has its own session: the provider-call metrics that `/verify` reports and, with `workspace: per_session`, the disk workspace that `search` and `browse` write pages to and `bash_command` reads.

- **Environment Server.** `/seed_session` takes a `ResourcesSeedSessionRequest` and keys the session by its `resources_session_id`. The seed is refused with 422 when `task_data` lacks the `question` and `ground_truth` that `/verify` needs, or, with a workspace, when the ID is not a plain directory name. `/close_session` removes the workspace and the metrics, and is idempotent. A close that cannot remove the workspace fails and keeps the session, so the caller can retry it. After a close, a seed for the same ID is refused with 409, and a tool call for it gets 404 (`session_lost`) instead of recreating the workspace. `/verify` of a closed session returns a masked sample (`reward: 0`, `mask_sample: true`, `failure_kind: session_lost`). The reward depends only on the response and the task, so the mask is kept on purpose: a closed session reads the same on every server under the resources session contract. `single_agent_turn` verifies before it closes, so only an out-of-order verify gets the mask.
- **An agent's `/run`.** `/seed_session` takes the flat row and keys the session by the cookie. `/verify` releases the sandbox and removes the workspace, since this path sends no close. The sandbox starts with the first `bash_command`, not at the seed. A run whose agent never sends `/verify`, as `browsecomp_agent` does after a timeout or an aborted run, keeps its sandbox until the provider's `ttl_s` reclaims it or the server shuts down; Enroot ignores `ttl_s`. Sandboxed runs should use the Environment Server path, which always closes.
- **An agent's `/run`.** `/seed_session` takes the flat row and keys the session by the cookie. `/verify` releases the sandbox and removes the workspace, since this path sends no close. The sandbox starts with the first `bash_command`, not at the seed. A run whose agent never sends `/verify`, as `browsecomp_agent` does after an aborted run, keeps its sandbox until the provider's `ttl_s` reclaims it or the server shuts down; Enroot ignores `ttl_s`. Sandboxed runs should use the Environment Server path, which always closes.

`/close_session`, and `/verify` on the `/run` path, stop the owned sandbox before deleting its workspace and metrics.
A failed stop leaves the session available for a retry. `/verify` of an episode session releases nothing,
Expand Down
14 changes: 9 additions & 5 deletions resources_servers/browsecomp_advanced_harness/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -1154,11 +1154,12 @@ def model_post_init(self, __context) -> None:
)
if self._search_cache.enabled:
LOG.info(
"Search cache enabled at %s (fuzzy=%s, read_only=%s, index norms=%s)",
"Search cache enabled at %s (fuzzy=%s, read_only=%s, index norms=%s, pack=%s)",
cache_dir,
self.config.search_cache_fuzzy_threshold or "off",
self._search_cache.read_only,
self._search_cache.index_size,
self._search_cache.pack_generation or "off",
)

print(f"Excluded domains: {self._exclude_domains}")
Expand Down Expand Up @@ -1201,6 +1202,8 @@ async def close_shell(sid: str) -> None:
yield maybe_state
finally:
await asyncio.gather(*(close_shell(sid) for sid in list(self._shell_sessions)))
# No request is in flight after the main lifespan ends, so the pack's descriptors can close.
self._search_cache.close()
if self.config.dump_session_id_to_metrics_on_exit:
out_file = Path(__file__).parent / "session_id_metrics.json"
if is_nemo_gym_fastapi_worker():
Expand Down Expand Up @@ -1234,8 +1237,9 @@ async def seed_session(
self._validate_shell_config()
if not isinstance(body, ResourcesSeedSessionRequest):
# An agent's /run seeds with its row; /verify owns its eventual cleanup. Such an agent can end a run
# without /verify (after a timeout, for example), so its sandbox starts with the first bash_command: only
# a run that used the shell can leave one behind, and a failed start cannot strand this seed's workspace.
# without /verify (after an agent error, for example), so its sandbox starts with the first bash_command:
# only a run that used the shell can leave one behind, and a failed start cannot strand this seed's
# workspace.
sid = request.session[SESSION_ID_KEY]
async with self._locks.locked(sid):
if self.config.workspace == "per_session":
Expand Down Expand Up @@ -2103,8 +2107,8 @@ async def _verify(self, request: Request, body: TavilySearchVerifyRequest) -> Ta

judge_error = None
if timed_out:
# Wrong by construction: the agent's /run scores it 0 without a verify, and an Environment Server's
# verify does the same without calling the judge.
# Wrong by construction, so it scores 0 without the judge. Both the agent's /run and an Environment Server
# send a timed-out rollout here.
judge_evaluation = JudgeEvaluation(
reasoning="The rollout reached its time limit.", extracted_final_answer="", reward=0.0
)
Expand Down
130 changes: 118 additions & 12 deletions resources_servers/browsecomp_advanced_harness/build_cache_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@
Payloads store "norm" before the (large) "results" field, so a bounded head
read + regex avoids parsing 400k full JSON bodies; falls back to a full parse.

With a pack (pack/MANIFEST.json), packed search entries whose flat file is gone
are indexed too, so deleting flat files after packing keeps their queries
visible to fuzzy matching. Each shard <ab> is one task: its flat files are
scanned first, and a packed entry with a flat file is skipped. For the rest only
a prefix of the blob is read and inflated (the same head read as a flat file);
an entry whose norm lies past that prefix is read in full.

Usage:
python build_cache_index.py <cache_root> [--workers N]
"""
Expand All @@ -30,10 +37,24 @@
import os
import re
import sys
import zlib
from collections import Counter
from multiprocessing import Pool
from os import PathLike

from resources_servers.browsecomp_advanced_harness.search_cache import INDEX_BASE, INDEX_DIR
from resources_servers.browsecomp_advanced_harness.search_cache_pack import (
INDEX_HEAD_SIZE,
LEN_MASK,
REC_SIZE,
RECORD,
STORED,
load_manifest,
open_pack,
pack_root_of,
read_index_head,
shard_paths,
)
from resources_servers.browsecomp_advanced_harness.sqlite_fuzzy_index import (
DEFAULT_TOKENIZER,
build_master_db,
Expand All @@ -42,31 +63,101 @@


_HEAD_BYTES = 8192
# Compressed bytes read for a packed entry's head; at the pack's ~3x ratio they
# inflate to more than _HEAD_BYTES.
_PACK_PREFIX_BYTES = 4096
_NORM_RE = re.compile(r'"norm":\s*"((?:[^"\\]|\\.)*)"')
_FLAT_NAME_RE = re.compile(r"^[0-9a-f]{64}\.json$")


def _norm_in_head(head):
m = _NORM_RE.search(head)
return json.loads(f'"{m.group(1)}"') if m else None


def _extract_norm(path):
try:
with open(path, "r", encoding="utf-8", errors="replace") as f:
head = f.read(_HEAD_BYTES)
m = _NORM_RE.search(head)
if m:
return json.loads(f'"{m.group(1)}"')
norm = _norm_in_head(head)
if norm is not None:
return norm
with open(path, "r", encoding="utf-8") as f: # norm beyond head (huge query) — rare
return json.load(f).get("norm")
except (OSError, json.JSONDecodeError, ValueError):
return None


def _scan_subdir(subdir):
def _packed_norm_from_prefix(fd, offset, length, stored):
"""The norm from the first bytes of a packed blob, or None when it is not in them."""
try:
if stored:
head = os.pread(fd, min(length, _HEAD_BYTES), offset)
else:
head = zlib.decompressobj().decompress(os.pread(fd, min(length, _PACK_PREFIX_BYTES), offset), _HEAD_BYTES)
return _norm_in_head(head.decode("utf-8", errors="replace"))
except (OSError, zlib.error, ValueError):
return None


def _packed_norm_in_full(fd, offset, length, raw_len, stored):
"""The norm from the whole blob, or None if it is unreadable."""
try:
blob = os.pread(fd, length, offset)
raw = blob if stored else zlib.decompress(blob, 15, raw_len)
norm = json.loads(raw.decode("utf-8")).get("norm")
return norm if isinstance(norm, str) else None
except (OSError, zlib.error, ValueError, AttributeError):
return None


def _packed_shard_norms(pack_root, ab, flat_names, counts):
"""Norms of the packed search entries of shard <ab> that have no flat file in flat_names."""
idx_path, dat_path = shard_paths(pack_root, "search", ab)
with open(idx_path, "rb") as f:
data = f.read()
count, _ = read_index_head(data[:INDEX_HEAD_SIZE], len(data), idx_path)
norms = []
for dirpath, _, fnames in os.walk(subdir):
fd = os.open(dat_path, os.O_RDONLY | os.O_CLOEXEC)
try:
for i in range(count):
digest, offset, length, raw_len = RECORD.unpack_from(data, INDEX_HEAD_SIZE + i * REC_SIZE)
if digest.hex() in flat_names:
counts["skipped_flat"] += 1
continue
stored, length = bool(length & STORED), length & LEN_MASK
norm = _packed_norm_from_prefix(fd, offset, length, stored)
if norm is not None:
counts["prefix"] += 1
else:
norm = _packed_norm_in_full(fd, offset, length, raw_len, stored)
counts["full" if norm is not None else "unreadable"] += 1
if norm:
norms.append(norm)
finally:
os.close(fd)
return norms


def _scan_shard(task):
"""(norms, counts) of one shard: the flat files under search/<ab>/, then the packed entries without one."""
cache_root, ab, pack_root = task
norms, flat_names, counts = [], set(), Counter()
shard_dir = os.path.join(cache_root, "search", ab)
for dirpath, _, fnames in os.walk(shard_dir):
cd = os.path.relpath(dirpath, shard_dir)
for fname in fnames:
if fname.endswith(".json"):
# Only a file at its canonical <ab>/<cd>/<digest>.json is what SearchCache reads before the pack, so
# only that one hides the packed copy. A misplaced copy elsewhere does not.
if _FLAT_NAME_RE.match(fname) and fname[:2] == ab and fname[2:4] == cd:
flat_names.add(fname[: -len(".json")])
norm = _extract_norm(os.path.join(dirpath, fname))
if norm:
norms.append(norm)
return norms
if pack_root is not None:
norms.extend(_packed_shard_norms(pack_root, ab, flat_names, counts))
return norms, counts


def build_index(cache_root: str | PathLike[str], *, workers: int = 1, tokenizer: str = DEFAULT_TOKENIZER) -> int:
Expand All @@ -81,15 +172,30 @@ def build_index(cache_root: str | PathLike[str], *, workers: int = 1, tokenizer:
norms cached since this build. See SearchCache._unmerged_norms.
"""
search_dir = os.path.join(cache_root, "search")
subdirs = sorted(
os.path.join(search_dir, d) for d in os.listdir(search_dir) if os.path.isdir(os.path.join(search_dir, d))
)
subdirs = set()
if os.path.isdir(search_dir): # with a pack, the flat tree can be gone
subdirs = {d for d in os.listdir(search_dir) if os.path.isdir(os.path.join(search_dir, d))}
# open_pack refuses a pack whose shard files do not match MANIFEST.json; only shards it lists are read.
reader = open_pack(cache_root)
packed = set()
if reader is not None:
reader.close()
packed = {key.split("/", 1)[1] for key in load_manifest(cache_root)["shards"] if key.startswith("search/")}
pack_root = pack_root_of(cache_root)
tasks = [(str(cache_root), ab, pack_root if ab in packed else None) for ab in sorted(subdirs | packed)]
if workers > 1:
with Pool(workers) as pool:
chunks = pool.map(_scan_subdir, subdirs)
results = pool.map(_scan_shard, tasks)
else:
chunks = [_scan_subdir(d) for d in subdirs]
norms = sorted({n for chunk in chunks for n in chunk})
results = [_scan_shard(t) for t in tasks]
counts = sum((c for _, c in results), Counter())
if packed:
print(
f"packed search entries: {counts['prefix']} read from a prefix, {counts['full']} read in full, "
f"{counts['skipped_flat']} skipped (flat file present), {counts['unreadable']} unreadable",
file=sys.stderr,
)
norms = sorted({n for chunk, _ in results for n in chunk})

index_dir = os.path.join(cache_root, INDEX_DIR)
os.makedirs(index_dir, exist_ok=True)
Expand Down
Loading
Loading