Skip to content

Commit 288d78b

Browse files
fix(eval): address review of the typed outcome
TaskFailure exposes evaluation_side and delivery, and the docs say that domain is a layer, not a fault class, and that terminal is not a retry hint. A masked rollout keeps the reward the verifier returned and the docs tell a caller that computes scores to leave masked rollouts out. Tests send a refused and a dropped connection through run_outcomes. The in-process API warns once per process through experimental(once=True), which leaves the other experimental commands warning on every call. The docs, the pins and the module docstring are corrected and reflowed. Signed-off-by: Ingo Guehring <[email protected]>
1 parent deffb89 commit 288d78b

7 files changed

Lines changed: 201 additions & 46 deletions

File tree

‎fern/versions/latest/pages/api-reference/index.mdx‎

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -116,25 +116,37 @@ Import everything from `nemo_gym.environment`: `plan_benchmark`, `serve_benchmar
116116
`RolloutOutcome`, `TaskFailure` and `EvalPlan`. The error type is `nemo_gym.config.ConfigError`.
117117

118118
This API is experimental: signatures, result fields and behavior may change or be removed without a deprecation
119-
period. `plan_benchmark`, `serve_benchmark` and `TaskRunner` warn on stderr when they are used. A test pins the current
120-
names and fields so that a change is deliberate.
119+
period. `plan_benchmark`, `serve_benchmark`, `TaskRunner` and `run_task` warn on stderr the first time they are used
120+
in a process. A test pins the current names and fields so that a change is deliberate.
121121

122-
`run_task` runs one rollout of a task and returns its typed `RolloutOutcome`: the `reward` (None when none
123-
exists, as for a failed `/run`), a `TaskFailure` when a failure was reported, whether it was `masked`, and the `prompt` and
124-
`output` as JSON text for display. A failed `/run` (a client error, a bad JSON body, a timeout or an unusable reply) does not raise: the outcome has a `failure` and no reward. Any other exception, such as a programming error, and cancellation propagate.
122+
`run_task` runs one rollout of a task and returns its typed `RolloutOutcome`:
123+
124+
- `reward` is None when no reward exists, as for a failed `/run`.
125+
- `failure` is a `TaskFailure` when a failure was reported.
126+
- `masked` is True when the verifier says the reward is not a valid measurement of the evaluated system, such as a
127+
lost session (it reports a reward of 0 and masks it). The outcome keeps that reward, so a caller that computes scores
128+
must leave masked rollouts out. A failed `/run` has no sample, so its `masked` is False and its `reward` is None.
129+
- `prompt` and `output` are `responses_create_params.input` and `response.output` as JSON text, for display. They are
130+
None for a result without that shape, such as a native episode result.
131+
132+
A failed `/run` (a client error, a bad JSON body, a timeout or an unusable reply) does not raise: the outcome has a
133+
`failure` and no reward. A connection that was refused is resent for a minute and one that dropped is sent twice, as
134+
`gym eval run` does. Any other exception, such as a programming error, and cancellation propagate.
125135

126136
A failure reports what Gym observed and leaves the decision to you:
127137

128138
| Field | Meaning |
129139
| --- | --- |
130-
| `kind`, `domain` | Gym's failure kind and, derived from it, the layer that observed it (the part of the kind before the first `_` or `:`, such as `agent`, `judge`, `session` or `provider`). When the reporter named no cause, the kind is `environment_server_failed` or `agent_request_failed`. |
140+
| `kind` | Gym's failure kind. The vocabulary is in `nemo_gym/core/failure_kinds.py`; a `<server>:<kind>` kind is an environment's own. When the reporter named no cause, it is `environment_server_failed` or `agent_request_failed`. |
141+
| `domain` | The layer that observed the failure: the part of the kind before the first `_` or `:`, such as `agent`, `judge`, `session` or `provider`. It is not a fault class: `agent_timeout` and `agent_run_error` are both in `agent`. |
142+
| `evaluation_side` | True for an evaluation-side fault, False for the model's own outcome (such as `model_request_error` or `agent_timeout`), None for a kind outside Gym's vocabulary. |
131143
| `source` | Who reported it: `environment` or `collector`. |
132-
| `stage`, `terminal` | Where in the episode it happened, when known, and the reporter's statement that the episode must not be attempted again. |
144+
| `delivery` | Whether the `/run` request reached the agent: `not_sent` (every connection was refused, so resending cannot start a second episode), `possibly_delivered` or `delivered`. Use it for a retry decision. |
145+
| `stage`, `terminal` | Where in the episode it happened, when known, and the reporter's statement that the episode must not be attempted again. `terminal=False` is not a retry hint. |
133146
| `reason`, `http_status`, `exception_type` | Diagnostics. |
134147

135-
Group failures by `domain` and a new kind under an existing domain needs no change from you.
136-
137-
`RolloutOutcome.raw` holds Gym's raw `/run` response (the failure record for a failed `/run`). Its keys are not part of the contract: depend on the other fields, and use `raw` for debugging.
148+
`RolloutOutcome.raw` holds Gym's raw `/run` response (the failure record for a failed `/run`). Its keys are not part
149+
of the contract: depend on the other fields, and use `raw` for debugging.
138150

139151
### Constraints
140152

‎nemo_gym/environment/in_process.py‎

Lines changed: 41 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,10 @@
2727
talks to it.
2828
2929
This is the API for callers outside Gym. They import the names `nemo_gym.environment` exports (`plan_benchmark`,
30-
`serve_benchmark`, `TaskRunner`, `PlannedBenchmark`, `RolloutOutcome`, `TaskFailure` and `EvalPlan`)
31-
and `ConfigError` from
32-
`nemo_gym.config`. It is experimental: signatures and result fields may change without a deprecation period, and
33-
tests pin the current ones. `RolloutOutcome.raw` is Gym's raw `/run` response (the failure record for a failed
34-
`/run`), whose keys can change: depend on the other fields, and use `raw` for debugging.
30+
`serve_benchmark`, `TaskRunner`, `PlannedBenchmark`, `RolloutOutcome`, `TaskFailure` and `EvalPlan`) and
31+
`ConfigError` from `nemo_gym.config`. It is experimental: signatures and result fields may change without a
32+
deprecation period, and tests pin the current ones. `RolloutOutcome.raw` is Gym's raw `/run` response (the failure
33+
record for a failed `/run`), whose keys can change: depend on the other fields, and use `raw` for debugging.
3534
"""
3635

3736
import json
@@ -57,6 +56,8 @@
5756
from nemo_gym.core.episode_types import is_materialized_task_row
5857
from nemo_gym.core.failure_kinds import (
5958
FailureStage,
59+
is_evaluation_side,
60+
is_registered,
6061
)
6162
from nemo_gym.data.task_selection import row_task_id, select_tasks
6263
from nemo_gym.environment.assets import asset_config_path
@@ -109,17 +110,22 @@ def from_json(cls, text: str) -> "PlannedBenchmark":
109110
class TaskFailure:
110111
"""What Gym observed when a rollout failed. It reports; what to do about it is the caller's decision.
111112
112-
`kind` is Gym's failure kind: the cause when the reporter named one, else `environment_server_failed` (the
113-
environment reported a failure without a kind) or `agent_request_failed` (the `/run` call failed). `domain` is
114-
derived from it.
115-
116-
`source` says who reported the failure, `stage` is where in the episode it happened when the reporter knows, and
117-
`terminal` is the reporter's statement that the episode must not be attempted again. `reason`, `http_status` and
118-
`exception_type` are diagnostics.
113+
`kind` is Gym's failure kind (the vocabulary is in `nemo_gym/core/failure_kinds.py`; a `<server>:<kind>` kind is an
114+
environment's own): the cause when the reporter named one, else `environment_server_failed` (the environment
115+
reported a failure without a kind) or `agent_request_failed` (the `/run` call failed). `domain` is derived from
116+
it and `evaluation_side` classifies it.
117+
118+
`source` says who reported the failure. `delivery` is Gym's evidence about whether the `/run` request reached the
119+
agent: `not_sent` (every connection attempt was refused, so resending cannot start a second episode),
120+
`possibly_delivered` (it may have been processed) or `delivered`. It is the evidence to use for a retry decision;
121+
`terminal` is only the reporter's statement that the episode must not be attempted again, and `False` does not mean
122+
it is safe to retry. `stage` is where in the episode it happened, when the reporter knows. `reason`, `http_status`
123+
and `exception_type` are diagnostics.
119124
"""
120125

121126
kind: str
122127
source: Literal["environment", "collector"]
128+
delivery: Literal["not_sent", "possibly_delivered", "delivered"]
123129
stage: Optional[FailureStage] = None
124130
terminal: bool = False
125131
reason: Optional[str] = None
@@ -132,19 +138,32 @@ def domain(self) -> str:
132138
133139
Names are `<domain>_<condition>` and an environment's own are `<server>:<kind>`, so `agent_run_error` is in
134140
`agent`, `judge_failed` in `judge` and `myenv:bad_input` in `myenv`. A name with neither, such as `cancelled`,
135-
is its own domain. A new kind under an existing domain needs no change from a caller that groups by domain.
141+
is its own domain. It names a layer, not whose fault the failure was: `agent_timeout` and `agent_run_error` are
142+
both in `agent`. Use `evaluation_side` for that.
136143
"""
137144
return re.split(r"[_:]", self.kind, maxsplit=1)[0]
138145

146+
@property
147+
def evaluation_side(self) -> Optional[bool]:
148+
"""Whether the kind is an evaluation-side fault (True) or the model's own outcome (False).
149+
150+
None for a kind that is not in Gym's vocabulary, such as an environment's own `<server>:<kind>`. This is the
151+
kind's own class; a recorded HTTP status can refine an occurrence of it (see `failure_kinds.py`).
152+
"""
153+
return is_evaluation_side(self.kind) if is_registered(self.kind) else None
154+
139155

140156
@dataclass(frozen=True)
141157
class RolloutOutcome:
142158
"""One rollout's outcome: its reward as the verifier returned it, and the failure if one was reported.
143159
144160
`reward` is None when no reward exists, as for a failed `/run`: an infrastructure failure is not a score of zero.
145-
`masked` is True when Gym excludes the rollout from training statistics. `prompt` and `output` are the input
146-
and output items as JSON text, for display and debugging, or None when the rollout has none. `raw` is Gym's own
147-
`/run` response (the failure record for a failed `/run`), whose keys can change: use it for debugging only.
161+
A masked rollout keeps the reward the verifier returned. `masked` is True when the verifier says that reward is not
162+
a valid measurement of the evaluated system (for example a lost session reports 0 and masks it), so a caller that
163+
computes scores must leave masked rollouts out. A failed `/run` has no sample, so its `masked` is False and its
164+
`reward` is None. `prompt` and `output` are `responses_create_params.input` and `response.output` as JSON text, for
165+
display and debugging, or None when the result has no such shape (for example a native episode result). `raw` is
166+
Gym's own `/run` response (the failure record for a failed `/run`), whose keys can change: use it for debugging only.
148167
"""
149168

150169
reward: Optional[float]
@@ -155,7 +174,7 @@ class RolloutOutcome:
155174
raw: dict[str, Any] = field(default_factory=dict, repr=False, compare=False)
156175

157176

158-
@experimental
177+
@experimental(once=True)
159178
def plan_benchmark(
160179
benchmark: str,
161180
*,
@@ -185,7 +204,7 @@ def plan_benchmark(
185204
return PlannedBenchmark(plan=plan, rows=rows)
186205

187206

188-
@experimental
207+
@experimental(once=True)
189208
@contextmanager
190209
def serve_benchmark(
191210
benchmark: str,
@@ -288,7 +307,7 @@ class TaskRunner:
288307
through the agent's `/run` and returns the rollout's outcome. Concurrent calls in one event loop are supported.
289308
"""
290309

291-
@experimental
310+
@experimental(once=True)
292311
def __init__(self, rows: Sequence[Mapping[str, Any]], *, registry_server: BaseServerConfig):
293312
self._helper = RolloutCollectionHelper()
294313
self._registry_server = registry_server
@@ -300,6 +319,7 @@ def __init__(self, rows: Sequence[Mapping[str, Any]], *, registry_server: BaseSe
300319
def task_ids(self) -> list[str]:
301320
return list(self._row_of_task)
302321

322+
@experimental(once=True)
303323
async def run_task(self, task_id: str, *, rollout_id: Optional[str] = None) -> RolloutOutcome:
304324
"""Run one rollout of a task.
305325
@@ -343,6 +363,7 @@ def _outcome(result: Mapping[str, Any] | RolloutFailureRecord) -> RolloutOutcome
343363
failure = TaskFailure(
344364
kind=str(kind),
345365
source="environment",
366+
delivery="delivered",
346367
reason=None if reason is None else str(reason),
347368
)
348369
prompt = (result.get("responses_create_params") or {}).get("input")
@@ -361,6 +382,7 @@ def _failure_of_record(record: RolloutFailureRecord) -> TaskFailure:
361382
return TaskFailure(
362383
kind=record.sidecar_failure_class,
363384
source=record.source,
385+
delivery=record.delivery,
364386
stage=record.failure.stage,
365387
terminal=record.failure.terminal,
366388
reason=record.failure.failure_reason,

‎nemo_gym/utils/decorators.py‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,26 @@
2121
_stderr = Console(stderr=True)
2222

2323

24-
def experimental(fn):
25-
"""Decorator that warns on stderr that a function is experimental, then runs it."""
24+
_warned: set[str] = set()
2625

27-
@functools.wraps(fn)
28-
def wrapper(*args, **kwargs):
29-
_stderr.print(
30-
f"[yellow]Warning:[/yellow] [bold]{fn.__qualname__}[/bold] is experimental and may change or be removed without notice."
31-
)
32-
return fn(*args, **kwargs)
3326

34-
return wrapper
27+
def experimental(fn=None, *, once=False):
28+
"""Decorator that warns on stderr that a function is experimental, then runs it.
29+
30+
It warns on every call, or with `once=True` only the first time the function is called in a process.
31+
"""
32+
33+
def decorate(fn):
34+
@functools.wraps(fn)
35+
def wrapper(*args, **kwargs):
36+
key = f"{fn.__module__}.{fn.__qualname__}"
37+
if not once or key not in _warned:
38+
_warned.add(key)
39+
_stderr.print(
40+
f"[yellow]Warning:[/yellow] [bold]{fn.__qualname__}[/bold] is experimental and may change or be removed without notice."
41+
)
42+
return fn(*args, **kwargs)
43+
44+
return wrapper
45+
46+
return decorate if fn is None else decorate(fn)

‎tests/unit_tests/environment/test_in_process.py‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -119,14 +119,28 @@ class TestOutcomes:
119119
(
120120
{"reward": 0.0, "failure_kind": "judge_failed", "failure_reason": "no verdict"},
121121
RolloutOutcome(
122-
reward=0.0, failure=TaskFailure(kind="judge_failed", source="environment", reason="no verdict")
122+
reward=0.0,
123+
failure=TaskFailure(
124+
kind="judge_failed", source="environment", delivery="delivered", reason="no verdict"
125+
),
123126
),
124127
),
125128
(
126129
{"reward": 0.0, "failure_kind": "session_lost"},
127-
RolloutOutcome(reward=0.0, failure=TaskFailure(kind="session_lost", source="environment")),
130+
RolloutOutcome(
131+
reward=0.0,
132+
failure=TaskFailure(kind="session_lost", source="environment", delivery="delivered"),
133+
),
128134
),
129135
({"reward": 0.0, "mask_sample": True}, RolloutOutcome(reward=0.0, masked=True)),
136+
(
137+
{"reward": 0.0, "mask_sample": True, "failure_kind": "session_lost"},
138+
RolloutOutcome(
139+
reward=0.0,
140+
masked=True,
141+
failure=TaskFailure(kind="session_lost", source="environment", delivery="delivered"),
142+
),
143+
),
130144
],
131145
)
132146
async def test_the_outcome_is_typed_and_the_raw_result_stays_beside_it(
@@ -177,7 +191,24 @@ class TestTaskFailure:
177191
def test_the_domain_is_the_part_of_the_kind_before_the_first_underscore_or_colon(
178192
self, kind: str, domain: str
179193
) -> None:
180-
assert TaskFailure(kind=kind, source="environment").domain == domain
194+
assert TaskFailure(kind=kind, source="environment", delivery="delivered").domain == domain
195+
196+
@pytest.mark.parametrize(
197+
"kind, evaluation_side",
198+
[
199+
("model_request_error", False),
200+
("agent_timeout", False),
201+
("model_transport_error", True),
202+
("agent_run_error", True),
203+
("agent_request_failed", True),
204+
("myenv:bad_input", None),
205+
("not_a_kind", None),
206+
],
207+
)
208+
def test_evaluation_side_tells_a_model_outcome_from_an_evaluation_fault(
209+
self, kind: str, evaluation_side: bool | None
210+
) -> None:
211+
assert TaskFailure(kind=kind, source="environment", delivery="delivered").evaluation_side is evaluation_side
181212

182213

183214
class TestFailedRuns:
@@ -194,6 +225,7 @@ async def test_a_failed_run_comes_back_as_an_outcome(self, monkeypatch: pytest.M
194225
failure=TaskFailure(
195226
kind="model_request_error",
196227
source="collector",
228+
delivery="delivered",
197229
stage="agent",
198230
terminal=True,
199231
reason="boom",
@@ -221,7 +253,7 @@ async def test_a_failure_that_names_no_cause_gets_the_kind_for_who_reported_it(
221253
failure = (await runner.run_task("a")).failure
222254

223255
assert failure is not None
224-
assert (failure.kind, failure.source) == (kind, source)
256+
assert (failure.kind, failure.source, failure.delivery) == (kind, source, delivery)
225257
assert failure.http_status is None
226258
assert failure.exception_type is None
227259

‎tests/unit_tests/rollouts/test_rollout_recovery.py‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2417,3 +2417,52 @@ def fake(self, examples, **kwargs):
24172417

24182418
assert (seen[0]["_max_num_tries"], seen[0]["_connect_grace_s"]) == (None, None)
24192419
assert (seen[1]["_max_num_tries"], seen[1]["_connect_grace_s"]) == (2, 60.0)
2420+
2421+
2422+
def _refused_connection():
2423+
from aiohttp import ClientConnectorError
2424+
from aiohttp.client_reqrep import ConnectionKey
2425+
2426+
return ClientConnectorError(ConnectionKey("127.0.0.1", 1, False, True, None, None, None), OSError(111, "refused"))
2427+
2428+
2429+
async def test_a_refused_connection_is_resent_within_the_grace_and_then_reported_as_not_sent(monkeypatch):
2430+
calls = []
2431+
2432+
async def post(*, _on_transport_failure=None, **kwargs):
2433+
calls.append(kwargs)
2434+
error = _refused_connection()
2435+
_on_transport_failure(error, False)
2436+
raise error
2437+
2438+
install_fake_server_client(monkeypatch, AsyncMock(side_effect=post))
2439+
2440+
_, outcome = await next(
2441+
RolloutCollectionHelper().run_outcomes([failing_row()], max_num_tries=2, connect_grace_s=0.3)
2442+
)
2443+
2444+
assert len(calls) > 1
2445+
assert (outcome.source, outcome.delivery) == ("collector", "not_sent")
2446+
assert outcome.exception_type == "ClientConnectorError"
2447+
2448+
2449+
async def test_a_connection_that_dropped_is_reported_as_possibly_delivered_and_not_resent_by_the_grace(monkeypatch):
2450+
from aiohttp import ServerDisconnectedError
2451+
2452+
calls = []
2453+
2454+
async def post(*, _on_transport_failure=None, **kwargs):
2455+
calls.append(kwargs)
2456+
error = ServerDisconnectedError()
2457+
_on_transport_failure(error, False)
2458+
raise error
2459+
2460+
install_fake_server_client(monkeypatch, AsyncMock(side_effect=post))
2461+
2462+
_, outcome = await next(
2463+
RolloutCollectionHelper().run_outcomes([failing_row()], max_num_tries=2, connect_grace_s=0.3)
2464+
)
2465+
2466+
assert len(calls) == 1
2467+
assert (outcome.source, outcome.delivery) == ("collector", "possibly_delivered")
2468+
assert outcome.exception_type == "ServerDisconnectedError"

‎tests/unit_tests/test_public_api.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,8 @@
7979
_REQUIRED = inspect.Parameter.empty
8080

8181
# nemo_gym.environment.in_process: plan a benchmark in one call, then run single tasks against running servers.
82-
# Changes must be additive: a new parameter is optional and keyword-only. Removing or renaming a parameter,
83-
# or changing its default, needs a deprecation first; update this list in the same change.
82+
# The API is experimental and may change without a deprecation period. This list makes a change deliberate:
83+
# update it in the same change.
8484
EXPECTED_IN_PROCESS_TASK_SIGNATURES = {
8585
"plan_benchmark": [
8686
("benchmark", _POSITIONAL, _REQUIRED),
@@ -111,14 +111,14 @@
111111
"PlannedBenchmark.from_json": [("text", _POSITIONAL, _REQUIRED)],
112112
}
113113

114-
# The fields of the two result types. Adding a field with a default is additive; removing or renaming one needs a
115-
# deprecation first. Update this list in the same change.
114+
# The fields of the result types. The API is experimental, so a change is allowed; update this list in the same change.
116115
EXPECTED_IN_PROCESS_RESULT_FIELDS = {
117116
"PlannedBenchmark": ["plan", "rows"],
118117
"RolloutOutcome": ["reward", "failure", "masked", "prompt", "output", "raw"],
119118
"TaskFailure": [
120119
"kind",
121120
"source",
121+
"delivery",
122122
"stage",
123123
"terminal",
124124
"reason",

0 commit comments

Comments
 (0)