Repository navigation
feat(critpt_custom_grader): sandboxed grader for CritPt-like tasks on Gym's sandbox API - #4629
Conversation
…d core
Rebuild resources_servers/critpt_custom_grader so the change touches only that
directory and one README index row, on top of current main. Drop every prior
edit to shared core (nemo_gym, responses_api_agents/simple_agent,
responses_api_models/openai_model, tests). The grader now runs against
unmodified core.
Dropped shared symbols, replaced by grader-local equivalents:
- nemo_gym.server_utils.{ServerRequestPolicy, ServerRequestPrivacy,
private_error_response} -> server_support.py. The two config models are
declarative operator intent. The grader enforces its own request privacy at
its HTTP boundary through its private route class, its private ingress, and
its overridden telemetry and exception hooks, which unmodified core still
calls.
- DaytonaProvider(category_only_diagnostics=...) and the missing-exit-code
guard -> provider_support.py. A local CategoryOnlyDaytonaProvider subclass
reads a missing or non-integer exit code as a typed sandbox failure, never as
success, and keeps the provider's own exec text and log lines to fixed
categories. Only _exec is overridden.
Config: the agent block points at the stock responses_api_agents/simple_agent
and carries no private-mode keys. The launch command drops the two model-server
overrides that unmodified core ignores. The grader server block keeps its
request-policy and request-privacy config, backed by the local models.
Tests: rewrote the two tests that exercised dropped features, added tests for
the local provider subclass and the local config models, kept every other test.
ng_test passes and validates the example data.
Grading semantics are unchanged. The comparator, codec, symbolic, task_data,
and runner modules are the lean commit's, byte for byte.
Review fixes, grader directory only:
- comparator.py: a test pins the unordered_undecided verdict, where a one-to-one
matching exists over undecided member pairs but not over certain ones.
- symbolic.py: the polynomial fast path is guarded, so an expression the
is_polynomial or Poly check cannot handle becomes the numeric fallback instead
of an unhandled exception.
- app.py: a latched-gate verify shares one queue-wait budget across its reconcile
and its execute, so it cannot wait the full queue timeout twice. The single-job
limit is unchanged.
Astra review fixes, grader directory only:
- symbolic.py (finding 1): an undecided difference that carries a branch
function (Abs, sign, floor, ceiling, Heaviside, Piecewise, Max, Min, re, im,
arg) returns None instead of accepting on fixed samples, since the samples can
all fall on one side of the branch point. Non-branch expressions keep the
sampling path. This guard sits after the polynomial guard above.
- comparator.py (finding 2): the accuracy kind read (abs/rel) is bounded to the
keyword's own sentence, the same bounds name attribution uses, and each number
is scored under its nearest keyword, so a number a wide window pulls across a
sentence break is not double-counted under two kinds.
- comparator.py (finding 4): a cross-pair that raises RepresentationError in the
unordered match is treated as no match, so a valid one-to-one matching still
passes.
- runner.py (finding 5): materialize_input has a SetValue branch that returns a
Python set of materialized members, so task code that uses the set API works.
- comparator.py (finding 6): a symbolic-carrier expectation of oo or zoo is
rejected as nonfinite_expected, matching the README rule. A plain categorical
string is unaffected.
- README.md (findings 9, 10): an emptied harvested promise reads as the strict
floor where no author spoke; a waiter completes only while its cumulative wait
stays within queue_timeout_s, not for as many jobs as the queue holds.
Astra review, second batch, grader directory only:
- app.py: a response that ends on an assistant message whose own status is not
completed now needs regeneration, through a _final_message_incomplete helper
feeding _needs_regeneration. An incomplete final message inside a completed
envelope is no longer read as a finished answer.
- execution.py: shutdown scans the journal's unresolved records the way reconcile
does, so a disk-recovered record whose first delete failed gets another attempt
at shutdown instead of waiting for the next restart. A corrupt record is
reported as corrupt_record, never resolved.
Signed-off-by: William <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01H1ap1cmdJDPbW1dj3KAovc
Signed-off-by: Erik Arakelyan <[email protected]>
Rename the failure classes to follow nemo_gym/failure_kinds.py: verifier_unavailable -> provider_unavailable, reference_failed -> verifier_error, needs_regeneration -> critpt_custom_grader:response_incomplete. The first two are registered core names that execution.py already produced, so app.py no longer translates them. failure_kind now carries the same value as _ng_failure_class. Routing, retry, and terminal behavior do not change. Correct the README recovery section. Core has no recover_failure_classes option, and --judge-failed-only selects only judge_failed rows. Select provider_unavailable rows from the failures file with jq, then run plain gym eval reverify on them. Document the reverify model overrides and the aggregate quoting that a live run showed are required. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01UCKgzMtDMkANTG7Xu9W1ef Signed-off-by: William <[email protected]> Signed-off-by: Erik Arakelyan <[email protected]>
… Gym's sandbox API Rebuild the critpt_custom_grader resources server on Gym's provider-neutral sandbox API. Every reference, candidate and comparator step runs in its own single-use sandbox through nemo_gym.sandbox.AsyncSandbox; the provider is selected through `sandbox_provider` (a shipped provider block or an inline mapping) and the sandbox is built from `sandbox_spec`. The provider-specific backend, the ownership journal and the reconciliation logic of the previous version are removed. Grading pipeline (unchanged in shape): reference run, comparator preflight, candidate run, comparator judge. The candidate sandbox receives only the source, the normalised inputs, the runner package and the operator's `sandbox_spec.files`; expectations and tolerances travel only to the comparator, which is the sole verdict authority. Result files are read only behind the accepted runner exits, with status/exit pairing and a per-run nonce; transfers and result sizes are bounded. Server: a standard SimpleResourcesServer with category-only HTTP errors (413 request_limit, 422 request_invalid / task_invalid, 503 server_not_ready), request-body bounds, `mask_sample` and `sandbox_observations` on every row, `_ng_failure_*` keys only on terminal unscorable rows, a startup probe (exec user, uid, interpreter pins, nested upload and read-back) whose failures refuse startup, a draining shutdown, and config validation for the create/ready/transfer, workdir and ttl/job-timeout bounds. Grader: a semaphore replaces the one-job pin; a reference cache stores only task-level refusals (task_invalid, reference_mismatch) and never raises into grading; provider failures map to a closed set of non-terminal categories and are logged by exception class only. Comparator and symbolic equality: authored tolerances take precedence over prose promises; the prose extractor honours a number only under an accuracy keyword with a stated kind; a statement is wrapped Markdown, so a soft line wrap inside a sentence is a space, not a sentence break (a blank line, a line ending in . ; : ? !, a heading, a table row and a list marker still end one), and the words of a multi-word keyword may be separated by any blank; typed symbolic observations are compared symbolically against legacy text expectations; a per-case comparison timeout is uncertain; symbolic equality is certified only by proof and disproved only at positive real sample points; a decided candidate failure on any case outranks candidate-side uncertainty. Runtime: a pinned grading image recipe (Python 3.13, pydantic, sympy, mpmath, numpy, scipy; non-root user) under runtime/, selected through `sandbox_spec.image` or CRITPT_CUSTOM_GRADER_IMAGE, with a published multi-architecture image as the default. README, docs row and root README row updated; tests use an in-memory scripted sandbox provider plus a local-provider end-to-end test. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Erik Arakelyan <[email protected]>
CritPtAgentRunRequest declares only problem_id and code_template and sets no model_config, so pydantic's default extra="ignore" drops every other field of a dataset row. The agent builds the /seed_session and /verify payloads from body.model_dump(), so a resources server that needs more task fields than those two never receives them. Set extra="allow", as SimpleAgentRunRequest already does, so the remaining row fields reach the resources server unchanged. problem_id and code_template stay required. Add tests that check the extra fields arrive in both payloads and that a request missing a declared field is still refused. Signed-off-by: Erik Arakelyan <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
/ok to test dc64a40 |
| handle = getattr(sandbox, "_handle", None) | ||
| if handle is not None and not getattr(sandbox, "_stopped", False): | ||
| self.sandbox_id = getattr(handle, "sandbox_id", None) | ||
| self.cleanup = "delete_failed" |
There was a problem hiding this comment.
When setup fails and its first stop also fails, this records the ID but leaves _sandbox=None. close() then cannot retry, even if the stop failure was transient. Could we retain the live facade so final cleanup can retry rather than relying solely on TTL?
There was a problem hiding this comment.
Thanks, fixed in ae67d85. When the stop after a failed setup fails or is cancelled, create() now keeps the facade together with the sandbox id. close(), and with it the grader's final sweep, retries the stop under the same lock: it records deleted when the retry succeeds and delete_failed otherwise. The TTL stays the provider-side backstop, and the kept facade is only used for that retry (_box() still refuses a domain whose create failed). Tests cover a transient and a persistent first-stop failure, a cancelled first stop, concurrent closers and the final sweep end to end.
| "exec_timeout_margin_s", | ||
| ) | ||
| }, | ||
| "runtime": runtime_digest, |
There was a problem hiding this comment.
With reference_cache_dir enabled, switching local to OpenSandbox can reuse a cached reference_mismatch because this key omits provider/runtime identity. The local provider ignores image, so that field isn't sufficient. Could we namespace persisted entries by the effective runtime, or invalidate them when it changes?
There was a problem hiding this comment.
Agreed, fixed in ae67d85 by namespacing the key. It now also carries the provider's module-qualified class name and execution.exec_user, alongside the image, the interpreter and the runner limits it already covered. Each runtime therefore gets its own entries in memory and on disk, and a reference_mismatch cached under local is never read under OpenSandbox. The added fields are deterministic (no endpoints, credentials or sandbox ids), and entries written under the old key are simply never looked up again. Tests cover separate persisted entries for two providers and for two images, and a refusal persisted under one provider not being returned under another.
…space the reference cache by runtime; declare ray_enabled When a sandbox's setup failed and the stop after it failed too, the domain recorded the sandbox id but dropped the facade, so close() could not retry and only the TTL would reap the sandbox; the domain now keeps the facade (also when that stop is cancelled) and close() retries the stop, recording deleted on success and delete_failed otherwise. The reference cache key did not name the provider, and the local provider ignores the image, so an outcome persisted under one provider could be read under another; the key now also carries the provider's class and the exec user. The server class declares ray_enabled = False, as the check that every shipped server declares its Ray use requires. Signed-off-by: Erik Arakelyan <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Review round 1 is addressed in ae67d85, with a reply on each thread:
Each change has regression tests. On the new head, CI has not run on this head yet: it needs a vetter's |
| # The grading image: Python 3.13 with pinned pydantic, sympy, mpmath, numpy and scipy in the interpreter's own | ||
| # site-packages (the runner runs with -I), a non-root `grader` user and a /work directory it owns. See | ||
| # runtime/Dockerfile. OpenSandbox does not create the workdir, so it must exist in the image. | ||
| image: ${oc.env:CRITPT_CUSTOM_GRADER_IMAGE,docker.io/earakelyan93701/critpt-custom-grader-rt:2026.10} |
There was a problem hiding this comment.
THis is a personal container. Rather than this, users should build the container with dockerfile use that one here?
There was a problem hiding this comment.
@oyilmaz-nvidia I fixed the issue in 277d789. The config ships no image: sandbox_spec.image is CRITPT_CUSTOM_GRADER_IMAGE when that is set and null otherwise, and the README's "The grading image" section gives the steps (build runtime/Dockerfile, publish it where your provider pulls from, set the variable or the key). The local provider used in CI runs the host interpreter and needs no image; on every other provider startup refuses to serve with image_missing before any sandbox starts, whether or not the startup probe is on, and an empty variable counts as unset. A provider's snapshot or template does not stand in for the image, on purpose: the reference cache names the runtime by its image. Tests cover the shipped config with the variable unset and set, the refusal with and without the probe, with an empty image and with a snapshot or template in place of the image, and startup without an image on the local provider.
… on every provider but local The shipped config defaulted sandbox_spec.image to a personal container image. It now ships none: sandbox_spec.image is CRITPT_CUSTOM_GRADER_IMAGE when that is set and null otherwise. Operators build runtime/Dockerfile, publish the image where their provider pulls from, and set CRITPT_CUSTOM_GRADER_IMAGE or sandbox_spec.image to it. Without an image (unset or empty), startup refuses to serve with image_missing on every provider but local, before any sandbox starts and also with startup_probe false. As for a failed probe, the provider is closed and the server holds neither provider nor grader. The local provider runs the host interpreter and ignores the image; it is recognised by the name every provider declares. The refusal also covers providers that could start without an image (a daytona or opensandbox snapshot_id, an e2b template, the openshell gateway's default image), on purpose: the reference cache names the runtime by its image, so it could not tell such runtimes apart. The README, the config comment, the docstring and the error hint say so. README: the build and publish steps (a local docker build serves only the docker provider on that host; apptainer and enroot pull a bare reference from a registry), the variable, image_missing as the seventh startup category, and the opensandbox row without the personal image. The Dockerfile header uses a generic <registry>/<path>/ placeholder. Tests cover the shipped config with the variable unset and set, the refusal with and without the probe and with an empty image (no sandbox created, provider closed), the refusal when provider_options names a snapshot or a template instead of an image, and startup without an image on a provider named local and on Gym's own local provider. Signed-off-by: Erik Arakelyan <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
/ok to test b3e828c |
…suite The core unit-test job measures coverage over every repository module its run imports and fails below 95.00 %. tests/unit_tests/test_task_data.py imports each resources server's task_data.py to validate the server's committed rows, so resources_servers/critpt_custom_grader/task_data.py is measured there. Only the paths those canonical rows reach ran: 122 of its 298 statements were missed (59.06 % covered), enough to pull the core job's total under the gate (94.83 % on the merged-main run). The server's own tests in resources_servers/critpt_custom_grader/tests/ cover the module, but the core job does not collect them (testpaths = ["tests"]). Add tests/unit_tests/test_critpt_custom_grader_task_data.py, a plain pytest file on synthetic values that exercises the schema module itself: the bounded JSON walk, decimal and tolerance text, JSON Pointer paths, the delivered row shapes and their legacy wire encoding, the tolerance, policy and expectation models, and the TaskData validators, field limits and byte budget. The tests carry no marker, so they run in the core job's "not sandbox" pass. With them, 297 of the module's 298 statements run in the core suite. The one left is the instance guard in WireValue.bounded, which validation never reaches: pydantic hands a model instance back before its mode="before" model validators run. Signed-off-by: Erik Arakelyan <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]>
Head branch was pushed to by a user without write access
|
Thanks for merging main and vetting. The unit-tests job had no failing test (both pytest passes were green); it failed the coverage gate at 94.83 % against 95 %: be4e43d adds one core-suite test file for that module, The harness-conformance probe jobs and the P0 publish check fail on main's latest runs as well, so they are not from this PR. CI needs a vetter's |
|
/ok to test 8b64ba9 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/39485052559 |
What does this PR do?
Supersedes #3430 and implements the proposal in #3342:
resources_servers/critpt_custom_grader, a sandboxed grader for CritPt-like tasks with operator-supplied task data (Python functions graded against test cases and stored expectations: numeric with tolerances, exact integers, composite values, symbolic expressions, categorical strings, expected exceptions). Compared with #3430, every reference, candidate and comparator step now runs through Gym's provider-neutral sandbox API (nemo_gym.sandbox.AsyncSandbox), so the server runs on any Gym sandbox provider and needs no backend of its own: the Daytona-only backend, the ownership journal and the reconciliation machinery are gone, the provider is selected by config, a task's reference preflight is cached, and concurrency is a semaphore. The grading core (runner, comparator, symbolic grammar, task schema, value codec) carries over with the review fixes below.resources_servers/critptis untouched. No core changes.The branch keeps #3430's two content commits with their authorship; the port is one commit on top, followed by one small commit in
responses_api_agents/critpt_agent: its run request now keeps extra dataset-row fields (extra="allow", asSimpleAgentRunRequestdoes), so the two-turn CritPt agent can drive this grader; before, it dropped the task fields the grader needs (reference code, entry point, test cases) and every row was refused. Regression tests cover both payloads. Two further commits answer the review. The first: a sandbox whose stop failed after a failed setup keeps its facade, soclose()retries the stop instead of leaving it to the TTL; the reference cache key is namespaced by the provider's class and the exec user, so an entry persisted under one provider or image is never read under another; and the server class declaresray_enabled = Falseexplicitly, since the verify path uses no Ray. The second ships no grading image:sandbox_spec.imagehas no default, operators buildruntime/Dockerfileand setCRITPT_CUSTOM_GRADER_IMAGE(or the config key), thelocalprovider needs none, and on any other provider startup refuses to serve without one (image_missing). Each change has regression tests.How it runs:
finally;sandbox_spec.ttl_sand the metadata labels are the provider-side backstop.provider_unavailablerow, never a score; the server is stateless, so such rows re-grade withgym eval reverify(README, Recovery).task_invalid,reference_mismatch) only; infrastructure and configuration faults are never cached.exec_user_unsupported,exec_user_is_root,interpreter_missing_dependency,provider_create,upload_unsupported,provider_exec). Shutdown drains: new jobs, and running jobs at their next sandbox create, answerserver_draining; live sandboxes are stopped, then the provider is closed.sandbox_providerselects the provider: a named config block (every shipped provider config bindssandbox) or an inline mapping.runtime/holds the grading image recipe (Python 3.13 with pinned pydantic, sympy, mpmath, numpy and scipy, a non-rootgraderuser,/work); no image is shipped: operators build it from that recipe, publish it where their provider pulls from and setCRITPT_CUSTOM_GRADER_IMAGEorsandbox_spec.image. Thelocalprovider runs the host interpreter and needs none; every other provider refuses to start without one.Review findings from #3430 addressed, each with a regression test: the environment-server routing block is in the config;
tool_choice=autowith no tools is accepted; framework_ng_*keys are stripped before task validation; symbolic equality is proved or left undecided, never certified from samples; authored tolerances beat statement promises, and incidental percentages are not promises; typed symbolic answers compare against legacy text expectations; unscorable rows setmask_sample;task_invalidandreference_mismatchstay distinct.Validation
gym env test --resources-server critpt_custom_grader +should_validate_data=trueon a Linux host: 1783 passed, 1 skipped, and the data validated. The skip is the hostile-runner suite, which runs only withNG_CRITPT_RUNNER_REMOTE=1inside a disposable sandbox. The run includes a real grade of the five example rows through thelocalprovider: each passes with its own reference as the candidate and fails with a wrong candidate.pre-commit run --all-files: clean.runtime/Dockerfile(amd64 and arm64, pinned by digest), every sandbox under a deny-by-default network policy, in two runs with identical results: the driving host reached the cell (health check 200) and the startup probe passed (commands run as the non-rootgrader, uid 1000, with the pinned libraries); the five synthetic example tasks passed with their own reference and failed with a wrong constant; 70 rows of one internal evaluation run were re-graded through the cell with no provider fault, 69 of them in the category thelocalprovider gave them in the parity run. The one differing row is the documented runtime difference: its task's reference fails its own preflight on the local validation environment's numpy 2.3.2 and passes on the image's pinned numpy 2.5.1. Re-grading the 70 rows created 210 sandboxes and stopped all 210, and the cell listed none of the run's sandboxes afterwards.Rollouts
data/example_rollouts.jsonl(5 rows) collected withgym env startandgym eval runthrough the OpenSandbox provider and that image, from a model served with Gym'svllm_modelserver (recorded asexample-model); all five rows arepassed. Each row carries its category,cleanup_statusand per-domainsandbox_observations(provider, sandbox id, outcome, exit code, wall time). The end-to-end run under Validation exercises the verifier on the same provider at a larger scale.Compatibility and benchmark impact
New server; no core changes;
resources_servers/critptunchanged. Differences from #3430's grading behaviour:rtol 5e-12,atol 0(twelve significant digits) for a leaf with no authored tolerance and no honoured statement promise. Authored tolerances now take precedence over statement promises, and a number in the statement counts only under an accuracy keyword with a stated kind..,;,:,?or!, a heading, a table row or a list item still ends the sentence. Add critpt_custom_grader: a sandboxed, locally executed grader for CritPt-style problems #3430 ended a sentence at every newline, so on tasks written that way the grader passes answers Add critpt_custom_grader: a sandboxed, locally executed grader for CritPt-style problems #3430 rejected at the default tolerance. It showed in the internal set's agreement rising from 97.74 % to 99.28 % (Validation), as the largest of the fixes behind that rise; in our evaluation runs it changed no row, so the parity run has zero pass/fail flips.compare_per_case_s); a case that runs out is uncertain, not charged to the candidate. A batch getsmin(compare_timeout_s, 20 s × cases + 30 s), shipped with a 600 s cap.In the parity run above none of these changes flips a row between pass and fail. They move some rows between scored and unscorable: a comparison that exhausts its per-case budget or an equality that cannot be proved leaves the row unscorable, and a decided failure that now outranks uncertainty makes a formerly unscorable row a failure.
Known limitations:
candidate_invalid_outputinstead ofcandidate_mismatch) and cannot flip pass/fail; a follow-up.?and!do not end a sentence for the statement reader, as.,;and:do, so an accuracy clause or its kind word can reach across them into the next sentence; a follow-up.domainiscoding, because Gym'sDomainenum has no physics value.sqrt(z**2)againstz), so such a case is uncertain rather than decided.exec_useris applied and whether memory andttl_sare enforced.Checklist
resources_servers/critpt_custom_grader/, its docs environment-list row, its root README table row, one line inresponses_api_agents/critpt_agentwith its tests, and one core-suite unit test for the server's task schema module,tests/unit_tests/test_critpt_custom_grader_task_data.py: the repo-wide schema check imports that module, so the coverage gate measures it, and the server's own tests are not collected by the core job.)update-readme-tablehook).pre-commit run --all-files).git commit -s).🤖 Generated with Claude Code