Skip to content

feat(hle_web_tools): add upstream HLE web tools server and Diamond preset - #5176

Merged
rimashahbazyan merged 72 commits into
mainfrom
rshahbazyan/hle-web-tools
Nov 17, 2026
Merged

rimashahbazyan merged 72 commits into
mainfrom
rshahbazyan/hle-web-tools

Conversation

@rimashahbazyan

@rimashahbazyan rimashahbazyan commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

New shared component for closer review. This PR adds a new resources server, resources_servers/hle_web_tools, that other presets can compose as a tool server. Per the maintainer's note on #4727 asking that new shared components be called out, flagging it here so it gets a closer look than a preset-only change. The second commit (05f96cdd) is the fail-closed fix that came out of review of the first.

What does this PR do?

Adds the HLE authors' two with-tools web tools, behind their blocklist, as a Gym tool server, and an HLE-Diamond preset that uses it as its only tool server.

resources_servers/hle_web_tools (new)

  • Implements section 3 of docs/evaluation-with-tools.md in centerforaisafety/hle at commit 22ed3074b1e7b134bcbc09028d0ba320839b0655. app.py records the SHA-256 of that document, of docs/blocklist.json and of docs/requirements-tools.txt at that commit.
  • Exposes exactly two MCP tools: web_search(query) (URL, title, snippet; at most 20 results after filtering) and web_fetch(url) (main content as Markdown, capped at 60,000 characters with a truncation indicator; data: URIs removed; PDFs rendered as text). mcp_allowed_tools_for_session returns only these two.
  • Tavily backend for both (/search at max_results: 20, search_depth: advanced, no generated answer, no page bodies; /extract in Markdown), reached through Gym's shared aiohttp client (nemo_gym.server_utils.request) rather than the tavily-python SDK. Key pool with failover on 401/432/433, a retry budget per call, and provider response bodies kept out of errors. Credentials stay server-side; the sandbox only receives the per-rollout MCP session token.
  • Ships the upstream blocklist.json byte-exact; its digest is pinned in the server and checked at start (blocklist_sha256: null opts into a different policy file). All seven rule families are enforced with the protocol's semantics: domains (220 rules, exact host or any subdomain after IDNA and lower-casing), url_prefixes (66, scheme and leading www. removed, case ignored), serp_url_patterns (12, anchored at the start of the scheme-less URL), url_patterns (22, applied to queries, URLs, result titles and snippets, fetched titles and Markdown), patterns_case_sensitive (4, as written), answer_title_patterns (5, also tried with trailing | Site / - Site style segments removed) and answer_title_allow_hosts (7, exempt from the title patterns only).
  • Query refusal: site: operands naming a blocked domain (scheme, www. and path stripped first); queries matching the text families; and queries that repeat a verbatim span of the question. Upstream states no span length, so the server refuses 8 consecutive question words (verbatim_span_words, configurable, ge=2), matched on case-folded maximal word runs so punctuation, case and whitespace do not evade it; a question shorter than the threshold is protected whole. The question reaches the server through /seed_session (question_field, default question; the last user message of responses_create_params.input as fallback; an Environment Server's task_data read the same way). Blocked span words are never logged, only their count.
  • Proxy and archive URL decoding before the URL check: up to four rounds of percent-decoding, the path remainder of Wayback (web.archive.org/web/<timestamp>/<url>), archive.org, r.jina.ai and Google cache wrappers, every host-bearing query-string value (?url=, ?u=, ?q=, ...) with or without a scheme, and any https?:// embedded in the URL. The other wrappers upstream names (archive.ph and siblings, translate.goog, 12ft.io, corsproxy.io, ...) are blocked outright by the domains family.
  • Fetched-content checks after the fetch: the final URL the backend reports (a redirect to a blocked host is refused), then the title and the full Markdown against url_patterns and patterns_case_sensitive. A failing page is refused whole and evicted from the cache; cache hits (max_cached_pages, keyed by requested URL) are re-checked under the current policy.
  • Every refusal is logged at WARNING with tool, session, family, rule, location and the first 200 characters of the subject; every dropped search result at INFO in the same form. The model reads a family-level reason, never the rule text.
  • verify is a stub (reward 0, mask_sample: true, explicit failure_reason); grading belongs to the preset's own resources server.

require_seeded_question (fix from review, commit 05f96cdd)

Gym's MCP exposure keeps the plain POST /web_search and POST /web_fetch routes served next to /mcp. A call without the rollout's cookie or token lands in a fresh session with no question, which silently skipped the verbatim-span rule (probe: the same 8-word query was refused with the rollout cookie and served without it). web_search now fails closed on any session that was not seeded with a question (require_seeded_question, default on), logged as family=unseeded_session; a seed without a question is logged at WARNING saying its searches will be refused. require_seeded_question: false serves such sessions without the span rule instead. The other families already applied on the direct routes and web_fetch has no session-dependent rule. The module docstring and both READMEs now describe the enforced behaviour instead of claiming the agent reaches the server only over MCP.

benchmarks/hle_diamond/opencode_hle_tools.yaml (new preset)

Composes benchmarks/hle_diamond/opencode.yaml with hle_web_tools as the agent's only tool_servers entry, network_access: model_and_tools, and an environment note telling the model that external information is available only through web_search and web_fetch. OpenCode names the tools hle_tools_web_search / hle_tools_web_fetch; its native webfetch / websearch stay denied. opencode_search is unchanged and remains the Tavily-native comparison. resources_servers/hle_web_tools/configs/hle_web_tools.yaml is the standalone instance.

Docs: new resources_servers/hle_web_tools/README.md (tools table, per-family semantics, refusals, configuration keys, tests) and a new "Upstream web tools" section in benchmarks/hle_diamond/README.md covering the residual Tavily-backend difference and the pilot below; the Diamond test command now includes the new test file.

Re-seeding guard (second fix from review, commit c6a7defb6)

A sandbox process that could reach the tool server's plain routes might also POST /seed_session again with a different question and so defeat the verbatim-span rule for its own session. The server now refuses to re-seed an already seeded session with another question (the second seed is rejected with an explanatory message and logged), so the question bound at rollout start is the one the span rule enforces for the whole rollout. Residual item for a follow-up: /seed_session itself is unauthenticated in Gym, so a fully authenticated seed channel (an agent-server secret, or MCP-only sessions minted by the agent) is the complete fix; this PR narrows the window without changing the Gym session API.

Validation

Run against c6a7defb6 in the branch worktree's own virtualenv.

pytest resources_servers/hle_web_tools/tests/test_app.py
# 32 passed

The 31 model-free tests stub the Tavily transport and build every rule on entries taken from the shipped upstream blocklist: one test per rule family (domains incl. subdomains; url_prefixes ignoring case, scheme and www.; SERP regexes; url_patterns on queries, result titles and snippets; case-sensitive patterns on fetched content as written; answer-title patterns with allow-hosts and trailing site-name stripping), the site: and verbatim-span query refusals (8 words refused, 7 served, another session's question not applied, question words absent from the log), the fail-closed refusal of a cookie-less POST /web_search after a seed with the backend never called and the opt-out restoring the old behaviour, five archive/proxy wrapper decodings including double encoding, the 60,000-character cap and marker, title/final-URL rendering and data: URI stripping, redirect-to-blocked-host refusal with cache eviction, cache re-check under a changed policy, the exact two-tool list over a real MCP initialize / tools/list exchange, the 20-result request and cap (and max_results=21 rejected by validation), key failover with provider bodies kept out of errors, and the blocklist digest pin (tampered copy rejected, accepted with blocklist_sha256: null).

pytest resources_servers/equivalence_llm_judge/tests/test_hle_diamond.py
# 62 passed

Extended with test_hle_tools_preset_wires_exactly_the_upstream_tool_server (one tool server, MCP exposure on, no per-preset blocklist override, no Tavily resource in the resolved config, environment note names both tools and not Tavily) and the new preset added to the judge-prompt, high-reasoning-effort and local-Docker-override parametrizations. Note for anyone running this locally: the sandboxed-preset cases in this file resolve the sandbox's advertised host through use_absolute_ip and fail with ConfigError: Host ... resolves to ..., which cannot advertise this host to a sandbox on a machine whose hostname resolves to loopback; that is pre-existing (the same 23 cases fail on origin/main there, none of them specific to this branch) and the 62/62 above was produced with the hostname resolving to a routable address.

pre-commit run --files <all 10 changed files>
# end-of-file-fixer, trailing-whitespace, ruff (both), ruff-format, verified-flag and README environment-list hooks: Passed

Both commits carry DCO sign-off; all three new Python files carry the Apache-2.0 SPDX header.

Rollouts

5-row pilot (2026-10-26, 5 HLE-Diamond text rows, GPT-6 Astra as policy, judge o3-mini, local Docker with host networking and ++use_absolute_ip=false, egress unrestricted; comparison infrastructure only):

  • Exit 0; 5/5 rows scored (3 correct); 4/5 rows made tool calls, among them two web_search calls that returned 20 and 16 results with no Tavily error.
  • All 14 captured OpenCode requests carried reasoning_effort: high and offered exactly hle_tools_web_search and hle_tools_web_fetch as MCP tools next to OpenCode's native file and shell tools.
  • Manual probes through the server's MCP endpoint: a web_search in a session seeded with a real question and quoting ten consecutive words of it was refused with the span message and logged as family=question_span rule='8 consecutive words of the question' where=query subject='8 words'; a web_fetch of a Hugging Face dataset page was refused as a blocked site.
  • The fail-closed fix was motivated by a direct probe: the same 8-word query refused with the rollout cookie, served with no cookie and no token before the fix, refused with family=unseeded_session after it.

Reproduce with the Diamond Quickstart's Docker recipe, --benchmark hle_diamond/opencode_hle_tools, and TAVILY_API_KEY exported in the shell that starts the servers. A full 728-row with-tools run has not been made on this branch; the pilot establishes that the preset composes and the tools and refusals work end to end, not a number.

Compatibility and benchmark impact

  • New component: resources_servers/hle_web_tools (server, pinned blocklist, config, README, tests). No existing server, agent or preset is modified; opencode_search and pi_search behave exactly as before. The only edits outside the new directory are the Diamond README section, the new Diamond preset, and the Diamond preset tests.
  • Configuration: the server requires tavily_api_key (one key, a list, or a comma-separated pool), expected from TAVILY_API_KEY in the environment of the process that starts the servers. Ships verified: false. Tunables documented in the server README: blocklist_file_path, blocklist_sha256, verbatim_span_words, question_field, require_seeded_question, max_results (hard-capped at 20), max_fetch_chars, max_query_chars, search_depth / extract_depth, cache sizes, retry budget and timeout.
  • Dependencies: none new. requirements.txt is nemo-gym[dev]; Tavily is reached via nemo_gym.server_utils.request.
  • Benchmark results: hle_diamond/opencode_hle_tools is a new column, not a change to any existing one. It is a comparison, not a reproduction, of the published with-tools column: the blocklist and all refusals now match the protocol (closing the four unenforced and one approximated families of opencode_search), but the backend is Tavily where upstream names no provider, so which pages a query surfaces, their ranking and the page-to-Markdown rendering are Tavily's, and a number from this preset should say so. The harness, sandbox image, text-rows-only and effort-transmission differences recorded in the Diamond README still apply.
  • Security posture of the new server: policy does not depend on transport (every family applies on /mcp and on the plain routes; web_search fails closed on an unseeded session). What the server cannot distinguish is a seed sent by the agent server from one the sandbox sends itself; keeping the sandbox from seeding its own session is the egress policy's job, as discussed under Sandboxed agents in the Diamond README.

Checklist

  • I have read the contributing guidelines.
  • The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs.
  • Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable).
  • Documentation added or updated, or N/A with justification.
  • Pre-commit checks pass locally (pre-commit run --all-files) (so CI lint/format checks pass).
  • New source files include the required Apache-2.0 SPDX header.
  • All commits have DCO sign-off (git commit -s) (so the DCO check passes).

Issue: No Gym issue tracks this server itself. The follow-up for the unauthenticated /seed_session residual is #5845.

Update after review

Five rounds of fixes are on top of c6a7defb6, 62 commits in all (58 commits and 4 merges), and no commit was rewritten:

Round Merge of origin/main Commits after it
1 6a1b075b4 (brought #5177) 13, 3b7ad9f9e through 2500e8539
2 none 19, bcb981593 through e075400a3
3 69c748d08 (brought #5175) 14, 7f08605de through e37e5ac22
4 8b2bb4b9d (main at bd6f5f0d8, 79 commits) 11, 4950cab31 through 02c7cba50
5 45e175e13 (main at 363af5e3e, 42 commits) 1, 7605355e7

Every commit carries a DCO sign-off that matches its author. Thread ids are the review comment ids; a second id is yaoyu-33's reply to a bot finding.

Round 1 (6a1b075b4, then 3b7ad9f9e through 2500e8539)

Change Commit(s) Threads
After the merge of origin/main, which brought #5177, the server imports nemo_gym names from their new public paths (nemo_gym.client, nemo_gym.server_runtime). 6a1b075b4, 3b7ad9f9e none
opencode_reference.yaml and the Diamond README no longer promise that the reference preset switches to hle_web_tools. opencode_hle_tools is the preset that runs it, and running it on the reference image is a follow-up. 498e34bc3 none
The key pool ends the call once every key is rejected. A rejected key no longer spends the retry budget. eb466ecb9 4398612291, 4405607009
A malformed Tavily body is now a tool error, not an HTTP 500. 5142f52df 4405604740
Added the example data that CI validates: 5 synthetic placeholder rows, metrics, and placeholder rollouts, behind a simple_agent and a single_agent_turn_legacy environment server. 47dc1fbda 4405604704
The README says the server must run single-worker. c4262af29 4398612312, 4405607900
More URL spellings are refused (details below this table). a872e7a7b 4405604669, 4405604682, 4405604693, 4398612349, 4405609223, 4398612353, 4405609590, 4405604730
The content check covers the whole fetched page before any cut. Pages above max_page_chars are refused, the heading regex runs in linear time, and the data-URI regex is wider. 465d43de4 4398612308, 4405607598, 4405604713, 4398612357, 4405609949
Episode sessions (an Environment Server's) are bound to their episode and task, fenced on close, and pass check_resources_session_contract. 16cd8c0f5 4398612319, 4405608214, 4398612325, 4405608615
A question with no words counts as no question, so the session fails closed. 6b86a38bb 4405607291 (zero-word seed)
A WARNING is logged when the session cap forgets a question. 12fbd2255 4398612339, 4405608916
The blocklist's MIT provenance is recorded: LICENSE-HLE, an ATTRIBUTIONS.md row, and a README section. 30aa876bd 4398612359, 4405610305
The Diamond README names the sandbox-seeded session residual. 2500e8539 4405604751, 4398612299

The URL spellings that a872e7a7b refuses:

  • url_prefixes and serp_url_patterns are also matched on the canonical form.
  • A backslash, whitespace, a control character or @ in the authority is refused.
  • https:/ is read as a scheme, and every *.archive.org host is a wrapper.
  • URLs are capped at 4,096 characters.
  • Expansion fails closed on overflow and on a fourth decoded form.
  • site: operands are read as hosts only.

Round 2 (bcb981593 through e075400a3)

Change Commit(s) Threads
Added task_data.py, which the core unit tests require for every resources server. It declares question and placeholder. bcb981593 4405604704
Hosts are mapped as UTS #46 fetchers map them (WHATWG and yarl), so sc🄰le.com no longer gets past domains. 9ac597e3a 4405604669
A wrapped URL that Python cannot parse is refused as malformed_url. Browsers read https://[::1]@scale.com/ as scale.com. 00380d451 4405604669
A wrapper's remainder is read as a URL however it is spelled: a trailing dot, userinfo, or full-width letters. 0112487cf 4405604682
A url_prefixes rule with a query also matches its pairs in any order, for example pdf?&id= and pdf?x=1&id=. bb5e802d4 4405604669
Runs of / are collapsed in the canonical form, so arxiv.org//abs/... is refused. 25f0c7f83 4405604669
The span and query checks fold NFKC forms, combining marks and _. Format characters are read both as removed and as a space. 4abb964f4, c7caff3e1, e075400a3 4398612299, 4405607291 (span rule)
The title-separator regex starts only at the first blank of a run, and shown titles are capped at 1,000 characters. The fetched Title: line no longer escapes the 60,000-character cap. e10df7a73 4405604713
A 200 whose body is not JSON (HTML or cut-off JSON) is now a tool error. c134aff87 4405604740
The retry-budget test now fails when a rejection spends an attempt. b4e52d757 4398612291, 4405607009
An episode session forgotten by the cap is fenced, so a later seed of its ID gets 409. 23d9c4d80 4398612339, 4405608916
Tests now cover three cases: the live-session close conflict, the binding release on close, and a seed whose last message has no words. d7263dcc7 4398612319, 4398612325, 4405607291
A site: operand that is not shaped like a hostname is refused. Trailing punctuation is dropped first. e01263f35 4405604730
data:;base64, URIs without a media type are now stripped. The README states the parameter bound and where the payload ends. 8b95221d7 4398612357, 4405609949
num_workers > 1 is refused through multiple_workers_unsupported_reason, before uvicorn starts and in dry runs. 5f61af08b 4398612312, 4405607900
Page checks run in a pool of up to two spawn worker processes. re holds the GIL, so the earlier to_thread still stalled the event loop for about 4 s per adversarial 1M-character page. The web_fetch stall is now 0.02 s. b132980c8 4398612308, 4405607598, 4405604713
The Diamond README lists the oversized-page refusal as a third residual. The README's redirect claim is marked as unverified against the live API. 77d3f0f5a 4405604751, 4405604682

Round 3 (69c748d08, then 7f08605de through e37e5ac22)

The merge brought #5175. Its conflicts were resolved as follows:

  • ATTRIBUTIONS.md: main's rows kept, and the blocklist row appended.
  • Diamond README: both new sections kept. opencode_hle_tools was added to the Scope table, the preset lists, the effort-inheritance note, the harness-validation list and the Rows departure. The Web tools and Leakage policy departures were scoped to the Tavily presets.
  • test_hle_diamond.py: both sides' parametrizations kept.
Change Commit(s) Threads
Merged origin/main again, resolving the conflicts listed above. 69c748d08 review-5689087895 (merge order)
The tests import their helpers from the moved nemo_gym.server_runtime paths. 7f08605de none
Fixed two core unit tests, which arrived or changed with that merge and failed on this branch's files. maybe_auto_expose is now imported from nemo_gym.server_runtime, and the CI environment server names its resources_server. 5742b1e5b review-5689087895 (unit tests)
429 then 200 rotates to the next key after a backoff, and every response is released. Both are now asserted. 5a3b24abb 4398612291
An episode seed of a live session for another task gets 409, and this is now tested. a4e927aa7 4398612319
A Wayback path with no timestamp is read as naming its target. archive.org redirects web.archive.org/web/scale.com/leaderboard to a snapshot. fbe894843 4405604682
Typographic quotes and guillemets around a site: operand are read like ASCII quotes, and stacked openers are allowed. Before, site:“scale.com” became a punycode host that matched nothing. 324f2ff20 4405604730
Every default-ignorable character (Hangul fillers, variation selectors) is folded. A third reading treats a zero-width space as a word break and removes every other ignorable, so a zero-width space between words mixed with a soft hyphen inside one is caught. ed904135b 4398612299 (span rule)
The canonical URL form is also taken with slash runs collapsed before dot segments, as nginx does (arxiv.org/abs/x//%2e%2e/2605.02442). d4d3b3d9b 4405604669
A title's site-name separator after a long blank run is found again despite the 1,000-character display cap. 485a835fd 4405604713
The README now states two things: when the session cap forgets a running rollout (OpenCode never closes its tool sessions), and that a forgotten agent-run session is not fenced. 0cd8d9c4e 4398612339, review-5680046430
The README and the regex comment state every bound of the data-URI regex. b0fb98886 4398612357
The README states the page-check pool's cost: each worker is about the server's size, and the first fetch waits about 2 s. It also states that web_search's per-result checks still run on the event loop. d199b82a3 4398612308
The README lists tavily_base_url, quotes the multi-worker refusal with the instance's own name, and says the key is needed only for live preset runs. 50042dc2d none
The Diamond README's sandbox-seeded residual also names sessions the cap has forgotten. e37e5ac22 4398612339

Round 4 (8b2bb4b9d, then 4950cab31 through 02c7cba50)

The merge brings main up to bd6f5f0d8, 79 commits since the last merge. No file had a textual conflict. The root README.md environment table merged cleanly; to be sure the row is generated, the table was reset to main's version and regenerated with scripts/update_env_list.py, and the only difference from main is the Hle Web Tools row. Two of main's changes required follow-up commits:

Change Commit(s) Threads
Merged origin/main at bd6f5f0d8. 8b2bb4b9d review-5689087895 (merge order)
The server uses main's split session helpers: ResourcesSessionLocks.locked() for one seed or close of an ID at a time, and ResourcesSessionFences (raise_if_fenced, get, fence) in place of the old raise_if_closed, closed_episode and mark_closed. Behaviour is unchanged. 4950cab31 4398612319, 4398612325
requirements.txt is replaced by pyproject.toml (the shared uv policy, nemo-gym[dev] and idna>=3.7) and uv.lock. The lock was seeded from the calendar server's lock, which has the same Gym dependencies, so it pins the same versions as the other component locks (idna 3.10, mcp 1.29.0) rather than a fresh resolve that moved mcp, fastapi and others to new releases. 60963f0d0 4405604704
A Wayback first segment that is timestamp-shaped (20240101000000, 2024id_, 2024*, *) is read as a timestamp only. Since fbe894843, every snapshot had also yielded https://<timestamp>/<url>, which names no page, so each layer spent extra candidates and decode rounds, and four timestamped layers around a percent-encoded page were refused as malformed_url. That URL is a table row as served, and a plain snapshot is back to two candidates. 912f26382 4405604682
A question shorter than the span threshold is protected as a whole in each ignorable-character reading. Each reading now has its own span length, checked longest first, and the refusal names the matched length. Before, a one-word question with a variation selector or zero-width space inside the word had fragments of that word blocked on their own in the "space" reading. 6715b072d 4398612299 (span rule)
When a title is capped, the shown text without its cut marker is also checked, so an answer phrase ending exactly at the 1,000-character cut, or a | Site separator starting exactly there, is caught. 53c568a4b 4405604713
The README's cap sentence counts exactly: a rollout's question is forgotten once 10,000 later sessions are seeded on the same server while it is running. b982314c0 4398612339
The README and the app.py comments describe the word-break reading as the server's own, crediting UAX #29 only for format and extend characters and noting that Hangul fillers are letters to UAX #29 and are dropped here as NFKC_Casefold drops them. 5199b2014 4398612299 (span rule)
The site: test table says why the stray-closer row (site:scale.com” leaderboard) exists (it alone catches a balanced-pair implementation) and drops a duplicate Hangul-filler row. ac46c2f58 4405604730
Session code, tests and READMEs use main's glossary (#5083, AGENTS.md): episode seed and episode session, agent-run seed, close retry window, release. The 422 detail is now invalid episode seed: ..., and the contract test is test_episode_sessions_follow_the_resources_session_contract. The README also names the checkpoint controller's retire of an attempt (retire_session_state) as a release path next to /close_session. 83c2e5a75 4398612319, 4398612339
A nested Wayback fixture wrapped to the 119-column limit. becc2d49c none
Both READMEs link the seed-channel residual to its tracking issue, #5845, in place of the placeholder. 02c7cba50 4398612299, review-5680046430

Points from the merge worth a reviewer's eye, none of which changes the PR's behaviour:

Round 5 (45e175e13, then 7605355e7)

The merge brings main up to 363af5e3e, 42 commits since the last merge. No file had a textual conflict. The root README.md environment table auto-merged, and regenerating it with scripts/update_env_list.py reproduced it byte for byte, so the only difference from main's table is the Hle Web Tools row. No test failed because of the merge and no code change was needed. One follow-up commit corrects documentation that main's changes had made inaccurate:

Change Commit(s) Threads
Merged origin/main at 363af5e3e. 45e175e13 review-5689087895 (merge order)
The README and multiple_workers_unsupported_reason give the true reason the server refuses num_workers > 1. The old text said a rollout's seed and its searches could reach different workers; session routing pins a resources request by its cookie's session_id, and an MCP call by its token's sid, to the owning worker, and #5709's add-benchmark skill now says so. What does stop several workers: app.py defines no module-level app for uvicorn workers, and the URL-keyed page cache and the page-check pool are per process. The refusal test asserts the new reason and the absence of the old one. Behaviour is unchanged. 7605355e7 4398612312, 4405607900

Points from the merge worth a reviewer's eye, none of which changes the PR's behaviour:

  • feat(sessions): centralize resources lifecycle and verification ownership #5709 (centralize resources lifecycle and verification ownership) adds an opt-in hook lifecycle to SimpleResourcesServer (has_session_state, initialize_session_state, release_session_state, seed_request_model, verifying(), ResourcesVerification) and keeps custom seed_session and close_resources_session overrides registered unchanged. No resources server on main implements release_session_state yet, so there is no migrated pattern to follow, and this server keeps its override. Its private attributes do not collide with the new base attributes (example_single_tool_call had to rename _session_episodes; this server did not). The new conformance assertion (a close from another episode gets 409 and releases nothing) and the new repository rule (a seed override that adds release_session_state without a close must call super().seed_session) both pass here. Two design questions for the maintainers: the skill now tells stateful servers to express their lifecycle through the hooks and override seed/close only when the hooks cannot (the question-digest re-seed rule, agent-run seeds and cap-based forgetting could plausibly move to the hooks); and the base now labels the cookie-based /seed_session path, which is how opencode_hle_tools seeds, deprecated, while this server's own override emits no such warning. The README's session statements stay true of the shipped preset.
  • feat(env): grant MCP tools of extra tool servers to session agents #5551 (grant MCP tools of extra tool servers to session agents) changes environment_servers/single_agent_turn and BaseResponsesAPIAgentConfig only. The preset binds opencode_sandboxed_agent with tool_servers: [hle_tools] and expose_tools_over_mcp: true under single_agent_turn_legacy, so nothing here changes. The new session path seeds tool servers with a ResourcesSeedSessionRequest carrying task_data, which this server already reads, so it is forward-compatible. feat(env): grant MCP tools of extra tool servers to session agents #5551's own message says the HLE search presets stayed on the deprecated sandboxed agents for lack of a session path; that path now exists (single_agent_turn + opencode_agent + tool_servers), so rebuilding opencode_hle_tools on it is a reasonable follow-up request.
  • fix(benchmarks): bound the HLE agent loop with max_steps 1 #5763 bounds benchmarks/hle/config.yaml with max_steps: 1. benchmarks/hle_diamond has no max_steps key and references benchmarks/hle only for prompts/judge.txt, which is unchanged. Its simple_agent instances therefore run with max_steps unset, which only matters if that judge-backed agent is ever given tools (it serves none); setting max_steps: 1 there for consistency is an optional follow-up.
  • feat(cli): report each entry's resources and agent servers by one rule in gym list environments #5446 and feat(cli): include entry paths in gym list environments --json #5392 (gym list environments by one rule, entry paths in --json): gym list benchmarks | grep hle_diamond returns the six entries that benchmarks/hle_diamond/README.md documents. opencode_hle_tools and the other presets that extend another preset without redeclaring the dataset are not listed, as that README already says; main's opencode_search behaves the same.
  • fix(configs): grant no tools from judge servers that serve none #5590 removed resources_tool_transports: [direct_http] from the judge configs as unnecessary for servers that serve no tools. benchmarks/hle_diamond/text.yaml still sets it on its single_agent_turn_legacy; the field exists and is harmless, and dropping it to follow main is a design question, not a merge fix.
  • fix: name the failure kind of masked samples (conversational_tool_use_simulation, opencode_search) #5688 changes failure_kind reporting in conversational_tool_use_simulation and opencode_search only; no overlap.

Round 6 (6c16b9256, then ffdaa5f9f and 19001a48f)

The merge brings main up to eb3f77dc9 (151 commits since the last merge). Three files had textual conflicts: the root README.md (environment table, regenerated with scripts/update_env_list.py; the only difference from main's table is the Hle Web Tools row), benchmarks/hle_diamond/README.md, and resources_servers/equivalence_llm_judge/tests/test_hle_diamond.py. In each, main's text and tests are kept verbatim and this PR's additions re-applied. The hle_web_tools lock was already fresh against main's pins.

Main's #5702 moved the HLE-Diamond text presets to opencode_agent and pi_agent agent sessions and renamed the relay presets *_legacy_agent.yaml. This PR's preset followed in two commits rather than staying on the deprecated relay, which answers the design question raised in Round 4 (#5550 bullet):

Change Commit(s) Threads
Merged origin/main at eb3f77dc9. The preset was temporarily repointed at opencode_legacy_agent.yaml so it kept composing, since opencode.yaml now defines opencode_agent. 6c16b9256 none
hle_diamond/opencode_hle_tools now extends opencode.yaml and runs as an opencode_agent session under the benchmark's single_agent_turn_legacy Environment Server, modelled on opencode_search.yaml. The Environment Server seeds hle_tools per episode (the question arrives in task_data) and grants web_search and web_fetch over MCP from the agent's tool_servers. Session knobs match opencode_search exactly: network_access: model_and_tools, absolute_ip_server_types: [responses_api_models, resources_servers], mcp_tool_timeout_seconds: 300, the environment note as system_prompt. Reasoning effort travels on the model server's extra_body; the OpenCode reasoningEffort option and the /tmp/nemo-gym-environment.txt note are gone. sandbox_docker_local.yaml composes with the preset again; its opencode_agent note now says "web search and browsing tools" instead of naming Tavily. Tests: the preset left LEGACY_PRESETS and joined the agent-session parametrisations; a new wiring test asserts the agent equals opencode_search's on every key except tool_servers and system_prompt, and fails on each reverted field (checked by mutation). No server code changed. ffdaa5f9f none
READMEs and config headers describe the preset as an agent-session preset; the 2026-10-26 five-row Docker pilot is marked as having run on the relay harness, and no with-tools number is quoted until a pilot is rerun on the session harness. The residual-difference statements (unauthenticated /seed_session reachable under model_and_tools, #5845) are unchanged. 19001a48f none

Validation at 19001a48f, in the worktree's own virtualenv (uv 0.13.4), with transports stubbed and no live Tavily or model calls:

  • pytest resources_servers/hle_web_tools/tests: 110 passed; CI form ng_test +entrypoint=resources_servers/hle_web_tools +delete_venvs_after_each_test=true +should_validate_data=true: exit 0, 110 passed, data validated.
  • resources_servers/equivalence_llm_judge/tests: 204 passed with the hostname shim (test_hle_diamond.py alone: 108 passed, including the migrated preset in the agent-session, Docker-override and documented-command cases).
  • tavily_search HLE exclusions and harness-overlay tests: 53 passed. Config dry render of the preset alone and composed with sandbox_docker_local.yaml matches opencode_search.yaml field for field except tool_servers and the note. In-process smoke: an Environment-Server seed (ResourcesSeedSessionRequest with task_data) returns the MCP grant, and tools/list over /mcp with that token advertises exactly web_fetch and web_search.
  • scripts/component_locks.py: 319 projects, 0 failed; uv lock --check unchanged. pre-commit run --from-ref origin/main --to-ref HEAD and the CI detect-secrets command: exit 0. Every commit carries the author's Signed-off-by.

Decisions

  • Placeholder data: CI example data follows the tavily_search precedent: 5 synthetic rows and <PLACEHOLDER ROW> rollouts, because a real rollout needs a policy model and a Tavily key.
    • Each row keeps a placeholder key that says it is synthetic and not an HLE item. task_data.py declares that key (consumed_by: provenance), and the server never reads it.
    • Regenerating example_metrics.json with gym dataset collate ... +mode=example_validation reproduces the committed file exactly.
  • Single worker: the server refuses num_workers > 1 with " needs num_workers=1: the module defines no module-level app for uvicorn workers, and the page cache and page-check pool are per process" (for example, hle_tools in the Diamond preset). A worker app footer is deliberately not added. Session-keyed state would be routed to its owning worker, so it is not the reason; the per-process page cache and page-check pool are, since each worker would fetch, scan and cache its own copy of a page (7605355e7).
  • Page-check pool: each server process creates its page-check pool, a ProcessPoolExecutor with the spawn context, on the first page check. The pool starts worker processes on demand, up to two. These need the entrypoint's __main__ guard, which app.py has.
  • Episode sessions: an Environment Server's episode seed is bound to its episode and task, serialized by ResourcesSessionLocks and fenced after close in ResourcesSessionFences. Agent-run seeds, which OpenCode sends, are neither bound nor fenced.
  • Dependencies: the server declares nemo-gym[dev] and idna>=3.7 in resources_servers/hle_web_tools/pyproject.toml, with the shared uv policy that scripts/component_locks.py manages, and commits uv.lock. The lock pins the versions the other component locks pin.
  • Reference preset: opencode_reference stays on the Tavily search tools in this PR. Running hle_web_tools on the reference image, with its egress policy, is a follow-up.
  • License: blocklist.json is a byte-exact copy of upstream docs/blocklist.json at 22ed3074, which is MIT-licensed (Copyright (c) 2025 centerforaisafety).
    • The notice is reproduced in resources_servers/hle_web_tools/LICENSE-HLE and listed under Vendored Components in ATTRIBUTIONS.md.
    • The rest of the server is Apache-2.0.
  • Residuals that a with-tools number should state (Diamond README, Upstream web tools):
    1. Tavily as the backend.
    2. Sandbox-seeded sessions: /seed_session is unauthenticated. This covers a fresh session and one the session cap has forgotten. It is tracked in hle_web_tools: authenticate /seed_session so a sandbox cannot seed its own session #5845.
    3. A page above 1,000,000 characters is refused, where upstream would serve its first 60,000.

Not changed (follow-ups)

  • Authenticated seed channel: deferred to hle_web_tools: authenticate /seed_session so a sandbox cannot seed its own session #5845. That issue also covers these related items:
    • a per-seed size bound for very large questions, and a digest-only comparison on a retried seed;
    • a forgotten agent-run session, or a closed episode session's ID, which takes an agent-run re-seed through its cookie (main's SWE servers refuse the latter with 409, a check this server could adopt);
    • an unauthenticated seed flood past the session cap.
  • Live /extract redirect check: no live Tavily call was made. The README says the final-URL check relies on results[].url reporting the post-redirect URL.
  • Gaps in the pinned upstream list: export.arxiv.org, and the /format/, /src/ and /e-print/ paths of 2605.02442. These are gaps in the list itself, not in how this server matches it.
  • Spellings that are not folded: look-alike letters from another script (a Cyrillic о), and words run together. Result titles are checked as the provider sends them, not NFKC-folded, so a full-width bar (|) is not a site-name separator.
  • site: operands in CJK brackets or followed by CJK punctuation (site:「scale.com」, site:scale.com、) are punycoded into hostname-shaped labels and pass the operand check; the results of such a query are still filtered per URL, title and snippet, so no blocked-domain result reaches the model. Wayback URL-listing forms (/web/*/host*, CDX and timemap queries) and a doubled leading slash before /web/ are likewise not unwrapped; the fetched text is still checked. These predate the review rounds and are candidates for a follow-up.
  • Over-refusals: two ordinary inputs are refused, and the model can retry with another spelling. One is a query value that names a blocked host (?utm_source=twitter.com). The other is a raw space in a URL.
  • Session cap and auxiliary sessions: OpenCode does not close its tool sessions, so a running rollout is forgotten once 10,000 later sessions are seeded on the same server. A Diamond text run seeds 728. The cap counts sessions rather than bytes. Admission control in place of eviction, and closing auxiliary tool sessions in the harness, are both deferred.
  • web_search result checks on the event loop: a provider title or snippet of 1M CJK characters holds the loop for about 4 s. We have not verified whether Tavily returns anything that long. So this is documented rather than given a pool round trip per search.
  • Answer phrases past the title cap: suppose an answer phrase lies wholly past the 1,000-character display cut of a result title. It is neither shown nor checked against answer_title_patterns.
  • Session terminology elsewhere: the Diamond README keeps "sandbox-seeded sessions" and "typed" no longer appears in the server's own files, except the ![untyped] alt text of a data-URI test fixture; no lint enforces the glossary.

Superseded statements in the description above

  • Dependencies: this PR does add one. resources_servers/hle_web_tools/pyproject.toml declares idna>=3.7 for the UTS Add Workbench validation dataset #46 host mapping (9ac597e3a, moved from requirements.txt in 60963f0d0), and the committed uv.lock pins 3.10, as the root lock does. Tavily is reached through nemo_gym.client.http_client.request, not nemo_gym.server_utils.request.
  • Edits outside the new directory: the description lists the Diamond README section, the new Diamond preset and the Diamond preset tests. The branch also edits these files:
    • ATTRIBUTIONS.md, for the vendored blocklist row;
    • the root README.md, for the environment list;
    • benchmarks/hle_diamond/opencode_reference.yaml, a comment.
  • Security posture: the egress policy cannot keep the sandbox from seeding its own session. network_access: model_and_tools admits the whole tool-server host, so closing the gap needs an authenticated seed channel (hle_web_tools: authenticate /seed_session so a sandbox cannot seed its own session #5845). Both READMEs say so.
  • Benchmark results: a number from this preset should state three residuals, not only the Tavily backend. They are the backend, sandbox-seeded sessions, and the refusal of pages above 1,000,000 characters (Diamond README, Upstream web tools).
  • Counts: the description's Validation section was measured at c6a7defb6: 31/32 tests, 62 Diamond tests and "10 changed files". The branch now changes 19 files against 363af5e3e (the 18 of round 3, plus pyproject.toml and uv.lock in place of requirements.txt). Current counts are below.
  • Commit notes: the description cites 05f96cdd and c6a7defb6 as the review fixes. They are now followed by the five rounds above.

Rollouts

No rollout was run at this head. The 5-row pilot in the description (2026-10-26) predates c6a7defb6 and every review fix, including:

  • the page-check worker processes;
  • the oversized-page refusal;
  • session fencing;
  • the URL-policy changes.

It was not rerun because a live run needs a policy model and a Tavily key, and the model-free tests below cover this round's changes. Rerun the 5-row Docker pilot, with at least one web_fetch, before quoting any with-tools number.

Validation at 7605355e7

The checks ran in the worktree's own virtualenv (uv 0.13.4, which the root pyproject.toml requires), refreshed after the merge, whose nemo_gym resolves inside the worktree. There were no live Tavily or model calls; transports were stubbed. If more commits, or a merge of origin/main, land before the push, rerun them at the pushed head.

Server tests and data validation

  • pytest resources_servers/hle_web_tools/tests: 110 passed (32 at c6a7defb6, 107 at e37e5ac22), in each of three runs. Each run starts the page-check workers and leaves no worker process behind. Round 5 changes the assertion of one existing test (test_a_launch_with_several_workers_is_refused checks the new refusal reason and the absence of the old one) and adds none.
  • CI changed-server step, ng_test +entrypoint=resources_servers/hle_web_tools +delete_venvs_after_each_test=true +should_validate_data=true: exit 0, 110 passed, "The data for resources_servers/hle_web_tools has been successfully validated!". The server's venv was created from the committed uv.lock.
  • resources_servers/equivalence_llm_judge/tests: 146 passed with a test shim that makes the hostname resolve to a routable address. tests/test_hle_diamond.py alone gives 73 passed with the shim, and 40 passed / 33 failed without it.
    • All 33 failures are ConfigError: Host ... resolves to 127.0.1.1, which cannot advertise this host to a sandbox, from this workstation's loopback hostname, and nothing else fails.

Core unit tests

  • Core unit tests that enumerate resources servers, benchmarks or repository files: tests/unit_tests/data/test_task_data.py, test_public_api_facades.py, tooling/test_add_legacy_agent_environment_servers.py, tooling/test_component_dependencies.py and test_session_contract_repo.py give 1,431 passed (1,416 before the round-5 merge; main added cases). environment/test_benchmarks.py gives 85 passed with the hostname shim (it includes test_every_repo_benchmark_appears_in_listing, which hits the loopback ConfigError without it). test_session_contract_repo.py includes feat(sessions): centralize resources lifecycle and verification ownership #5709's new rule for seed overrides.
  • responses_api_agents/opencode_sandboxed_agent tests: 166 passed and 2 skipped. The 2 skipped tests need Node.js for the OpenCode extension and plugin hooks.
  • Full core suite (pytest tests/unit_tests -m "not sandbox" -n 8), on this head and on a clean export of main 363af5e3e with the same virtualenv (nemo_gym verified to import from the export):
    • This head: 19,224 passed, 47 failed (45 test IDs), 213 skipped, 5 collection errors. Main: 19,212 passed, 57 failed (55 test IDs), 213 skipped, 5 collection errors.
    • The 5 collection errors are the missing optional mlflow and cloudpickle packages, on both.
    • 42 of the 45 failed test IDs fail identically on main: missing optional extras (mlflow, wandb, cloudpickle, jinja2), the loopback ConfigError, and tests that build real component environments with uv or exercise the resubmit fixtures.
    • The other 3 are harbor tests that read endpoint settings from a git-ignored local file in the checkout. All 3 pass on a clean export of this head, and main's export has no such file.
    • Main's 13 extra failures: 11 come from git ls-files and git rev-parse in a non-git export, and 2 are timing-sensitive collection tests that pass on this head and touch nothing this PR changes.
    • No failure is caused by this branch.
  • CI jobs this PR triggers: scripts/component_locks.py checks 276 managed projects with 0 failed (the component_locks job), and uv lock --check in the server directory resolves its lock unchanged. The harness-conformance tooling tests (121) pass, and the harness-conformance selector picks no harness for this PR's paths. scripts/migrate_imports.py --check on the PR's paths reports nothing.

Lint, secrets and sign-off

  • pre-commit: pre-commit run --files on the 19 changed files and pre-commit run --all-files both exit 0, with no file changes. The guardwords hook was skipped because its private catalog is unavailable.
  • CI detect-secrets (git diff --name-only --diff-filter=d --merge-base origin/main -z | xargs -0 detect-secrets-hook --baseline .github/workflows/config/.secrets.baseline), over the 19 files including uv.lock: exit 0, no findings.
  • DCO: all 62 commits after the published head (58 commits and 4 merges) carry a Signed-off-by matching their author.
  • Test necessity: each new or changed test was shown to fail on the code before its fix, or on the named mutant, and to pass after. The commit messages record this evidence.

🤖 Generated with Claude Code

rimashahbazyan and others added 3 commits October 26, 2026 15:36
… blocklist over MCP

Add resources_servers/hle_web_tools, a tool server that implements section 3 of
centerforaisafety/hle docs/evaluation-with-tools.md (commit 22ed307): exactly two
MCP tools, web_search (at most 20 results) and web_fetch (Markdown capped at
60,000 characters with a truncation indicator, no media payloads), with Tavily as
the search and extraction backend and the keys held server-side. The pinned
upstream docs/blocklist.json is shipped byte-exact and digest-checked at start;
all seven rule families are enforced with the protocol's semantics, plus query
refusal for blocked site: domains and verbatim question spans (8 consecutive
words, configurable; the question arrives through /seed_session), fetch-URL
checks after percent-decoding archive and proxy wrappers, title-and-Markdown
re-checks of fetched and cached pages, and a log line per blocked call naming
the family and rule.

Add benchmarks/hle_diamond/opencode_hle_tools.yaml, the OpenCode preset with this
server as its only tool server, document it and the residual Tavily-backend
difference in the Diamond README, and extend the Diamond preset tests to it.

Signed-off-by: Rima Shahbazyan <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…uestion

The plain POST /web_search route stays served next to /mcp under Gym's MCP
exposure, and a call without the rollout's cookie or token lands in a fresh
session that carries no question, so the verbatim-span rule was silently
skipped (probe: the same 8-word query refused with the rollout cookie, served
with no cookie and no token). Fail closed instead: web_search refuses any
session that was not seeded with a question under the new
require_seeded_question flag (default on), logged as family=unseeded_session;
a seed without a question says its searches will be refused. The other
families already applied on the direct route, and web_fetch has no
session-dependent rule.

Add the model-free test (seed, then a cookie-less POST /web_search is refused
and the backend is never called; the flag off restores the old behaviour),
and reword the module docstring and both READMEs to describe the enforced
behaviour rather than claiming the agent reaches the server only over MCP.

Signed-off-by: Rima Shahbazyan <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
…uestion

A session now keeps the question it was seeded with: a retried seed with the
same words is served again, a seed that would change or drop the question
answers HTTP 409 (ResourcesSessionConflictError), so a caller holding a
session cannot swap the verbatim-span check out from under it. QuestionSpans
keeps a SHA-256 of the normalized words, never the text, to tell the two
apart.

This does not close the fresh-session path: /seed_session is unauthenticated
and network_access model_and_tools admits the whole tool-server host, so a
sandbox can seed a new session with a question of its choice and search from
it without the span rule. The server README and the opencode_reference.yaml
header now state that residual and what closing it needs (an authenticated
seed channel the sandbox never sees).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
(cherry picked from commit 27187af4bc522d498ca64039b14570f41434aae2)
@copy-pr-bot

copy-pr-bot Bot commented Oct 28, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers feature New capabilities, enhancements, or enablement work labels Oct 28, 2026

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HOLD

Found one BLOCKER, nine RISK findings, and one provenance NOTE. The blocker can freeze the tool-server worker when a single configured key is rejected or its quota expires.

Completed the broad review across all 10 changed files and their affected session, MCP, HTTP, configuration, and harness paths. The unseeded-search and same-session reseeding guards are present, but fresh-session seeding still bypasses the question policy. Review was static: I did not execute tests or reproduce the reported smoke rollouts. Suggested code and proposed checks below require author verification.

Note: formal approval is not available for this request, so this review is posted as a comment only.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

Comment thread resources_servers/hle_web_tools/app.py Outdated
return await response.json()
if response.status in TAVILY_KEY_REJECTED_CODES:
rejected.add(key)
if len(rejected) < len(keys):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BLOCKER — Exhausting the key pool freezes the event loop

Failure: With the documented single-key configuration, let Tavily return 401, 432, or 433. This branch records the only key as rejected but does not exit. After backoff, the next attempt spins forever in while keys[key_index] in rejected, without an await. That blocks every rollout and health request on this worker; neither the HTTP timeout nor the attempt budget can interrupt it. Duplicate configured keys cause the same problem because the rejected set is compared with the list length. See the complete retry path.

Correction: Could you replace the rejected-status branch at lines 487–491 with the following? The invariant is that another selection occurs only when a distinct eligible key remains and the attempt budget permits it.

if response.status in TAVILY_KEY_REJECTED_CODES:
    rejected.add(key)
    if len(rejected) == len(set(keys)) or attempt + 1 == self.max_attempts:
        raise RuntimeError(
            f"Tavily HTTP {response.status} on {endpoint} after {attempt + 1} attempts"
        )
    key_index = (key_index + 1) % len(keys)
    continue

Preservation / acceptance: Proposed regressions: one invalid key, two identical invalid keys, and two distinct invalid keys must terminate with a sanitized RuntimeError. Inspect the selector invariant statically too: an asyncio timeout cannot interrupt this synchronous spin. Retain the existing 401→200 failover assertions: key-one then key-two succeeds, rejected bodies are not read, and HTTP 400 exposes no body. Also check 429→200 still rotates with backoff and all obtained responses are released. This replacement is source-reasoned, not executed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced independently: a single key answering 401 or 432, two identical keys, and two distinct keys all hang in while keys[key_index] in rejected, while one key answering 429 still ends with a RuntimeError after 3 attempts. One more thing the fix could cover: the continue at L491 consumes an attempt despite its "same attempt budget" comment, so a pool [bad1, bad2, bad3, good] with max_attempts=3 fails without ever trying good (the patch above keeps that). Iterating distinct keys separately from the transient-retry budget, and raising once every key is rejected as tavily_search does, handles both; a regression test needs signal.alarm, since an asyncio timeout cannot interrupt the synchronous loop.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in eb466ecb9 (end the Tavily call when every key is rejected). Distinct keys are now iterated separately from the transient-retry budget. A key Tavily rejects (401, 432, 433) is skipped for the rest of the call at once, with no backoff and without spending an attempt. The call raises a sanitized RuntimeError once every distinct key is rejected, and a key listed twice counts once. So [bad1, bad2, bad3, good] with max_attempts=3 reaches good.

An asyncio timeout cannot interrupt the synchronous spin, so the key-pool tests run under a signal.alarm deadline:

  • test_every_key_rejected_ends_the_call_without_backoff covers one key at 401, at 432 and at 433, two identical keys, and two distinct keys. Each ends with "every configured key was rejected", with no backoff and no provider body in the error.
  • test_rejected_keys_do_not_spend_the_retry_budget was made stricter in b4e52d757 (make the retry-budget test fail when a rejection spends it). It uses two keys and two attempts, and Tavily answers 401, 429, then 200. The call must succeed after trying key-one, key-two, key-two. The test fails on the pre-fix code, on a mutant where a rejection spends an attempt, and on one where key selection no longer wraps round to the current key.
  • test_rejected_key_fails_over_and_provider_bodies_stay_private keeps the 401→200 failover assertions: key-one then key-two, the rejected body is not read, and an HTTP 400 exposes no body. 5a3b24abb (pin key rotation after a 429 and the release of every response) adds a 429→200 case to it: the call rotates to the next key after one backoff, and both responses are released. The test fails on a mutant that retries the same key after a 429, and on one that releases only 200 responses.

Comment thread resources_servers/hle_web_tools/app.py Outdated
self, request: Request, body: HLEWebToolsSeedSessionRequest
) -> ResourcesSeedSessionResponse | BaseSeedSessionResponse:
session_id = request.session[SESSION_ID_KEY]
question = extract_question(body.model_dump(), self.config.question_field)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RISK — A fresh seed still bypasses the rollout's question policy

Failure: From the sandbox, POST /seed_session without its existing cookie and with {"question":"unrelated neutral words"}, then use the returned cookie or MCP token to search eight consecutive words of the actual question. This handler accepts the replacement question and the search reaches Tavily. The new preset admits the tool-server host, and the network helper restricts hosts, not paths. The component README acknowledges this reachable bypass. It remains a benchmark-policy correctness gap, not demonstrated credential or tenant compromise.

Correction: Could initial seeding require authentication held only by the host-side agent? Validate it before installing question state or minting MCP access. Pass it through the host-side seed_mcp_servers caller, without placing it in sandbox files, environment, or MCP headers. The invariant is that the sandbox cannot choose the question bound to a searchable session. The inspected source does not establish that authentication API, so an exact patch would be speculative.

Preservation / acceptance: Proposed checks: an unauthenticated fresh seed from a second client returns 401/403 and obtains no searchable session; a trusted initial seed still permits unrelated queries and refuses eight original-question words through MCP and plain HTTP. Preserve normalized same-question retries, 409 on changed/dropped questions, seven-word allowance, other-session isolation, the two-tool token, and the explicit require_seeded_question: false opt-out for unseeded searches. These checks were not executed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed; this matches the residual the README already discloses, and since it bears on how the new with-tools column can be read, a tracking issue linked from there would help. Two notes for that follow-up: the session and MCP-token signing key is derived from public config (get_session_middleware_key), so an authenticated seed needs a real secret rather than that key. And in the meantime, a seed whose question has no words ({"question": "?!"} or an empty input) is stored as seeded with a zero-length span (L410-L417), so returning None there would keep such seeds in the fail-closed path.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not closed in this PR, by design. Closing it needs an authenticated seed channel, meaning a secret that the agent server holds and the sandbox never sees. It also needs a real signing secret in place of get_session_middleware_key. Both go in a tracking issue, #5845, which carries the acceptance checks from this thread, and both READMEs link to it. The server README names the residual in its own paragraph. The Diamond README lists it as one of three residuals that a with-tools number from this preset should state: 2500e8539 (name the sandbox-seeded session residual) and 77d3f0f5a (list the oversized-page refusal as a third residual).

On your zero-word note: a question with no words now counts as no question. That covers "?!", an empty field, and an empty user message. The session stays unseeded, and its searches fail closed over plain HTTP and over MCP (6b86a38bb, treat a question with no words as no question). d7263dcc7 (cover the live-session close conflict and the wordless fallback) adds a test for a wordless last user message with no question field.

Separately, the span rule now folds more spellings of the question's words: full-width, zero-width, accented and underscore-joined forms (4abb964f4, fold Unicode presentation variants before query checks; e075400a3, read format characters both as removed and as a space). ed904135b (fold every default-ignorable character and read ZWSP as a word break) also folds Hangul fillers and variation selectors. It adds a third reading in which a zero-width space separates words and every other ignorable is removed, which is how UAX #29 reads format and extend characters; that catches a zero-width space between words mixed with a soft hyphen inside a word. 6715b072d (protect a short question whole in every ignorable reading) then gives each reading its own span length, so a question shorter than the threshold is protected as a whole in all three readings and a reading that splits a word at an ignorable character never blocks a fragment of it on its own. The test seeds a one-word question in two spellings, serves a query that repeats one fragment, and refuses the whole question in each spelling.

Comment thread resources_servers/hle_web_tools/app.py Outdated
return WebFetchResponse(text=f"Fetch failed for {url}{detail}", truncated=False, refused=False)
result = results[0]
markdown = _DATA_URI_RE.sub("[data URI removed]", str(result["raw_content"]))
markdown = markdown[: self.config.max_cached_page_chars]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RISK — Cache truncation removes policy evidence before validation

Failure: Stub extraction for an allowed URL with raw_content = "x" * 500_001 + " HLE answers". The shipped case-sensitive family matches the suffix, but this slice removes it before the content check, so the page is returned and cached instead of refused whole. Cache-hit rechecks cannot recover the discarded evidence. Separately, with max_cached_page_chars=100, a clean 200-character page returns only 100 characters with truncated=False. Both violate the documented full-Markdown check and whole-page refusal.

Correction: In web_fetch, remove this slice and replace the cache insertion guard with:

if self.config.max_cached_pages and len(markdown) <= self.config.max_cached_page_chars:

Keep complete sanitized Markdown in the fresh local CachedPage; oversized pages should be checked and served without caching. Every retained entry then contains all policy evidence while respecting the cache bound. Only max_fetch_chars should truncate the public response.

Preservation / acceptance: Proposed regressions: the blocked-tail example returns refused=True with no cache entry; a clean 200-character body with cache limit 100 returns all 200 characters, truncated=False, and is not cached; a clean 600,001-character body returns 60,000 body characters and reports 540,001 omitted. Preserve the existing 70k/exact-60k assertions, cache-hit policy recheck, and redirect refusal/cache eviction. Suggested changes were not executed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed with a stubbed extract: "x" * 500_001 + " HLE answers" is served and cached, while the same suffix at character 499,000 is refused. We'd rate it NOTE rather than RISK, though: the model only receives the first 60,000 characters, all of which are checked, and the truncated=False case needs a non-default max_cached_page_chars below max_fetch_chars. The suggested change is still the simplest way to make the README's "full Markdown" statement true.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 465d43de4 (check the whole fetched page before it is cut), along the lines you suggested:

  • The content families see the provider's whole page before any cut, and then the sanitized Markdown.
  • A refused page is never cached.
  • A page whose Markdown is longer than max_cached_page_chars is served whole and not cached, so every cached entry holds all of its policy evidence.
  • Only max_fetch_chars cuts the response.

To keep that scan bounded, a page longer than max_page_chars (1,000,000) is refused unread as oversized_page. test_fetched_content_is_checked_whole_before_it_is_cut covers three cases:

  • The "x" * 500_001 + " HLE answers" page is refused and not cached.
  • An oversized page is refused.
  • A clean 200-character page with a cache limit of 100 is served whole twice, with truncated=False, and is not cached.

The 70,000-character cap test, the exact-60,000 test, the cache-hit recheck and the redirect refusal with cache eviction are unchanged.

Two follow-ups:

  • The wider scan exposed a GIL stall. Python's re holds the GIL for a whole scan, so a thread does not free the event loop: about 4 s for 1,000,000 characters of 抱抱脸. b132980c8 (run page checks in worker processes) moves the page work to a pool of up to two spawn worker processes. test_page_checks_do_not_stall_the_event_loop asserts the loop is never held for 0.5 s or more; the measured stall is 0.02 s.
  • web_search's per-result checks still run on the event loop. A provider title or snippet of 1,000,000 such characters would hold it about 4 s. We have not verified whether Tavily ever returns one that long, so d199b82a3 (state the page-check pool's cost and what still runs on the loop) documents this rather than adding a pool round trip to every search.

77d3f0f5a lists the oversized-page refusal as a residual next to upstream's behaviour, which serves the first 60,000 characters.

)


if __name__ == "__main__":

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RISK — The new server cannot start with multiple workers

Failure: Configure this resource with num_workers: 2. Shared startup gives Uvicorn the import target resources_servers.hle_web_tools.app:app. Importing this module neither enters __main__ nor defines a module-level app, so workers cannot load the application. Single-worker script startup is unaffected.

Correction: Import is_nemo_gym_fastapi_entrypoint from nemo_gym.server_utils and replace this footer with the established worker-entrypoint pattern:

if __name__ == "__main__":
    HLEWebToolsResourcesServer.run_webserver()
elif is_nemo_gym_fastapi_entrypoint(__file__):
    app = HLEWebToolsResourcesServer.run_webserver()

The invariant is that a designated worker import creates the exact application attribute requested by the launcher, while ordinary imports remain side-effect-free.

Preservation / acceptance: Proposed smoke check: start the standalone configuration with two workers, confirm readiness, seed a session and make an MCP search. Retain single-worker startup and ordinary test imports without starting a server. Static acceptance: the designated import branch defines app and calls the existing shared startup rather than constructing a reduced app. The suggestion was source-traced but not executed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mechanism is right: with num_workers > 1 the launcher hands Uvicorn resources_servers.hle_web_tools.app:app (server_utils.py) and this module defines no app. We'd call it a NOTE: neither config sets num_workers, and only 23 of the 165 resources servers at this head carry the is_nemo_gym_fastapi_entrypoint branch (tavily_search and equivalence_llm_judge don't). The two-line footer is a cheap optional addition.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't add the worker app footer. Instead, 5f61af08b (refuse a multi-worker launch with the standard hook) returns a reason from multiple_workers_unsupported_reason, so a launch with num_workers > 1 is refused before uvicorn starts, dry runs included. test_a_launch_with_several_workers_is_refused covers it.

The reason the server gives was corrected in 7605355e7 (give the true reason the server refuses several workers). The earlier text said a rollout's seed and its searches could reach different workers. That is not what stops several workers: session routing pins a resources request by its cookie's session_id, and an MCP call by its token's sid, to the worker that owns the session (since #3905, and restated by #5709 in the add-benchmark skill), so the seeded question and the episode binding, which are keyed by session ID, would be routed correctly. What does stop it: app.py defines no module-level app for uvicorn workers to import, and the URL-keyed page cache and the page-check pool are per process, so each worker would fetch, scan and cache its own copy of a page. The refusal now reads " needs num_workers=1: the module defines no module-level app for uvicorn workers, and the page cache and page-check pool are per process", and the test asserts the new reason and the absence of the old one. Behaviour is unchanged.

The README says the server runs single-worker (c4262af29, say the server must run single-worker). Since 50042dc2d (correct the configuration and preset notes), it quotes the refusal with the instance's own name, and 7605355e7 gives it the same corrected reasoning.

# (a sandbox reaching the plain route with the rollout's credentials) cannot swap the span check
# out from under it. A fresh session seeded from inside the sandbox is NOT caught here: that needs
# an authenticated seed channel (see the README).
if question is None or QuestionSpans(question, self.config.verbatim_span_words).digest != current.digest:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RISK — Typed sessions are bound only to question words, not episode/task identity

Failure: Seed typed resources session s for episode A/task A with question Q, then seed the same ID and Q for episode B or task B. This comparison accepts the second seed because only the question digest is retained. A close naming episode B also unconditionally removes A's state. The typed session contract and conformance checks require conflicting episode bindings to return 409. Default session routing checks the ID, not episode/task ownership. This affects the advertised Environment Server integration.

Correction: Distinguish typed seeds from legacy agent seeds, validate typed identity with ResourcesSeedSessionRequest, retain episode/task ownership alongside question state, and verify ownership on seed replay and close. Normalized-question equality must be an additional condition, not the identity check. The record representation is not established here, so no speculative patch is supplied.

Preservation / acceptance: Proposed minimal setup: use ID s, episode {"rollout_id":"A"}, task {"taskset":"test","task_id":"1"}, and task_data={"question":Q} through runtime-equivalent session routing. Identical replay must succeed; changing episode or task must return 409 without altering the original question. A close from another episode must return 409 and leave A usable. Preserve legacy seeds without typed identity, normalized-question retries, changed/dropped-question rejection, and cookie-less cleanup by resources_session_id. Retain the existing eight-versus-seven-word behavior. These checks were not executed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed in process: check_resources_session_contract(..., keeps_state=True) fails at its first stateful check (a seed binding the same ID to another episode gets 200, not 409). In the shipped preset the path is latent, though: OpenCode seeds its tool servers with the legacy run body (agent_tools.py), and a same-question seed from another episode leaves the span policy unchanged, so we'd rate it NOTE. Implementing the typed path with ResourcesSessionFence (as example_single_tool_call does) plus the conformance check in the tests, or rejecting typed seeds until a composition needs them, would close it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 16cd8c0f5 (bind typed sessions to their episode and fence closes):

  • An Environment Server's episode seed is validated as ResourcesSeedSessionRequest.
  • Its episode and task are recorded next to the question.
  • Seed and close go through the shared session helpers, as in example_single_tool_call. After main's refactor(sessions): one name per session lifecycle concept before release #5083 split that helper, 4950cab31 (use the split session locks and fences from main) maps each call onto ResourcesSessionLocks (one seed or close of an ID at a time) and ResourcesSessionFences (refuse a seed after a close until the close retry window ends), with no change in behaviour.

Question equality is an extra condition, not the identity check. Agent-run seeds, which carry the Agent's run body, are unchanged. test_episode_sessions_follow_the_resources_session_contract runs check_resources_session_contract(..., keeps_state=True). 83c2e5a75 (use main's session terms and name the retire release path) renamed it and the surrounding comments, docstrings and README to main's glossary: episode seed and episode session, agent-run seed, close retry window, release.

The other cases you listed are now tested too:

  • d7263dcc7: a close naming another episode of a live session gets 409 and leaves its question and binding in place, and holds_state now counts the binding.
  • a4e927aa7 (refuse a typed re-seed of a live session for another task): an episode seed of the live session for another task gets 409 and leaves the question digest and the binding unchanged. The test fails on a mutant that compares only the episode.

Comment thread resources_servers/hle_web_tools/app.py Outdated
self._session_spans[session_id] = QuestionSpans(question, self.config.verbatim_span_words)
self._session_spans.move_to_end(session_id)
while len(self._session_spans) > MAX_SESSION_QUESTIONS:
self._session_spans.popitem(last=False)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RISK — The question cache can evict a still-running rollout

Failure: Seed A, then seed MAX_SESSION_QUESTIONS other distinct sessions before A finishes. This eviction forgets A even if it has been searching throughout: web_search does not refresh the order. A's next unrelated valid query is refused as unseeded_session; a later seed can replace its supposedly immutable question because the binding was forgotten. OpenCode cleanup stops the sandbox but does not close auxiliary tool sessions, so cumulative starts can reach this limit below 10,000 concurrent rollouts. Long-lived/shared-server evaluations are affected.

Correction: Could accepted active question bindings remain until explicit close/retirement rather than LRU eviction? Bound capacity with an explicit admission decision instead of forgetting live state. Normal reclamation also needs auxiliary-tool-session cleanup in the owning harness, retaining the host-side session identity needed to close it. Merely refreshing LRU order on search does not restore the invariant. The complete lifecycle design is uncertain, so no blanket patch is proposed.

Preservation / acceptance: Proposed regression: temporarily lower capacity, keep A active, and create more distinct sessions than capacity. A must retain its original question policy and unrelated-query allowance; excess admission must be handled explicitly, not by silently invalidating A. Closing/retiring another session must free capacity without changing A. Preserve the memory bound, genuine-unseeded refusal, normalized retry, and changed-question rejection for every accepted active session. Checks were not executed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed with the cap lowered to 2. At the real cap it needs more than 10,000 newer seeds (L132) while a rollout is still running; the Diamond text preset is 728 rows per run, eviction follows seed order, and the failure is a logged unseeded_session refusal, so we'd rate it NOTE. A WARNING on eviction would make it visible if a long-lived shared server ever reaches the cap.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, agreed on NOTE. Here is what changed and what didn't.

Changed:

  • 12fbd2255 (log a warning when the session cap forgets a question): when the cap drops a session that held a question, the server logs a WARNING naming the session and the cap. That session's later searches are refused as unseeded_session.
  • 23d9c4d80 (fence a typed session the cap forgets): a forgotten episode session (an Environment Server's) is fenced as if its episode had closed it. A later seed of that ID gets 409 instead of re-binding it, and a close from its own episode is still accepted.
  • test_sessions_past_the_cap_are_forgotten_with_a_warning lowers the cap to 1 and covers both changes. It fails if either one is reverted.
  • 0cd8d9c4e (state when the session cap forgets a running rollout) corrects the README. Before, it said the cap only had to exceed the peak number of rollouts open at once, which holds only for a harness that closes its sessions. b982314c0 (count the later sessions that evict a rollout exactly) makes the count exact: a rollout's question is forgotten once 10,000 later sessions are seeded on the same server while it is still running. e37e5ac22 (name cap-forgotten sessions in the sandbox-seeded residual) aligns the Diamond README.
  • 83c2e5a75 names the other release path: before the cap evicts, a slot is released by an episode session's /close_session or by the checkpoint controller retiring the attempt that seeded it (retire_session_state releases every session of that attempt, whatever seed created it, without fencing the ID).
  • Closing another session releases capacity without touching the held ones. Same-question retries, the 409 on a changed question and the unseeded refusal are unchanged.

Not changed:

  • Eviction is still by seed order, and web_search does not refresh it. Admission control in place of eviction is deferred.
  • OpenCode seeds its tool servers with the agent-run body and never closes them, so in this preset sessions are reclaimed only by the cap. A Diamond text run seeds 728.
  • The fence does not cover those agent-run seeds. After eviction, an OpenCode session can be seeded again with another question. A flood of unauthenticated seeds can likewise push other rollouts out of the cap, and their searches then fail closed. Neither goes beyond the fresh-seed bypass tracked in hle_web_tools: authenticate /seed_session so a sandbox cannot seed its own session #5845, and that issue covers both.
  • Closing auxiliary tool sessions in the harness is a follow-up, listed in the PR description.

Comment thread resources_servers/hle_web_tools/app.py Outdated
for _ in range(MAX_URL_DECODE_ROUNDS):
next_frontier: List[str] = []
for candidate in frontier:
if candidate in seen or len(seen) >= MAX_URL_CANDIDATES:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RISK — Candidate overflow accepts URLs with unchecked wrapped targets

Failure: Construct https://reader.example/fetch? followed by 63 distinct parameters uN=https://example.org/N, then url=https://scale.com/leaderboard. The original URL plus the 63 harmless values exhaust the 64-candidate limit; this guard silently skips the blocked final value. url_block() consequently returns None, although scale.com is a shipped domain rule. Fetch and result filtering accept the unchecked URL. This demonstrates a missed validator check, not a broader proxy exploit.

Correction: Keep the resource bound but refuse overflow. Suggested change: define a dedicated URLCandidateLimitError(ValueError), then replace this combined guard with:

if candidate in seen:
    continue
if len(seen) >= MAX_URL_CANDIDATES:
    raise URLCandidateLimitError("URL expansion limit exceeded")

In Blocklist.url_block, replace the direct candidate-loop setup with:

try:
    candidates = url_candidates(url)
except URLCandidateLimitError:
    return Block(
        MALFORMED_URL_FAMILY, "URL expansion limit exceeded", url, where
    )
for candidate in candidates:

Retain the existing loop body. The invariant is that bounded traversal never certifies a URL after silently omitting an unseen target.

Preservation / acceptance: Proposed fetch regression: use the constructed URL and a stub extract backend; expect refusal and no backend call. Simple allowed URLs and duplicate query values must remain accepted. Preserve all five existing archive/proxy wrapper refusals. Suggested changes were not executed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced: with exactly 63 decoy parameters, url_block() returns None for the trailing url=https://scale.com/leaderboard, and with fewer decoys it is refused as domains. Since any reader proxy with a ?url= parameter would then fetch the target, RISK seems right. Refusing as malformed_url whenever expansion stops with candidates unexplored (cap or round limit) would fix this thread and the decode-round thread together.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a872e7a7b (refuse URL spellings the policy could misread). Your suggestion was to refuse when expansion stops with candidates unexplored. The URL is now refused as malformed_url in that case, whether the 64-candidate cap or the round limit stopped it, rather than certified on a partial check. The 63-decoy reader.example/fetch?...&url=https://scale.com/leaderboard URL is a row in the URL table, and it is refused with no /extract call. The five archive/proxy wrapper refusals are unchanged, and the table's ordinary redirect and query URLs stay allowed. As a consequence, a URL with more than 63 distinct embedded or wrapped candidates now fails closed even when every candidate is harmless.

Comment thread resources_servers/hle_web_tools/app.py Outdated
"""The URL, its percent-decoded forms (several rounds) and every URL wrapped inside any of them."""
seen: List[str] = []
frontier = [url]
for _ in range(MAX_URL_DECODE_ROUNDS):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RISK — The fourth decoded URL form is computed but never checked

Failure: Four loop iterations check the original URL and only three decoded forms. For https://example.com/%2525252Famphtml/, successive decoded paths are /%25252Famphtml/, /%252Famphtml/, /%2Famphtml/, and //amphtml/. Only the fourth matches the shipped /amphtml/ rule. It is appended to the next frontier but discarded at loop exit, so url_block() allows the URL despite the documented four decoding rounds. This establishes a validator failure, not how Tavily would render the URL.

Correction: Count checking the original separately from the decoding rounds. Replace this loop header with:

for _ in range(MAX_URL_DECODE_ROUNDS + 1):

The invariant is that the original and every decoded result through the fourth permitted unquote() are checked. This does not replace the separate need to refuse candidate-count overflow.

Preservation / acceptance: Proposed checks: url_block() refuses this example as url_patterns; the same four-level encoding of a neutral path remains allowed. Retain the existing double-encoded safe.ai proxy refusal, encoded and bare-host Wayback refusals, Google-cache refusal, and nested OpenReview-prefix refusal in the wrapper tests. The suggested replacement is source-traced, not executed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: three encodings are refused and four are allowed, so the loop checks the original plus three decoded forms rather than the four rounds the README states. We'd rate it NOTE: a server decodes a direct URL once, so a four-times-encoded path does not reach the blocked page. The fail-closed rule suggested in the candidate-overflow thread covers it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a872e7a7b with the overflow thread. The original and four decoding rounds are checked, and a URL with a fifth level still unexplored fails closed. Both are rows in the URL table:

  • %2525252Famphtml is refused as url_patterns.
  • %252525252Famphtml is refused as malformed_url.

A four-level encoding of a neutral path stays allowed (checked by probe, not a table row).

Comment thread resources_servers/hle_web_tools/app.py Outdated
_WAYBACK_PATH_RE = re.compile(r"^/web/[^/]*/(.+)$", re.IGNORECASE | re.DOTALL)
_GOOGLE_CACHE_RE = re.compile(r"cache:(?:[A-Za-z0-9_-]+:)?(.+)$", re.DOTALL)
_WORD_RE = re.compile(r"\w+")
_DATA_URI_RE = re.compile(r"data:[a-z]+/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=\s]+", re.IGNORECASE)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RISK — Non-base64 data URIs bypass the media sanitizer

Failure: For an allowed fetched page containing ![figure](data:image/svg+xml,%3Csvg%3E%3C/svg%3E), this regex does not match because it requires literal ;base64,. A parameterized base64 URI such as data:image/png;charset=utf-8;base64,AAAA also survives. The embedded media payload is returned despite the data-URI removal/no-media contract. The current regression covers only an unparameterized base64 PNG.

Correction: Expand _DATA_URI_RE/the web_fetch sanitizer to recognize data-URI destinations with optional media-type parameters and both base64 and percent-encoded payloads. Replace the complete destination without consuming following prose or ordinary URLs. The delimiter-safe implementation depends on which Markdown destination forms are supported, so a blanket greedy regex would not be a safe suggested patch. Apply sanitization consistently before policy checks and caching.

Preservation / acceptance: Proposed cases: both minimal URIs above disappear and receive the removal marker on fresh and cached fetches. Retain the existing PNG removal, title/final-URL rendering, adjacent end prose, and ordinary https://... image links. These are proposed checks, not executed tests.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: the percent-encoded SVG and the ;charset=utf-8;base64, PNG pass unchanged. The class also over-deletes in one narrow case: a bare data:image/png;base64,AAAA followed by prose removes the following words, because \s is in the payload class (L122). We'd rate it NOTE (payload size and fidelity, not the blocklist); something like data:[\w.+-]+/[\w.+-]+(?:;[\w.+-]+=[^;,\s)]*)*(?:;base64)?,[^\s)"'>]* handled the cases above and the existing PNG case in a quick check.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 465d43de4 (check the whole fetched page before it is cut). _DATA_URI_RE now matches an optional media type with up to 16 ;name=value parameters, an optional ;base64, and a base64 or percent-encoded payload. The payload stops at the first whitespace, ), quote or >. So the destination is replaced whole, and prose after a bare URI is kept: in data:image/png;base64,AAAA followed by prose, the words followed by prose stay.

I bounded every repetition rather than using the suggested form as written. On a page of repeated data:a/b;c=, the unbounded form is quadratic (80,000 characters took about 14 s), while the bounded one is linear (under 1 s for 1,000,000 characters, the max_page_chars cap). The price is that some URIs are left in place:

  • a type or subtype over 127 characters;
  • a parameter name over 127 characters;
  • a parameter value over 256 characters;
  • a 17th parameter.

b0fb98886 (state every bound of the data-URI regex) states these bounds in the README and in the regex comment. The README also says where the payload ends, so a base64 payload wrapped over several lines keeps its later lines.

In the same commit, the order of checks changed:

  1. The provider's raw page is checked against the content families before any data URI is removed.
  2. The sanitized Markdown is checked.
  3. Only the sanitized Markdown is cached.

A cache hit serves the stripped page and checks it again.

8b95221d7 (strip data URIs that omit the media type) also strips data:;base64,..., which RFC 2397 allows.

test_fetch_renders_title_and_final_url_and_strips_data_uris fetches one page twice, fresh and then cached, with a single /extract call, and asserts the exact text:

  • The existing PNG, the percent-encoded SVG, the ;charset=utf-8;base64, PNG and the data:;base64, image each become [data URI removed].
  • The title and the final URL render.
  • The adjacent end and the prose after the bare URI stay.
  • The https:// image link is unchanged.

The test fails with the original regex, and with the regex as it was before 8b95221d7.

@@ -0,0 +1,352 @@
{

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NOTE — Suggestion: retain the vendored policy's license provenance

The new byte-exact policy records its source/revision/digest through the wrapper, but the component documentation and PR description do not identify its applicable license, and the vendored-component catalog has no entry for it. Existing base-tree provenance identifies this upstream artifact as MIT. This is a provenance omission, not a claim of license incompatibility.

Could you verify the pinned artifact's applicable license, retain its upstream copyright/license notice in an adjacent attribution file, document it in the component README and PR description, and add the catalog entry? Keep the JSON byte-exact rather than adding fields or comments that invalidate the policy schema or digest. The wrapper's own Apache-2.0 provenance should remain distinct.

Static acceptance: recipients can find the artifact's upstream URL, exact revision, applicable license and retained notice; the existing pinned-snapshot assertion remains unchanged and still expects the original digest. I could not inspect the external upstream license text in this environment.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirming the license: LICENSE at the pinned revision is MIT, Copyright (c) 2025 centerforaisafety, and this repo already records it for the same artifact (build_search_exclusions.py). Since the JSON has to stay byte-exact, a sibling notice file plus a row in ATTRIBUTIONS.md's Vendored Components table would match how other MIT sources are recorded.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 30aa876bd (record the MIT license of the vendored blocklist), as documentation only:

  • LICENSE-HLE reproduces upstream's MIT LICENSE at 22ed3074 unchanged (Copyright (c) 2025 centerforaisafety).
  • ATTRIBUTIONS.md has a Vendored Components row and a notes entry.
  • The server README has a Licensing section that keeps the server's own Apache-2.0 provenance separate.

blocklist.json stays byte-exact, and the pinned-digest test is unchanged. The PR description now names the license too.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added benchmark-onboarding Self-contained benchmark onboarding blocked Work cannot move forward until an external dependency is cleared labels Oct 28, 2026

@yaoyu-33 yaoyu-33 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HOLD. The blocker is the key-pool spin already raised in this PR's review thread (reproduced below); the CI data check flagged inline will also fail once Unit Tests run.

Thanks for the careful work here: the pinned protocol and the per-family write-up made this straightforward to check. What we verified at c6a7defb6:

  • blocklist.json is byte-identical to upstream docs/blocklist.json at 22ed3074 (SHA-256 3abaf35e…6575), and the protocol and requirements digests pinned in app.py match the upstream files.
  • Every family is enforced where section 3 of the protocol asks: the query, each result's URL, title and snippet, the requested URL with wrapper decoding, the reported final URL, the fetched title and Markdown, and cache hits. The domains check holds up against case, trailing dots, ports, fullwidth dots, percent-encoded hosts and userinfo.
  • Tavily is reached through nemo_gym.server_utils.request (no httpx), with a per-attempt timeout, _max_connection_retries=0, responses released in finally, and provider bodies kept out of errors.
  • Both new configs are verified: false, and scripts/update_env_list.py makes no change, as expected for a tool-only server.
  • tests/test_app.py: 32 passed with TAVILY_API_KEY unset and network access blocked. test_hle_diamond.py: 62 passed with a routable hostname; on a host whose name does not resolve, the 4 new cases fail with the same ConfigError as 19 existing cases on main.

Inline:

  • Risks: the page-level families (url_prefixes, serp_url_patterns) and the Wayback unwrapping accept equivalent spellings of blocked URLs; a long model-supplied URL ties up the event loop and memory; and the server has no data/ examples, which the changed-server CI step requires.
  • Notes: heading-regex backtracking, site: operand parsing, unguarded Tavily results, and a README cross-reference.
  • Existing threads: we reproduced all eleven. We'd keep the key-pool spin as the blocker and the fresh-seed and candidate-overflow threads as risks, and suggest NOTE for seven of the other eight, mostly because their paths are latent in the shipped preset or cannot reach the model; the reasons are in each reply.

Not verified here: no live Tavily calls (in particular, whether /extract reports the post-redirect URL that the final-URL check relies on), no real sandbox egress, and no full 728-row run.

PR hygiene:

  • Could the title follow Conventional Commits, for example feat(hle_web_tools): add upstream HLE web tools server and Diamond preset?
  • The body doesn't link an issue or say why none is needed.
  • The checklist ticks pre-commit run --all-files, while the validation section shows a file-scoped run.
  • Unit Tests haven't run on this head yet.

Merge order: #5175 and #5177 also edit benchmarks/hle_diamond/README.md and resources_servers/equivalence_llm_judge/tests/test_hle_diamond.py, so whichever lands later will need a small rebase.

Comment thread resources_servers/hle_web_tools/app.py Outdated
block = self.host_block(host, url, where)
if block is not None:
return block
form = prefix_form(url)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

app.py:258

RISK. domains compares the parsed, IDNA-normalized host, but url_prefixes and serp_url_patterns match the raw string, so equivalent spellings of a blocked page pass the pre-fetch check and go to Tavily as written: https://arxiv.org:443/abs/2605.02442, https://arxiv.org./abs/2605.02442, https://arxiv.org/x/../abs/2605.02442, https://@arxiv.org/abs/2605.02442 (the empty userinfo also gets past the credential refusal at L272), https://www.google.com:443/search?q=x. A backslash hides the host from urlsplit as well: https://scale.com\.example.org/leaderboard is allowed, while WHATWG parsers, pydantic's HttpUrl and urllib3 all read the host as scale.com.

Could url_block refuse \, control characters and any @ in the authority, and also run these families on a canonical form (normalized host, default port dropped, dot segments removed)? The post-fetch check at L763 would only catch these if Tavily's results[].url reports the canonical URL, which its API reference doesn't say.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a872e7a7b (refuse URL spellings the policy could misread). url_prefixes and serp_url_patterns are now also tried on a canonical form: the host normalized, the default port, userinfo and fragment dropped, and dot segments resolved. A backslash, whitespace, a control character or any @ in the authority (including an empty userinfo) is refused as malformed_url. Each of your examples, the backslash host included, is a row in the URL table.

Later probing found more spellings, each fixed with a row that fails before its fix:

  • 9ac597e3a (map hosts the way UTS Add Workbench validation dataset #46 fetchers do): sc🄰le.com.
  • 00380d451 (refuse a wrapped URL Python cannot parse): https://[::1]@scale.com/.
  • bb5e802d4 (match url_prefixes with a query in any parameter order): openreview.net/pdf?&id=....
  • 25f0c7f83 (collapse slash runs in the canonical URL form): arxiv.org//abs/....
  • d4d3b3d9b (also match the canonical form with slash runs merged before dots): arxiv.org/abs/x//%2e%2e/2605.02442, as nginx's merge_slashes reads it.

I did not check Tavily's results[].url against the live API. The README says the post-fetch check covers a redirect or rewrite only if Tavily reports the final URL there.

Comment thread resources_servers/hle_web_tools/app.py Outdated
# blocklist names outright (archive.ph and friends, r.jina.ai, translate.goog, translate.google.com,
# 12ft.io, corsproxy.io, allorigins, codetabs, thingproxy, whateverorigin) are refused by the ``domains``
# family before any unwrapping is needed.
WRAPPER_HOSTS = frozenset({"web.archive.org", "archive.org", "webcache.googleusercontent.com", "r.jina.ai"})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

app.py:129

RISK. Two Wayback spellings get past the unwrapping, and archive.org redirects both to the blocked snapshot: https://web.archive.org/web/2024/https:/scale.com/leaderboard (one slash after the scheme, so neither _SCHEME_RE nor _BARE_URL_RE matches the remainder at L347-L350) and https://wayback.archive.org/web/2024/scale.com/leaderboard (only the exact host web.archive.org counts as a wrapper). Upstream asks for blocked URLs inside archive links to be caught before the fetch (evaluation-with-tools.md L36).

Could the remainder accept https?:/+ and every *.archive.org host count as a wrapper? One live /extract call on a redirecting link would also tell whether the final-URL check covers redirects at all.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a872e7a7b. Every *.archive.org host now counts as a wrapper, and a remainder of https:/, https:/// or https:host is read as https://host. Both of your examples are refused as domains. Three later commits refine the Wayback reading:

  • 0112487cf (read a wrapper's remainder as a URL however it is spelled) reads a scheme-less remainder whatever its host spelling: scale.com./, [email protected]/, or full-width letters.
  • fbe894843 (read a Wayback path with no timestamp as naming its target) covers web.archive.org/web/scale.com/leaderboard, which archive.org redirects to a snapshot. The first segment after /web/ is read both as a timestamp and as the start of the URL.
  • 912f26382 (read a Wayback timestamp segment as a timestamp only) limits that second reading to a first segment that is not timestamp-shaped (20240101000000, 2024id_, 2024*, *), which no hostname is. Before, every timestamped snapshot also yielded the candidate https://<timestamp>/<url>, which names no page, so each Wayback layer spent extra candidates and decode rounds, and four timestamped layers around a percent-encoded page were refused as malformed_url. That four-layer URL is now a row in the URL table as served, and a plain snapshot is back to two candidates.

I did not make the live /extract call on a redirecting link. 77d3f0f5a qualifies the README's claim: the redirect refusal holds only if Tavily reports the post-redirect URL in results[].url, which has not been checked against the live API.

Comment thread resources_servers/hle_web_tools/app.py Outdated
if cache:
found.append(cache.group(1))
found.append(value)
found.extend(match.group(1) for match in _EMBEDDED_URL_RE.finditer(url) if match.start() > 0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

app.py:341

RISK. _EMBEDDED_URL_RE is a lookahead, so every embedded https:// yields a substring running to the end of the URL, and url_candidates keeps up to 64 of them per round: the cost grows with the square of the URL length, synchronously on the event loop. A model-supplied https://a.example/ followed by repeated https:// took 1.8 s at 8 KB and 7 s with 1.4 GB RSS at 16 KB in our probe, and the URL was then allowed.

Since WebFetchRequest.url has no length limit, could you cap it (for example Field(max_length=4096), or refuse longer URLs as malformed_url)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a872e7a7b. A URL over 4,096 characters is refused as malformed_url, with a logged refusal rather than a validation error, and an embedded URL ends where the next one starts, so expansion is linear. test_long_urls_and_headings_are_handled_in_linear_time has two URL rows, and each must be refused in under 1 s:

  • a 3,898-character URL holding 190 distinct embedded URLs, which overflows the candidate cap;
  • a 10,018-character URL of repeated https://.

@@ -0,0 +1,11 @@
# Standalone instance of the HLE web tools (web_search, web_fetch over MCP, Tavily backend, upstream
# blocklist). Benchmark presets compose their own instance; see benchmarks/hle_diamond/opencode_hle_tools.yaml.
hle_web_tools:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

configs/hle_web_tools.yaml:3

RISK. CI's changed-server step runs ng_test +entrypoint=resources_servers/hle_web_tools +should_validate_data=true (unit-tests.yml), and _validate_data_single requires data/example.jsonl (5 rows), data/example_metrics.json and data/example_rollouts.jsonl in every resources_servers/* directory. This is currently the only resources server without them, so Unit Tests will fail once they run on this head.

Could you add the three files (5 synthetic rows with a question and responses_create_params, no gated HLE text), generated through a config with an agent the way tavily_search does?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 47dc1fbda (add the example data CI validates), following tavily_search:

  • configs/hle_web_tools.yaml now has a simple_agent with an example dataset, behind a single_agent_turn_legacy environment server over direct HTTP.
  • data/example.jsonl holds 5 synthetic general-knowledge rows. They are not HLE items, and each has a placeholder note saying so. Each row has a question and responses_create_params exposing web_search and web_fetch.
  • data/example_metrics.json was generated from that config with gym dataset collate ... +mode=example_validation, and regenerating it reproduces the committed file exactly.
  • data/example_rollouts.jsonl holds <PLACEHOLDER ROW> lines, as in tavily_search, since no live model or Tavily call was made.

The README says the rows and rollouts are placeholders.

The core unit tests also require a task_data.py for every resources server. bcb981593 (declare the task-data schema CI validates) adds one, declaring the optional question and the placeholder note. After the main merge, 5742b1e5b (pass the core public-API and environment-resources tests) names the resources server on the example environment server, which a new core check requires. After the latest merge, 60963f0d0 (declare dependencies in pyproject.toml and uv.lock) replaces the server's requirements.txt with the pyproject.toml and uv.lock that main's #4837 requires of every component; the lock was seeded from the calendar server's, so it pins the same versions as the other component locks, and scripts/component_locks.py passes on it.

ng_test +entrypoint=resources_servers/hle_web_tools +should_validate_data=true exits 0 with the data validated (110 tests), and tests/unit_tests/data/test_task_data.py and tests/unit_tests/tooling/test_component_dependencies.py pass.

Comment thread resources_servers/hle_web_tools/app.py Outdated
_WORD_RE = re.compile(r"\w+")
_DATA_URI_RE = re.compile(r"data:[a-z]+/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=\s]+", re.IGNORECASE)
_TITLE_SEPARATOR_RE = re.compile(r"\s+(?:\||-|–|—|·|•|»|::)\s+")
_MARKDOWN_HEADING_RE = re.compile(r"^#{1,6}\s+(.+?)\s*$", re.MULTILINE)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

app.py:124

NOTE. \s+(.+?)\s*$ backtracks quadratically on a heading line with a long whitespace run before a non-space character (about 3 s at 40,000 spaces, 18 s at 100,000), and since Tavily's /extract returns no title, this fallback runs on every fresh fetch (L750-L753). The form below captures the same text on ordinary headings and is linear. (The full-page scan at L766 also runs on the event loop, 0.07 to 0.9 s per 500,000-character page; that one is smaller, so just flagging it.)

Suggested change
_MARKDOWN_HEADING_RE = re.compile(r"^#{1,6}\s+(.+?)\s*$", re.MULTILINE)
_MARKDOWN_HEADING_RE = re.compile(r"^#{1,6}[ \t]+(.*\S)", re.MULTILINE)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 465d43de4. The heading capture now starts at the first non-blank character and runs to the end of the line, and the closing # sequence and trailing blanks are stripped outside the regex. This is linear and captures the same text on ordinary headings. The heading-100k row of the linear-time test must parse a 100,000-blank heading in under 1 s.

On the full-page scan you flagged: it now runs in worker processes (b132980c8), off the event loop. Four more fixes came out of follow-up probing:

  • e10df7a73 (bound title work and cap shown titles) starts the title-separator match only at the first blank of a run, since it was quadratic on blank runs, and caps shown titles at 1,000 characters.
  • 485a835fd (find a title's site-name separator after a long blank run) keeps that cap from hiding a separator, so Quiz answers<5,000 blanks>| Site is dropped again.
  • 53c568a4b (check the shown title text at the cut) also checks the shown text without its cut marker whenever a title is capped, since the marker made the end-anchored answer_title_patterns miss a phrase that ends exactly at the cut. A title whose text before | Site is exactly 1,000 characters and ends in Quiz answers is now dropped, like the same title one character shorter. Every variant stays at most 1,000 characters, so the linear bound holds.
  • d199b82a3 states the one scan still on the loop: web_search's per-result checks.

Comment thread resources_servers/hle_web_tools/app.py Outdated
_EMBEDDED_URL_RE = re.compile(r"(?=(https?://[^\s\"'<>]+))", re.IGNORECASE)
# A query value or path remainder that names a host, with or without a scheme: ``hf.co/datasets/x``.
_BARE_URL_RE = re.compile(r"^(?:https?:)?(?://)?(?:[a-z0-9-]+\.)+[a-z]{2,}(?:[:/?#]|$)", re.IGNORECASE)
_SITE_OPERATOR_RE = re.compile(r"\bsite:\s*[\"']?([^\s\"']+)", re.IGNORECASE)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

app.py:118

NOTE. The operand class [^\s"']+ keeps trailing ), , and |, so (site:example.org OR site:scale.com) x, site:example.org|site:scale.com x and site:scale.com, x are served, and site:.huggingface.co raises on the empty IDNA label and is skipped by the continue at L292-L293. Results are still domain-filtered, so this is about the refusal and audit log upstream asks for. Capturing host characters only handles these (and refusing instead of continue on UnicodeError covers the rest):

Suggested change
_SITE_OPERATOR_RE = re.compile(r"\bsite:\s*[\"']?([^\s\"']+)", re.IGNORECASE)
_SITE_OPERATOR_RE = re.compile(r"\bsite:\s*[\"'(\[]?\.?([^\s\"'()\[\],;|]+)", re.IGNORECASE)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a872e7a7b. The operand is read as host characters only, and an operand that fails IDNA is refused rather than skipped. Your examples are rows in the site: table and are refused as domains: (site:example.org OR site:scale.com), site:example.org|site:scale.com, site:scale.com, and site:.huggingface.co. Two later commits close more cases:

  • e01263f35 (refuse a site: operand that is not hostname-shaped) drops trailing punctuation (site:huggingface.co!). It also refuses, as malformed_url, an operand that is still not shaped like a hostname.
  • 324f2ff20 (read typographic quotes around a site: operand like ASCII quotes) reads typographic quotes and guillemets like ASCII quotes: site:“scale.com” and site:scale.com” had become punycode hosts that matched nothing. It also allows stacked openers, as in site:((scale.com)). The stray-closer row (site:scale.com” leaderboard) is kept on purpose, since it alone catches an implementation that strips quotes only in balanced pairs (ac46c2f58).

Comment thread resources_servers/hle_web_tools/app.py Outdated
Comment on lines +707 to +708
for result in response.get("results", []):
url, title, snippet = result.get("url"), result.get("title") or "", result.get("content") or ""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

app.py:707

NOTE. web_search reads Tavily's payload unguarded: results: null, a non-dict item or a non-string title raises TypeError/AttributeError and reaches the model as a 500 (AGENTS.md asks for guarded nested fields). web_fetch at L741 has the same results: null gap.

Suggested change
for result in response.get("results", []):
url, title, snippet = result.get("url"), result.get("title") or "", result.get("content") or ""
for result in response.get("results") or []:
if not isinstance(result, dict):
continue
url, title, snippet = result.get("url"), str(result.get("title") or ""), str(result.get("content") or "")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5142f52df (turn malformed Tavily bodies into tool errors). Both tools now read results through one guarded helper:

  • In web_search, a body that is not an object, or a results that is not a list (including null), returns the tool error "Search failed: the search provider returned a malformed response." Non-object items and items without a string url are skipped. A non-string title or content is treated as empty rather than passed through str(), so a dict or list is never shown to the model or matched as text.
  • In web_fetch, the same results: null gap, a list with no object item, or a first result whose raw_content is missing or not a string returns "Fetch failed for ". failed_results is type-checked the same way, and a non-string title falls back to the page's first heading.

c134aff87 (answer a non-JSON 200 body as a tool error) covers a 200 whose body does not decode, such as a gateway HTML page or cut-off JSON. The transport returns no body for it, so the two tool errors above apply, and the request is not retried.

test_malformed_tavily_payloads_become_tool_errors has one row per shape: body not an object, results: null, non-object items, non-string fields, an HTML body and cut-off JSON. Each row checks both tools, and each fails on the pre-fix code.

does) can seed a new session with a question of its choice and search from it without the span rule.
Closing that needs an authenticated seed channel (a secret the agent server holds and the sandbox never
sees); until then the span rule is a check on a cooperative harness, not on the sandboxed model, and the
Diamond README lists it as a residual under Reference preset.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

README.md:27

NOTE. The Diamond README at this head has no "Reference preset" section (it may arrive with #5177), and line 36 here and the new Diamond section both call the backend the one residual difference from upstream. Could the Diamond section also list the fresh-seed residual described above, with this sentence pointing at it, so a with-tools number from this preset carries both caveats?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2500e8539 (name the sandbox-seeded session residual). The Diamond section lists the fresh-seed residual, and the server README's sentence now points to it. 77d3f0f5a adds the oversized-page refusal as a third residual. The Diamond README now says that a with-tools number from this preset should state all three: the Tavily backend, sandbox-seeded sessions and oversized pages. e37e5ac22 adds sessions the cap has forgotten to the sandbox-seeded residual. The Reference preset section arrived with #5177; 498e34bc3 (say hle_web_tools exists as its own preset) keeps the reference preset's notes accurate.

@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Oct 29, 2026
rimashahbazyan and others added 14 commits November 2, 2026 15:11
Resolved benchmarks/hle_diamond/README.md: the Tests block keeps main's
opencode_sandboxed_agent/tests/test_hle_reference_image.py line (#5177)
and adds this branch's resources_servers/hle_web_tools/tests/test_app.py.
resources_servers/equivalence_llm_judge/tests/test_hle_diamond.py merged
without conflict; both sides' additions are kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
main moved the modules this server imported (nemo_gym.base_resources_server,
nemo_gym.server_utils names, nemo_gym.mcp_auto_exposure) and serves the old
paths only through deprecation shims removed in nemo_gym 0.10.0. Rewritten
with scripts/migrate_imports.py to the public API (nemo_gym.client,
nemo_gym.server_runtime) and, for the MCP test, the defining module, as
the other servers on main do; the README names the new request path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
opencode_reference.yaml and the README's Reference preset section, both
from main (#5177), said the reference preset would switch to the
hle_web_tools server once it existed. This branch adds that server, so
the sentence would turn into an unfulfilled promise on merge. The
reference preset keeps the Tavily tools here; the wording now names
opencode_hle_tools as the preset that runs hle_web_tools (on the science
image) and leaves running it on the reference image and egress policy to
a follow-up change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
A key pool whose keys Tavily all rejects (401, 432, 433) spun forever in
the key-selection loop without an await, freezing the worker's event
loop: one configured key, a key listed twice, or two distinct rejected
keys were enough. A rejected key also spent the transient retry budget,
so [bad, bad, bad, good] with three attempts never reached the good key.

The pool is now deduplicated when the backend is built, rejected keys
move on without spending an attempt, the next key comes from a bounded
helper over the keys still accepted, and the call raises a RuntimeError
naming the status once every key is rejected. Transient failures keep
their backoff and budget.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
web_search read Tavily's payload unguarded: a body that is not an
object, `results: null`, a non-object item or a non-string title or
content raised AttributeError or TypeError and reached the model as an
HTTP 500. web_fetch had the same `results: null` gap and rendered a
non-string raw_content as page text.

Both tools now read the results list through one guarded helper.
web_search answers a malformed body with a "Search failed" tool error,
skips non-object items and treats non-string title and content as
empty; web_fetch reports any malformed body, item or raw_content as
"Fetch failed", and guards failed_results the same way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
CI's changed-server step runs ng_test with should_validate_data=true,
which requires data/example.jsonl (5 rows), data/example_metrics.json and
data/example_rollouts.jsonl, plus an agent with an example dataset in the
server config; hle_web_tools had none of them.

Following resources_servers/tavily_search: the config gains a
simple_agent with an example dataset behind a single_agent_turn_legacy
environment server over direct HTTP, example.jsonl holds 5 synthetic
general-knowledge rows (no HLE text, each marked by a placeholder field)
whose tools are web_search and web_fetch with the server's own schemas,
example_metrics.json comes from gym dataset collate in
example_validation mode, and example_rollouts.jsonl holds placeholder
rows since no live model or Tavily call was made. The server stays
verified: false. The README says so, and the update-readme-table hook
adds the server to the environment list now that its config has an
agent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
Seeded questions and the page cache are per process, so with
num_workers > 1 a rollout's seed and its searches could land in
different workers; the module also defines no worker app, so such a
launch fails to start. Rather than add the multi-worker entrypoint
footer, the README states the single-worker requirement.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
The URL check certified URLs it had not fully checked and matched the
page-level families on the raw string only. Now url_block:

- refuses as malformed_url any URL longer than 4,096 characters, with a
  backslash, whitespace or control character, or with any @ in the
  authority (an empty https://@host included);
- fails closed when candidate expansion stops with candidates unexplored,
  at the 64-candidate cap or after the original plus four rounds, so 63
  decoy query values or a fourth decoded form no longer hide a target;
- runs url_prefixes and serp_url_patterns on a canonical form as well
  (IDNA lower-cased host, trailing dot, userinfo and default port
  dropped, dot segments resolved), so :443, a trailing dot or /x/../
  no longer evade a prefix;
- treats every *.archive.org host as a wrapper and reads https:/,
  https:/// and https: remainders as https://;
- reads wrapped and decoded URLs the way WHATWG fetchers do (backslash
  as /, tab and newlines deleted);
- takes each embedded http(s):/ up to the next one instead of through a
  lookahead to the end of the string, so extraction is linear.

site: operands are read as host characters only, so (site:a OR
site:b), site:a|site:b and site:b, yield bare hosts, and an operand
whose IDNA encoding fails is refused instead of skipped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
Fetched content was sanitized and cut at max_cached_page_chars before
the content families ran, so a blocked span past 500,000 characters was
served and cached, and a cache cap below max_fetch_chars served a cut
page as truncated=False. Now:

- a fresh page is checked against url_patterns and
  patterns_case_sensitive on the provider's raw Markdown, before data
  URIs are removed or anything is cut, and on the sanitized Markdown;
  a refused page is never cached;
- the scan is bounded: a page longer than max_page_chars (new,
  default 1,000,000) is refused unread as oversized_page, and the regex
  work runs in a worker thread instead of on the event loop;
- max_cached_page_chars no longer cuts the page: a longer page is
  served whole but not cached, so cache-hit rechecks see the complete
  sanitized Markdown;
- data URIs with media-type parameters or a percent-encoded payload are
  removed too, the payload stops at the Markdown destination's end so
  following prose is kept, and every repetition is bounded so the
  regex stays linear (the unbounded suggested form is quadratic);
- the heading fallback for the title is linear on long blank runs
  (100,000 characters took 42 s) and drops a closing # sequence.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
…oses

A typed seed (an Environment Server's resources_session_id, episode_id,
task_id and task_data) kept only the question, so the same ID could be
seeded or closed for another episode or task, and a seed replayed after a
close recreated a searchable session. Typed seeds are now validated as
ResourcesSeedSessionRequest, their episode and task are recorded next to
the question, and seed and close go through ResourcesSessionFence, as in
example_single_tool_call: a conflicting seed or close answers 409, and a
seed after its session closed is refused for the retry window. The
identity map shares the 10,000-session cap with the questions and is
evicted with them. Legacy Agent seeds are unchanged.

The test runs check_resources_session_contract with keeps_state=True.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
A seed whose question has no word characters ("?!", or an empty user
message) was stored as seeded with span_words=0, which disabled the
verbatim-span rule while require_seeded_question still saw a seeded
session. extract_question now returns None for such text (the question
field falls back to the last user message first), so the session stays
unseeded and its searches fail closed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
…tion

Past MAX_SESSION_QUESTIONS (10,000) seeded sessions the least recently
seeded one was dropped silently, and its later searches were refused as
unseeded_session with nothing pointing at the cause. The eviction now logs
a WARNING naming the session and the cap. The test lowers the cap to one
and also checks that the question and the episode binding leave together.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
blocklist.json is an unmodified copy of docs/blocklist.json from
centerforaisafety/hle at 22ed3074b1e7b134bcbc09028d0ba320839b0655, which
is MIT (Copyright (c) 2025 centerforaisafety). The JSON stays byte-exact
for its digest check, so the upstream LICENSE at that revision is
reproduced unchanged in the sibling LICENSE-HLE, the file gets a row and
a note under Vendored Components in ATTRIBUTIONS.md, and the server
README gains a Licensing section.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
Both READMEs called the Tavily backend the one residual difference from
upstream's wrapper, and the Diamond section said a session not seeded
with the question is refused "so the span rule cannot be skipped". Both
overstate the policy: /seed_session is unauthenticated, so a sandbox
process can seed a fresh session with a question of its choice and
search from it; the 409 on re-seeding covers existing sessions only, and
the session and MCP-token signing key derives from public config.

The server README now names that residual in its own paragraph, the
Diamond section lists it next to the backend as the second residual, the
fail-closed sentences are scoped to unseeded sessions, and the server
README's dangling pointer to the Diamond "Reference preset" section now
points at "Upstream web tools", where the residual is listed. Closing it
needs an authenticated seed channel; both READMEs carry the marker
TRACKING_ISSUE_TBD for the tracking issue, to be replaced by its number
before push.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Rima Shahbazyan <[email protected]>
@rimashahbazyan

Copy link
Copy Markdown
Contributor Author

Thanks for the careful pass. Status at the new head:

  • Blocker (key-pool spin): fixed in eb466ecb9 (end the Tavily call when every key is rejected). The budget test was tightened in b4e52d757, and 5a3b24abb pins 429 rotation. Details are in that thread.

  • CI example data: 47dc1fbda adds data/example.jsonl (5 synthetic rows), the metrics and placeholder rollouts, as in tavily_search. bcb981593 adds the task_data.py that the core tests require. The changed-server step (ng_test ... +should_validate_data=true) passes for hle_web_tools.

  • Title: now feat(hle_web_tools): add upstream HLE web tools server and Diamond preset.

  • Issue: no Gym issue tracks this server itself, and the description says so. The follow-up for the unauthenticated /seed_session residual is hle_web_tools: authenticate /seed_session so a sandbox cannot seed its own session #5845, linked from the description and both READMEs.

  • pre-commit: the Validation section now lists both pre-commit run --files on the changed files and pre-commit run --all-files. Both exit 0 at the new head with no file changes. The guardwords hook was skipped locally because its catalog is private.

  • Merge order: Rshahbazyan/hle reference sandbox image #5177 and Rshahbazyan/opencode image attachments #5175 are both merged, and this branch has merged main four times, after each and twice more before the push. Rshahbazyan/hle reference sandbox image #5177 came in with 6a1b075b4. Rshahbazyan/opencode image attachments #5175 came in with 69c748d08, which resolved the conflicts in ATTRIBUTIONS.md, the Diamond README and test_hle_diamond.py by keeping both sides. 8b2bb4b9d merges main at bd6f5f0d8 (79 commits) with no textual conflict; the root README's environment table was regenerated with scripts/update_env_list.py. 45e175e13 merges main at 363af5e3e (42 more commits), again with no conflict and a regenerated table identical to the auto-merge; it needed no code change (feat(sessions): centralize resources lifecycle and verification ownership #5709 keeps custom seed_session/close_resources_session overrides registered, and its new conformance and repo-contract checks pass for this server). Follow-ups that main required:

    • 7f08605de (import test helpers from their moved nemo_gym paths).
    • 5742b1e5b (pass the core public-API and environment-resources tests) imports maybe_auto_expose from nemo_gym.server_runtime and names the resources server on the example single_agent_turn_legacy server, which the new core checks require.
    • 4950cab31 (use the split session locks and fences from main): refactor(sessions): one name per session lifecycle concept before release #5083 split ResourcesSessionFence into ResourcesSessionLocks and ResourcesSessionFences, and the server now uses those, with no change in behaviour.
    • 60963f0d0 (declare dependencies in pyproject.toml and uv.lock): build(env): AUT-2574 lock managed environments and use uv sync #4837 forbids component requirements.txt files, so the server's one dependency (idna>=3.7) moved to a pyproject.toml with the shared uv policy and a committed uv.lock. The new component_locks CI job passes on it locally.
    • 83c2e5a75 (use main's session terms and name the retire release path) adopts the session glossary that refactor(sessions): one name per session lifecycle concept before release #5083 added to AGENTS.md: episode seed and episode session, agent-run seed, close retry window, release.
    • 7605355e7 (give the true reason the server refuses several workers), after the last merge: feat(sessions): centralize resources lifecycle and verification ownership #5709's add-benchmark skill states that session-ID-keyed state needs no num_workers: 1, which contradicted the reason the README and multiple_workers_unsupported_reason gave; both now give the true reason (no module-level app; per-process page cache and page-check pool). Behaviour is unchanged.
  • Unit tests: locally, with Tavily stubbed:

    • The server tests give 110 passed, three runs.
    • tests/unit_tests/data/test_task_data.py, test_public_api_facades.py, tooling/test_add_legacy_agent_environment_servers.py, tooling/test_component_dependencies.py and test_session_contract_repo.py give 1,416 passed.
    • test_hle_diamond.py gives 73 passed with a routable hostname.
    • scripts/component_locks.py checks 276 projects with 0 failed.
    • Every core-suite failure in my environment also fails on a clean export of main 363af5e3e, or is caused by a git-ignored local file in my checkout and passes on a clean export of this head.

    CI hasn't run on this head yet; could a maintainer comment /ok to test 7605355e77b0ea8e1a8f46769bdf522938812d53? (Use the pushed head's full SHA if it differs.)

  • Live /extract redirect: still not checked against the live API. The server README now says the redirect refusal holds only if Tavily reports the post-redirect URL in results[].url.

@rimashahbazyan rimashahbazyan changed the title Rshahbazyan/hle web tools feat(hle_web_tools): add upstream HLE web tools server and Diamond preset Nov 9, 2026
rimashahbazyan and others added 2 commits November 12, 2026 17:10
Conflicts resolved:
- ATTRIBUTIONS.md: kept main's "OpenCode max-steps prompt" row and note,
  then appended this branch's "HLE with-tools blocklist" row and note after
  them, following the table and note order.
- README.md: took main's environment table and regenerated it with
  scripts/update_env_list.py so the Hle Web Tools row is present.

Signed-off-by: Rima Shahbazyan <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
After merging origin/main, scripts/component_locks.py --jobs 8 reported
"FAIL resources_servers/hle_web_tools: The lockfile at uv.lock needs to be
updated" and ng_test failed at uv sync --locked for the same reason, because
main's root pyproject moved openai from 2.44.0 to 2.45.0 (#5464). Regenerated
with uv lock --project resources_servers/hle_web_tools; the only change is
openai 2.44.0 -> 2.45.0. component_locks now passes 286/286.

Signed-off-by: Rima Shahbazyan <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ools

Signed-off-by: Rima Shahbazyan <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
@Kipok

Kipok commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

/review reset=True

The upstream web tools preset extended opencode_legacy_agent.yaml and so
ran opencode_sandboxed_agent behind the deprecated legacy_agent relay,
the one text preset left on it after #5702 moved the others to agent
sessions. It now extends opencode.yaml and overrides the opencode_agent
instance the way opencode_search.yaml does for Tavily:

- absolute_ip_server_types adds resources_servers, since the sandbox
  reaches the hle_tools server's MCP endpoint by address.
- The environment note moves from the sandbox file
  /tmp/nemo-gym-environment.txt to the agent's system_prompt, and
  mcp_tool_timeout_seconds is 300 for a web_fetch of a long page or PDF.
- The opencode_config reasoningEffort block goes: a session's
  opencode_config takes no model options, and the effort travels on the
  policy model server's extra_body like the other session presets.
- tool_servers ([hle_tools]) and network_access (model_and_tools) stay;
  SingleAgentTurnEnvironmentServer reads the grant from the bound agent
  and requires expose_tools_over_mcp, which the server instance sets.

sandbox_docker_local.yaml composes with the preset again (the override's
hle_diamond_opencode_agent block targets opencode_agent); its note names
no search backend now, since it serves the Tavily and the upstream web
tools preset alike.

Tests: the preset leaves LEGACY_PRESETS and joins the agent-session,
reasoning-effort and local-Docker parametrisations; the config test
asserts the session wiring and holds the agent equal to
opencode_search.yaml's apart from tool_servers and system_prompt. No
server code changes.

Signed-off-by: Rima Shahbazyan <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
@Kipok

Kipok commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

/ok to test 6c16b92

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 17, 2026 01:51
…eset

The benchmark README listed opencode_hle_tools among the deprecated
relay presets (Scope row, relay paragraphs, effort bullets, Known
limitations, Reading sandboxed results, Agent sessions, Reference
preset). It now sits with the session presets everywhere, and the
Upstream web tools section replaces its Deprecated relay paragraph with
the session wiring (episode seed, MCP grant, address exposure, MCP
timeout, extra_body effort), a documented run command composed like the
other presets (the Docker override composes again), and a note that the
2026-10-26 five-row Docker pilot ran on the relay harness, so no
with-tools number is quoted until a pilot is rerun on the session
harness. The residual-difference statements (backend, unauthenticated
/seed_session under model_and_tools, Gym#5845, oversized pages) are
unchanged. The hle_web_tools README's Use in a preset paragraph and the
opencode_reference.yaml header say the same.

Signed-off-by: Rima Shahbazyan <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
@rimashahbazyan

Copy link
Copy Markdown
Contributor Author

Updated to 19001a48fdcf6211c1abd2038a628a974bacac87 (merge of main plus two follow-up commits); the PR is no longer conflicting.

  • Merged main at eb3f77dc9 (151 commits). Three textual conflicts (root README.md table, benchmarks/hle_diamond/README.md, equivalence_llm_judge/tests/test_hle_diamond.py) resolved by keeping main's text and tests verbatim and re-applying this PR's additions.
  • Preset moved to agent sessions. Following feat(hle_diamond): run the text tool presets as opencode_agent and pi_agent sessions #5702, hle_diamond/opencode_hle_tools now runs as an opencode_agent session like opencode_search.yaml, with the Environment Server seeding hle_tools per episode and granting web_search/web_fetch over MCP. It no longer sits on the deprecated opencode_sandboxed_agent relay. No server code changed. Details and validation are in the description under "Round 6".

Could a vetter please run /ok to test 19001a48fdcf6211c1abd2038a628a974bacac87 and lift blocked so the unit-test and Guardwords jobs run? Happy to address anything further.

@Kipok

Kipok commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

/ok to test a237ed3

@yaoyu-33

Copy link
Copy Markdown
Contributor

/ok to test f077d04

@yaoyu-33 yaoyu-33 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed f077d04, including the current-main integration, with independent contract and bug reviews and a challenge pass.

Expected: expose the two HLE web tools with task-bound question filtering, bounded provider failures, and session cleanup. The current Environment Server/MCP/OpenCode path implements those contracts; the earlier key-exhaustion hang and episode-binding/fencing findings are fixed. No new blocking code defect found. The documented unauthenticated-seed and provider redirect-reporting limitations remain.

Validation on the workstation: 218 HLE tools and Diamond tests passed; full pre-commit run --all-files passed, including guardwords and import layering. Regeneration with uv 0.13.4 left the component lock unchanged, and uv lock --check passed. The validated source tree is 7d41a07fceea1904b68f1ae5908d0c737b77ede9.

Full applicable CI passed on this commit: https://github.com/NVIDIA-NeMo/Gym/actions/runs/44137756360 . The separate optional reviewer-suggestion workflow failed; it is not a required check.

Current-preset real-model/Tavily smoke was explicitly waived by the requesting maintainer. The historical pilot is not validation of the current preset, and this approval makes no benchmark-parity claim.

@rimashahbazyan
rimashahbazyan added this pull request to the merge queue Nov 17, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/44141620698

Merged via the queue into main with commit ae58396 Nov 17, 2026
85 of 86 checks passed
@rimashahbazyan
rimashahbazyan deleted the rshahbazyan/hle-web-tools branch November 17, 2026 18:07
akshaver pushed a commit to akshaver/Gym that referenced this pull request Nov 23, 2026
… upstream fidelity audit, full 1000-row preset (NVIDIA-NeMo#6362)

* feat(hle_diamond): run opencode_hle_tools on the HLE reference image

The upstream web-tools preset ran on the offline science image (Python
3.13, SageMath, Lean/Mathlib) and told the model so, while upstream's
docs/evaluation-with-tools.md (centerforaisafety/hle 22ed3074) prescribes
Python 3.11.16 with the twelve pinned packages and nothing else. The
reference image and environment note already existed for
opencode_reference.yaml; the two presets were built in parallel and never
joined.

opencode_hle_tools.yaml now extends opencode_reference.yaml instead of
opencode.yaml: it keeps the reference agent (hle_diamond_opencode_reference_agent,
reference image, network_access model_and_tools, MCP timeout, address
exposure), removes the Tavily resource (`tavily: null`) and swaps in the
hle_tools server as the only tool server. The note is the reference note
with the two tools named as OpenCode shows them to the model
(hle_tools_web_search, hle_tools_web_fetch). Because the agent name is the
reference agent's, sandbox_docker_local.yaml now refuses to compose with
this preset unless HLE_DIAMOND_ACK_UNRESTRICTED_EGRESS=egress-not-restricted
is exported, so a Docker run of the upstream-tools preset can no longer
lift the egress policy silently.

Tests: the NVIDIA-NeMo#5176 parity test now holds the agent equal to the reference
agent apart from tool_servers and system_prompt and asserts the image and
the model-visible tool names; the reference-note (twelve packages, no
SageMath/Lean//opt/science/Tavily) and Docker-refusal tests run over both
reference-image presets; the Docker override's unconditional-inherit list
drops the preset.

Signed-off-by: Rima Shahbazyan <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(hle_diamond): judge the bare question under upstream's cap, keep the judge off the sandbox's reach

Three fidelity gaps against hle_eval/run_judge_results.py and section 1 of
docs/evaluation-with-tools.md (centerforaisafety/hle 22ed3074), on the
opencode_hle_tools preset:

- [question]: upstream's judge sees question['question']; here the judge
  read the whole last user message, which on the opencode prompt is the
  question plus the folded answer-format instruction. The preset sets
  question_extract_regex to cut the instruction off (first capture group);
  a bare question, as the default prompt sends it, matches nothing and
  passes through unchanged.
- Judge output: upstream caps the judge at max_completion_tokens=4096; the
  preset's judge call now carries max_output_tokens: 4096. A verdict cut
  off by the cap scores 0 as no_verdict, as it would upstream.
- Reach: absolute_ip_server_types moves every Resources server to the
  routable address so the sandbox can reach hle_tools, and the egress
  policy opens each allowed host on every port, so the judge resources
  server (and with judge_openai.yaml the o3-mini judge model) was
  reachable from the sandbox. A server's own host wins over the
  type-scoped address (TestAbsoluteIpServerTypes), so both pin
  host: 127.0.0.1; only the judge resources server calls the judge model,
  from the same host. The sandbox now reaches exactly the model server
  and hle_tools.

Tests: a full (non-offline) parse of the preset with judge_openai.yaml,
hostname resolution patched, asserts the per-server hosts; the judge test
renders both prompt files and asserts the extracted question, the cap and
that the other presets keep the judge's defaults.

Signed-off-by: Rima Shahbazyan <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(hle_web_tools): serve long pages cut at the cap, log dropped results at WARNING, bound the cap

Three section-3 gaps against docs/evaluation-with-tools.md (centerforaisafety/hle
22ed3074):

- Oversized pages. The protocol caps web_fetch at 60,000 characters with a
  truncation indicator and checks "the title and Markdown" of the response;
  it never refuses a page for its length. The server checked the provider's
  whole page before the cut and refused anything over max_page_chars
  (1,000,000) unread as the Gym-only family oversized_page, so long PDFs
  came back refused where upstream serves their start. The page is now
  sanitized, cut at max_fetch_chars and checked as served, title included,
  fresh and from the cache; the cut is what the cache holds. That bounds
  the content scan at the cap (0.25 s for 60,000 adversarial characters,
  measured) without a size refusal, so max_page_chars, oversized_page and
  the now-moot max_cached_page_chars are removed. The page-check pool
  stays: the scan still holds the GIL for its whole run.
- Audit log. "Log blocked calls and the matching rule" held for refusals
  (WARNING) but dropped search results went out at INFO, which Gym's server
  processes never emit (no root logger is configured outside --verbose).
  Dropped results are logged at WARNING too, same line shape.
- Cap bound. max_fetch_chars accepted any value above the protocol's
  60,000; it is now bounded le=60,000, as max_results already was.

Tests, written first and failing on the old code: the domains test reads
the dropped-result lines at WARNING and asserts their level; a 1.5 M-char
page is served cut with the indicator, a blocked span inside the served
Markdown or in the title refuses, the cached cut page is rechecked; the
cap above 60,000 is rejected. The event-loop stall test's gap bound drops
to 0.1 s, under the bounded scan, and was checked to fail with the page
check run inline.

Signed-off-by: Rima Shahbazyan <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>

* docs(hle_diamond): fidelity table for opencode_hle_tools against upstream 22ed3074

The Upstream web tools section of the Diamond README now describes the
preset as it is (opencode_reference's agent, image and egress with the
Tavily tools replaced by hle_web_tools) and replaces its departures list
with a fidelity table: one row per requirement of docs/evaluation-with-tools.md
sections 1 to 4 and of hle_eval/ at centerforaisafety/hle 22ed3074, each
marked matched or cannot match with where and why, plus a harness mapping
for section 4 (Claude Code, Codex CLI, Gemini CLI, Muse Code against the
agents Gym has). The two residuals (Tavily backend, unauthenticated seed,
Gym#5845) stay; the oversized-page residual is gone with the server change.
The documented run line adds ++count_missing_rollouts_as_zero=true
(upstream's denominator) and the OpenSandbox dns+nft preflight is stated.
The preset still has no with-tools number: the one pilot ran the previous
harness on the science image with open egress.

Scope row, the sandboxed-agents departures list, the Reference preset
paragraph (the follow-up is done), the Docker-override refusal note and
the Scoring judge-request paragraph (this preset's cap and bare-question
regex) follow. The reference image README names both presets and says
that pip is neutralised by the network policy, not removed.

Signed-off-by: Rima Shahbazyan <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>

* feat(hle_diamond): run opencode_hle_tools over all 1000 questions, image rows included

The published HLE-Diamond with-tools numbers divide by all 1000 questions; the agent-session
presets ran only the 728 text rows, so no comparable denominator existed. opencode_hle_tools_full
composes opencode_hle_tools and swaps only the reference agent's dataset for the full set that
prepare_opencode_legacy.py writes (one user message with the folded HLE instruction and, on the
272 image rows, an input_image block). The opencode_agent session stages each image into the
sandbox and attaches it with `opencode run --file`; the dataset's `detail: high` is never read, so
the request carries image_url with no detail, as upstream's does. Same agent, image, tool server,
egress policy, note and judge; a test holds the two compositions equal apart from the dataset.

Docs follow: preset table and coverage paragraph, fidelity row for the 1000/272 requirement
(harness analogue: OpenCode's Read tool places two synthetic text parts and the image ahead of the
question), prepare docstrings, the Docker override's header (three reference-image presets), and the
removal of "no session preset covers the image rows yet" everywhere it appeared.

Signed-off-by: Rima Shahbazyan <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>

* docs(hle_diamond): record the 2026-11-18 Docker pilot of opencode_hle_tools over all 1000 questions

GPT-6 Astra, reasoning high, judge o3-mini, local Docker with open egress (comparison infrastructure
only): 624/728 = 85.7 % on the text rows, 203/272 = 74.6 % on the image rows through the same
composition with the dataset swapped (what opencode_hle_tools_full declares), 827/1000 = 82.7 %
composed against the published 82.9 %. Every first policy call of the 272 image rows carried the
image as a data URI with no detail. Replaces the "unrun / no run exists yet" wording of the README
and the preset header; the OpenSandbox gate stays open.

Signed-off-by: Rima Shahbazyan <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>

* docs(hle_diamond): paired judge regrade for opencode_hle_tools, fix override target

Address review on NVIDIA-NeMo#6362.

Record a paired regrade of the 2026-11-18 pilot's 1,000 saved rollouts
(gym eval reverify, same completions, same judge) under this preset's
judge settings and the earlier ones. Earlier settings: 824/1000 with 18
no_verdict calls where the judge copied the folded answer-format
instruction, 6 of them on answers it called correct. This preset's
settings: 826 and 827 over two passes, 0 no_verdict, no call near the
4096-token cap.

The compaction and step-limit overrides named the wrong agent for
opencode_hle_tools and opencode_hle_tools_full, which run
hle_diamond_opencode_reference_agent.

Signed-off-by: Rima Shahbazyan <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>

* fix(hle_diamond): rename the hle_tools server to web_tools so tool names do not name the benchmark

Review on NVIDIA-NeMo#6362: OpenCode shows MCP tools as <server>_<tool>, so the
model saw hle_tools_web_search and hle_tools_web_fetch. The server
instance is now web_tools (web_tools_web_search, web_tools_web_fetch),
and the refusal text returned to the model no longer says "HLE".

The 2026-11-18 pilot ran under the old names and was not rerun; the
README says so. A one-row run after the rename offered the new names
in every policy request, with no "hle" string in any of them.

Signed-off-by: Rima Shahbazyan <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>

* fix(hle_diamond): address review of opencode_hle_tools (isolation, fetch title, audits, docs)

Review on NVIDIA-NeMo#6362.

Behaviour:
- config.yaml pins the judge resources server to loopback on every
  preset; opencode_hle_tools pins the Environment Server too, so an
  explicit default_host leaves only the model server and web_tools
  reachable from the sandbox.
- hle_web_tools: the title fallback reads the first heading of the cut
  Markdown, so text past the 60,000-character cut is neither served nor
  checked; dropped search results are logged at INFO, refusals stay at
  WARNING.

Tests: the host test lists every started server and covers an explicit
default_host; the fetch tests fail on an unchecked provider title, an
uncut cached page, "HLE" in a refusal and an ignored max_fetch_chars.

Docs: audit of the 2026-11-18 pilot's saved tool calls. The pilot told
the model egress was open; about 135 rows made network calls from bash
(102 fetched web content, 57 installed packages, 10 fetched a chess
engine, at least 12 reached blocklisted GitHub hosts), and OpenCode hid
356 of 2,115 web_fetch replies behind its 50 KiB tool-output limit.
Fidelity rows corrected for web_fetch, web_search, the judge cap, the
denominator, effort verification and logging.

Signed-off-by: Rima Shahbazyan <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>

---------

Signed-off-by: Rima Shahbazyan <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers benchmark-onboarding Self-contained benchmark onboarding blocked Work cannot move forward until an external dependency is cleared feature New capabilities, enhancements, or enablement work sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants