Skip to content

feat(eval): label every failure with where it happened - #4843

Closed
AdamRajfer wants to merge 5 commits into
NVIDIA-NeMo:mainfrom
AdamRajfer:eval/failure-cause-labels
Closed

AdamRajfer wants to merge 5 commits into
NVIDIA-NeMo:mainfrom
AdamRajfer:eval/failure-cause-labels

Conversation

@AdamRajfer

@AdamRajfer AdamRajfer commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Part 1 of 9, merge in order.

What and why. Gym records failures under component-local labels that do not say whether the model or a service it does not control broke. This adds that label, infra or model, without changing any decision. failure_cause_of reads a raised error (its chain, exception groups, HTTP status, class names, and where a TimeoutError was raised); failure_cause_of_text reads an error known only as text; episode_failure_cause covers environment servers. Gym's exception middleware names the cause of each 500 it returns in X-NeMo-Gym-Failure-Cause, and an environment server (single_agent_turn, nemo_user_sim) names the cause of a handled episode failure in the same header, so the versioned RolloutFailure record keeps its version-1 fields; the collector stamps _ng_failure_cause on failure rows. OpenSandbox's operation timeout raises a named TimeoutError subclass. Terminal-Bench names the environment and harness failures it retries; a missing reward file and the agent's own exits are the model's.

Methodology. No scoring change.

Eval scores. None move.

Training and RL: no change. Every change is additive: a response header, a new _ng_failure_cause key on the failure row run_examples returns when the caller opts into route_failures_to_sidecar, and on an environment server's episode reply that carries a handled failure, and a TimeoutError subclass that every except TimeoutError still catches. terminal, rewards, masks and exceptions are as before. Checked by test_run_examples_adds_only_the_cause_to_a_failure_row and the existing run_examples tests passing unchanged.

Unit tests. tests/unit_tests/test_failure_retry_rule.py (cause from status, chain, groups, text, legacy_agent relay), test_failure_retry_rule_evidence.py (timeouts, Ray, environment-server cause), test_rollout_collection.py::test_run_examples_adds_only_the_cause_to_a_failure_row; test_failure_retry_rule_evidence.py::TestEnvironmentServerPath::test_the_cause_travels_in_the_header_and_the_failure_record_is_unchanged, and test_rollout_outcomes.py passing unchanged.

🤖 Generated with Claude Code

Gym records failures under component-local labels that do not say
whether the model or a service it does not control broke. This adds that
label, `infra` or `model`, without changing any decision.
`failure_cause_of` reads a raised error (its chain, exception groups,
HTTP status, class names, and where a `TimeoutError` was raised);
`failure_cause_of_text` reads an error known only as text;
`episode_failure_cause` covers environment servers. Gym's exception
middleware names the cause of each 500 it returns in `X-NeMo-Gym-
Failure-Cause`, and an environment server (`single_agent_turn`,
`nemo_user_sim`) names the cause of a handled episode failure in the
same header, so the versioned `RolloutFailure` record keeps its
version-1 fields; the collector stamps `_ng_failure_cause` on failure
rows. OpenSandbox's operation timeout raises a named `TimeoutError`
subclass. Terminal-Bench names the environment and harness failures it
retries; a missing reward file and the agent's own exits are the
model's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adam Rajfer <[email protected]>
@AdamRajfer AdamRajfer self-assigned this Oct 21, 2026
@AdamRajfer

Copy link
Copy Markdown
Contributor Author

/ok to test 2ea50e8

@copy-pr-bot

copy-pr-bot Bot commented Oct 21, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@github-actions

github-actions Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

@svcnvidia-nemo-ci svcnvidia-nemo-ci added area:evaluation Evaluation, rollout collection, reward profiling, comparison, and exporters feature New capabilities, enhancements, or enablement work labels Oct 21, 2026
@AdamRajfer
AdamRajfer marked this pull request as ready for review October 21, 2026 15:00
@AdamRajfer
AdamRajfer requested a review from ananthsub October 21, 2026 15:00
@AdamRajfer

Copy link
Copy Markdown
Contributor Author

/review

Resolve the failure_kinds import in rollout_collection: keep main's
AGENT_TIMEOUT and this branch's cause names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adam Rajfer <[email protected]>
Resolves the one conflict, in environment_servers/single_agent_turn/app.py: the handled-failure helper keeps both main's trajectory field and this part's failure cause.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adam Rajfer <[email protected]>
Main added NG_FAILURE_MAX_ATTEMPTS_KEY, the attempt cap stamped on each sidecar row, on the same line where this branch adds NG_FAILURE_CAUSE_KEY. The merge keeps both keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adam Rajfer <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adam Rajfer <[email protected]>
@ananthsub

Copy link
Copy Markdown
Contributor

@AdamRajfer this comment is about the stack as a whole (#4843 through #4890), so it sits on the first part instead of being repeated on each one. The per-PR reviews cover individual bugs. This comment asks a different question: is the stack's core design the right way to meet the failure-handling contract in #2750?

The problem the stack goes after is real. Model failures should not get free retries and then drop out of the score, and infrastructure failures should not be scored as the model's 0. The core design, though, adds a second failure classification next to the existing one, and then moves retry, scoring and publication policy onto it. #2750 asks for the opposite: Gym reports facts about each failure, and the caller decides what to do with them.

The infra/model cause conflicts with the existing failure vocabulary

nemo_gym/failure_kinds.py on main already groups failures by the layer that observed them. The model_* kinds (model_request_error, model_transport_error, model_context_limit) are documented as "requests made to a model endpoint", so most of them describe infrastructure. The new cause uses the same word for the opposite meaning: model means the evaluated policy is to blame. A model_transport_error row therefore carries _ng_failure_cause: infra, and after #4890 a sandbox exec error carries _ng_failure_cause: model. Anyone reading a sidecar row, a metric label or a dashboard now has to know which of the two axes a "model" refers to.

The same module also states a design rule that the stack reverses. Its docstring says a failure name describes what went wrong and nothing else, and that retry and masking "are all properties of the occurrence, not of the name", because "metadata attached to a name goes stale the moment one caller wants to retry what another caller does not". #4844 deletes that paragraph and replaces it with a fixed FAILURE_RULES table keyed on names, "so no agent or benchmark decides it". No caller can override that table, and count_failure_classes_as_zero=[] can no longer leave final failures out of the score.

The cause is inferred, not observed

The cause decides retry (#4844), scoring (#4845) and exclusion from the score (#4851), so it needs to be a fact. Today it is assembled from fallbacks, and those fallbacks disagree:

The stack also changes its own answer. Sandbox exec errors are infra in #4843 and model in #4890. AgentInfrastructureError is infra in #4843, retried in #4846, and the model's final 0 in #4890. A label that changes this much within one stack does not yet describe the failure itself.

Retries re-run the policy after an answer already exists

Every retry in the stack re-dispatches the whole rollout, so the policy model writes a new answer. That is the right retry when the failure happened before the policy acted. After an answer exists, it replaces the answer that failed verification, and any failure the answer itself caused gets resampled until a draw passes. The stack routes several post-answer failures into this path:

#4890 also removes SWE-bench Pro's in-server re-verification of the same patch, which was the one retry that did not resample the model. The effect is upward score bias wherever a failure correlates with the answer, which is the concern laszkiewiczp raised on #4848.

flowchart LR
    A["Policy wrote an answer"] --> F["Judge or verifier fails"]
    F -->|"stack today"| R["Re-dispatch /run"]
    R --> N["New answer replaces the measured one"]
    F -->|"requested"| V["Retry the judge or verifier on the stored answer"]
    V -->|"still failing"| U["Left out of the score and counted as unresolved"]
Loading

Later parts reverse earlier parts

Merged in order, several parts ship behavior that a later part declares wrong:

Every part from #4845 upward is built on the first commit of #4844, so the six fix commits on #4844's current head are in none of them.

What should land on its own

Several changes fix real bugs and do not depend on the cause or on the rule table. Each could be a small PR with its own tests:

Requested direction

Every retry and scoring decision in the stack can be made from facts Gym already records, plus one it does not:

With those facts, gym eval run can apply a default policy that callers can replace. A failure before the policy acted re-dispatches the rollout. A failure after an answer exists retries verification on the stored answer. A failure that still cannot be measured is left out of the score and counted by cause.

Concretely, please:

  1. Split the fixes listed above into separate PRs so they can land now.
  2. Hold the cause, the rule table, the scoring default and the completeness fields until they are agreed with feat(eval): persist failures and resume unfinished evaluations #3302 (the candidate for feat(core): define typed rollout outcomes and recovery #2135), feat(core): define completed verifier-result failure semantics #2608 and feat(agent): report native causes for shared grading policy #4834. feat(eval): persist failures and resume unfinished evaluations #3302 already defines failure records, a retry budget and coverage counts with different meanings from this stack, and feat(agent): report native causes for shared grading policy #4834 adds a second status table in single_agent_turn.
  3. Replace model/infra with facts such as the phase reached and the platform evidence seen, and let the policy derive ownership from them. If an ownership value is still needed, it needs an unknown value, a name that does not collide with the model_* kinds, and a field in the versioned failure record instead of a response header.
  4. Attach smoke rollouts for each scoring change, showing scores and failure counts before and after on the affected benchmarks (arena, SWE-bench Pro, Terminal-Bench 4, PinchBench, OSWorld, critpt).

Comment thread nemo_gym/failure_kinds.py
return MODEL
if failure_cause_of(error) == INFRA:
return INFRA
return MODEL if terminal else INFRA

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.

When the error carries no evidence, the cause is copied from terminal, the server's own retry decision. The collector's fallback does the same thing (rollout_collection.py#L439). So infra and model are not independent facts about the failure. In many rows they are the retry flag under another name.

Two results follow:

Issue #2750 asks Gym to report facts that do not encode a policy, and to let callers decide. #3179 says the same about the shared vocabulary. Would you consider a third value, such as unknown, or leaving the cause unset when nothing points either way? #4844 can then still treat unknown as final on purpose, and a training caller or #4851 can choose differently.

Comment thread nemo_gym/server_utils.py
)
return JSONResponse(content=repr(e), status_code=500)
return JSONResponse(
content=repr(e), status_code=500, headers={FAILURE_CAUSE_HEADER: failure_cause_of(e)}

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.

This is the branch every unhandled server bug takes. A KeyError in a resources server, a model server or an agent gets model here, because failure_cause_of returns model whenever nothing matched.

failure_cause_of also checks this header before the status (failure_kinds.py#L292-L299). So when one Gym server calls another and the inner one crashes, the outer server sees a 500 that says model. The rule that a 5xx is a broken service never applies between Gym servers. Could a crash with no evidence say unknown here, or send no header?

Comment thread nemo_gym/server_utils.py
except CancelledError:
return JSONResponse(content="Request was cancelled", status_code=500)
return JSONResponse(
content="Request was cancelled", status_code=500, headers={FAILURE_CAUSE_HEADER: INFRA}

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.

I don't think this branch can run for an endpoint that raises CancelledError. Gym's exception middleware is registered with @app.middleware("http"), which is Starlette's BaseHTTPMiddleware. In Starlette 1.3.1, call_next catches only Exception (middleware/base.py#L145). The cancellation becomes RuntimeError("No response returned.") (#L169), and the generic branch below labels it model.

The other way here is a client disconnect. In that case nobody reads the reply. A test that raises asyncio.CancelledError() from an endpoint behind setup_exception_middleware and checks the header would settle it. Today the header says model.

# infra text decides, and with no evidence either way the server's own terminal=False is a retry.
cause = response.get(NG_FAILURE_CAUSE_KEY)
if cause not in (INFRA, MODEL):
if failure.get("stage") in ("admission", "seed", "cleanup"):

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.

This stage rule only applies when the reply has no cause header. single_agent_turn and nemo_user_sim always send one, and episode_failure_cause ignores the stage. So the same seed or cleanup failure gets opposite labels depending on which environment server reported it:

  • In single_agent_turn, a terminal seed failure, such as a missing session cookie or a 422 from the resources server, is model. This PR's own test asserts that (test_failure_retry_rule_evidence.py#L172).
  • nemo_user_sim always marks cleanup terminal (app.py#L510, #L543), so a cleanup error is model.
  • Harbor sends no header, so the same failures are infra there.

Could the stage rule live in episode_failure_cause, with the stage passed in, so both paths use one rule?

return " ".join(str(record.get(key) or "") for key in _FAILURE_TEXT_KEYS)


def failure_cause_of_row(record: Mapping[str, Any]) -> str:

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.

Flat rows from single_agent_turn_legacy come through here with no cause. That server overrides setup_webserver and never sends the header, and _legacy_result drops HandledEpisodeError.cause (app.py#L88-L104). This function reads only text, so neither the stage rule nor the terminal fallback applies.

For example, a seed TimeoutError() has empty text, so it is model here and infra on the materialized path. "Episode timed out" is also model here and infra there. This route is used by benchmarks/swebench/pro/hermes.yaml and benchmarks/gdpval/config.yaml. #4844 adds the missing accessor to the legacy server. Could that fix land here with the label instead?



# The cause of the handled failure the current /run request returns, for its response header.
_failure_cause: contextvars.ContextVar[FailureCause | None] = contextvars.ContextVar("failure_cause", default=None)

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 cause travels only in a response header, so the versioned failure record does not change. That means it is lost for anyone not reading that header through run_examples:

If later PRs retry and score on this value, it is part of the failure contract. A new optional field in the record, with a version bump, would put it where every consumer can see it.

assert set(body["failure"]) == {"failure_reason", "terminal"}
assert reply.headers.get(FAILURE_CAUSE_HEADER) == cause
if cause is not None:
body[NG_FAILURE_CAUSE_KEY] = cause # what the collector adds from the header

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.

This line sets the key by hand, so the collector code that copies the header into the row (rollout_collection.py#L4527-L4531) is never run. Each of these still passes the suite when deleted:

  • that header copy;
  • the stage fallback at #L434;
  • the sidecar stamp at #L3649;
  • the cause= wiring in single_agent_turn and nemo_user_sim;
  • the OpenSandbox rename.

A test that posts to a real BaseEpisodeResponse server through run_examples and asserts the row's cause would cover the first one. Short unit tests on _episode_record, failure_cause_of_row, both _failure helpers and _await_sdk_call would cover the rest.

The None parameter case cannot tell the text fallback from the terminal fallback either, because the reason is "500, message=" and terminal=False, so both give infra.

# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Where a failure happened: in a service the model does not control (infra), or in what the model produced."""

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.

This PR changes no retry decision, but the file names say "retry rule". Several test names also say _is_retried or _is_final while asserting only the label:

  • test_a_500_carrying_a_dead_model_server_is_retried
  • test_a_500_from_a_model_output_parse_error_is_final
  • test_no_reply_at_all_is_retried, which asserts only the failure class
  • test_a_dead_model_server_is_retried
  • test_a_judge_429_or_500_is_retried
  • test_a_malformed_model_tool_call_is_final, which never checks the row's cause

How about test_failure_cause.py, with names ending _is_infra or _is_model? The comment at rollout_collection.py#L3647, "the cause the rule reads, so the sidecar shows the decision", also refers to a rule that does not exist until #4844.

- **Counting lost rollouts.** `+count_missing_rollouts_as_zero=true` scores as zero a rollout that is in the materialized inputs but left no row in the output JSONL or the sidecar, such as one killed mid-flight or one `dispatch_budget_s` never started. The zero goes into the metric input only, so `--resume` still runs the rollout and the resumed run scores it. A rollout recorded in the sidecar is never counted here, so this does not widen `+count_failure_classes_as_zero`. The count is reported as `coverage/imputed`. With `--disable-aggregation` nothing is scored, so a run with no row still fails. `gym eval aggregate` checks each shard against its own rows, materialized inputs and sidecar.
- **Matching.** On resume, completed work is matched by `(task_index, rollout_index)` against the materialized inputs, and already-completed rows are skipped. The run prints a summary such as the number of original input rows, rows already done, and rows that still need to be run.
- **Terminal failures.** A sidecar row stamped `_ng_failure_terminal` is never retried. `+retry_terminal_timeouts=true` retries rows of class `timeout_exceeded` even when they are stamped terminal. Retries still stop at `NEMO_GYM_MAX_ROLLOUT_ATTEMPTS`. Off by default, because some agents stamp their timeouts terminal on purpose.
- **Terminal failures.** A sidecar row stamped `_ng_failure_terminal` is never retried. `+retry_terminal_timeouts=true` retries rows of class `timeout_exceeded` even when they are stamped terminal. Retries still stop at `NEMO_GYM_MAX_ROLLOUT_ATTEMPTS`. Off by default, because some agents stamp their timeouts terminal on purpose. Each sidecar row also records where its failure happened as `_ng_failure_cause`: `infra` for a failure of a model server, judge, sandbox or tool (an HTTP 401, 403, 429 or 5xx, or a connection error), `model` otherwise. A Gym server names the cause of each 500 it returns in the `X-NeMo-Gym-Failure-Cause` header, and an environment server names the cause of a handled episode failure the same way, so the episode failure record keeps its version-1 fields.

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.

A few parts of this line do not match the code:

  • "each 500" does not hold: the bare except: branch in the middleware sends no header, and a cancelled endpoint gets model.
  • "model otherwise" leaves out several cases that are infra:
    • 408 and 425;
    • Ray and sandbox errors;
    • admission, seed and cleanup failures on the fallback path;
    • any failure a server marks retryable that has no evidence.
  • This line sits under the "Terminal failures" bullet. That ties the cause to retries, although in this PR it changes nothing.

Could the line describe exactly the rule, and live in its own bullet?

Comment thread nemo_gym/failure_kinds.py
}
)
# Ray's wrapper of a task's own exception: "RayTaskError(ImportError): ...". The wrapped name decides.
_RAY_TASK_ERROR_PATTERN = re.compile(r"\bRayTaskError\((\w+)\)")

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.

This substitution never changes the result. RayTaskError is in neither infra set, and the name pattern finds the wrapped name either way. With the .sub removed, the whole suite still passes, including the RayTaskError(ImportError) case. The docstring also says the wrapper's cause comes from X alone, but an infra name anywhere in the wrapped traceback still wins. Could this be removed?

@github-actions github-actions Bot added sla:review-overdue Review response is over the one-business-day SLA and removed sla:review-overdue Review response is over the one-business-day SLA labels Oct 22, 2026

@giuliolovisotto giuliolovisotto 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.

Had a discussion round about surfacing and classifying failures with @iguehring-nvidia @marta-sd @AdamRajfer:

Our thoughts on how we could move in Gym (decisions mostly made early in this PR stack).

  1. Complement the failure registry in failure_kinds.py with failures that are not covered - break down those that are ambiguous where possible.

  2. Create a datatype that collects failure details (eg NgFailureEvent , similar to what Ananth previously suggested here in the context of timeouts). It should have at least these fieds: (i) a named failure reason from failure_kinds.py (ii) a stage where the failure happened (iii) when related to an http error, include its details:

class NgFailureEvent(BaseModel):
    model_config = ConfigDict(extra="forbid")

    event_id: str = Field(min_length=1)
    phase: FailureStage
    reason: str = Literal[*KNOWN_REASONS, "unknown"]
    http_response: ... | None
    metadata: dict | None

These failure events are passed upstream to the callers.

  1. Callers own the decision on what is terminal, what to retry, whether to verify in case of errors, based on the content of the received failure events. I would suggest generalizing AgentOutcome and AgentOutcomePolicyConfig like I introduced in this PR for each component's boundary:
EnvironmentServerOutcome
ResourceServerOutcome

The OutcomePolicy is configurable with the config, and prescribes how this component shall react to failures (is it retriable? can it still go to /verify? should it be masked from scores, etc). We could create defaults per-benchmark types (eg. agentic vs single turn), overrides are decided per-benchmarks. In a future where MFN executes rollouts in Gym as a service, if they want full visibility on failures MFN should set these values conservatively in configs (eg, no retries).

  1. We should not mask failures from scores, unless there are very specific reasons. If we mask them, people will tend to ignore them.

  2. The stack wants to separate model and infra failures - the boundary is not always clear. Where it is, we could attach a label to the categories in failure_kinds.py. But also I can think of cases where it's inherently ambiguous, eg running on API endpoint, is a model call failure attributable to model or to infra?. We prob need to accept some ambiguity.

  3. At the lower parts of the stack (interactions with harnesses/sandboxes) we also need to accept the fact that often reporting may be imprecise. We can start focusing on a set of benchmarks using harnesses which pass the conformance checks, where we know error reporting is mostly correct. We could think of conformance checks for sandbox providers.

  4. We agree that for the future we should only focus on benchmarks that use Gym-orchestration refactor execution paths. For legacy paths, it's not a worthwhile effort to be policing the above.

@github-actions github-actions Bot added sla:review-overdue Review response is over the one-business-day SLA and removed sla:review-overdue Review response is over the one-business-day SLA labels Oct 23, 2026
@AdamRajfer

Copy link
Copy Markdown
Contributor Author

Closing this version to consolidate review on #5072 (failure reporting) and #5073 (saved-state recovery). This does not mean those PRs implement every proposal from this earlier stack; scoring policy and persistence follow-ups remain separate.

@AdamRajfer AdamRajfer closed this Oct 26, 2026

This branch was previously deployed

1 inactive deployment
public — 74315fdb Deployed Oct 22, 2026 by copy-pr-bot[bot] via release / finalize / notify #6645
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:evaluation Evaluation, rollout collection, reward profiling, comparison, and exporters feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer 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.

4 participants