Skip to content

feat(spatialclaw): port original GitLab evaluation harness - #3996

Open
ehosseiniasl wants to merge 10 commits into
NVIDIA-NeMo:mainfrom
ehosseiniasl:feat/spatialclaw-native-evaluation
Open

ehosseiniasl wants to merge 10 commits into
NVIDIA-NeMo:mainfrom
ehosseiniasl:feat/spatialclaw-native-evaluation

Conversation

@ehosseiniasl

@ehosseiniasl ehosseiniasl commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Ports GitLab Gym MR !471 at 229815ecfddab961dc36806bad73fa2159df0462 to current NVIDIA-NeMo/Gym. Adds SpatialClaw as a reusable NeMo Gym evaluation harness for spatial-reasoning benchmarks.

  • Adds a shared SpatialClaw Responses API agent that supports image, multi-image, video, multi-video, grouped-frame, and reference-image samples.
  • Adds one native SpatialClaw dataset-preparation and verification path for all 20 benchmarks.
  • Adds a suite configuration plus individual benchmark configurations for all 20 benchmarks represented by the pinned SpatialClaw revision.
  • Preserves each benchmark's native aggregation protocol, including macro averages, category breakdowns, mean-relative-accuracy calculations, and group-aware Video-MME-v2 scoring.

Architecture

SpatialClaw implementation structure

The same preparation, agent, tool, and evaluation pipeline applies across all 20 benchmark configurations.

Supported benchmarks

  • Single-image spatial: ERQA, Omni3D, OmniSpatial, SPBench
  • Multi-view spatial: MindCube, MMSI, SPAR-Bench
  • General spatial: BLINK, SpatialTree, ViewSpatial
  • Video spatial / 4D: MMSI-Video, OSI-Bench, PAI-Bench, VSI-Bench-U, VSTI-Bench, DSI-Bench
  • General video: CV-Bench, PerceptComp, Video-MME, Video-MME-v2

benchmarks/spatialclaw/config.yaml composes the complete suite. Every benchmark also has an individual YAML configuration so it can be prepared and run independently.

Implementation

  • responses_api_agents/spatialclaw_agent runs the pinned SpatialClaw planning, reasoning, and perception-tool loop through Gym's Responses API contract.
  • benchmarks/spatialclaw converts native SpatialClaw samples into portable Gym JSONL rows while retaining relative media paths and benchmark metadata.
  • resources_servers/spatialclaw is the shared verifier for all 20 benchmarks. SpatialClaw's BenchmarkFactory selects each native benchmark's evaluate_single and full evaluate implementations.
  • SPATIALCLAW_ROOT selects the pinned source checkout and SPATIALCLAW_DATA_ROOT selects the shared benchmark-data root.

Historical validation from GitLab MR !471

The following results are reported by the original MR. They are
preserved as provenance, not a fresh full evaluation of this GitHub commit.

  • A regression test verifies that all 20 benchmark configurations compose the same SpatialClaw agent and resource server.
  • Video-MME was prepared with the pinned native SpatialClaw loader; all 2,700 IDs, prompts, answers, and media mappings matched the completed inference run.
  • The completed 2,700 predictions were rescored with the native SpatialClaw evaluator with zero per-row reward mismatches.
  • Focused test suite: 22 passed.
  • Ruff lint and formatting checks passed.
Video-MME run Correct Total Accuracy
NeMo Gym reproduction (Nano GA Omni) 1,816 2,700 67.2593%
Accepted SpatialClaw reference 1,811 2,700 67.0741%
Difference +5 - +0.1852 pp

The reproduced run had no missing, duplicate, conflicting, or malformed rows.

Notes for reviewers

  • The _256f configurations inherit frame/FPS behavior from the pinned SpatialClaw dataset configurations rather than redefining sampling independently in Gym.
  • Reconstruct and SAM3 remain external SpatialClaw GPU services and are discovered through the SpatialClaw GPU-server registry.

Review update (November 9, 2026)

Candidate: cf2976a7b7bee70a90b331a6f7f7789a2e1f77f0, rebased onto upstream main acb67734cc37d201e1350395ae422a771582ac21.

  • Reuses one dependency-light TaskData schema in resource requests and exposes it from the agent for dataset validation.
  • Preserves Video-MME-v2's native dataset order and complete four-question groups after Gym removes masked rows. A group with any absent/masked member is excluded as a whole; spatialclaw/num_evaluated_groups and spatialclaw/num_dropped_groups report coverage against the loaded dataset, including groups outside a requested subset. Row-level pass metrics still cover all measured rows.
  • Adds spatialclaw/final_rating/total to the headline metrics and normalizes empty extractions to None for no-answer/majority accounting.
  • Rejects multiple repeats in native aggregation, including a surviving nonzero rollout index after masking. These presets require num_repeats: 1.
  • Scores overall agent timeouts and agent/model-caused execution errors zero, with explicit failure metadata. Clear model transport/service failures remain masked. Model HTTP status/failure records survive native nodes catching exceptions and are shared with Jupyter kernels; subsequent native retries do not resend a terminal failed request. Media-download errors are classified separately.
  • Adds opt-in tests against pinned native Video-MME-v2 and SpatialTree evaluators and the real native llm_step_node (400 and 503). These skip without SPATIALCLAW_ROOT.
  • Removes the shared _CaptureMiddleware change and its added core test from this PR. Current main already contains response deferral and the capture-write barrier from #4593; no separate capture fix is needed from this branch. The diff contains no core model-server changes.
  • Marks the integration internal-only and experimental in all three READMEs. The external source requires NVIDIA GitLab access and its own LICENSE §3.3 limits use to non-commercial scientific research. Gym's Apache-2.0 license does not change those terms; no external implementation is vendored.

No separate issue is needed for this direct port of the existing GitLab MR !471; this PR tracks the integration and its remaining merge gates.

Fresh local validation of this candidate

  • 515 tests passed, covering both SpatialClaw components, benchmark preparation/configuration, native evaluator/node regressions, and the complete core task-data schema suite.
  • 97.39% SpatialClaw coverage, above the 95% gate, with coverage over the agent, resource server, and benchmark preparation modules.
  • pre-commit run --all-files: passed.
  • Resource-server five-example data/metrics/rollout gate: passed.
  • All 20 benchmark configurations remain covered by the configuration regression.
  • Historical rollout examples and scores above remain historical; they were not regenerated on this candidate.

Remaining merge gates

This PR is ready for review, with verified: false. The requested head-SHA Video-MME smoke and Video-MME-v2 model run over several complete groups, each compared with native evaluation on the same predictions and reporting masked counts, remain pending. The old model endpoint is unreachable. The scheduler reports no GPU nodes in the GPU partitions; both a three-GPU nemotron_edge_omni/batch_singlenode preflight and a one-GPU nemotron_omni_vision/batch_block1 preflight were rejected with More processors requested than permitted. No validation job was created. The passing native regression tests are not a substitute for those model runs.

The licensing/access decision remains for the maintainers/licensor; the README disclosure does not claim approval or public reproducibility.

Eval Factory MR !2020 is ready for review. Before merge, it requires this PR to merge and its pin to be replaced with the eventual NVIDIA-NeMo/Gym merged main SHA. Its historical fork pin is not a deployment-ready release pin.

Training compatibility: this evaluation harness does not implement the companion training/pivot adapter required by NeMo RL #4235 and #4236.

@ehosseiniasl ehosseiniasl added feature New capabilities, enhancements, or enablement work area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers labels Oct 4, 2026
@copy-pr-bot

copy-pr-bot Bot commented Oct 4, 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.

@ehosseiniasl ehosseiniasl self-assigned this Oct 5, 2026
@ehosseiniasl ehosseiniasl changed the title feat(spatialclaw): evaluate with the original SpatialClaw workflow feat(spatialclaw): port original GitLab evaluation harness Oct 5, 2026
@ehosseiniasl
ehosseiniasl marked this pull request as ready for review October 5, 2026 05:20
@yaoyu-33 yaoyu-33 added complexity:high Cross-component or shared-contract change with a large review surface needs-review PR is ready for code review and waiting on a reviewer labels Oct 5, 2026
@github-actions github-actions Bot added the sla:triage-overdue Review assignment is over the one-business-day SLA label Oct 6, 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.

Thanks for porting SpatialClaw. Reusing the native evaluators rather than reimplementing them is the right call, and the capture-race regression test is a good catch. A few things need attention before this can merge:

  • Rebase: the PR conflicts with main. Please rebase.
  • Video-MME-v2 scoring: see the inline comment on resources_servers/spatialclaw/app.py:179. This is the headline score the companion Eval Factory MR !2020 ships.
  • Baseline: verified: false is right. The fresh smoke ran on e5d891b5, not this head, and Video-MME-v2 has not been run at all. Could you share:
    • a Video-MME-v2 run (at least a few complete four-question groups) at the head SHA, compared with native evaluate on the same predictions;
    • a head-SHA rerun of the Video-MME smoke, with masked counts reported next to accuracy.
  • Scope: the _CaptureMiddleware change in nemo_gym/base_responses_api_model.py changes every model server. Could it move to its own fix(capture) PR? After rebasing, could that PR explain why it's still needed alongside #4593?
  • Linked issue: please link an issue, or say why none is needed.
  • Eval Factory pin: MR !2020 pins ehosseiniasl/Gym@8b1345ea. That SHA won't exist on NVIDIA-NeMo/Gym after a rebase or squash, so the MR should stay in draft until it's re-pinned to the merged main SHA.

Comment thread resources_servers/spatialclaw/app.py Resolved
Comment thread resources_servers/spatialclaw/app.py Resolved
Comment thread resources_servers/spatialclaw/app.py Resolved
from responses_api_agents.spatialclaw_agent.observability import read_observations, response_usage


SPATIALCLAW_URL = "ssh://[email protected]:12051/ehosseiniasl/spatial_claw.git"

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.

responses_api_agents/spatialclaw_agent/app.py:61

The agent, the verifier and prepare all clone gitlab-master.nvidia.com/ehosseiniasl/spatial_claw at runtime. Outside NVIDIA this isn't reachable, and its LICENSE (§3.3) limits use to non-commercial research. Could we get a maintainer/legal call on depending on it from this Apache-2.0 repo, for example a public mirror under a compatible license, or marking the benchmark internal-only? Could the README state the access and license limits either way?

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.

Documented in cf2976a: the benchmark, agent, and resource-server READMEs now mark this integration internal-only and experimental, state the NVIDIA GitLab access requirement and the external LICENSE §3.3 non-commercial scientific research restriction, and make clear that Gym Apache-2.0 does not change those terms. No native code is vendored. Leaving this thread open because a maintainer/licensor decision is still required; both this PR and Eval Factory MR !2020 are now draft.

Comment thread resources_servers/spatialclaw/app.py Resolved
Comment thread resources_servers/spatialclaw/app.py Resolved
@github-actions github-actions Bot removed the sla:triage-overdue Review assignment is over the one-business-day SLA label Oct 20, 2026
Port GitLab Gym !471 at 229815ecfddab961dc36806bad73fa2159df0462, preserving its 20 presets and native runtime pin. Adapt routing, worker startup, Python 3.13 dependencies, and Jupyter HTTP transport for current Gym.

Signed-off-by: Ehsan Hosseini Asl <[email protected]>
@ehosseiniasl
ehosseiniasl marked this pull request as draft November 9, 2026 19:31
@ehosseiniasl
ehosseiniasl force-pushed the feat/spatialclaw-native-evaluation branch from 8b1345e to cf2976a Compare November 9, 2026 19:34
@ehosseiniasl

Copy link
Copy Markdown
Contributor Author

Pushed cf2976a, rebased onto current main acb6773. GitHub now reports MERGEABLE.

The code findings are fixed, with individual thread replies. Local validation: 515 tests passed, 97.39% SpatialClaw coverage, all pre-commit hooks passed, and the five-example resource data gate passed. Native evaluator/node tests ran against the exact external pin.

The shared capture middleware change and added core regression were removed from this PR. Current main already has response deferral and the pending-write barrier from #4593, so this branch needs no separate capture fix.

No separate issue is needed for this direct port of existing GitLab Gym MR !471; this PR tracks the integration and merge gates.

This PR and Eval Factory MR !2020 are now draft. MR !2020 explicitly requires the eventual NVIDIA-NeMo/Gym merged main SHA before it is ready; the old fork pin is historical.

Two gates remain open: the maintainer/licensor decision on the internal non-commercial native dependency, and fresh head-SHA model runs for Video-MME plus several complete Video-MME-v2 groups, compared with native evaluation and reporting masked counts. The previous model endpoint is unreachable. Both GPU preflight submissions were rejected by Slurm with “More processors requested than permitted”; no job was created. Native regression tests and historical smoke artifacts do not replace that requested model evidence. verified remains false.

@yfw yfw 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. Two required CI gates fail on main merged with this PR: the component dependency gate (requirements.txt:6-10) and the public-API import test (app.py:14-22).

Thank you for the thorough fix round on Yu Yao's review. Eight of nine threads have a code fix. For most of them, a test that CI runs fails when the fix is reverted. The READMEs now state the access and license limits.

Yu Yao's threads on TaskData, Video-MME-v2 groups, timeouts and agent errors, repeats, the headline key, empty extractions and the gated tests are resolved. The thread-4 fix records the HTTP status as asked, but it also refuses later model calls (app.py:372-375). Thread 6, on license and access, waits for a maintainer decision.

Two points for the maintainers, with no ruling from this review:

  1. The thread-6 license decision. Please include the example rows in it. example.jsonl and example_rollouts.jsonl hold five real Video-MME questions with their gold answers. The Video-MME terms say: "Without prior approval, you cannot distribute, publish, copy, disseminate, or modify Video-MME in whole or in part." Gym #6071 uses invented rows for the same dataset.
  2. What CI runs. CI runs 61 of the PR's 72 tests. The 6 tests that load real SpatialClaw code skip without SPATIALCLAW_ROOT (server, agent). No CI job collects the 5 tests in benchmarks/spatialclaw/tests. Core CI uses testpaths = ["tests"], and the server suites cover only the server folders. So CI never runs a SpatialClaw evaluator. An outside user sees 20 spatialclaw/* benchmarks and cannot run any of them.

Still open, as the PR description says: the model runs at this head that Yu Yao asked for. They are a Video-MME smoke with masked counts, and a Video-MME-v2 run over complete groups against SpatialClaw's evaluate.

The comment on videomme.yaml:39-45 recommends landing this PR together with #5894. It does not block merge.

Gym #6071 also scores Video-MME-v2, with a different rule for masked rows. There a masked row counts as wrong, and here it drops its group of four. So the two Video-MME-v2 numbers are not comparable.

CI ran only four jobs at this head, and all four pass: DCO, lint, copyright and secrets. The unit and server tests wait for a maintainer to start CI. There is no merge conflict, and all 10 commits are signed off.

Generated by Claude Code

Comment on lines +6 to +10
wcwidth>=0.2
pyzmq>=25.0
shortuuid>=1.0
numpy>=2.1,<3
opencv-python-headless>=4.8,<4.13

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.

responses_api_agents/spatialclaw_agent/requirements.txt:6-10

Both new components ship only requirements.txt, so main's dependency gate fails on this PR.

On main merged with this PR, 5 tests in test_component_dependencies.py fail, and each failure names only SpatialClaw paths. test_servers_declare_locked_dependencies and test_servers_do_not_use_requirements_txt report the missing lock files and the two requirements.txt files. test_component_uv_policy_matches_root_with_declared_exceptions, test_locks_satisfy_shared_security_floors and test_managed_git_requirements_pin_full_revisions raise FileNotFoundError on resources_servers/spatialclaw/pyproject.toml. The Component locks job also fails, because check_project returns "Missing pyproject.toml". The required Nemo_CICD_Test then exits 1. The gate came with #4837, which is already in this PR's base, so the PR head fails the same way.

The same move must also turn opencv-python-headless and wcwidth back on. This file asks for both, and resources_servers/spatialclaw/requirements.txt asks for OpenCV. Gym's root override-dependencies sets wcwidth and opencv-python-headless to sys_platform == 'never', and the root file says:

server venvs install nemo-gym editably and inherit this list, so anything here is also silently dropped from them

So the venvs that Gym builds today miss both packages: import cv2 fails in both component venvs, and import wcwidth fails in the agent venv. The PR tests stay green, because no PR file imports cv2 or wcwidth, and the tests stub the spatial_agent modules. Your own overrides.txt in #5894 states the need: "The native drawing/video and IPython runtimes require these opt-in dependencies."

Suggested fix (it spans several files, so it cannot be a suggestion block):

  1. Replace requirements.txt with pyproject.toml and uv.lock in both components. Lock each one with uv lock --project <component>, as the new-environment guide shows. Do not run scripts/component_locks.py --update, because it regenerates every lock in the repository.
  2. In each new pyproject.toml, replace the matching sys_platform == 'never' lines with the versions below, like agentic_mme_agent. Add the same entries to scripts/component-lock-policy.json, like its agentic_mme_agent and miniswe_sandboxed_agent entries:
    "resources_servers/spatialclaw": {"override-dependencies": ["opencv-python-headless>=4.8,<4.13"]},
    "responses_api_agents/spatialclaw_agent": {"override-dependencies": ["opencv-python-headless>=4.8,<4.13", "wcwidth>=0.2"]},
  3. _ensure_server_venv runs uv pip install ... -r requirements.txt, which breaks once the file is gone. Set prepare_project: resources_servers/spatialclaw on the dataset of each preset. Then delete _ensure_server_venv and the subprocess branch of prepare(). With prepare_project, gym eval prepare syncs the locked project and runs the prepare script in it (_prepare_environment). gdp_pdf uses this shape.

Please delete requirements.txt in the same change. A component that keeps it next to pyproject.toml still fails test_servers_do_not_use_requirements_txt. Main's server setup also raises "Found both pyproject.toml and requirements.txt in {dir_path}; use only one."

Do not copy the root override list unchanged into the new pyproject.toml. That keeps both packages out, and test_component_uv_policy_matches_root_with_declared_exceptions still passes.

Comment on lines +14 to +22
from nemo_gym.metrics.reward_profile import compute_pass_majority_metrics, highest_k_metrics
from nemo_gym.server_runtime.base_resources_server import (
BaseResourcesServerConfig,
BaseRunRequest,
BaseVerifyRequest,
BaseVerifyResponse,
ReverifyMode,
SimpleResourcesServer,
)

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.

resources_servers/spatialclaw/app.py:14-22

New code in this PR imports Gym names from submodules, so main's public-API import test fails.

test_code_outside_the_library_imports_exported_names_from_the_public_api fails at the PR head and on main merged with this PR. It lists 27 imports in five files of this PR, and these lines hold 8 of them. The rule is in AGENTS.md: code outside nemo_gym/ imports public names with from nemo_gym.<package> import Name. Separately, 14 imports in the agent's app.py and observability.py use paths that moved in 0.8.0. They warn now and stop working in 0.10.0.

Suggested fix: please import each name from its package's public API. For this file, that is the block below.

Suggested change
from nemo_gym.metrics.reward_profile import compute_pass_majority_metrics, highest_k_metrics
from nemo_gym.server_runtime.base_resources_server import (
BaseResourcesServerConfig,
BaseRunRequest,
BaseVerifyRequest,
BaseVerifyResponse,
ReverifyMode,
SimpleResourcesServer,
)
from nemo_gym.metrics import compute_pass_majority_metrics, highest_k_metrics
from nemo_gym.server_runtime import (
BaseResourcesServerConfig,
BaseRunRequest,
BaseVerifyRequest,
BaseVerifyResponse,
ReverifyMode,
SimpleResourcesServer,
)

The other four files need the same change: the agent's app.py, observability.py, tests/test_app.py and tests/test_observability.py. They are other files, so their tested import blocks are in the fold below. scripts/migrate_imports.py alone is not enough: it fixes only the moved paths and leaves all 27 submodule imports in place.

Tested import blocks for the other four files

Agent app.py, in place of L33-L56:

from nemo_gym.agents import BaseResponsesAPIAgentConfig, Body, SimpleResponsesAPIAgent
from nemo_gym.client import get_response_json, raise_for_status
from nemo_gym.client import request as http_request
from nemo_gym.config import ModelServerRef, ResourcesServerRef, get_first_server_config_dict
from nemo_gym.core import (
    NeMoGymChatCompletion,
    NeMoGymEasyInputMessage,
    NeMoGymResponse,
    NeMoGymResponseCreateParamsNonStreaming,
    NeMoGymResponseOutputMessage,
    NeMoGymResponseOutputText,
)
from nemo_gym.server_runtime import BaseRunRequest, BaseVerifyResponse
from nemo_gym.server_runtime.base_resources_server import AggregateMetrics, AggregateMetricsRequest
from nemo_gym.trajectory import AgentObservationBundle
from nemo_gym.utils import is_nemo_gym_fastapi_entrypoint

observability.py, in place of L13-L26:

from nemo_gym.config import ModelServerRef
from nemo_gym.core import (
    NeMoGymResponseInputItem,
    NeMoGymResponseInputTokensDetails,
    NeMoGymResponseOutputTokensDetails,
    NeMoGymResponseUsage,
)
from nemo_gym.trajectory import (
    AgentInvocation,
    AgentObservationBundle,
    ModelCallRef,
    ObservationGap,
    ToolCallObservation,
)

tests/test_app.py, in place of L13-L15:

from nemo_gym.client import ServerClient
from nemo_gym.config import ModelServerRef, ResourcesServerRef
from nemo_gym.core import NeMoGymResponseCreateParamsNonStreaming

tests/test_observability.py, in place of L11-L12:

from nemo_gym.client import ServerClient
from nemo_gym.config import ModelServerRef, ResourcesServerRef

The test does not flag AggregateMetrics and AggregateMetricsRequest, because the package does not export them. With these blocks, the public-API test finds no submodule imports in the PR files. The PR tests pass (61 passed, 6 skipped), and ruff is clean.

Comment on lines +372 to +375
# Native nodes catch model exceptions and retry. Keep terminal failures
# across processes so retries cannot hide or repeatedly send a rejected call.
if self.journal and (failure := _model_transport_failure(Path(self.journal))):
raise RuntimeError(failure["failure_reason"])

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.

responses_api_agents/spatialclaw_agent/app.py:372-375

After one failed model call, _create refuses every later call, so native retries never reach the model and the answer is lost.

The code comment states the goal:

Native nodes catch model exceptions and retry. Keep terminal failures across processes so retries cannot hide or repeatedly send a rejected call.

But L374-L375 treat every journaled failure as terminal. A 503 or a dropped connection counts too. They also refuse all later calls, not only a resend of the rejected one. Each call goes out once (_max_num_tries=1), so the native retries are the only recovery inside the episode. After arun, responses() replaces the final answer with an empty string for any journaled failure.

Two cases show it. Both ran on the PR head and on main merged with this PR, with a stand-in workflow that retries like the native nodes. Case 1: one 503 on the first planner call, then a healthy server. Only one request reaches the model, the answer is empty, and the row is masked. Case 2: one 400 on a vision call inside a code step, then a good planner call. The answer is empty, and the row is scored 0 as spatialclaw:model_request_rejected. With the fix below, both cases reach the model again and return the workflow's answer.

The PR's own native test encodes this: it runs the real llm_step_node twice and expects one request. This came with the thread-4 fix in cf2976a. Yu Yao asked: "Could the transport record the HTTP status in the journal (or raise a sentinel the native nodes can't swallow) and classify from that after arun?" He did not ask to stop the retries after a 503 or a dropped connection.

Suggested fix: please refuse only a resend of a rejected request, and make _model_transport_failure use only the last journal record. The journal keeps a hash of each failed request for this. The change has three parts in this file. Each part alone leaves the bug, so this is a plain diff, not a suggestion.

--- a/responses_api_agents/spatialclaw_agent/app.py
+++ b/responses_api_agents/spatialclaw_agent/app.py
@@ -369,9 +369,10 @@
         return await self._create(payload)
 
     async def _create(self, payload: dict[str, Any]) -> NeMoGymChatCompletion:
-        # Native nodes catch model exceptions and retry. Keep terminal failures
-        # across processes so retries cannot hide or repeatedly send a rejected call.
-        if self.journal and (failure := _model_transport_failure(Path(self.journal))):
+        # Native nodes catch model exceptions and retry. Never resend a request the
+        # model server rejected; other calls still go out, so the episode can recover.
+        request_sha256 = hashlib.sha256(json.dumps(payload, sort_keys=True, default=str).encode()).hexdigest()
+        if self.journal and (failure := _rejected_request(Path(self.journal), request_sha256)):
             raise RuntimeError(failure["failure_reason"])
         try:
             return await self._request(payload)
@@ -386,6 +387,7 @@
                     "failure_reason": f"{type(exc).__name__}: {exc}",
                     "http_status": status,
                     "mask_sample": infrastructure,
+                    "request_sha256": request_sha256,
                 }
             )
             raise
@@ -416,14 +418,27 @@
         return result
 
 
+def _journal_records(journal: Path) -> list[dict[str, Any]]:
+    if not journal.is_file():
+        return []
+    with _checkout_lock(Path(f"{journal}.lock")):
+        return [json.loads(line) for line in journal.read_text().splitlines()]
+
+
 def _model_transport_failure(journal: Path) -> dict[str, Any] | None:
-    if journal.is_file():
-        with _checkout_lock(Path(f"{journal}.lock")):
-            for line in journal.read_text().splitlines():
-                record = json.loads(line)
-                if record.get("failure_kind"):
-                    return record
-    return None
+    records = _journal_records(journal)
+    return records[-1] if records and records[-1].get("failure_kind") else None
+
+
+def _rejected_request(journal: Path, request_sha256: str) -> dict[str, Any] | None:
+    return next(
+        (
+            record
+            for record in _journal_records(journal)
+            if record.get("failure_kind") and not record["mask_sample"] and record["request_sha256"] == request_sha256
+        ),
+        None,
+    )
 
 
 class _AiohttpOpenAIClient:

