Skip to content

refactor(agent): decouple simple-agent compaction from model serving - #3368

Merged
yfw merged 36 commits into
NVIDIA-NeMo:mainfrom
aroshanghias-nvd:cc-capture-redesign-20260914
Nov 19, 2026
Merged

yfw merged 36 commits into
NVIDIA-NeMo:mainfrom
aroshanghias-nvd:cc-capture-redesign-20260914

Conversation

@aroshanghias-nvd

@aroshanghias-nvd aroshanghias-nvd commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

The native compaction agent now returns ordinary accepted rollout history and uses the regular vllm_model server. NeMo-RL owns captured-token reconstruction and training segments; the harness owns its semantic history and compaction policy.

Semantic history, recency policies, guards, and the sequential context client live in nemo_gym.agents.context_management, reusable by other native Responses agents. The earlier nemo_gym.context_management import uses Gym's existing deprecation-alias mechanism. The agent shares reasoning-only/empty-output termination semantics with simple_agent, while preserving main's ordinary-agent session, retry, and checkpoint implementation.

The shared capture infrastructure (#4128) has merged. This PR contains the optional native-agent migration against current main; external harnesses that perform their own compaction do not need it. It removes the obsolete ContextCompactionSession and vllm_model_with_compaction adapter, including that adapter's generated lockfile and ASR model entry. Use the regular vllm_model with the paired external-capture configuration described in the agent README. Root dependencies, root lockfile, shared capture implementation, and secrets baseline match main.

November 19 integration refresh

Merged main at 4164c51e6fa2c01714ea7bcbe574c110ad8debf0. The two modify/delete conflicts concerned the removed vllm_model_with_compaction server and its tests. Its deletion remains intentional; regular vLLM and retained subclasses keep main's non-generating-route fixes. The agent's session/checkpoint and timeout handling retain current main's behavior.

Updated the compaction transport test fixture to supply an actual aiohttp ClientTimeout, as main's bounded connection-retry path now reads that field. This changes the test fixture, not runtime retry policy. The previous review fixes remain: core-suite test placement, source_history prerequisite checks, model-call budget consistency, cached semantic digests, capture collection configuration, usage accumulation and migration documentation. No separate issue is needed for this integration and review follow-up on the existing compaction PR.

Compatibility: this agent requires training token capture and a framework rollout ID. Capture-disabled evaluation remains unsupported. Both max_steps and context_history.max_model_calls default to 256; raise both for longer episodes. Rewriting policies and token guards require source_history capture. Other agents can reuse the shared client and policy.

Validation

  • 4,356 CPU tests passed across core context management, model/capture, client, simple-agent and regular-vLLM suites. Two tests in test_model_failure_observations.py (never-connected, connect-timeout) fail identically on an isolated, unmodified main checkout on this Mac; they do not exercise the new compaction code. Both code and test files match main. Full repository CI and combined 95% coverage remain required; no threshold or omit changes.
  • Full pre-commit run --all-files passed, including private guardword and package-layering checks. New merge commit has DCO sign-off.
  • Optional local_vllm_model tests require the vLLM package, which is not installed in this Mac CPU environment; no GPU result is claimed for this refresh.
  • Previous GPU serving/capture evidence (DFW job 21685395) verified three image/tool calls per mode, budget measurements, captured-prefix reconstruction and processed-image retrieval. Identity image counts were [1, 2, 3]; recency counts were [1, 1, 1]. The model template preserved six assistant boundaries across seven image-only observations. This evidence predates the current main merge and is not learner, TMPE, or fresh 20-step training qualification.

Historical paired-training evidence

The following runs completed 20 optimizer steps before this refresh; they have not been repeated against the new main merge:

Run Training rows Selected calls
Manufactured, no compaction 40 800
Manufactured, image K2 400 800
Custom OpenCode, identity 40 850
Custom OpenCode, compaction 120 880

Those historical runs used paired source in a private aligned runtime. The custom OpenCode evidence used the disclosed collector correction and bounded task; it does not qualify stock OpenCode or SWE-bench. Repository CI on the refreshed head remains required.

Maintainer CI authorization is needed for /ok to test 785664b695c065b954517fe6c976ad2bca50d3d6. Review replies are already present; the nine threads remain open for reviewer confirmation.

@copy-pr-bot

copy-pr-bot Bot commented Sep 14, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

lauradang pushed a commit to lauradang/Gym that referenced this pull request Sep 23, 2026
Pass immutable local tensor attachments through worker capture and preserve image descriptors in vLLM extras. Retain stage-before-ack ordering and token-only sink compatibility. Builds on the served-response ancestry fix from NVIDIA-NeMo#3301 and the VLM capture work in NVIDIA-NeMo#3368.

Signed-off-by: Pranav Prashant Thombre <[email protected]>
@aroshanghias-nvd
aroshanghias-nvd force-pushed the cc-capture-redesign-20260914 branch from 3e8a828 to 21965f1 Compare September 30, 2026 01:04
@aroshanghias-nvd aroshanghias-nvd changed the title feat(cc): shared context compaction over worker-owned capture feat(capture): support framework-owned context reconstruction Sep 30, 2026
@aroshanghias-nvd
aroshanghias-nvd force-pushed the cc-capture-redesign-20260914 branch from 21965f1 to 4769525 Compare September 30, 2026 01:13
@aroshanghias-nvd

aroshanghias-nvd commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Please authorize the standard Gym CI for draft PR #3368 at 4870eb240475e078c4ea96af54ca2393298f4170. This updates the existing CC draft with the reviewed synthetic-digest baseline correction; the changed-file secrets scan passes locally. The paired RL PR is rebased onto merged #4191. Native/runtime qualification remains pending, and this PR remains a draft.

@aroshanghias-nvd
aroshanghias-nvd marked this pull request as ready for review September 30, 2026 21:35
@aroshanghias-nvd
aroshanghias-nvd requested a review from a team as a code owner September 30, 2026 21:35
@yaoyu-33 yaoyu-33 added area:training Training framework integrations and training-data interfaces complexity:high Cross-component or shared-contract change with a large review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer labels Sep 30, 2026
@github-actions github-actions Bot added the sla:triage-overdue Review assignment is over the one-business-day SLA label Oct 1, 2026
@aroshanghias-nvd
aroshanghias-nvd force-pushed the cc-capture-redesign-20260914 branch from cf90856 to 115f2db Compare October 6, 2026 19:43
@aroshanghias-nvd aroshanghias-nvd changed the title feat(capture): support framework-owned context reconstruction refactor(agent): build compaction agent on shared capture Oct 6, 2026
Let training frameworks own capture roots and continuation decisions using request replay evidence and committed coordinates. Preserve completion identity, buffered Responses capture, explicit retry controls, and exact measurement through the ordinary vLLM server.

Keep the existing compaction agent and model intact in this infrastructure layer. The native agent migration is a separate stacked change.

Validation: 618 core/model cases and 56 retained legacy agent/model cases passed on Mac CPU across the documented runs. Combined-head GPU smoke evidence is recorded separately.

Co-authored-by: alexandery <[email protected]>
Signed-off-by: Ali Roshan Ghias <[email protected]>
Preserve concurrent framework capture alongside upstream rollout timing, outbound telemetry, tool-call attribution, and canonical finish reasons. Keep retry suppression effective with metrics and tracing enabled.

Validation: 2,475 affected Gym CPU tests and 184 paired RL compatibility tests passed; two optional custom OpenCode exporter cases skipped. Full pre-commit passed. Fern check passed with the unauthenticated redirect check skipped.
Signed-off-by: Ali Roshan Ghias <[email protected]>
@adil-a

adil-a commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

/review

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

HOLD. The projected core coverage is below the 95% gate, because the tests of the new core package do not run in the core suite (test_compaction.py:7). The inline comments also hold four risks and four notes.

Thank you for the fixes in this head. The image-only observation fix is correct and well tested: the new tests run it through the real Responses-to-Chat converter (test_observation_boundaries.py). The three guard regression cases are in (test_client.py:246-294). The vllm_model tests no longer import the deleted server. The nemo_gym.context_management alias keeps the imports of that path in open NeMo-RL #4581 working.

Process state, in order:

  1. This PR now conflicts with main (64348970d) in four files. They are responses_api_agents/simple_agent_with_compaction/app.py, its tests/test_app.py, responses_api_models/vllm_model_with_compaction/uv.lock and fern/versions/latest/pages/model-server/vllm.mdx. The conflicts come from #4790 and #5464, which merged after this head. Please rebase on main. In app.py, keep the is_nemo_gym_fastapi_entrypoint block that #4790 added at the end of the file, so the agent can run with several workers. For the uv.lock file, keep this PR's deletion.
  2. Every commit has a DCO sign-off, and the DCO job passes.
  3. At this head, only the pre-test jobs ran: DCO, lint, copyright, secrets and locks. The /ok to test comment for the earlier head b8c69c50e started no run, and the head moved after it. The automated review bot refused to run at the earlier head 7f8e5cc42, because that head was not vetted. A maintainer needs to post the /ok to test command with the full head SHA (44f3dee6b88f1d6cf9be35f5cbf47188483876f0).
  4. The PR description links no issue and does not say why none is needed (AGENTS.md:42-44).

Two user-facing changes are not in the PR description. First, without training token capture, every /run of this agent now fails (app.py:141-144). Before this PR, the agent also ran without capture, for evaluation (app.py:522, linked at the base, since it is gone at head). Second, max_steps now defaults to 256 (app.py:30). Before this PR, it had no limit. Please list both in the PR description.

These lines outside the diff still name the deleted server or its adapter:

For information: simple_agent retries definite model errors up to max_model_retries times, but this client never retries a failed model call, by design (client.py:47).

Generated by Claude Code

@@ -4,42 +4,48 @@
import subprocess
import sys

from responses_api_agents.simple_agent_with_compaction.compaction import (
from nemo_gym.agents.context_management.config import (

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.

responses_api_agents/simple_agent_with_compaction/tests/test_compaction.py:7

The new core package nemo_gym/agents/context_management keeps its tests in this agent's tests/ folder, so the core coverage gate does not run them.

The gate collects tests only from tests/ (pyproject.toml:719) and fails below fail_under = 95.0 (pyproject.toml:785-786). At this head, the only core test that imports the package is the alias test test_moved_module_is_the_same_object_under_both_names. It runs only the module-level lines, so it covers 326 of the package's 894 statements and misses 568. Before this PR, the agent's own compaction package lived under responses_api_agents/, and the gate did not count it.

The coverage job on main (Unit tests / Combined core coverage at 274eb768e) reports 72,282 statements with 3,476 missed (95.19%). This head contains that main commit. With this PR, the projected total is 94.48%, below 95.0, so the coverage job fails, and the Test job fails with it (unit-tests.yml:306-308). The statement counts are measured. The totals are projections, because the unit tests did not run in CI at this head.

Suggested fix (it moves files, so it is not a suggestion block):

  1. Move test_compaction.py and test_observation_boundaries.py to tests/unit_tests/agents/context_management/. Add an __init__.py there. AGENTS.md:222-225 asks for this place.
  2. Move the 14 test_* functions of test_client.py and make_client to tests/unit_tests/agents/context_management/test_client.py. Give that file its own copies of the four helpers in step 4.
  3. In the moved files, import each name from the module that defines it, as AGENTS.md:252-254 asks.
  4. Keep answer, http_response, observation and reasoning in this agent's test_client.py.
  5. Keep make_agent, run_agent, tool_call and run_body in test_app.py.

This agent's test_app.py imports the four helpers in step 4 (test_app.py:19-24). Open NeMo-RL #4581 imports make_agent, run_agent and http_response from these paths (test_agent_output_compatibility.py:34-40). NeMo-RL cannot import Gym's top-level tests/.

With these moves, the 67 moved tests pass in the core suite, and the 28 tests that stay here pass. The package then misses 55 statements, and the projected total is 95.18%. A lower fail_under or an omit entry for the package hides a core package from the gate.

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.

Addressed in a5bc5458. Moved the shared context-management tests into tests/unit_tests/agents/context_management, using defining-module imports. Kept the four native-agent helpers and the agent integration helpers at their existing paths for paired RL consumers. All 70 core package tests pass; the package covers 836/890 statements. The repository-wide 95% threshold and omit list are unchanged; the full combined coverage job still needs CI.

Comment on lines +141 to +144
def _require_capture(self, logical_rollout_id: str | None) -> str:
if not self._token_id_capture_enabled() or not logical_rollout_id or "/" in logical_rollout_id:
raise ValueError("This agent requires training token capture and a framework logical rollout ID")
return logical_rollout_id

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.

responses_api_agents/simple_agent_with_compaction/app.py:141-144

Rewriting history policies and guards.max_total_tokens work only under parent_resolution: source_history, but _require_capture does not require it.

Gym's default resolution is fingerprint (config.py:156). NeMo-RL main also writes fingerprint when capture is on and token_capture.forest_training is off (nemo_gym.py:1376-1378). Off is the NeMo-RL default (config.py:704). Under fingerprint, these configurations start, and then:

context_history under fingerprint under source_history
identity policy, as in the shipped YAML trains trains
recency, reasoning keep_last_blocks set to 0 trains, but the model still sees the reasoning that the policy removed. Gym and NeMo-RL log no failure. trains
recency, reasoning keep_last_blocks set to 1, or images keep_last_groups set to 1 Gym records the calls after the first rewrite as unresolved_parent. The rollout gets a reward, but NeMo-RL masks it (0 trained tokens). trains
guards.max_total_tokens set vllm_model does not register /context/measure (vllm_model/app.py:919-920). The first measure gets a 404, and /run returns 500. works with NeMo-RL's vLLM worker

No row trains tokens that differ from what the model saw. What goes wrong is an ignored setting, a masked rollout or a failed /run. The README names source_history, but it does not say that these configurations need it.

Suggested fix (three files, and the first part alone turns 2 tests in this PR red, so it is plain code, not a suggestion block):

  1. Import TOKEN_CAPTURE_BLOCK on line 15, the key that _token_id_capture_enabled reads. Refuse the combination in _require_capture:
from nemo_gym.config import (
    TOKEN_CAPTURE_BLOCK,
    AggregateMetrics,
    AggregateMetricsRequest,
    ModelServerRef,
    ResourcesServerRef,
)
    def _require_capture(self, logical_rollout_id: str | None) -> str:
        if not self._token_id_capture_enabled() or not logical_rollout_id or "/" in logical_rollout_id:
            raise ValueError("This agent requires training token capture and a framework logical rollout ID")
        history = self.config.context_history
        rewrites = history.enabled and history.policy.type != "identity"
        capture = self.server_client.global_config_dict.get(TOKEN_CAPTURE_BLOCK) or {}
        if (rewrites or history.guards.max_total_tokens is not None) and capture.get(
            "parent_resolution"
        ) != "source_history":
            # Fingerprint resolution masks or silently undoes rewritten views, and has no measurement route.
            raise ValueError(
                "A rewriting context_history policy or a token guard requires "
                "token_id_capture.parent_resolution=source_history"
            )
        return logical_rollout_id
  1. Add "parent_resolution": "source_history" to the fake token_id_capture configuration in tests/test_app.py:32 and tests/test_simple_agent_parity.py:30.

  2. Add this test to tests/test_app.py:

@pytest.mark.parametrize(
    ("history", "parent_resolution", "refused"),
    [
        ({"enabled": True, "policy": {"type": "recency", "config": {"images": {"enabled": True}}}}, None, True),
        (
            {"enabled": True, "policy": {"type": "recency", "config": {"images": {"enabled": True}}}},
            "fingerprint",
            True,
        ),
        ({"guards": {"max_total_tokens": 100}}, "fingerprint", True),
        ({"enabled": True}, "fingerprint", False),
    ],
)
async def test_rewriting_policy_or_token_guard_requires_source_history(history, parent_resolution, refused):
    agent, calls = make_agent(config={"context_history": history})
    capture = {"enabled": True} | ({"parent_resolution": parent_resolution} if parent_resolution else {})
    agent.server_client.global_config_dict = {"token_id_capture": capture}
    if refused:
        with pytest.raises(ValueError, match="parent_resolution=source_history"):
            await run_agent(agent)
        assert calls == []
    else:
        assert (await run_agent(agent)).reward == 0.75

With all three parts, this agent's tests and simple_agent/tests/test_app.py pass (227). The new test fails its 3 refused cases at this head. A guard on context_history.enabled alone also refuses the shipped YAML, which uses the identity policy and trains under fingerprint. It also misses a token guard set without enabled, because the client applies guards even when enabled is false (client.py:92, client.py:170).

Why each fingerprint row behaves that way

The rows come from runs of the real client through Gym's capture route at this head, with NeMo-RL main's capture decision on the training side.

  1. keep_last_blocks: 0 removes only the reasoning of the response just before the new call. The fingerprint leaves out standalone reasoning items on purpose (fingerprint.py:155-161). So the new request matches the fingerprint that Gym stored for the parent (lineage.py:276). Then _continues compares only the parent's recorded request, not its response. Gym therefore admits the call as token_in on the parent chain (sink.py:307-316). NeMo-RL passes that admission through unchanged (capture_context.py:42-43). The worker then uses the parent's stored tokens as the prompt prefix (vllm_worker_async.py:1361-1369), and those tokens still hold the removed reasoning.
  2. A rewrite of an earlier request (an image drop, or keep_last_blocks: 1) fails _continues: "A rewritten or summarized context fails verification." Gym logs one WARNING and records unresolved_parent (sink.py:350-363). NeMo-RL makes that the receipt's failure reason (nemo_gym.py:2360-2369), and its finalizer rejects the rollout (rollout_reassembler.py:485-486).

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.

Addressed in a5bc5458. Added the source_history requirement before seed/model/tool requests when the enabled policy rewrites history or a token guard is configured. Identity and disabled recency remain allowed under fingerprint resolution when no token guard is set. Regression tests cover refused combinations and allowed controls, including guards with context_history.enabled false.

Comment on lines +30 to 32
max_steps: int = Field(default=256, ge=1)
token_id_capture: bool = True
context_history: ContextHistoryConfig = Field(default_factory=ContextHistoryConfig)

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.

responses_api_agents/simple_agent_with_compaction/app.py:30-32

The loop allows max_steps model calls, but the context client raises after context_history.max_model_calls, so a max_steps above that crashes /run.

app.py:92-93:

for _ in range(self.config.max_steps):
    model_response = await client.create()

client.py:194-195, with the default of 256 at config.py:124:

if self._model_calls >= self.config.max_model_calls:
    raise RuntimeError("Context model-call limit reached")

Both 256 defaults are new in this PR. Before it, max_steps had no default limit (max_steps: int = None, linked at the base, since the line is gone at head). The agent never resamples, so each step is one model call. With max_steps: 300, simple_agent makes 300 model calls and calls /verify. This agent makes 256 calls and then raises RuntimeError: Context model-call limit reached. It never calls /verify, and /run returns 500. NeMo-RL counts the 500 as an infrastructure failure (nemo_gym.py L653-656) and retries the whole prompt group up to max_infra_attempts_per_prompt (5) times. A group that keeps failing stops training under the default max_consecutive_dropped_prompts: 0 (rollout_manager.py L2831-2838).

Suggested fix: refuse the configuration when the agent starts.

Suggested change
max_steps: int = Field(default=256, ge=1)
token_id_capture: bool = True
context_history: ContextHistoryConfig = Field(default_factory=ContextHistoryConfig)
max_steps: int = Field(default=256, ge=1)
token_id_capture: bool = True
context_history: ContextHistoryConfig = Field(default_factory=ContextHistoryConfig)
def model_post_init(self, context: Any) -> None:
# One model call per step; past max_model_calls the client raises instead of ending the trajectory.
if self.max_steps > self.context_history.max_model_calls:
raise ValueError(
f"max_steps={self.max_steps} exceeds context_history.max_model_calls="
f"{self.context_history.max_model_calls}; raise max_model_calls to at least max_steps"
)
return super().model_post_init(context)

With it, max_steps: 300 fails at startup with a ValidationError. max_steps: 300 with max_model_calls: 300 passes, and so do the defaults. The agent tests still pass. A cap at min(max_steps, max_model_calls) in the loop silently ignores the user's max_steps.

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.

Addressed in a5bc5458. The agent configuration now rejects max_steps above context_history.max_model_calls at construction. Tests cover rejection and exhausting an equal two-call budget through two tool calls followed by verification. Documented both 256 defaults and the need to raise both for longer episodes.

return canonical_digest(value)


def _semantic_part_digest(event: SemanticEvent, part: SemanticPart) -> 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.

nemo_gym/agents/context_management/history.py:454

_semantic_part_digest hashes each part's full payload, and every model call runs it on every part, so each call hashes every raw image again.

This PR drops the image store, so raw base64 images now stay in the semantic history. Before this PR, the history hashed each image once on append and stored a _nemo_gym_media_id reference in its place. That code is compaction/history.py:739-745, linked at the base, since it is gone at head. Now every prepare() (client.py:169) digests every part in the history, also the images that the policy omits. It does so twice: in the policy (policies.py:247) and in _lineage_record (history.py:492). Both built-in policies do this, only to build lineage records. The work runs synchronously inside ContextManagedResponsesClient.create, so it blocks the other rollouts that this agent process serves.

Measured with 1.5 MB base64 screenshots and recency keeping 3 (best of 3 runs):

one prepare() 10 images 50 images 100 images
before this PR 12.2 ms 10.3 ms 11.7 ms
at this head 69.5 ms 300.8 ms 586.9 ms
with the fix below 12.1 ms 9.6 ms 10.9 ms

A second run used 1.5 MB raw screenshots (about 2 MB as base64) and a model that answers in 0.3 s. There, 8 concurrent 30-step rollouts take 66.9 s at this head and 16.0 s with the fix.

Suggested fix: compute each part's digest once in append_items. Store it as a required digest: str field on SemanticPart. The edits span the dataclass, both constructors and the function, so it is a diff, not a suggestion block:

--- a/nemo_gym/agents/context_management/history.py
+++ b/nemo_gym/agents/context_management/history.py
@@ -109,6 +109,8 @@
     part_id: str
     kind: SemanticPartKind
     content_index: int | None
+    # Hashed once on append: policies digest every part on every call, and image payloads are large.
+    digest: str
     observation_group_id: str | None = None
 
 
@@ -409,6 +411,7 @@
                             part_id=part_id,
                             kind=kind,
                             content_index=content_index,
+                            digest=_part_digest(kind, content_part, observation_group_id),
                             observation_group_id=observation_group_id,
                         )
                     )
@@ -430,6 +433,7 @@
                         part_id=part_id,
                         kind=kind,
                         content_index=None,
+                        digest=_part_digest(kind, semantic_item, None),
                     )
                 )
 
@@ -451,21 +455,12 @@
     return canonical_digest(value)
 
 
+def _part_digest(kind: str, payload: Any, observation_group_id: str | None) -> str:
+    return canonical_digest({"kind": kind, "payload": payload, "observation_group_id": observation_group_id})
+
+
 def _semantic_part_digest(event: SemanticEvent, part: SemanticPart) -> str:
-    content = event.item.get("content")
-    if isinstance(content, list):
-        if part.content_index is None:
-            raise ValueError(f"Semantic part {part.part_id!r} has no content index")
-        payload = content[part.content_index]
-    else:
-        payload = event.item
-    return canonical_digest(
-        {
-            "kind": part.kind,
-            "payload": payload,
-            "observation_group_id": part.observation_group_id,
-        }
-    )
+    return part.digest
 
 
 def _lineage_record(

Lineage IDs and view digests stay byte-identical, this agent's tests and simple_agent/tests/test_app.py pass (223), and ruff is clean. Only append_items builds a SemanticPart in Gym, and NeMo-RL main builds none, so the new required field breaks no caller.

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.

Addressed in a5bc5458. Semantic-part source digests are now computed once at append time and reused in lineage. Regression tests cover identity and recency, including omitted historical images, and verify the original digest formula. A private benchmark with 100 historical 1.5 MB image strings reduced minimum prepare time from about 599 ms to 13 ms; policy decisions and view digests were identical. This is a hashing benchmark, not live agent throughput.

Comment on lines 11 to 12
context_history:
enabled: true

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.

responses_api_agents/simple_agent_with_compaction/configs/simple_agent_with_compaction.yaml:11-12

The agent opts into training capture only through its Python default, but rollout collection reads the opt-in from the YAML configuration.

app.py:31, which _token_id_capture_enabled reads:

token_id_capture: bool = True

token_capture_enabled_for_agent, which rollout collection calls (rollout_collection.py:4204):

bool(agent_config.get("token_id_capture", False))

Under Gym-owned capture without token_id_capture.all_agents: true, the two sides disagree. The agent runs as a capture participant, but rollout collection treats its rows as rows without capture. It skips the stale-capture clearing (rollout_collection.py:4220-4224) and the capture finalize step (rollout_collection.py:4456) for them. NeMo-RL sets all_agents: true (nemo_gym.py:1365), so NeMo-RL runs are not affected. opencode_sandboxed_agent.yaml:12 declares the same key in its YAML.

Suggested fix: declare the key in the shipped YAML.

Suggested change
context_history:
enabled: true
# Rollout collection reads the opt-in from this config, not from the Python default.
token_id_capture: true
context_history:
enabled: true

With the key, rollout collection sees the agent as a capture participant.

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.

Addressed in a5bc5458. Added token_id_capture: true to the shipped agent YAML and a test exercising the collection classifier with all_agents false.

Comment on lines +5 to +13
Use the regular `vllm_model` server with framework-owned external capture. NeMo-RL sets `token_id_capture.parent_resolution: source_history` when its `token_capture.forest_training` option is active. The paired capture protocol uses schema v3; both repositories must be upgraded together.

# Licensing information
The result uses ordinary Gym response history: the final response ID names the last accepted action, and output retains accepted generations before and after compaction. NeMo-RL owns serving-prefix decisions, captured model inputs, training-row planning, logical advantages, and processed media. This agent keeps policy decisions, tool execution and verification. Its reasoning-only/empty-output termination follows the ordinary simple agent.

Configure `context_history.enabled`, the recency policy, optional turn-chunk schedule and guards. Token-budget guards call `/ng-rollout/{attempt}/training-token-capture/context/measure`; that endpoint uses the worker's generation preprocessing without staging a call. The client rejects streaming, provider session state and concurrent use of one client. Deliberate response resampling is bounded by the configured retry and model-call limits. A lost response acknowledgement terminates the attempt instead of automatically replaying a model or tool call.

The reusable client lives in `nemo_gym.agents.context_management`; the earlier `nemo_gym.context_management` import follows Gym's standard deprecation alias.

CPU tests cover policy, original-image retention, adapter parity and HTTP custody. Real model and verifier smoke rollouts remain required for release.

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.

responses_api_agents/simple_agent_with_compaction/README.md:5-13

The README does not say that this agent now runs only with training token capture, or what replaces the deleted compaction library and server.

These points are missing or wrong at this head:

Suggested fix: replace lines 5-13 with this text.

Suggested change
Use the regular `vllm_model` server with framework-owned external capture. NeMo-RL sets `token_id_capture.parent_resolution: source_history` when its `token_capture.forest_training` option is active. The paired capture protocol uses schema v3; both repositories must be upgraded together.
# Licensing information
The result uses ordinary Gym response history: the final response ID names the last accepted action, and output retains accepted generations before and after compaction. NeMo-RL owns serving-prefix decisions, captured model inputs, training-row planning, logical advantages, and processed media. This agent keeps policy decisions, tool execution and verification. Its reasoning-only/empty-output termination follows the ordinary simple agent.
Configure `context_history.enabled`, the recency policy, optional turn-chunk schedule and guards. Token-budget guards call `/ng-rollout/{attempt}/training-token-capture/context/measure`; that endpoint uses the worker's generation preprocessing without staging a call. The client rejects streaming, provider session state and concurrent use of one client. Deliberate response resampling is bounded by the configured retry and model-call limits. A lost response acknowledgement terminates the attempt instead of automatically replaying a model or tool call.
The reusable client lives in `nemo_gym.agents.context_management`; the earlier `nemo_gym.context_management` import follows Gym's standard deprecation alias.
CPU tests cover policy, original-image retention, adapter parity and HTTP custody. Real model and verifier smoke rollouts remain required for release.
Use the regular `vllm_model` server with framework-owned external capture. The agent runs only with training token capture (`token_id_capture.enabled: true`). Without it, every request fails with `This agent requires training token capture and a framework logical rollout ID`. A policy that rewrites history needs `token_id_capture.parent_resolution: source_history`, and so does `guards.max_total_tokens`. NeMo-RL sets it when its `token_capture.forest_training` option is active. The paired capture protocol uses schema v3. Upgrade both repositories together.
The result uses ordinary Gym response history. The final response ID names the last accepted action. The output keeps the accepted generations from before and after compaction. The verifier receives every image. The `/run` result leaves raw image parts out of `response.output` and `responses_create_params.input`. NeMo-RL owns serving-prefix decisions, captured model inputs, training-row planning, logical advantages, and processed media. This agent keeps policy decisions, tool execution and verification. Its reasoning-only/empty-output termination follows `simple_agent`.
Configure `context_history.enabled`, the recency policy, an optional turn-chunk schedule and guards. Token-budget guards call `/ng-rollout/{attempt}/training-token-capture/context/measure`. That endpoint uses the worker's generation preprocessing and does not stage a call. The client rejects streaming, provider session state and concurrent use of one client. This agent keeps the first response of each model call, so `context_history.max_response_retries` has no effect. A lost response acknowledgement ends the attempt. The agent does not replay the model call or a tool call.
Gym 0.6.0 and 0.7.0 shipped a different compaction library as `responses_api_agents.simple_agent_with_compaction.compaction`. They ran this agent against the `vllm_model_with_compaction` server (`policy_model_for_compaction`). Gym no longer ships either one. The shared client is now `ContextManagedResponsesClient` in `nemo_gym.agents.context_management`. Point `model_server.name` at a `vllm_model` server, such as `policy_model` from `responses_api_models/vllm_model/configs/vllm_model_for_training.yaml`. Reasoning recency needs `uses_reasoning_parser: true` on that server. The removed server's configuration set it.

The block drops line 11. Gym's scripts/migrate_imports.py also rewrites Markdown, and it turns that sentence into one that calls the new path the earlier one. The block also drops line 13, a test and release note for the PR description.

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.

Addressed in a5bc5458. Updated the README to state the capture-only contract and migration from the removed compaction library/server to ContextManagedResponsesClient plus regular vllm_model. It now covers source_history, the paired schema-v3 worker, reasoning-parser configuration, the two 256-call/step limits, verifier versus returned image history, and first-response/no-model-retry behavior. Capture-disabled evaluation remains unsupported in this focused refactor.

Comment on lines +141 to +163
elif case == "usage":
responses.insert(0, answer(0, output=[reasoning(0)]))
for response in (responses[0], responses[-1]):
response.usage = NeMoGymResponse.model_validate(
response.model_dump()
| {
"usage": {
"input_tokens": 10,
"input_tokens_details": {"cached_tokens": 2},
"output_tokens": 3,
"output_tokens_details": {"reasoning_tokens": 1},
"total_tokens": 13,
}
}
).usage

ordinary, ordinary_calls = await exercise(False, responses, **options)
managed, managed_calls = await exercise(True, responses, **options)
assert managed_calls == ordinary_calls
assert managed.model_dump() == ordinary.model_dump()
assert "context_compaction_result" not in managed.model_dump()
if case == "usage":
assert managed.response.usage.total_tokens == 13

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.

responses_api_agents/simple_agent_with_compaction/tests/test_simple_agent_parity.py:141-163

The usage case ends after one model call, so it cannot catch a bug in how usage adds up across calls.

Line 142 inserts a reasoning-only first response, which ends the run. So the result counts only one usage (13). If app.py:94 becomes usage = model_response.usage, all 95 tests of this agent still pass.

Suggested fix: run the tool call and the answer, both with usage, and expect the sum.

Suggested change
elif case == "usage":
responses.insert(0, answer(0, output=[reasoning(0)]))
for response in (responses[0], responses[-1]):
response.usage = NeMoGymResponse.model_validate(
response.model_dump()
| {
"usage": {
"input_tokens": 10,
"input_tokens_details": {"cached_tokens": 2},
"output_tokens": 3,
"output_tokens_details": {"reasoning_tokens": 1},
"total_tokens": 13,
}
}
).usage
ordinary, ordinary_calls = await exercise(False, responses, **options)
managed, managed_calls = await exercise(True, responses, **options)
assert managed_calls == ordinary_calls
assert managed.model_dump() == ordinary.model_dump()
assert "context_compaction_result" not in managed.model_dump()
if case == "usage":
assert managed.response.usage.total_tokens == 13
elif case == "usage":
# Two model calls (tool call, then answer), so the result must sum both usages.
for response in (responses[0], responses[-1]):
response.usage = NeMoGymResponse.model_validate(
response.model_dump()
| {
"usage": {
"input_tokens": 10,
"input_tokens_details": {"cached_tokens": 2},
"output_tokens": 3,
"output_tokens_details": {"reasoning_tokens": 1},
"total_tokens": 13,
}
}
).usage
ordinary, ordinary_calls = await exercise(False, responses, **options)
managed, managed_calls = await exercise(True, responses, **options)
assert managed_calls == ordinary_calls
assert managed.model_dump() == ordinary.model_dump()
assert "context_compaction_result" not in managed.model_dump()
if case == "usage":
assert managed.response.usage.total_tokens == 26

With it, the 95 tests pass, and the usage = model_response.usage change turns this case red.

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.

Addressed in a5bc5458. The usage parity case now executes the tool response and final answer, each with 13 tokens of usage, and asserts the accumulated total is 26. It no longer terminates on a reasoning-only first response.

Comment on lines +547 to +550


# Compatibility alias retained for existing callers.
CanonicalHistory = SemanticHistory

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.

nemo_gym/agents/context_management/history.py:547-550

The comment says that CanonicalHistory stays for existing callers, but nothing imports it from this new module.

Nothing in Gym at this head, in NeMo-RL main or in open NeMo-RL #4581 imports CanonicalHistory. The name was public at the old path responses_api_agents.simple_agent_with_compaction.compaction (compaction/__init__.py:74, linked at the base, since it is gone at head). This PR deletes that path, so an old caller cannot reach the new name.

Suggested fix: delete the alias and the two blank lines above it.

Suggested change
# Compatibility alias retained for existing callers.
CanonicalHistory = SemanticHistory

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.

Addressed in a5bc5458. Removed the ineffective CanonicalHistory alias; the migration documentation names the supported shared client and explains removal of the old package.

@@ -253,8 +253,8 @@ Make sure your input JSONL respects the selected mode in the [Constraint matrix]
| `drop_custom_tools` | `bool` | `false` | Streaming requests only; available on every model server. When `true`, `custom` (free-form) tools are dropped instead of being converted to Chat Completions custom tools, which a backend that expresses function tools only rejects with 422. Leave `false` for a backend with free-form tool support, or set `custom_tool_strategy: function_bridge` to keep the capability on a function-only backend instead of dropping it. |
| `custom_tool_strategy` | `str` | `"passthrough"` | How a Responses `custom` (free-form) tool reaches a backend whose chat schema admits function tools only. `passthrough` sends the converted request unchanged and the backend decides: vLLM's chat route refuses a request carrying a Chat custom tool, and `drop_custom_tools` remains the kill switch. `function_bridge` lowers each custom tool to a function tool with one required plain-string `input` parameter, replays `custom_tool_call`/`custom_tool_call_output` history in the lowered form, lifts a returned call whose name the request declared as custom back into a `custom_tool_call` item, and hoists custom entries from a streaming harness's `additional_tools` carrier instead of dropping them. A grammar `format` on the tool is dropped at the lowering (warned once per tool name): no vLLM tool parser enforces a grammar through function calling. Honored by the servers that run the Responses-to-Chat conversion — `vllm_model` and its subclasses (the compaction and GenRM servers included), `inference_provider`, and `azure_openai_model`; rejected together with `is_responses_native: true`, whose native route renders function tools only. Parser caveat: with a JSON-format tool parser (`hermes`, `llama3_json`, `mistral`) the model must JSON-escape the free-form payload inside the bridged arguments object, and an escaping mistake surfaces as plain text with no tool call; XML-style parsers (`qwen3_coder`, `nemotron_v3`) carry the payload as raw text. |

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.

fern/versions/latest/pages/model-server/vllm.mdx:254

The custom_tool_strategy row still names the compaction server, which this PR deletes.

This PR removes that server from the two other rows of this table that named it (lines 256-257 at the base). The GenRM half stays true, because GenRMModel builds on LocalVLLMModel(VLLMModel).

Suggested fix: drop the compaction server from the list.

Suggested change
| `custom_tool_strategy` | `str` | `"passthrough"` | How a Responses `custom` (free-form) tool reaches a backend whose chat schema admits function tools only. `passthrough` sends the converted request unchanged and the backend decides: vLLM's chat route refuses a request carrying a Chat custom tool, and `drop_custom_tools` remains the kill switch. `function_bridge` lowers each custom tool to a function tool with one required plain-string `input` parameter, replays `custom_tool_call`/`custom_tool_call_output` history in the lowered form, lifts a returned call whose name the request declared as custom back into a `custom_tool_call` item, and hoists custom entries from a streaming harness's `additional_tools` carrier instead of dropping them. A grammar `format` on the tool is dropped at the lowering (warned once per tool name): no vLLM tool parser enforces a grammar through function calling. Honored by the servers that run the Responses-to-Chat conversion — `vllm_model` and its subclasses (the compaction and GenRM servers included), `inference_provider`, and `azure_openai_model`; rejected together with `is_responses_native: true`, whose native route renders function tools only. Parser caveat: with a JSON-format tool parser (`hermes`, `llama3_json`, `mistral`) the model must JSON-escape the free-form payload inside the bridged arguments object, and an escaping mistake surfaces as plain text with no tool call; XML-style parsers (`qwen3_coder`, `nemotron_v3`) carry the payload as raw text. |
| `custom_tool_strategy` | `str` | `"passthrough"` | How a Responses `custom` (free-form) tool reaches a backend whose chat schema admits function tools only. `passthrough` sends the converted request unchanged and the backend decides: vLLM's chat route refuses a request carrying a Chat custom tool, and `drop_custom_tools` remains the kill switch. `function_bridge` lowers each custom tool to a function tool with one required plain-string `input` parameter, replays `custom_tool_call`/`custom_tool_call_output` history in the lowered form, lifts a returned call whose name the request declared as custom back into a `custom_tool_call` item, and hoists custom entries from a streaming harness's `additional_tools` carrier instead of dropping them. A grammar `format` on the tool is dropped at the lowering (warned once per tool name): no vLLM tool parser enforces a grammar through function calling. Honored by the servers that run the Responses-to-Chat conversion — `vllm_model` and its subclasses (the GenRM server included), `inference_provider`, and `azure_openai_model`; rejected together with `is_responses_native: true`, whose native route renders function tools only. Parser caveat: with a JSON-format tool parser (`hermes`, `llama3_json`, `mistral`) the model must JSON-escape the free-form payload inside the bridged arguments object, and an escaping mistake surfaces as plain text with no tool call; XML-style parsers (`qwen3_coder`, `nemotron_v3`) carry the payload as raw text. |

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.

Addressed in a5bc5458. Removed the deleted server from the custom_tool_strategy documentation and cleaned remaining stale adapter, component-lock-policy, and legacy timing references. Current main had already removed two of the other stale code/test references.

@github-actions github-actions Bot removed the sla:triage-overdue Review assignment is over the one-business-day SLA label Nov 11, 2026
@aroshanghias-nvd

Copy link
Copy Markdown
Contributor Author

@yfw — pushed the review fixes in a5bc5458 and replied to each of the nine inline comments.

For the overall review:

  • Merged main at f26664c7 and resolved the conflicts, preserving the multi-worker FastAPI entrypoint and deletion of the obsolete server's lockfile.
  • The README now explicitly documents capture-only operation, the two 256-step/model-call defaults, source-history prerequisites, and migration to the shared client and regular model server. Capture-disabled evaluation remains outside this focused refactor.
  • This is the optional native-agent migration completing the existing context-compaction work, so there is no separate issue for this review-fix refresh.

Validation on the pushed source: 1,666 broad Mac CPU tests passed; the final native-agent checks passed 24/24 (overlapping that suite); all 70 core context-management tests passed. Paired RL compatibility checks passed 7 tests with 4 skipped. Full pre-commit passed with the private guardword audit unavailable; Fern reported zero errors and one warning.

DFW job 21685395 completed 0:0 against the real vLLM worker and TQ: each mode verified three image/tool calls, three token-budget measurements, captured-prefix reconstruction, and processed-image tensor retrieval. Identity used image counts [1, 2, 3] and one context root; recency used [1, 1, 1] and three roots. The model's chat template also preserved six assistant boundaries across seven image-only observations. This used the established private container with dependency overlays and the paired instrumented RL snapshot; it was a serving/capture smoke, not learner, TMPE, or fresh 20-step training qualification.

The repository-wide 95% coverage gate is unchanged and still needs the combined CI run. I have left the review threads open for your re-review.

Integrate the validated source tree while retaining the published PR history.

Signed-off-by: Ali Roshan Ghias <[email protected]>
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the risk:high Autobot PR risk: high label Nov 19, 2026
@athitten

Copy link
Copy Markdown
Contributor

/ok to test 785664b

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 19, 2026 22:26
@github-actions

Copy link
Copy Markdown
Contributor

@yfw
yfw enabled auto-merge November 19, 2026 22:36
@yfw
yfw added this pull request to the merge queue Nov 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/44631293492

Merged via the queue into NVIDIA-NeMo:main with commit bd3753b Nov 19, 2026
80 of 85 checks passed
fayejf added a commit that referenced this pull request Nov 20, 2026
Conflicts:
- scripts/component-lock-policy.json: main removed the vllm_model_with_compaction component (#3368), so its
  entry goes; vllm_model_with_guards keeps its pathspec override.
- responses_api_agents/opencode_sandboxed_agent/app.py: both sides added config fields (this branch:
  opencode_data_home_in_tmp, idle_nudge, stuck_detector; main: opencode_provider_id, opencode_model_id,
  sandbox_upload_roots, sandbox_row_option_keys); both are kept.

Component locks: Checked 329 projects; 0 failed.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: Fei Jia <[email protected]>
khazic pushed a commit to khazic/Gym-lao that referenced this pull request Nov 26, 2026
NVIDIA-NeMo#5984)

* feat(capture): support framework-owned context reconstruction

Let training frameworks own capture roots and continuation decisions using request replay evidence and committed coordinates. Preserve completion identity, buffered Responses capture, explicit retry controls, and exact measurement through the ordinary vLLM server.

Keep the existing compaction agent and model intact in this infrastructure layer. The native agent migration is a separate stacked change.

Validation: 618 core/model cases and 56 retained legacy agent/model cases passed on Mac CPU across the documented runs. Combined-head GPU smoke evidence is recorded separately.

Co-authored-by: alexandery <[email protected]>
Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(capture): allow concurrent calls and own continuity checks

Signed-off-by: Ali Roshan Ghias <[email protected]>

* refactor(capture): remove unused custody field list restored by merge

Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(capture): preserve Responses string input in context evidence

Normalize string input as a user message before capture matching and measurement. Verify unchanged history continues while omitted or changed initial questions start new roots.

Validation: 840 affected Gym CPU tests, three HTTP prefix checks using the actual RL input decision, and pre-commit checks passed.
Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(capture): address framework context review boundaries

Signed-off-by: Ali Roshan Ghias <[email protected]>

* refactor(agent): build compaction agent on shared capture

Move semantic history, policies and the context client into the reusable context_management package. Return ordinary accepted rollout history from simple_agent_with_compaction and use the ordinary vLLM capture server.

Preserve shared termination semantics and remove the replaced legacy compaction session/model with its paired ASR configuration entry. Context management stays optional for external harnesses.

The combined source tree exactly matches the qualified Gym PR head cf90856; no dependency or lockfile changes.

Signed-off-by: Ali Roshan Ghias <[email protected]>

* test(agent): remove obsolete capture-parent header expectation

Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(agent): route context measurement with rollout identity

Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(agent): use supported connection-safe retry controls

Replace removed _retry arguments in context measurement, generation, and resources calls. Exercise the real ServerClient retry stack against aiohttp's accepted arguments, preserving safe connection retries and refusing ambiguous resends.

Signed-off-by: Ali Roshan Ghias <[email protected]>

* refactor(capture): name source-history parent resolution explicitly

Signed-off-by: Ali Roshan Ghias <[email protected]>

* docs(agent): update parent-resolution configuration

Signed-off-by: Ali Roshan Ghias <[email protected]>

* test(capture): preserve tracing and replay controls across dispatch

Signed-off-by: Ali Roshan Ghias <[email protected]>

* refactor(capture): distinguish capture ownership from rollout identity

Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(compaction): preserve image-only observation boundaries

Signed-off-by: Ali Roshan Ghias <[email protected]>

* test(compaction): import converter through public facade

Signed-off-by: Ali Roshan Ghias <[email protected]>

* refactor(agent): snapshot context-management dependency from Gym NVIDIA-NeMo#3368

Tree-identical snapshot of 44f3dee.
Preserves the tested upstream dependency without carrying development merge history.
Original PR: NVIDIA-NeMo#3368

Signed-off-by: Ali Roshan Ghias <[email protected]>

* feat(visgym): add visual environments with optional context compaction

Consolidates validated adapter tree from bc4a65088b21a063426a7bbeabd8704a3443f51c.
Depends on Gym NVIDIA-NeMo#3368; runtime content is unchanged.

Signed-off-by: Ali Roshan Ghias <[email protected]>

* Separate VisGym experiments and qualify component locks

Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(agent): address compaction validation and core coverage review

Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(tests): follow shared helper and component import contracts

Signed-off-by: Ali Roshan Ghias <[email protected]>

* test: isolate visual resource discovery without a shared package marker

Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(visgym): preserve capture identity and enforce rollout failure contracts

Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(visgym): preserve task state and score malformed actions safely

Signed-off-by: Ali Roshan Ghias <[email protected]>

---------

Signed-off-by: Ali Roshan Ghias <[email protected]>
Co-authored-by: alexandery <[email protected]>
khazic pushed a commit to khazic/Gym-lao that referenced this pull request Nov 26, 2026
…NVIDIA-NeMo#5983)

* feat(capture): support framework-owned context reconstruction

Let training frameworks own capture roots and continuation decisions using request replay evidence and committed coordinates. Preserve completion identity, buffered Responses capture, explicit retry controls, and exact measurement through the ordinary vLLM server.

Keep the existing compaction agent and model intact in this infrastructure layer. The native agent migration is a separate stacked change.

Validation: 618 core/model cases and 56 retained legacy agent/model cases passed on Mac CPU across the documented runs. Combined-head GPU smoke evidence is recorded separately.

Co-authored-by: alexandery <[email protected]>
Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(capture): allow concurrent calls and own continuity checks

Signed-off-by: Ali Roshan Ghias <[email protected]>

* refactor(capture): remove unused custody field list restored by merge

Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(capture): preserve Responses string input in context evidence

Normalize string input as a user message before capture matching and measurement. Verify unchanged history continues while omitted or changed initial questions start new roots.

Validation: 840 affected Gym CPU tests, three HTTP prefix checks using the actual RL input decision, and pre-commit checks passed.
Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(capture): address framework context review boundaries

Signed-off-by: Ali Roshan Ghias <[email protected]>

* refactor(agent): build compaction agent on shared capture

Move semantic history, policies and the context client into the reusable context_management package. Return ordinary accepted rollout history from simple_agent_with_compaction and use the ordinary vLLM capture server.

Preserve shared termination semantics and remove the replaced legacy compaction session/model with its paired ASR configuration entry. Context management stays optional for external harnesses.

The combined source tree exactly matches the qualified Gym PR head cf90856; no dependency or lockfile changes.

Signed-off-by: Ali Roshan Ghias <[email protected]>

* test(agent): remove obsolete capture-parent header expectation

Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(agent): route context measurement with rollout identity

Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(agent): use supported connection-safe retry controls

Replace removed _retry arguments in context measurement, generation, and resources calls. Exercise the real ServerClient retry stack against aiohttp's accepted arguments, preserving safe connection retries and refusing ambiguous resends.

Signed-off-by: Ali Roshan Ghias <[email protected]>

* refactor(capture): name source-history parent resolution explicitly

Signed-off-by: Ali Roshan Ghias <[email protected]>

* docs(agent): update parent-resolution configuration

Signed-off-by: Ali Roshan Ghias <[email protected]>

* test(capture): preserve tracing and replay controls across dispatch

Signed-off-by: Ali Roshan Ghias <[email protected]>

* refactor(capture): distinguish capture ownership from rollout identity

Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(compaction): preserve image-only observation boundaries

Signed-off-by: Ali Roshan Ghias <[email protected]>

* test(compaction): import converter through public facade

Signed-off-by: Ali Roshan Ghias <[email protected]>

* refactor(agent): snapshot context-management dependency from Gym NVIDIA-NeMo#3368

Tree-identical snapshot of 44f3dee.
Preserves the tested upstream dependency without carrying development merge history.
Original PR: NVIDIA-NeMo#3368

Signed-off-by: Ali Roshan Ghias <[email protected]>

* feat(gym-v): add visual environments with optional context compaction

Consolidates validated adapter tree from 48d8e6407aac2bfade2ca4fb6e1e658c153eade7.
Depends on Gym NVIDIA-NeMo#3368; runtime content is unchanged.

Signed-off-by: Ali Roshan Ghias <[email protected]>

* Simplify Gym-V adapter and inherit component lock policy

Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(agent): address compaction validation and core coverage review

Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(tests): follow shared helper and component import contracts

Signed-off-by: Ali Roshan Ghias <[email protected]>

* test: isolate visual resource discovery without a shared package marker

Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(gym-v): preserve capture identity and enforce rollout failure contracts

Signed-off-by: Ali Roshan Ghias <[email protected]>

* fix(gym-v): keep failed session construction retryable

Signed-off-by: Ali Roshan Ghias <[email protected]>

---------

Signed-off-by: Ali Roshan Ghias <[email protected]>
Co-authored-by: alexandery <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:training Training framework integrations and training-data interfaces complexity:high Cross-component or shared-contract change with a large review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer risk:high Autobot PR risk: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants