Repository navigation
feat(eval): label every failure with where it happened - #4843
AdamRajfer wants to merge 5 commits into
Conversation
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]>
|
/ok to test 2ea50e8 |
|
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. |
|
/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]>
|
@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
|
| return MODEL | ||
| if failure_cause_of(error) == INFRA: | ||
| return INFRA | ||
| return MODEL if terminal else INFRA |
There was a problem hiding this comment.
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:
- A failure with no evidence that a server marks retryable becomes
infra.single_agent_turnmarks everyTimeoutErrorretryable (app.py#L526), so the model's own over-long turn is labeledinfra. feat(eval): leave infra failures that persist out of the score #4851 dropsinfrarows from the score at the attempt cap, which would raise the score. - A failure with no evidence that a server marks terminal becomes
model. That includes environment server bugs, resources server crashes, and configuration errors. feat(eval): retry infra failures and make model failures final by one rule #4844 and feat(eval): record every failure and count failed rollouts as 0 by default #4845 make those final and score them 0.
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.
| ) | ||
| return JSONResponse(content=repr(e), status_code=500) | ||
| return JSONResponse( | ||
| content=repr(e), status_code=500, headers={FAILURE_CAUSE_HEADER: failure_cause_of(e)} |
There was a problem hiding this comment.
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?
| 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} |
There was a problem hiding this comment.
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"): |
There was a problem hiding this comment.
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, ismodel. This PR's own test asserts that (test_failure_retry_rule_evidence.py#L172). nemo_user_simalways marks cleanup terminal (app.py#L510,#L543), so a cleanup error ismodel.- Harbor sends no header, so the same failures are
infrathere.
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: |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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:
- a trainer that calls
/rundirectly; - an in-process
run_requestcaller; - harbor, which sends no cause;
- the typed
RolloutFailurerecords in feat(eval): persist failures and resume unfinished evaluations #3302, which the work for feat(core): define typed rollout outcomes and recovery #2135 builds on.
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 |
There was a problem hiding this comment.
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 insingle_agent_turnandnemo_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.""" |
There was a problem hiding this comment.
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_retriedtest_a_500_from_a_model_output_parse_error_is_finaltest_no_reply_at_all_is_retried, which asserts only the failure classtest_a_dead_model_server_is_retriedtest_a_judge_429_or_500_is_retriedtest_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. |
There was a problem hiding this comment.
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 getsmodel. - "
modelotherwise" leaves out several cases that areinfra:- 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?
| } | ||
| ) | ||
| # Ray's wrapper of a task's own exception: "RayTaskError(ImportError): ...". The wrapped name decides. | ||
| _RAY_TASK_ERROR_PATTERN = re.compile(r"\bRayTaskError\((\w+)\)") |
There was a problem hiding this comment.
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?
giuliolovisotto
left a comment
There was a problem hiding this comment.
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).
-
Complement the failure registry in
failure_kinds.pywith failures that are not covered - break down those that are ambiguous where possible. -
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 fromfailure_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.
- 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
AgentOutcomeandAgentOutcomePolicyConfiglike 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).
-
We should not mask failures from scores, unless there are very specific reasons. If we mask them, people will tend to ignore them.
-
The stack wants to separate
modelandinfrafailures - the boundary is not always clear. Where it is, we could attach a label to the categories infailure_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 tomodelor toinfra?. We prob need to accept some ambiguity. -
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.
-
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.
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,
infraormodel, without changing any decision.failure_cause_ofreads a raised error (its chain, exception groups, HTTP status, class names, and where aTimeoutErrorwas raised);failure_cause_of_textreads an error known only as text;episode_failure_causecovers environment servers. Gym's exception middleware names the cause of each 500 it returns inX-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 versionedRolloutFailurerecord keeps its version-1 fields; the collector stamps_ng_failure_causeon failure rows. OpenSandbox's operation timeout raises a namedTimeoutErrorsubclass. 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_causekey on the failure rowrun_examplesreturns when the caller opts intoroute_failures_to_sidecar, and on an environment server's episode reply that carries a handled failure, and aTimeoutErrorsubclass that everyexcept TimeoutErrorstill catches.terminal, rewards, masks and exceptions are as before. Checked bytest_run_examples_adds_only_the_cause_to_a_failure_rowand the existingrun_examplestests 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, andtest_rollout_outcomes.pypassing unchanged.🤖 Generated with Claude Code