With this change, a rejected request goes out only once, as the current code comment intends. Yu Yao's thread-4 comment noted that native nodes retry a 400 max_retries times. Other calls still go out, and a later successful call clears an earlier failure. If every retry fails, the last record is still the failure, so the row ends as it does today. hashlib and json are already imported in this file. The hash also appears in _ng_agent_failure on rows with a failed model call, next to http_status.

Refusing every call after any 4xx is not enough. It still zeroes an episode that recovered from one rejected image query.

Please also change two test lines. In tests/test_app.py L356, model_request.assert_awaited_once() becomes assert model_request.await_count == (1 if model_status in {400, 422} else 3). In tests/test_native.py L53, request.assert_awaited_once() becomes assert request.await_count == (2 if masked else 1). The 503 case now sends two requests, and the 400 case still sends one.

Comment on lines +721 to +735
session_dir = Path(self.config.workspace_root).expanduser().resolve() / session_id
session_dir.mkdir(parents=True, exist_ok=False)
workflow = None
result = {}
failure = None
started_at = time()
journal = session_dir / "gym-model-responses.jsonl"
try:
spatial_config = self._build_spatialclaw_config(root, session_dir, body, request)
instruction, images, metadata = await self._materialize_inputs(body, session_dir, spatial_config)
from spatial_agent.config import set_config
from spatial_agent.workflow import SpatialAgentWorkflow

set_config(spatial_config)
workflow = SpatialAgentWorkflow(spatial_config)

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.

responses_api_agents/spatialclaw_agent/app.py:721-735

A configuration error masks every row as spatialclaw:media_error, so a run with a typo reports coverage only.

The except branch labels any exception before the workflow exists as spatialclaw:media_error and masks the row. That covers _build_spatialclaw_config and the spatial_agent imports in this range, not only media. For example, config_overrides: {video_max_fsp: 4} (a typo of video_max_fps) gives this failure on every row:

{"failure_kind": "spatialclaw:media_error", "failure_reason": "ValueError: Unknown SpatialClaw config override: video_max_fsp", "mask_sample": true}

A missing model-role JSON gives the same label with a FileNotFoundError from _config_path. The run still completes, and with every row masked it reports coverage only. The label also sends the user to look for missing videos.

Suggested fix: please build the configuration and import spatial_agent before the try and before mkdir.

Suggested change
session_dir = Path(self.config.workspace_root).expanduser().resolve() / session_id
session_dir.mkdir(parents=True, exist_ok=False)
workflow = None
result = {}
failure = None
started_at = time()
journal = session_dir / "gym-model-responses.jsonl"
try:
spatial_config = self._build_spatialclaw_config(root, session_dir, body, request)
instruction, images, metadata = await self._materialize_inputs(body, session_dir, spatial_config)
from spatial_agent.config import set_config
from spatial_agent.workflow import SpatialAgentWorkflow
set_config(spatial_config)
workflow = SpatialAgentWorkflow(spatial_config)
session_dir = Path(self.config.workspace_root).expanduser().resolve() / session_id
spatial_config = self._build_spatialclaw_config(root, session_dir, body, request)
from spatial_agent.config import set_config
from spatial_agent.workflow import SpatialAgentWorkflow
session_dir.mkdir(parents=True, exist_ok=False)
workflow = None
result = {}
failure = None
started_at = time()
journal = session_dir / "gym-model-responses.jsonl"
try:
instruction, images, metadata = await self._materialize_inputs(body, session_dir, spatial_config)
set_config(spatial_config)
workflow = SpatialAgentWorkflow(spatial_config)

Then a configuration error fails the request with its real message, instead of a masked row. A spatial_agent import error also fails the request, instead of masking every row. _build_spatialclaw_config only stores session_dir as work_dir, so it can run before mkdir, and a raise leaves no empty session folder. Media errors stay inside the try and keep their label.

server.compute_metrics([[{"sample_id": "one"}, {"sample_id": "one"}]])
with pytest.raises(ValueError, match="num_repeats=1"):
server.compute_metrics([[{"sample_id": "one", "_ng_rollout_index": 1}]])

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.

resources_servers/spatialclaw/tests/test_app.py:245

The Video-MME-v2 group fix and the final_rating/total headline key have no test that runs in CI.

The group rebuild, its group counts and the spatialclaw/final_rating/total key metric are tested only in tests/test_native.py. That file skips without SPATIALCLAW_ROOT, and no CI workflow sets it. So reverting either fix keeps the offline suite green. The server picks the group path by class name, so a stand-in class named VideoMMEv2Bench can test it without the SpatialClaw source. This adds to the SPATIALCLAW_ROOT tests that Yu Yao asked for, and it does not replace them.

Suggested fix: please add this offline test. It drops row 5, as masking does, and feeds the rows in reverse order. It fails if the server keeps partial groups or skips the grouping. It also fails if the group count counts rows, dropped groups go uncounted, or final_rating/total leaves the key metrics.

Suggested change
def test_video_mme_v2_drops_whole_groups_without_native_source():
class VideoMMEv2Bench:
def __init__(self):
self.data = [SimpleNamespace(sample_id=str(index)) for index in range(8)]
self.evaluated = None
def evaluate(self, predictions, output_dir=None):
self.evaluated = [sample.sample_id for sample in self.data]
return {"final_rating": {"total": 100.0}}
server, _, _ = _server()
benchmark = VideoMMEv2Bench()
server._benchmark_instance = benchmark
server._sample_by_id = {sample.sample_id: sample for sample in benchmark.data}
tasks = [
[{"sample_id": str(index), "prediction": "A", "extracted_answer": "A", "native_score": 1.0}]
for index in reversed(range(8))
if index != 5
]
metrics = server.compute_metrics(tasks)
assert benchmark.evaluated == ["0", "1", "2", "3"]
assert metrics["spatialclaw/num_evaluated_groups"] == 1
assert metrics["spatialclaw/num_dropped_groups"] == 1
assert server.get_key_metrics(metrics)["spatialclaw/final_rating/total"] == 100.0

Comment on lines +39 to +45
spatialclaw_videomme_benchmark_environment_server:
environment_servers:
legacy_agent:
entrypoint: app.py
agent_server:
type: responses_api_agents
name: spatialclaw_videomme_benchmark_agent

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.

benchmarks/spatialclaw/videomme.yaml:39-45

All 20 presets run through the legacy_agent relay, so only spatialclaw_agent can run these rows today.

The relay sends each row to the agent's own /run, and main's run() docstring calls that path deprecated. prepare.py puts the media paths in responses_create_params.metadata. On main, a prepared row gets a 422 from opencode_agent ("OpenCode sandbox execution does not support request field metadata; configure Gym model limits/sampling") and from pi_agent ("Pi does not support request field metadata"). Without metadata, both accept the row with no media, so the model sees no video.

This is a recommendation, not a merge requirement. It matters only if you want other harnesses to run SpatialClaw, and the choice is yours. Your stacked #5894 already moves all 20 presets to single_agent_turn (videomme.yaml at #5894). The Harness-Ready Environments runbook says to keep a new benchmark there once it uses single_agent_turn (section 3, "Which Environment Server"). SpatialClaw is its case C, a custom agent (section 4, "Decide your case and your two settings").

Recommended change, if you want other harnesses: please land this PR and #5894 together, as one stack. The reasons:

If Yu Yao agrees, one model run on the final preset path can serve both PRs. If #5894 stalls, it is still fine to merge this PR first. Gym's add-harness skill covers the move off the relay, and you can point a coding agent at it.

Comment on lines +9 to +10
spatialclaw_url: ssh://[email protected]:12051/ehosseiniasl/spatial_claw.git
spatialclaw_commit: 946ac114dfcabf9df997629bfa8b6f2f66da1425 # pragma: allowlist secret

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.

resources_servers/spatialclaw/configs/spatialclaw_resources.yaml:9-10

These two lines repeat the SpatialClaw pin, but prepare.py reads a different copy of it.

The pin is in three places: the SPATIALCLAW_URL and SPATIALCLAW_COMMIT constants, these two lines, and spatialclaw_agent.yaml. The servers read the YAML values, and prepare.py reads the constants. Each component compares its SpatialClaw source tree only with its own pin. Without SPATIALCLAW_ROOT, each component clones its own pin. Then a bump of one copy alone prepares rows with one commit and grades them with another, and nothing fails. If the new loader changes sample IDs, every /verify raises "Unknown SpatialClaw sample id". The agent then masks each row as verifier_error.

Suggested fix: please delete these two lines and the same two lines in spatialclaw_agent.yaml. The configuration defaults already read the constants (server, agent).

Suggested change
spatialclaw_url: ssh://[email protected]:12051/ehosseiniasl/spatial_claw.git
spatialclaw_commit: 946ac114dfcabf9df997629bfa8b6f2f66da1425 # pragma: allowlist secret

This branch has not been deployed

No deployments
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 complexity:high Cross-component or shared-contract change with a large review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants