Skip to content

feat(compat): keep old import paths working across the package reorganization - #5167

Merged
ananthsub merged 1 commit into
mainfrom
ananthsub/layout-compat
Oct 30, 2026
Merged

ananthsub merged 1 commit into
mainfrom
ananthsub/layout-compat

Conversation

@ananthsub

@ananthsub ananthsub commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

What and why

The first PR of the nemo_gym package reorganization. It moves nothing. It adds what keeps every current import path working while later PRs move modules, so users, open branches, and NeMo RL do not break.

  • Old module paths resolve to the same module object as the new path.
  • Split-out names resolve to the same object from their new module.
  • Other ways of reaching a module work too: a module imported through its old path keeps its own __spec__, so importlib.reload and find_spec still work; python -m <old path> runs the new module, with the same warning; and a package attribute such as nemo_gym.global_config resolves before anything imports it.
  • Each old path and each split-out name warns once, naming the new path and the release that removes it. A test fails once that release arrives.
  • scripts/migrate_imports.py rewrites old paths for move PRs, open branches, and downstream projects, and reports what it cannot fix safely.
  • Fallbacks for an older nemo-gym: a line marked # path before nemo_gym 0.8.0 keeps its old path. Scripts that a sandbox runs against its own installed nemo-gym use it to fall back to the old layout.

Where this PR sits

The stack lands bottom-up; each PR's base is the branch of the PR before it, so each diff shows only that PR's change.

flowchart LR
  compat["#5167<br/>Old import paths<br/>keep working"]
  linter["#5168<br/>import-linter<br/>layer contract"]
  prep["#5169<br/>Remove path and<br/>name couplings"]
  config["#5189<br/>Move config/"]
  utils["#5195<br/>Move utils/"]
  core["#5203<br/>Move core/"]
  client["#5206<br/>Move client/,<br/>start telemetry/"]
  trajectory["#5209<br/>Move trajectory/"]
  verification["#5210<br/>Move verification/"]
  metrics["#5211<br/>Move metrics/"]
  artifacts["#5212<br/>Move artifacts/"]
  srmods["#5214<br/>Move server_runtime/<br/>modules"]
  su["#5215<br/>Split server_utils"]
  model["#5224<br/>Move models/<br/>modules"]
  modelbase["#5225<br/>Split model<br/>call capture"]
  agents["#5228<br/>Move agents/"]
  data["#5229<br/>Move data/"]
  harbor["#5230<br/>Split the<br/>Harbor task CLI"]
  rollouts["#5231<br/>Move rollouts/"]
  rsplit["#5232<br/>Split the<br/>rollout collector"]
  testing["#5233<br/>Dissolve testing/"]
  orch["#5234<br/>Move orchestration/<br/>modules"]
  sup["#5235<br/>Split the<br/>server supervisor"]
  eval["#5244<br/>Move eval/"]
  env["#5298<br/>Move environment/<br/>registries"]
  cli["#5300<br/>Retire the<br/>cli_setup_command shim"]
  docs["#5385<br/>Describe the<br/>package layout"]
  owners["next<br/>CODEOWNERS:<br/>per-package groups"]
  remove["0.10.0<br/>Remove the<br/>old paths"]
  compat --> linter
  linter --> prep
  prep --> config
  config --> utils
  utils --> core
  core --> client
  client --> trajectory
  trajectory --> verification
  verification --> metrics
  metrics --> artifacts
  artifacts --> srmods
  srmods --> su
  su --> model
  model --> modelbase
  modelbase --> agents
  agents --> data
  data --> harbor
  harbor --> rollouts
  rollouts --> rsplit
  rsplit --> testing
  testing --> orch
  orch --> sup
  sup --> eval
  eval --> env
  env --> cli
  cli --> docs
  docs --> owners
  owners --> remove
  classDef this fill:#fde68a,stroke:#b45309,stroke-width:2px,color:#1f2937
  classDef later fill:#f3f4f6,stroke:#9ca3af,color:#4b5563,stroke-dasharray: 4 3
  class compat this
  class owners,remove later
Loading

How an old module path keeps working

flowchart LR
  U["import nemo_gym.server_utils"] --> F{"MovedModuleFinder<br/>first on sys.meta_path"}
  F -->|"path is in MOVED_MODULES"| W["Warn once: new path,<br/>moved in, removed in, running"]
  W --> N["Import nemo_gym.server_runtime.server_utils"]
  N --> S["Register the same module object<br/>under the old name"]
  F -->|"any other path"| P["Normal import"]
  classDef this fill:#fde68a,stroke:#b45309,stroke-width:2px,color:#1f2937
  class F,S this
Loading
  • The module never runs twice, so classes, registries, and context variables stay single.
  • mock.patch("<old path>.<name>"), from nemo_gym import <old module>, config strings such as "nemo_gym.token_id_capture.lineage:FileLineageStore", and old pickles all reach the code that runs.

How a split-out name keeps working

flowchart LR
  A["nemo_gym.server_utils.request"] --> G{"Still defined or imported<br/>in server_utils?"}
  G -->|"yes"| R["That object"]
  G -->|"no"| M["Module __getattr__<br/>reads MOVED_NAMES"]
  M --> X["Warn once, return the same object from<br/>nemo_gym.client.http_client"]
  classDef this fill:#fde68a,stroke:#b45309,stroke-width:2px,color:#1f2937
  class M,X this
Loading

A module that serves split-out names can move later itself, as episode_types and server_utils do. Its entries stay under its old path, and its __getattr__ still finds them once the module runs under its new name.

When old paths go away

flowchart LR
  S["Entry records since = 0.8.0"] --> R["removed_in = since + 2 minor releases = 0.10.0"]
  R --> B["Version bump to 0.10.0"]
  B --> T["Unit test fails while the entry still exists"]
  T --> D["That PR deletes the old path"]
Loading

What the tests check

  • Finder, against a temporary package tree: one module object under both names, no second execution of a moved package's submodules, patches and config strings through the old path, old pickles, find_spec origins, the warning text and the file it points at, one warning per path. After an old-path import the module keeps its own __spec__, so importlib.resources still reads a moved package's data files and importlib.reload works. A nested key wins over its parent's, and python -m <old path> runs the new module.

  • Move tables, with fake entries while the real tables are empty: an entry is overdue from the removal release's prereleases on (0.10.0rc0), a moved name's warning points at the importing file, and no entry's destination is itself an old path, which would warn twice.

  • Recorded import surface: tests/unit_tests/fixtures/import_surface.json lists every module and the names an importer can rely on, including values such as PARENT_DIR and type aliases Gym defines, such as NeMoGymResponseInputItem. A module that moves without an alias, or loses a recorded name, fails. Every recorded module is checked name by name, so a split that forgets its whole MOVED_NAMES block fails too, and the names an existing moved_attr_getter shim serves are recorded with the rest. A PR that removes a name on purpose refreshes that module's entry.

  • NeMo RL: every from nemo_gym... import ... in NeMo RL's code, tests, and examples, the lineage store it names in config, and its patches of RunHelper and RolloutCollectionHelper.

  • Import rewriter: split from imports, imports in strings and docs, patch targets, CODEOWNERS and CI paths, idempotence, and the files it must skip (the move list, the frozen docs for released versions, fern/docs.yml redirects, and paths inside links pinned to a commit). It reports what it leaves for a person to check:

    • a patch of a split-out name through the module its receiver is bound to (import ... as su included) or names directly (nemo_gym.server_utils), which reaches only code that still looks the name up there;
    • old_module.Name in code when the file does not import the name's new module above that line, so it may not be loaded there;
    • a relative import, resolved against the file's package, that reaches a moved module or name.

    A split from import that follows other code on its line (if flag: from ..., or after a backslash continuation) stays in that line's statement list, and each line of a split keeps a trailing # noqa or # type: ignore. An import with comments inside its parentheses is left as it is, with a note. The script checks that a rewritten file still parses before writing it, keeps CRLF line endings and a UTF-8 byte order mark, and reports files it skips because they do not parse or are not UTF-8.

Each finder property was checked by breaking it: registering the finder after the normal finders, blaming the warning on Gym's import machinery, and running a copy of the module each fail the tests.

Validation

  • pytest -n 16 tests/unit_tests. The failures are the same on main at 5911d62 on this machine: the benchmark listing test and the Harbor run summary tests, which fail because this machine's hostname resolves to 127.0.1.1, and the Docker PTY tests for a PID file that is not a regular file.
  • pre-commit run --all-files.
  • The PRs above this one apply it to real moves: their unit suites pass with -W error for the moved paths, and NeMo RL's Gym-facing unit tests pass against them.

Rollout evidence: N/A. Nothing moves here. The finder matches no path until a move adds an entry.

Compatibility

No user-visible change. import nemo_gym installs the finder, which matches only paths listed in MOVED_MODULES.

Issue

Part of #5166.

@copy-pr-bot

copy-pr-bot Bot commented Oct 28, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@ananthsub
ananthsub added this pull request to stack #5170 October 28, 2026 00:08
@ananthsub ananthsub added the area:core Shared APIs, servers, telemetry, health, and registries label Oct 28, 2026
@ananthsub ananthsub self-assigned this Oct 28, 2026
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the feature New capabilities, enhancements, or enablement work label Oct 28, 2026
@ananthsub
ananthsub force-pushed the ananthsub/layout-compat branch 2 times, most recently from dc59503 to 9e70f8b Compare October 28, 2026 16:24
@ananthsub
ananthsub force-pushed the ananthsub/layout-compat branch 2 times, most recently from 77a9e2d to c266804 Compare October 28, 2026 17:45
@ananthsub
ananthsub marked this pull request as ready for review October 28, 2026 17:47
@ananthsub
ananthsub requested a review from yaoyu-33 October 28, 2026 17:47
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team October 28, 2026 17:49
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the needs-review PR is ready for code review and waiting on a reviewer label Oct 28, 2026

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SHIP WITH CARE

Five RISK findings affect migration correctness and compatibility-test coverage; one NOTE concerns warning frequency. The move tables are currently empty, so these are defects in the new migration/compatibility mechanisms, not demonstrated production outages.

Completed static inspection of all six changed files and directly affected paths. Two delegated report payloads were unavailable; their assignments were re-inspected directly. Tests were not executed, and the suggested corrections require author verification.

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

Comment thread scripts/migrate_imports.py Resolved
Comment thread scripts/migrate_imports.py Resolved
Comment thread scripts/migrate_imports.py Resolved
Comment thread scripts/migrate_imports.py Resolved
Comment thread tests/unit_tests/test_moved_paths.py Resolved
Comment thread nemo_gym/_moved_paths.py Resolved

@yaoyu-33 yaoyu-33 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SHIP WITH CARE

This PR adds the compatibility layer the package reorganization (#5166) depends on: MovedModuleFinder serves an old module path as the same module object, moved_names_getattr serves names split out of a module, and the PR adds a versioned removal guard, the recorded import surface, and scripts/migrate_imports.py. Aliasing the old path to the same object, instead of stub re-export modules, is the right design. Classes, registries, pickles and mock.patch through old paths all keep working, and we checked isinstance, pickle and Ray's cloudpickle through an alias. Both move tables are empty here, so nothing changes at runtime yet. The comments are about the mechanism that the move PRs will rely on.

Two things are worth fixing before the first move lands:

  • RISK: an old-path import replaces the moved module's __spec__. That breaks importlib.resources for every caller, for example NeMo RL's assert_golden_vectors() once token capture moves. The fix is about four lines; see the suggestion.
  • RISK: the import-surface guard checks names only for modules that already have a MOVED_* entry. A split PR that forgets the whole MOVED_NAMES block for a module still passes CI.

The other inline comments are NOTEs, your call:

  • python -m <old path> fails;
  • moved modules stop being attributes of nemo_gym;
  • chained moves warn twice;
  • the rewriter does not validate its output and drops comments when it splits an import;
  • some guard tests only run once the tables have entries.

Two earlier automated-review threads still have a small open case; I replied on both.

Notes for later PRs in the stack
  • #5224: needs the __spec__ fix before nemo_gym.token_id_capture moves. A NeMo RL usage test that calls assert_golden_vectors() through the old path would pin it.
  • #5195: 7 of its 12 MOVED_NAMES entries never reach __getattr__, because the old module still imports those names. They are the six server_process helpers in server_utils.py and cli.utils.did_you_mean. So they never warn, and deleting the entries in 0.10.0 removes nothing.
  • #5225 and #5232: base_responses_api_model and rollout_collection already install a moved_attr_getter __getattr__. A split there has to merge it with moved_names_getattr, not replace it.
  • #5189: makes the nemo_gym attribute note live, for example nemo_gym.global_config after import nemo_gym.server_utils.

Validation. Reviewed at 3b7adfa. 2ee5790 is the same six-file diff rebased onto #5317.

  • Locally, the two new test files pass (87 tests).
  • The unit suite (sandbox-marked tests deselected) fails the same tests as the base commit, so this PR adds no failures.
  • CI ran on 3b7adfa: Server suite shard 0 failed on a Docker Hub pull rate limit in harbor_agent_general, which is unrelated. CI has not run on the rebased head yet.
  • Not run: GPU tests.

Comment thread nemo_gym/_moved_paths.py Resolved
Comment thread tests/unit_tests/test_moved_paths.py Resolved
Comment thread nemo_gym/_moved_paths.py Resolved
Comment thread nemo_gym/__init__.py Resolved
Comment thread nemo_gym/_moved_paths.py Resolved
Comment thread scripts/migrate_imports.py Resolved
Comment thread scripts/migrate_imports.py Resolved
Comment thread tests/unit_tests/test_moved_paths.py Resolved
yaoyu-33
yaoyu-33 previously approved these changes Oct 29, 2026

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

Approving. Both move tables are empty in this PR, so the two RISKs above can't break anything yet. They should land before the first move PR that depends on them:

  • the __spec__ restore in create_module/exec_module, before token capture moves (#5224);
  • the surface guard checking names for every recorded module, before a split PR relies on it (#5195).

@ananthsub

Copy link
Copy Markdown
Contributor Author

On the notes for later PRs in the stack:

yaoyu-33
yaoyu-33 previously approved these changes Oct 29, 2026

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

Re-approving at cb763ae. Both RISKs from the earlier approval are fixed: exec_module now restores the module's own __spec__, so find_spec and reload on the new path work after an old-path import, and the surface test now checks every recorded name at its old path. The failing checks are the non-blocking harness conformance job.

…nization

Add the machinery that keeps every current nemo_gym import path working
while modules move into the new package layout, before any module moves.

- nemo_gym/_moved_paths.py records each moved module and each name split
  out of a module, with the release the move first ships in. A finder
  installed first on sys.meta_path serves an old module path as the same
  module object as its new path, so code never runs twice and patches
  through the old path still take effect. Each use warns once, naming the
  new path, the removal release and the running version.
- Old paths are removed two minor releases after they move. A unit test
  fails once the running version reaches an entry's removal release.
- A recorded import surface of today's modules and names, checked for
  every module the reorganization touches.
- Tests for the imports and patches NeMo RL relies on.
- scripts/migrate_imports.py rewrites old paths to new ones, for move PRs,
  open branches and downstream projects.

Gaps found while moving the first packages:

- A one-line `from <module> import <names>` written as text, such as a
  code sample in docs or a code template in a string, was left on the old
  path when names split out of that module. It is now rewritten like a
  real import statement.
- fern/docs.yml holds redirects whose sources are the URLs of moved
  modules, so it is no longer rewritten. Library reference URLs
  (.../nemo-gym/nemo_gym/<module>) are left alone everywhere, because
  those redirects cover them.
- monkeypatch.setattr(<old module>, "<name>", ...) and patch.object for a
  name that split out of that module now produce a note: such a patch
  reaches only code that still looks the name up in the old module, so
  it needs checking by hand.

The recorded import surface left out every typing object, so it missed
the type aliases Gym defines, such as NeMoGymResponseInputItem, and a
module split could drop one without the surface test noticing. Aliases a
module defines are now recorded, names imported from typing itself are
still left out, and keys that are not identifiers (pydantic's cached
generic classes such as `BaseEpisodeRequest[Any]`) are skipped.

The surface is recorded again on the current main.

A module that serves names split out of it can later move itself:
episode_types, rollout_correlation and server_utils all do. Its
MOVED_NAMES entries stay under its old path, but its __getattr__ then
runs under the new module name and found nothing. Look the names up
under every old path MOVED_MODULES maps to the module, directly or as
part of a moved package.

The import rewriter rewrote nemo_gym/server_utils.py inside a GitHub
link pinned to a commit, which pointed the link at a file that commit
does not have. Skip paths that follow /blob/<sha>/, /tree/<sha>/ or
/raw/<sha>/.

Review fixes for scripts/migrate_imports.py:

- A split `from` import that follows other code on its line
  (`if flag: from ...`, `x = 1; from ...`) now stays in that line's
  statement list, joined with `;`. One that starts its line keeps that
  line's own indentation, tabs included.
- `old_module.Name` in code, for a name split out of old_module, is
  rewritten only when the file imports the new module. Otherwise it is
  left at the old module, which still serves the name, and reported:
  the new module may not be loaded there.
- Relative imports are resolved against the file's package, so
  `from .server_utils import X` and `from .openai_utils import Name`
  are reported, and relative imports outside nemo_gym are not.
- A patch of a split-out name is reported by the module its receiver
  is bound to (`import ... as su`, `from nemo_gym import x as su`),
  not by the name alone, and not for receivers bound otherwise.

Review fixes:

- moved_names_getattr warned on every access. It now warns once per
  old name, like old module paths, and still looks the name up on
  every access, so a patch of the new module shows through.
- The recorded import surface missed seven modules that exist before
  any move, among them nemo_gym.verifiers and four Harbor task modules.
  Record it again from the whole tree the moves start from.

Scripts that a sandbox runs against its own installed nemo-gym need a
fallback to the paths before the reorganization. The rewriter now leaves
any line marked `# path before nemo_gym 0.8.0` unchanged, in code and in
text such as a runner template held in a string.

Names split out of a module stay recorded under its old path. Once that
module moves too, code imports the names from the new path, and the
rewriter did not recognize them there. Register each name move under the
module's current path as well.

RunHelper reaches nemo_gym.cli through the CLI refactor's __getattr__
shim. monkeypatch.setattr restored it with setattr, which left it in the
module's namespace, so a later test that expects the shim's warning
failed when it ran after this one on the same worker. Patch the module's
namespace instead, so undoing the patch removes the name.

Signed-off-by: Ananth Subramaniam <[email protected]>

This branch was previously deployed

1 inactive deployment
public — 4eb9471a Deployed Oct 30, 2026 by copy-pr-bot[bot] via release / finalize / notify #8614
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core Shared APIs, servers, telemetry, health, and registries feature New capabilities, enhancements, or enablement work ready-to-merge PR is approved, current, and waiting for final CI or merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants