Skip to content

Studio Desktop on Windows: probe only backend ports with a TCP listener at launch - #19000

Merged
danielhanchen merged 4 commits into
mainfrom
perf/r39-desktop-probe-listening-ports
Nov 23, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
perf/r39-desktop-probe-listening-ports

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Problem

On every warm Desktop launch, desktop_preflight runs probe_backend_ports, which sends GET http://127.0.0.1:{port}/api/health to all 21 candidate ports (8888..=8908, plus the UNSLOTH_STUDIO_PORT range when set) with the shared 2 s loopback client. Desktop stops its backend on quit, so on a normal launch every one of those ports is closed.

On Linux and macOS a connect to a closed loopback port is refused in well under a millisecond. On Windows the TCP stack retransmits the SYN after the reset, so each refused connect runs until the 2 s client timeout. The probes run concurrently, so a single closed port costs the whole scan 2 s, and the backend spawn waits for preflight.

Change

  • New studio/src-tauri/src/tcp_listeners.rs:
    • loopback_listening_ports(): on Windows, reads the IPv4 and IPv6 listener tables once with GetExtendedTcpTable(TCP_TABLE_OWNER_PID_LISTENER) and returns the ports a 127.0.0.1 connect can reach: IPv4 listeners on 127.0.0.1 or 0.0.0.0, and IPv6 listeners on :: (possibly dual-stack) or the v4-mapped forms of those. A listener on ::1 or a LAN address alone is not counted, since probing it would still pay the 2 s refused connect. Returns None (unknown, probe everything) on any table read failure and on every other platform.
    • retain_listening(ports, listening): pure, order-preserving filter; None keeps every port.
  • probe_backend_ports filters the candidates through it before spawning the health probes, and logs probing N of M candidate ports with a loopback TCP listener when it drops any.
  • Cargo.toml: adds the Win32_NetworkManagement_IpHelper feature to the existing windows-sys 0.61 dependency. No new crate, Cargo.lock unchanged.

Probe results are unchanged: a dropped port has no listener a 127.0.0.1 connect can reach, so it could only refuse, and a refused connect already yields no candidate. Linux and macOS take the None path and probe exactly as before. Timing-only difference: a backend that starts listening during the old 1 to 2 s SYN retry window was previously caught by the retry; now it is treated as not running at scan time, as Linux and macOS already do. probe_owned_backend_state (owner metadata, watchdog) is untouched.

Results

Standalone crate on GitHub runners: this PR's tcp_listeners.rs verbatim, a reqwest client built like loopback_http::client (2 s timeout, no proxy, no pool), 21 concurrent GET /api/health probes on 8888..=8908. Three arms interleaved per scenario (all ports / first revision of this PR that counted every listener / this PR), median of 6. Scenarios are cumulative (each adds listeners).

Scenario windows-latest: all ports / first revision / this PR windows-11-arm: all / first / this PR ports found (all arms, all OSes)
nothing listening 2007.4 / 0.2 / 0.1 ms 2006.2 / 0.2 / 0.1 ms []
127.0.0.1:8890 2007.3 / 0.9 / 0.7 ms 2008.1 / 1.0 / 0.7 ms [8890]
+ 0.0.0.0:8892, [::1]:8895 2005.2 / 2007.8 / 1.1 ms 2010.0 / 2006.7 / 1.1 ms [8890, 8892]
+ [::1]:8899 2004.7 / 2005.1 / 1.0 ms 2008.6 / 2015.2 / 1.0 ms [8890, 8892]

The listener table read costs 0.1 to 0.25 ms. ubuntu-latest and macos-15 report the listener set as unknown and probe every port as before (0.2 to 10 ms on all arms). Every arm found the same ports in every run on all four OSes.

Tests

  • tcp_listeners unit tests (all platforms): unknown listener set probes every port, a known set keeps only listening ports in order, an empty table probes nothing, table ports decode from network byte order, and only addresses a 127.0.0.1 connect reaches count (127.0.0.1, 0.0.0.0, ::, ::ffff:127.0.0.1 yes; 127.0.0.2, LAN, ::1, fe80::1, ::ffff:10.0.0.1 no).
  • Windows-only test: binds 127.0.0.1:0 and 0.0.0.0:0 listeners and asserts both are listed, a [::1]:0 listener is not, and a just-closed port is not. Passes on windows-latest and windows-11-arm.

A refused loopback connect takes 1-2 s on Windows because the stack
retransmits the SYN, so the warm-launch health probe over the 21
candidate ports waits on that even when no backend runs. Read the IPv4
and IPv6 listener tables once with GetExtendedTcpTable and probe only
ports with a listener; on any table failure, and on other platforms,
every port is probed as before.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T08:18:02.413478Z 87602a7 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: aa65c8267a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen marked this pull request as ready for review November 23, 2026 08:14
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 87602a7eea

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 725e8f9 into main Nov 23, 2026
@danielhanchen
danielhanchen deleted the perf/r39-desktop-probe-listening-ports branch November 23, 2026 08:36
danielhanchen added a commit that referenced this pull request Nov 23, 2026
…VFP4 nested kernel, Kaggle input via env) (#19027)

## Summary

Four tests are red on `main` and fail on every PR whose staging run
includes them (seen on #18918, #18925 and #19000). Each was reproduced
on `main` before fixing. In all four the code under test is right and
the test is not.

| Failing test (shard) | Introduced by | Cause | Fix |
|---|---|---|---|
|
`test_diffusion_ddp_effective_precision.py::test_real_gloo_two_ranks[fp8,*]`
(`(Python 3.13, diffusion)`) | #18967 | The verdicts are right (`SAME`,
`REFUSED ...`), but gloo prints `[Gloo] Rank N is connected to 1 peer
ranks ...` on the child's stdout first, and the test required the output
to start with the verdict. | Read the verdict from the child's last
line. |
|
`test_diffusion_base_precision.py::test_resolve_auto_uses_klein_variant_size`
and `test_auto_sizes_flux2_klein_9b_off_its_own_weights[*]` (`(Python
3.13, diffusion)`): `'nf4' == 'fp8'` | #18967 | Near the 8-bit band (20
GB free against the 18.2 GB dense 9B), Auto's fp8 pick also checks host
RAM through `_auto_swap_host_ram_ok`, because that load holds the bf16
base on the host. The tests fake the GPU but read the runner's real RAM,
so a 16 GB CI runner gets `nf4` (correctly) and a large dev box gets
`fp8`. | An autouse fixture pins host RAM high, like the file's existing
`_not_rocm` pin, since these cases simulate GPU tiers. New
`test_klein_9b_near_the_8bit_band_falls_back_to_nf4_on_a_small_host`
pins the small-host fallback explicitly. |
|
`tests/test_nvfp4_qat_backward_skip.py::test_cpu_forward_kernel_is_restored_on_exit`
(`Repo tests (CPU, rest)`): `there's already a kernel registered from
python overriding nvfp4_qat_linear_v2's behavior for CPU` | #18864 | The
test enters `_cpu_forward_kernel(op)` inside the module-scoped `op`
fixture, which has already registered that kernel. torch 2.10 refuses a
second Python registration for the same op, key and namespace, so the
test fails on every run. | The `op` fixture is per test, and the restore
test takes the bare op (new `raw_op` fixture), so it checks a real
register-then-restore from a clean state. |
|
`tests/kaggle/test_fire_and_forget.py::test_every_gate_budget_covers_the_reaper_window`
(`Repo tests (CPU, rest-2)`): `the collector's default age ceiling is
not readable from the workflow` | #18969 | #18969 correctly moved the
dispatch input out of the script into `MAX_AGE_HOURS: ${{
inputs.max_age_hours \|\| '3' }}`, and the test's regex only knew the
inline form. | Read the default from either form, and when it is an env
var, assert that variable is what reaches `--max-age-hours`. |

Only tests change.

## Testing

- The four files: all red on `main`. With this change, 98 passed / 6
skipped (the two diffusion files) and 125 passed (the NVFP4 and Kaggle
files); `tests/kaggle/` as a whole: 1081 passed.
- Sabotage, each guard still catches what it is for:
- **gloo:** making `check_effective_precision` a no-op fails the
`REFUSED` case.
- **klein:** removing the host RAM gate from `_resolve_base_precision`
fails the new small-host test. Forcing a 16 GB runner over the whole
file fails the same 5 cases CI did, plus the new one.
- **NVFP4:** keeping the test library alive instead of destroying it
fails the restore test.
- **Kaggle:** a workflow default of `9` fails (it no longer matches
`collect.DEFAULT_MAX_AGE_HOURS`), and so does not passing
`$MAX_AGE_HOURS` to `--max-age-hours` (`MAX_AGE_HOURS never reaches
--max-age-hours`).
danielhanchen added a commit that referenced this pull request Nov 23, 2026
…le for Dynamo (#19034)

## Summary

`Repo tests (CPU, rest-2)` fails on PR runs rebased past #18975 (for
example the staging run for #19000), and the same two tests fail on a
local checkout of current `main`:

```
tests/test_prefix_grouper_compile_check.py::test_rocm_new_padded_length_inside_a_fullgraph_compile[grad]
tests/test_prefix_grouper_compile_check.py::test_rocm_new_padded_length_inside_a_fullgraph_compile[no_grad]
E   torch._dynamo.exc.InternalTorchDynamoError: ModuleNotFoundError: No module named '_pg_check_pkg_under_test'
```

Both tests were added by #18975 and already fail at its merge commit
(`03c989b0a7`) with torch 2.10 CPU, the same as CI.

## Root cause

The test, not the kernel. `_load()` imports `prefix_grouper.py` under a
throwaway package and removes it from `sys.modules` straight away. These
two tests are the only ones in the file that wrap the kernel in
`torch.compile(fullgraph=True)`, and Dynamo resolves a traced function's
globals by importing its module by name
(`symbolic_convert._import_module`), so the compile dies on the missing
package before reaching the code under test.

Keeping the package registered exposed a second problem:
`_import_module` is `functools.cache`d for the process, so with one
fixed package name the `[no_grad]` compile resolved the `[grad]` test's
kernel module and guarded on its `_COMPILE_CHECKED` (`Guard failed on
the same frame it was created`). Each parametrization passes on its own.

## Fix

`tests/test_prefix_grouper_compile_check.py` only:

- `_load(monkeypatch)` registers the package and both modules through
`monkeypatch`, so they stay importable for the whole test and are
removed at teardown.
- Each load uses its own package name (`_pg_check_pkg_under_test_<n>`),
so Dynamo's import cache can never hand one test another test's kernel
state.

No change to `unsloth/utils/prefix_grouper_kernel.py`.

## Testing

- `tests/test_prefix_grouper_compile_check.py`: 18 passed (was 2
failed), also under `-n 3`.
- All `tests/test_prefix_grouper*.py`: 100 passed, 3 skipped.
- No `_pg_check_pkg_under_test*` module is left in `sys.modules` after
the file runs.
- Sabotage: removing the kernel's in-graph reuse (`if in_graph_reuse:
needs_check = False`) makes both tests fail, so they now check the
kernel instead of failing before it.
danielhanchen added a commit that referenced this pull request Nov 23, 2026
…the package scan baseline (#19030)

## Summary

`Security audit` / `pip scan-packages :: hf-stack` fails on every PR
that runs it (for example the run for #19000 on top of current `main`):

```
  5 of the 183 finding(s) above are at a site already reviewed in scripts/scan_packages_baseline.json. What differs from the reviewed entry:
    CRITICAL  trl          trl/experimental/async_distillation/vllm_client.py  1 matched line(s) added and 1 gone: the flagged code was rewritten
    HIGH      unsloth-zoo  unsloth_zoo/compiler.py                     same matched code, file digest outside the pin
    CRITICAL  unsloth-zoo  unsloth_zoo/vision_utils.py (env+network)   same matched code, file digest outside the pin
    CRITICAL  unsloth-zoo  unsloth_zoo/vision_utils.py (IMDS+network)  same matched code, file digest outside the pin
    HIGH      unsloth-zoo  unsloth_zoo/vllm_utils.py                   same matched code, file digest outside the pin
```

plus one site with no reviewed entry at all:
`trl/generation/async_vllm_client.py` (C2 polling loop).

## Root cause

Two new releases, neither caused by a PR here:

- unsloth-zoo 2026.11.9. The scanner pins each reviewed zoo site to the
file digest it was reviewed at, so a release reopens its sites until
they are re-reviewed. Same as the earlier re-pins (#18724, #18551,
#17999).
- trl 1.18.2 (the requirement cap is `trl<=1.18.2`). It moved the async
GRPO vLLM client to `trl/generation/async_vllm_client.py` and shifted
the `while True:` in the async distillation client from L56 to L55,
which changes the evidence hash.

## Re-review

- `unsloth_zoo/compiler.py`, `vision_utils.py` (both checks),
`vllm_utils.py`: evidence hash identical to the reviewed entries, so the
flagged lines are unchanged. Since the pin covers the whole file, I
diffed each file from 2026.11.8 (the pinned digests `4fcbb4cb25...`,
`bc3e71536d...`, `e21b70aab1...`) to 2026.11.9:
- `compiler.py`: the temp compile folder ownership check now also
rejects group-writable folders (`0o002` to `0o022`), and two Inkling 2
attention residual classes join the do-not-compile list.
- `vision_utils.py`: the UNC / network-share guard now also decodes
`bytes` and `PathLike` paths before checking them. Stricter, not looser.
- `vllm_utils.py`: speculative decoding support (config parsing and
validation, redaction of credentials nested in the speculative config
before vLLM logs it, draft weight sizing via the Hub for the user-named
draft repo) and a cuBLAS workspace hold during CUDA graph capture. No
new network destination, subprocess, or dynamic code path beyond the
reviewed `exec` / `eval` lines.
- `trl/experimental/async_distillation/vllm_client.py` and
`trl/generation/async_vllm_client.py`: both flagged loops are
`wait_for_server_ready`, which polls `{server_url}/health` on the
user-configured vLLM server every 2 s and raises `TimeoutError` after
`timeout`. Every request in both files goes to `self.server_url`; no
environment reads, subprocess, `exec` or encoded payloads. Same loop as
the already reviewed `async_grpo/vllm_client.py` and
`async_distillation/vllm_client.py` entries.

## Changes

- `scripts/scan_packages_baseline.json`: six new entries (four zoo
entries pinned to the 2026.11.9 file digests, two trl entries keyed on
the new evidence). Appended at the end; no existing entry is changed or
removed (52 lines added, 0 removed), so no reviewed pin is widened.
- The local scan also reports two `multiprocess` sites; those only
appear under Python 3.13 and CI scans on 3.12, so they are left out.

## Testing

- `python scripts/scan_packages.py unsloth-zoo==2026.11.9 trl==1.18.2`
against `main`'s baseline: exit 1, `4 CRITICAL, 2 HIGH`, the six sites
above.
- The same scan against this branch's baseline: exit 0 (`Summary: 21
MEDIUM`, 26 findings suppressed by baseline).
- `tests/security/test_scan_packages.py`: 152 passed.
- Full hf-stack requirement set (the workflow's
`audit-reqs/unsloth-deps.txt` + `no-torch-runtime.txt`, `--with-deps`)
against this branch: the six sites above are suppressed; only the two
Python 3.13 `multiprocess` sites remain, as expected on this host.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant