Skip to content

fix: rescue lingering finished SWE episodes and mask infra failures - #2410

Open
tdene wants to merge 3 commits into
NVIDIA-NeMo:mainfrom
tdene:tde/swe_rescue_and_masking
Open

tdene wants to merge 3 commits into
NVIDIA-NeMo:mainfrom
tdene:tde/swe_rescue_and_masking

Conversation

@tdene

@tdene tdene commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

This PR contains two fixes.

For the first, the harness will commonly be left running despite the model having finished the episode. This usually happens due to lingering commands. Currently this leads to a long timeout and failure. Rescuing these episodes from the harness allows them to complete early and retrieve rewards for what would otherwise be marked as a failure.

For the second, infra failures are now tagged so that the training backend can choose to mask out their gradients instead of training with them as 0 reward.

@tdene

tdene commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

/claude review

@claude

claude Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

SHIP — solid, well-tested reliability fix. One NOTE inline; nothing blocking.

The core change is correct: _finish_container_command now polls the OpenHands process instead of a single blocking communicate(), so a finished-but-lingering container (a shell command the model left running) is rescued and scored on its valid output files rather than burning the full timeout and being reported as a failure. What I verified:

  • Timeout semantics preserved. The deadline-based loop and the remaining <= 0 → raise TimeoutError reproduce the old wall-clock behavior; the min(_CONTAINER_COMMAND_POLL_INTERVAL_S, remaining) bound prevents overshooting the deadline. Non-agent modes fall through to continue unchanged.
  • Rescue path is safe. terminated_after_completion correctly suppresses the SIGKILL-induced non-zero return code at the returncode != 0 check (2556), so a rescued episode isn't misreported as a command failure. Output completeness is gated on full-file json.loads, so a mid-flush partial file waits out the grace window instead of being killed early.
  • Fail-loud on empty output. Marker-seen-but-no-output after the grace raises rather than hanging — the right call.
  • Masking plumbing is consistent. mask_sample/failure_reason are set on the infra-failure path and OR'd into the downstream mask decision in responses(), then persisted via metrics_to_update. Reward stays 0.0 and mask_sample propagates into SWEBenchVerifyResponse (covered by the updated wrapper test).
  • Tests exercise all three branches (missing/complete/late output) with monkeypatched intervals — good coverage of the new logic.

No async-HTTP, ray.get-in-async, or public-API concerns. The one NOTE (inline) is that this new infra-failure path stamps failure_reason = "agent_command_failure" even for timeouts/OOMs, and the downstream if not failure_reason: guard then won't refine it — so the more specific agent_timeout/agent_oom reasons this PR adds are shadowed for those cases. Telemetry granularity only; masking is unaffected.

Comment thread responses_api_agents/swe_agents/app.py Resolved
@tdene

tdene commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test bbc003e

@tdene
tdene force-pushed the tde/swe_rescue_and_masking branch from bbc003e to c132548 Compare August 18, 2026 10:59
@tdene
tdene force-pushed the tde/swe_rescue_and_masking branch from c132548 to 439bd44 Compare August 21, 2026 15:16
@tdene
tdene force-pushed the tde/swe_rescue_and_masking branch from 439bd44 to cb2074f Compare August 25, 2026 08:56
@tdene

tdene commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 944b9d9

@tdene
tdene force-pushed the tde/swe_rescue_and_masking branch from cb2074f to 944b9d9 Compare October 2, 2026 03:28
@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team October 2, 2026 03:29
@svcnvidia-nemo-ci svcnvidia-nemo-ci added area:agent Agent harnesses and Responses API agent behavior bug Something isn't working needs-review PR is ready for code review and waiting on a reviewer labels Oct 20, 2026
@adil-a

adil-a commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

@sdevare-nv can you please review this?

@adil-a

adil-a commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

/review

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

SHIP WITH CARE — three RISK defects and one RISK validation gap.

RISK — Required real-rollout evidence is missing

The supplied PR description and discussion contain no representative model rollout evidence. This changes episode completion and sample masking in a wrapper used for training and SWE-bench evaluation. The added tests use synthetic processes or mocked responses; they don't validate the real harness-to-verifier path. AGENTS.md requires representative real rollouts for behavior-changing agent work. The review rubric also requires before/after reward evidence for fixed-evaluation reward changes.

Correction: Record the commands, model, task IDs, revisions and rollout artifact references in the PR description. Inspect the extracted patch, trajectory, verifier result and returned failure fields. For fixed SWE-bench evaluation, include a matched base/head comparison with rollout count, aggregate reward, mask count and explanations for changed outcomes. Training-only validation doesn't require a full reward profile, but still requires representative model rollouts.

Preservation and acceptance: Show that a rescued completed episode receives the same patch grade as its cleanly exiting counterpart; an ordinary wrong patch remains reward 0 and unmasked; and a confirmed infrastructure failure carries the expected failure kind and is masked. Retain the documented resolved-only masking of iteration/context-limit errors. These are proposed checks, not executed results. The gap leaves the real integration and intended score changes unvalidated; it isn't evidence of a runtime failure.

I reviewed both changed files and traced the affected subprocess, output-copy, metrics and response paths. The historical timeout/OOM taxonomy concern is fixed in the current source. This was a static review; I didn't execute tests or rollouts. The external harness checkout isn't mounted, so I couldn't independently verify its completion-marker emission order or its failure-origin signals.

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

Comment thread responses_api_agents/swe_agents/app.py Outdated
complete_pred_files.append(pred_file)
except (OSError, orjson.JSONDecodeError):
continue
if complete_pred_files:

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 — Validate the prediction that will actually be returned before killing its writer.

Failure / blast radius: With two matching outputs, let an older prediction be complete and the newest prediction still be partial. This branch accepts the older file and kills the container, but the later selection returns the newest file regardless of completeness. The consumer then fails to parse it. Before this rescue path, the writer could finish before selection. Multiple matching outputs are explicitly supported by the existing selection contract.

Correction: Select the newest candidate before validating it, wait for that candidate, and retain its path for the return. The invariant is that the rescued prediction returned to the caller is the same newest prediction validated before termination. Initialize rescued_pred_file: Optional[str] = None, then replace the readiness block through its successful break with:

pred_files = glob.glob(command.expected_file_pattern, recursive=True)
if pred_files:
    pred_file = max(pred_files, key=os.path.getmtime)
    try:
        orjson.loads(Path(pred_file).read_text().strip())
    except (OSError, UnicodeDecodeError, orjson.JSONDecodeError):
        pass
    else:
        await self._terminate_lingering_process(active_command)
        terminated_after_completion = True
        rescued_pred_file = pred_file
        break

After the existing watchdog/nonzero-exit guards, return rescued_pred_file when it isn't None, before re-globbing. Leave ordinary completion and eval-mode selection unchanged. This suggestion wasn't executed; verify it before adopting it.

Preservation / acceptance: Add a proposed regression with an older complete prediction and a newer partial prediction that finishes after several polls. Expect no early kill, then return and successfully parse the newer prediction. With two complete files, still return the newest. Retain the "output2.json" in result assertion in the existing multiple-file test, and retain the complete, delayed and missing-output rescue cases, including their process-termination assertions.

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. The newest output file is the one checked before the kill, and that same file is returned. The newer_unfinished case covers it: an older complete output beside a newer unfinished one, and the container stays alive until the newer one is complete.

Comment thread responses_api_agents/swe_agents/app.py Outdated
try:
orjson.loads(Path(pred_file).read_text().strip())
complete_pred_files.append(pred_file)
except (OSError, orjson.JSONDecodeError):

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 — Let incomplete UTF-8 writes use the output grace window.

Failure / blast radius: The new polling read decodes the file before parsing JSON. If a write currently ends inside a multibyte character—for example b'{"patch":"\xe2\x82'—Path.read_text() raises UnicodeDecodeError, which this handler doesn't catch. Instead of waiting for the writer, _finish_container_command exits, closes the log and cancels the watchdog without terminating the agent. The caller's error path kills only the eval command. This affects partial prediction writes containing non-ASCII text; the added delayed-write case starts from an empty file and doesn't cover it.

Correction: Include decoding failures among transient readiness failures:

Suggested change
except (OSError, orjson.JSONDecodeError):
except (OSError, UnicodeDecodeError, orjson.JSONDecodeError):

The invariant is that incomplete prediction content waits within the existing grace/deadline bounds rather than abandoning supervision. Verify the suggestion before adopting it; it wasn't executed.

Preservation / acceptance: Add a proposed case to the rescue test that writes an incomplete UTF-8 sequence, then completes valid JSON before the grace expires. Expect the output path to be returned and the process to be terminated, without an early decoding exception. Permanently invalid encoding should reach the existing incomplete-output grace failure and terminate the process. Retain the ASCII complete/late cases and bounded missing/malformed-output failure behavior.

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. A decode error counts as not ready yet. The cut_multibyte case covers it: a write cut inside a multi-byte character, completed later.

Comment thread responses_api_agents/swe_agents/app.py Outdated
metrics.failure_kind = PROVIDER_OOM_KILLED
metrics.failure_reason = "agent container OOM-killed by the memory watchdog"
else:
metrics.failure_kind = AGENT_RUN_ERROR

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 — Establish failure origin before masking every remaining agent-command exception.

Failure / blast radius: This else assigns AGENT_RUN_ERROR whenever the command or output-copy operation raises before the timeout without watchdog OOM evidence. That proves a command failure, not an infrastructure failure. A model action can terminate its own harness—for example, an overly broad process-kill command, which the OpenHands prompt explicitly warns against. Its nonzero exit takes this branch, and the new non-null kind makes _inner_responses mask it. A model-caused failure therefore disappears from training and score calculations instead of remaining a valid zero-reward outcome. The base error path didn't mask these generic failures.

Correction / preservation: Separate evidenced infrastructure failures from policy-caused command/extraction failures in process_single_datapoint. Keep AGENT_RUN_ERROR as a diagnostic if useful, but carry an explicit infrastructure-mask decision and make _inner_responses honor it rather than treating every generic named error as mask-worthy. Preserve the specific timeout/OOM classification and masking branches. The invariant is that a generic exception or nonzero exit alone doesn't invalidate a policy outcome. The external driver isn't mounted, so the exact attribution signal needs confirmation; I can't provide a safe complete patch for that contract.

Acceptance — proposed, not executed: Add a worker-to-response regression for a below-timeout, non-OOM run whose tool terminates its driver: expect reward 0.0 and mask_sample=False. A separately identified infrastructure command failure should remain masked. Retain the worker test's timeout → AGENT_TIMEOUT, watchdog OOM → PROVIDER_OOM_KILLED, and OOM → agent_error_kind="oom" assertions, and check their final responses remain masked. A generic RuntimeError("boom") alone shouldn't establish infrastructure origin. Ordinary wrong patches must also remain unmasked zero-reward samples.

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've changed this, but not to an unmasked 0 since that defeats the purpose of the PR.

A failed agent command is provider_unavailable only when nothing the model chose had run: no model call was recorded and the request had no replay prefix. Otherwise it is swe_agents:agent_command_failed, which claims neither side, as swe_agents:eval_timeout does.

Both are masked, because nothing was graded: the eval container is killed and resolved is filled in as false. Main masks an agent timeout and an agent OOM for the same reason, and a model action can cause those too.

@athitten

Copy link
Copy Markdown
Contributor

@tdene main now names and masks these failures in _masked_failure (#5342, #4002). Please rebase onto it, drop the masking part and the new SWEBenchMetrics failure fields, and keep the rescue. Before killing the run, check the newest output file (the one that's returned), treat a decode error as "not ready yet", and add a smoke run showing a rescued episode gets the same grade as a clean exit.

tdene and others added 2 commits November 26, 2026 10:40
Co-Authored-By: Jorge Albericio <jalbericiola@nvidia.com>
Signed-off-by: Teodor-Dumitru Ene <teodord.ene@gmail.com>
Co-Authored-By: Jorge Albericio <jalbericiola@nvidia.com>
Signed-off-by: Teodor-Dumitru Ene <teodord.ene@gmail.com>
@tdene
tdene force-pushed the tde/swe_rescue_and_masking branch from 944b9d9 to 50ebd66 Compare November 26, 2026 17:03
@nemo-pr-automation
nemo-pr-automation Bot requested a review from a team November 26, 2026 17:03
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the risk:mid Autobot PR risk: mid label Nov 26, 2026
@tdene

tdene commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

@tdene main now names and masks these failures in _masked_failure (#5342, #4002). Please rebase onto it, drop the masking part and the new SWEBenchMetrics failure fields, and keep the rescue. Before killing the run, check the newest output file (the one that's returned), treat a decode error as "not ready yet", and add a smoke run showing a rescued episode gets the same grade as a clean exit.

The rebase is done, the SWEBenchMetrics failure fields are gone, and the rescue has both fixes you asked for.

One part of the masking stays, and can't be dropped: an agent command that kills the harness (nothing is graded, but the reward used to still be 0 instead of masked). It's now masked the same way that a timeout or OOM is.

Meanwhile a run that stopped at its context limit (it was graded, the reward should be 0) is not masked; anyswe_agent on main already has this rule in _should_mask_sample

@tdene

tdene commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Rollout evidence (astropy__astropy-12907):

  • Scripted agent that uses the entire infra chain except hardcodes model responses and artificially introduces crashes, one episode per ending:

    Ending Main This PR
    Golden patch, agent finishes reward 1 reward 1
    Agent driver killed after the model acted reward 0, unmasked masked, swe_agents:agent_command_failed
    Agent command failed before any model call reward 0, unmasked masked, provider_unavailable
    Agent container hangs after OpenHands finished, golden patch successful masked agent_timeout after 424 s, patch not graded resolved, reward 1, in 129 s
    Same, no successful patch masked agent_timeout after 424 s reward 0, unmasked, in 63 s
    Iteration limit for agent, passing patch masked masked
    Iteration limit for agent, no passing patch masked reward 0, unmasked, agent_limit
  • Putting a real model through OpenHands, 30 turns, 4 episodes on each: all reached the iteration limit without a passing patch. Main masks them; this PR returns reward 0, unmasked, failure_kind=agent_limit. There were no container hangs of the type this PR seeks to resolve.

  • Putting a real model through OpenHands, 100 turns, 16 episodes on each: this PR saw 16 of 16 resolved, reward 1, unmasked. Main saw 12 resolved; of its 4 unresolved episodes, 2 finished (reward 0, unmasked) and 2 stopped at a limit and were masked. There were no container hangs of the type this PR seeks to resolve.

Signed-off-by: Teodor-Dumitru Ene <teodord.ene@gmail.com>
@tdene

tdene commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

I pushed one more commit.

When the agent hits its turn limit or its context limit, the patch it left behind is still graded. After this latest commit that grade always counts, whether the patch passes or fails.

Before this commit, on this PR, (see table above), only the failing patches counted. A passing patch from a run that hit a limit was still masked. So these runs could lower the score but never raise it. Now both count. The "Iteration limit for agent, passing patch" now gives reward 1.

The row is still labelled agent_limit or model_context_limit, so you can tell these runs apart. anyswe_agent gets the same change, so the two agents agree.

I'm making this change because in a real SWE RL run it is actually very impactful; iteration limits happen often, and the model is learning better if we allow these successes.

@athitten

Copy link
Copy Markdown
Contributor

/review reset=true

This branch was previously deployed

1 inactive (outdated) deployment
public — 944b9d9c Deployed Oct 2, 2026 by copy-pr-bot[bot] via release / finalize / notify #4157
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agent Agent harnesses and Responses API agent behavior bug Something isn't working needs-review PR is ready for code review and waiting on a reviewer risk:mid Autobot PR risk: mid

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants