Skip to content

fix(data-plane): move mooncake's ports out of the ephemeral range - #4103

Merged
terrykong merged 1 commit into
NVIDIA-NeMo:mainfrom
saumishr:fix/mooncake-port-reservation
Sep 12, 2026
Merged

terrykong merged 1 commit into
NVIDIA-NeMo:mainfrom
saumishr:fix/mooncake-port-reservation

Conversation

@saumishr

@saumishr saumishr commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Overview

The ports this stack lands on for the mooncake data plane -- 50050 for the metadata server and 50051 for the master RPC, both from TransferQueue's config.yaml rather than from mooncake, which defaults its HTTP metadata server to 8080 and off, plus 9003 for the master's metrics server from mooncake_master's own gflag -- all sit inside the 9000-65000 ephemeral range these nodes use. The kernel can hand any of them to an outgoing connection during the minutes between job start and the master's bind, after which the master exits with EADDRINUSE and takes the run down with every node already up. Job 3678431 lost 10 nodes for 22 minutes this way: the master bound 50051 and 50050, then died on 9003 a second later.

ray.sub's port map already documents this hazard and pins every other service below 9000. This allocates all three ports from one data-plane band in the gap that map leaves free (1150-1199) and records the band in both copies of the map, instead of hardcoding ports inside the range the kernel draws from. Every one of them reaches clients through the TQ controller actor rather than being assumed, so relocating them costs nothing.

The reservation (_reserve_data_plane_ports) lives next to the other port helpers in virtual_cluster.py and allocates through _get_free_port_local with excluded_ports, the way ManagedDynamoRuntime already allocates its etcd/NATS/frontend ports: distinct by construction, and bound without SO_REUSEADDR, matching mooncake_master -- a port obtainable only by reusing a lingering slot is not one the master could bind either.

The metrics port needs a different route to the master

TransferQueue passes mooncake_master neither --metrics_port nor a --config_path file that could carry one (mooncake_bootstrap.py#L110-L128), and mooncake_master reads a config file only when --config_path is given, so a config key for it is inert. Its bind is not optional either: MasterAdminServer::Start binds the socket before it consults enable_metric_reporting, and the master returns 1 when that bind fails. 9003 is the port that actually killed job 3678431.

TQ does build the master's argv in this process, though -- tq.init -> _maybe_create_tq_storage -> initialize_mooncake_storage all run on the driver -- so _patch_mooncake_master_metrics_port wraps the subprocess.Popen that bootstrap calls and appends --metrics_port=<reserved>, alongside the three TQ patches this adapter already installs. gflags takes the last occurrence of a repeated flag, so this stays correct if upstream starts passing its own.

The provider registry holds a functools.wraps wrapper closed over the original bootstrap function, so the registry entry is re-registered too -- the same trap extract_field_schema has, where rebinding only the defining module leaves the called function unpatched. That wrapper is also where the drift check lives: if a future TQ revision launches the master by some other route, the flag would stop landing silently and the metrics server would be back on 9003, so the bootstrap is required to have gone through the wrapped Popen. The patch can be deleted outright once TQ forwards a metrics_port from conf.backend.MooncakeStore.

What does this PR do ?

Moves every port mooncake's master listens on -- metadata server, master RPC and master metrics -- into the 1150-1199 band that ray.sub's port map leaves free, so none of them is drawn from the kernel's ephemeral range any more.

Issues

Job 3678431 (10 nodes lost for 22 minutes to mooncake_master exiting with EADDRINUSE).

Usage

No user-facing configuration change: the ports are allocated on the driver and reach clients through the TQ controller actor.

Before your PR is "Ready for review"

Pre checks:

  • Make sure you read and followed Contributor guidelines
  • Did you write any new necessary tests?
  • Did you run the unit tests and functional tests locally? Visit our Testing Guide for how to run tests
  • Did you add or update any necessary documentation? Visit our Document Development Guide for how to write, build and test the docs.

Additional Information

Band and allocator tests sit with the other port helpers in tests/unit/distributed/test_virtual_cluster.py and import no TransferQueue, so they run in the base unit-test environment: TestReserveDataPlanePorts (distinctness, band, ephemeral floor, occupied-port avoidance, exhaustion), test_data_plane_band_does_not_collide_with_ray_sub_ports, and data-plane assertions in test_default_port_ranges_ordered_and_below_ephemeral_floor (including that the band is wide enough for all three ports).

The argv patch is covered in tests/unit/data_plane/test_mooncake_metrics_port.py: the flag is appended for mooncake_master (bare or absolute path) and never for the offload client, unknown attributes delegate to the real subprocess, the registry entry that is actually called gets patched, re-init repoints the port instead of stacking wrappers, a bootstrap that skips the wrapped Popen raises, and _init_tq end-to-end hands out three distinct in-band ports with no metrics_port key in the config TQ reads.

@copy-pr-bot

copy-pr-bot Bot commented Sep 11, 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.

@saumishr
saumishr marked this pull request as ready for review September 11, 2026 21:06
@saumishr
saumishr requested review from a team as code owners September 11, 2026 21:06
@saumishr saumishr added the CI:L1 Run doctests, unit tests, and functional tests label Sep 11, 2026

@saumishr saumishr left a comment

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.

Reviewed with the repo's review-pr skill. The band choice and the reservation mechanics check out (no other file hardcodes 50050/50051, TQ honors both addresses via urlparse, and the extra config key cannot raise because TQ reads that section with .get()), but one substantive gap: the metrics port is still on mooncake's default inside the ephemeral range, because TQ never forwards --metrics_port to mooncake_master -- so the crash described in the commit message is not actually fixed. Details inline, plus one maintainability point (this duplicates ManagedDynamoRuntime's port allocator), one test point, and one doc point.

Comment thread nemo_rl/distributed/virtual_cluster.py Resolved
@ZhiyuLi-Nvidia

Copy link
Copy Markdown
Contributor

Thank you @saumishr

Can we also cover metrics port as well?

This PR moves the two ports that worked and leaves the one that failed.

Port In ephemeral pool Moved by this PR Failed in job 3678431
50050 metadata yes ✅ no — bound fine
50051 rpc yes ✅ no — bound fine
9003 metrics yes ❌ no ✅ this is what killed the job

Merge as-is and job 3678431 reproduces identically.

Why 9003 doesn't actually move

The PR reserves a port and writes "metrics_port": metrics_port into the config
— but TransferQueue never reads that key, so --metrics_port is never passed to
mooncake_master, which falls back to its gflag default of 9003. Per the
description:

it reads this config with .get() throughout, so the key is inert until then
and 9003 stays exposed

"Inert" is the operative word: the value is written into a dict nothing consumes.

The log the PR cites shows the same split:

12:16:17.593614  HTTP metadata server started on <head>:50050      <- bound fine
12:16:18.599622  Failed to start master admin server on port 9003  <- died here

Fix — no TransferQueue change needed

transfer_queue.py already prepends mooncake's package dir to PATH, because TQ
Popens the bare binary name. Put a mooncake_master shim earlier on that
PATH that execs the real binary with --metrics_port=<reserved> appended.
That closes it in-repo today, using the port this PR already reserves.

If you'd rather scope this PR to metadata/rpc, fine — but please file the
follow-up before merge, since the motivating incident stays live until it lands.

Premise confirmed (measured)

Four GB200 nodes in the fleet where 3678431 failed:

$ cat /proc/sys/net/ipv4/ip_local_port_range
9000    65000

Identical on all four — fleet default, not node variance. 9003 is 3 ports inside
the pool. The reasoning here is right; only the coverage is short.

Minor: none of the four new tests would fail today, since they pass while
metrics_port is inert. One asserting every port in the launch argv is < 9000
would guard both this and the shim.

Approving the direction — happy to re-review once metrics_port reaches the master.

@saumishr
saumishr force-pushed the fix/mooncake-port-reservation branch from be76e8e to 3dacb03 Compare September 12, 2026 01:23
@saumishr

Copy link
Copy Markdown
Contributor Author

/ok to test 3dacb03

@saumishr
saumishr force-pushed the fix/mooncake-port-reservation branch from 3dacb03 to c99f473 Compare September 12, 2026 01:29
@saumishr

Copy link
Copy Markdown
Contributor Author

Two corrections to my own review, both now folded into c99f473.

The caveat I attached to the metrics-port comment was wrong, and the finding is firmer than I said. I claimed the TransferQueue pin was b266d39 and that I could therefore only verify against TQ's main. That b266d39 came from a different local branch's pyproject.toml, not this one. This branch pins c51614308b68c8d7a87c9b3ef62d59e14c69bde2, which is TQ 0.1.9 — the exact commit my clone was sitting on. So the mooncake_master argv I quoted is the argv this PR actually gets, with no version gap to worry about.

"Mooncake's defaults -- 50050, 50051 and 9003" misattributes the first number, and I repeated it in the code rather than catching it. 50050 is TransferQueue's config.yaml default; mooncake defaults http_metadata_server_port to 8080 and enable_http_metadata_server to false, so the metadata server exists on this stack only because TQ turns it on and picks the port (master.cpp#L176-L179). Nothing behavioral changes — NeMo-RL always passes an explicit metadata_server — but the comments, docstrings, test docstrings, commit message and description now say "the defaults this stack lands on ... both from TransferQueue's config.yaml" instead of crediting mooncake. 9003 is mooncake's own gflag default, so that attribution stands.

While confirming that, I also found a stronger reason for the pre-flight check than "the master happens to die": the metrics socket is bound unconditionally. MasterAdminServer::Start calls http_server_.async_start() and returns false on failure before it looks at enable_metric_reporting, and master.cpp returns 1 when Start() fails — so an occupied 9003 kills the master even with metric reporting off. That is now cited where the constant is defined.

CI: /ok to test c99f473856f3e75042319e06dba2d03d4166e724

@saumishr
saumishr force-pushed the fix/mooncake-port-reservation branch from c99f473 to afe042f Compare September 12, 2026 02:15
@saumishr

Copy link
Copy Markdown
Contributor Author

Revised in afe042f10 (force-push over the previous c99f473), in response to the question of what the metrics-port change actually bought: the previous revision left 9003 exactly where it was and only improved the error, so the port is now genuinely moved.

  • All three of the master's listening ports -- metadata server, master RPC, master metrics -- come from one data-plane band, DEFAULT_DATA_PLANE_PORT_RANGE_* (1150-1199), via _reserve_data_plane_ports(count).
  • The metrics port reaches mooncake_master through a patched argv, since TQ forwards no --metrics_port and reads no config key for it. Details in the thread above and in the description.
  • _assert_mooncake_metrics_port_free and the "one exception to all below 9000" note in ray.sub are both gone; the argv patch has a drift check instead.
  • New tests: tests/unit/data_plane/test_mooncake_metrics_port.py (9 tests, run locally against the pinned TQ revision c516143); TestReserveMooncakePorts became TestReserveDataPlanePorts.

/ok to test afe042f

@saumishr saumishr left a comment

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.

Re-review at afe042f after the metrics-port rework. Five findings, one of which breaks CI.

The headline is the inline comment on test_mooncake_metrics_port.py: two of its tests fail as soon as any earlier test calls _init_tq, which alphabetical collection guarantees. I reproduced both failures locally, so this is not a theoretical ordering concern — it was missed because the file was validated in isolation.

One finding has no line to attach to, since the file is not in the diff:

[DOC] tests/unit/data_plane/README.md — it describes itself as a "Generated audit of every test function under tests/unit/data_plane/" and carries a section per test file with a test count and one-line summaries (## test_mooncake_gdr.py (4 tests) and so on). The new test_mooncake_metrics_port.py (9 tests) needs a section, or the README stops being the inventory it claims to be.

Checked and deliberately not raised, so the next reader does not redo the work:

  • pyrefly is unchanged at one pre-existing error with none in the new code. Both changed source files are in pyrefly.toml project-includes, and CI runs the check, so this was worth confirming rather than assuming.
  • The proxy's __getattr__ delegation covers every attribute TQ's bootstrap actually touches (Popen, run, PIPE, STDOUT), and subprocess.run(["pgrep", ...]) cannot set master_launched spuriously.
  • Re-registering through StorageBootstrapProvider.register_provider does replace the entry get_provider returns at the pinned TQ SHA, cannot stack wrappers, and cannot lose the original.
  • tq.close() followed by a re-init repoints the proxy correctly rather than leaving a stale port.
  • Both port maps (ray.sub and virtual_cluster.py) agree with the half-open constants and clear the Ray GCS ports at 1200-1201 and the router band at 1202.
  • Hardening the drift guard against a gflags -- terminator or space-separated flag was considered and dropped as speculative: the pinned argv is entirely -flag=value with no positionals and no terminator, and gflags permutes non-option arguments rather than terminating parsing.

@saumishr
saumishr force-pushed the fix/mooncake-port-reservation branch from afe042f to 715d097 Compare September 12, 2026 04:58
@saumishr

Copy link
Copy Markdown
Contributor Author

Every finding from my re-review is fixed in 715d097 (force-push over afe042f). Four are answered in their threads; the fifth had no line to attach to:

tests/unit/data_plane/README.md — added the test_mooncake_metrics_port.py section with a one-line summary per test, in the format the rest of that inventory uses, so the "audit of every test function" claim stays true.

The one that mattered was the test-order failure: two tests in the new file asserted on installation state while any earlier _init_tq call — test_mooncake_gdr.py, which pytest collects first, or the session-scoped mooncake client — had already installed the patch process-wide. Reproduced, fixed, and re-verified in both collection orders.

Also re-checked after the fixes: ruff check and ruff format --check clean on all changed files, and pyrefly unchanged at its one pre-existing error with nothing new in the patched code.

/ok to test 715d097

@saumishr

Copy link
Copy Markdown
Contributor Author

/ok to test 715d097

@saumishr

Copy link
Copy Markdown
Contributor Author

@ZhiyuLi-Nvidia Please take a look. Included the metrics port as well.

@ZhiyuLi-Nvidia

Copy link
Copy Markdown
Contributor

Thank you @saumishr, LGTM.

ZhiyuLi-Nvidia
ZhiyuLi-Nvidia previously approved these changes Sep 12, 2026
The ports this stack lands on for the mooncake data plane -- 50050 for the
metadata server and 50051 for the master RPC from TransferQueue's config.yaml,
9003 for the master's metrics server from mooncake_master's own gflag -- all sit
inside the 9000-65000 ephemeral range these nodes use. The kernel can hand any
of them to an outgoing connection during the minutes between job start and the
master's bind, after which the master exits with EADDRINUSE and takes the run
down with every node already up. Job 3678431 lost 10 nodes for 22 minutes this
way: the master bound 50051 and 50050, then died on 9003 a second later.

ray.sub's port map already documents this hazard and pins every other service
below 9000. Allocate all three from one data-plane band in the gap that map
leaves free, and record the band in both copies of the map, instead of
hardcoding ports inside the range the kernel draws from. Every one of them
reaches clients through the TQ controller actor rather than being assumed, so
relocating them costs nothing.

The reservation lives next to the other port helpers in virtual_cluster.py and
allocates through _get_free_port_local with excluded_ports, the way
ManagedDynamoRuntime already allocates its etcd/NATS/frontend ports: distinct by
construction, and bound without SO_REUSEADDR, matching mooncake_master -- a port
obtainable only by reusing a lingering slot is not one the master could bind
either. That placement also keeps the band's tests off TransferQueue, so they
run wherever the rest of the virtual_cluster port tests do.

The metrics port takes a different route to the master. TransferQueue passes
mooncake_master neither --metrics_port nor a --config_path file that could carry
one, and mooncake_master reads a config file only when --config_path is given,
so a config key for it would be inert -- and its bind is not optional either:
MasterAdminServer::Start binds the socket before it consults
enable_metric_reporting, and the master exits non-zero when that bind fails.
TQ does build the master's argv in this process, though (tq.init ->
_maybe_create_tq_storage -> initialize_mooncake_storage all run on the driver),
so the bootstrap's subprocess.Popen is wrapped to append the flag, alongside the
three TQ patches this adapter already installs. gflags takes the last occurrence
of a repeated flag, so this stays correct if upstream starts passing its own.

The provider registry holds a functools.wraps wrapper closed over the original
bootstrap function, so the registry entry is re-registered too -- the same trap
extract_field_schema has. That wrapper is also where the drift check lives: if a
future TQ revision launches the master by some other route, the flag would stop
landing silently and the metrics server would be back on 9003, so the bootstrap
is required to have gone through the wrapped Popen.

Signed-off-by: Saurabh Mishra <[email protected]>
@saumishr

Copy link
Copy Markdown
Contributor Author

Lint is fixed in 92459f67c. Both pyrefly errors were real, and my earlier "pyrefly is clean" claim was wrong for a reason worth writing down: I checked with pyrefly 1.3.0, which resolves transfer_queue as Any and therefore saw neither error. This repo pins pyrefly==0.24.2, and under that version both reproduce locally — so that is what I verified against this time.

not-callable at the bootstrap(conf) call. get_provider returns Callable | None, and the is None check above it does not narrow the capture inside the nested function. Now rebound under a typed name that the closure captures instead:

registered_bootstrap: Callable[..., Any] = bootstrap

bad-assignment at _bs.subprocess = argv. Standing a proxy object in place of a module attribute typed Module[subprocess] is the whole mechanism, so this one is suppressed in the house style used elsewhere in this file, with the reason inline:

# pyrefly: ignore[bad-assignment]  the proxy stands in for the module on purpose

After the fix, with the pinned version and TransferQueue resolving for real: errors shown: 0 on both changed source files. ruff check and ruff format --check clean, and the tests still pass in CI's collection order (13 in tests/unit/data_plane, 14 port tests in test_virtual_cluster.py).

/ok to test 92459f6

@saumishr

Copy link
Copy Markdown
Contributor Author

/ok to test 92459f6

@terrykong
terrykong enabled auto-merge (squash) September 12, 2026 22:01
@terrykong
terrykong merged commit c8c2209 into NVIDIA-NeMo:main Sep 12, 2026
185 of 188 checks passed
asolergi-nv added a commit that referenced this pull request Sep 14, 2026
Eleven commits, two conflicts.

nemo_rl/algorithms/single_controller.py -- NOT a keep-both. #3925 (telemetry
for rollout checkpointing) replaced the retry-count approach with a reason-typed
result: it deletes _MAX_CONSECUTIVE_ROLLOUT_CHECKPOINT_FAILURES and adds the
_RolloutCheckpointSaveResult dataclass in the same place this branch's
_SUPERVISOR_DRAIN_TIMEOUT_S sits. Resolved as ours + main's dataclass, with the
constant dropped: it has no remaining users anywhere in the merged tree, this
branch never referenced it, and RolloutCheckpointAttemptReason is imported and
used by the replacement. Keeping it would have resurrected a name main removed
on purpose.

tests/unit/environments/test_nemo_gym_utils.py -- adjacency, as before. #3368
(actor failure and teardown ownership) appends module-level tests to the same
end-of-file this branch appended TestUnresolvedAgentRefsAreDiagnosable to.
main's functions first, this branch's class after.

The other nine merged clean, including #3739 (nccl_reshard M-to-N refit for
Megatron generation) and #4063 (refit_with_reload_api in the v2 entrypoint),
both of which touch refit paths this PR hardens.

Verified after the merge: every artefact this PR adds is still present
(_refit_participants, _SUPERVISOR_DRAIN_TIMEOUT_S, the aggregated router drain,
shard_liveness_ref, record_weight_version, should_rebuild, restart_backoff_s,
the router's transport-cause log), submodule pins match main on all three, and
1398 tests pass across single_controller, fleet_health, the generation router,
the gym utils and weight_sync.

pyrefly reports two new import errors beyond the known one, all three in
data_plane/adapters/transfer_queue.py from #4103, inside a try/except ImportError
that exists to report exactly that drift. Optional TQ submodules absent from this
container, not a regression.

Signed-off-by: asolergibert <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
ArEsKay3 pushed a commit to ArEsKay3/RL that referenced this pull request Sep 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:L1 Run doctests, unit tests, and functional tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants