Skip to content

fix(backend): report a closed loopback port immediately on Windows - #205

Open
LuviaSeraphina wants to merge 2 commits into
AstrBotDevs:mainfrom
LuviaSeraphina:fix/windows-loopback-probe-fast-fail
Open

LuviaSeraphina wants to merge 2 commits into
AstrBotDevs:mainfrom
LuviaSeraphina:fix/windows-loopback-probe-fast-fail

Conversation

@LuviaSeraphina

@LuviaSeraphina LuviaSeraphina commented Dec 2, 2026 •

Copy link
Copy Markdown

Fixes #203.

Desktop 4.30.0 refuses to start the backend on Windows. Since #191 the endpoint check runs before every managed start, and it only accepts a refused connection as proof that the port is free. Windows does not refuse a connection to a closed loopback port immediately: the stack retransmits the SYN and only then reports WSAECONNREFUSED, which takes about two seconds, while the probe timeout defaults to 800 ms. The check therefore always times out on a free port and Desktop answers with Cannot confirm backend endpoint ... connection timed out. Refusing to start another backend., so the backend is never spawned.

Summary / 改动概述

  • src-tauri/src/backend/http.rs: the per-address probe now goes through connect_probe, which keeps TcpStream::connect_timeout semantics but, on Windows loopback targets, connects on a raw Winsock socket with SIO_TCP_INITIAL_RTO set to TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS — the same opt-out Chromium, curl and libuv use for loopback. A closed port is reported in about 10 ms instead of about 2 s.
  • The surrounding behaviour is unchanged: an endpoint that answers still blocks a respawn (already answering), a timeout is still inconclusive and refuses to start a second backend, non-loopback addresses keep using TcpStream::connect_timeout, and any failure to prepare the raw socket falls back to that same path.
  • src-tauri/Cargo.toml: enable the Win32_Networking_WinSock and Win32_System_IO features of windows-sys, which is already a Windows-only dependency. No new crate and no Cargo.lock change.
  • One regression test asserts that a closed loopback port is refused well under a second.

Relationship to #204: that PR raises the probe floor to 3 s so the timeout absorbs the two seconds. This change removes the two seconds instead, so the probe keeps its configured timeout and every managed start stays fast. They are alternatives rather than additions — happy to fold this into #204 if you would rather keep one thread.

Verification / 验证方式

Windows 10 26H2 (build 26300.9974), Desktop 4.30.0, rustc 1.100.1, cargo test --manifest-path src-tauri/Cargo.toml --locked.

Timing of a probe against a closed loopback port (127.0.0.1:6187) on the same machine:

path result
TcpStream::connect_timeout (before) ConnectionRefused after 2 043 ms
SIO_TCP_INITIAL_RTO probe (after) ConnectionRefused after 14 ms

Same suite, same machine:

passed failed
main @ d7a97c9 (before) 222 57
this branch 232 48

The nine tests this fixes are exactly the endpoint-probe ones that fail on main on Windows:

backend::http::tests::restart_endpoint_probe_accepts_refused_loopback_connections
backend::http::tests::restart_endpoint_probe_can_retry_after_the_timed_out_resolver_finishes
backend::http::tests::restart_endpoint_probe_checks_every_resolved_address
backend::restart::tests::failed_endpoint_confirmation_retains_the_pid_for_a_retry
bridge::commands::tests::run_native_update_install_prepares_before_installing_and_validating
bridge::commands::tests::run_native_update_install_rejects_post_install_validation_failures
bridge::commands::tests::run_native_update_install_reports_restart_failures_after_install_failure
bridge::commands::tests::run_native_update_install_reports_success_when_install_succeeds
bridge::commands::tests::run_native_update_install_restarts_backend_after_failed_install

The remaining 48 failures are environmental and unrelated: they fail identically on main, because tempfile cannot create directories under this machine's %TEMP% (PermissionDenied). They are the same set on both sides — no test regresses with this change, and the new test passes.

cargo fmt --all -- --check and cargo clippy --locked --all-targets are clean.

I did not build and run a packaged installer with this change; the verification above is the unit suite plus the timing measurement.


Checklist / 检查清单

  • This change is not a breaking change. / 此改动不是破坏性变更。
  • I have verified the change locally (and provided logs/screenshots above). / 我已在本地验证并附上上面的日志。
  • This PR does not change workflows. / 此 PR 未修改 workflow。
  • No new dependencies; windows-sys features only, Cargo.lock unchanged. / 未引入新依赖,仅启用 windows-sys feature,Cargo.lock 无变化。
  • This PR does not include malicious code. / 此 PR 不包含恶意代码。

Summary by Sourcery

Restore managed backend startup on Windows when the configured loopback port is closed.

Bug Fixes:

  • Make Windows loopback checks report a closed port promptly, allowing the backend to start when its endpoint is free.

Build:

  • Enable the existing Windows-only windows-sys Winsock and system I/O features.

Tests:

  • Add a Windows regression test verifying closed loopback ports are refused within the probe timeout.

The managed-backend preflight added in AstrBotDevs#191 only accepts a refused
connection as proof that the endpoint is free. On Windows a refused
connection to a closed loopback port is reported only after the SYN
retransmission budget expires, which takes about two seconds, and that is
longer than the 800 ms default probe timeout. Every managed start was
therefore refused with "connection timed out", so Desktop 4.30.0 could
not start the backend at all on Windows (AstrBotDevs#203).

Probe loopback targets on a raw Winsock socket with
SIO_TCP_INITIAL_RTO / TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS, the same
opt-out that Chromium, curl and libuv use. A closed port now reports
WSAECONNREFUSED in about 10 ms instead of about 2 s.

The behaviour around it is unchanged: an endpoint that answers still
blocks a respawn, an inconclusive probe still refuses to start another
backend, non-loopback addresses keep using TcpStream::connect_timeout,
and every failure to prepare the raw socket falls back to that path.

On Windows 11 the nine endpoint-probe tests that fail on main pass with
this change: the three probes in backend::http,
backend::restart::tests::failed_endpoint_confirmation_retains_the_pid_for_a_retry
and the five bridge::commands::tests::run_native_update_install_* cases.
@sourcery-ai

sourcery-ai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit bc10839

#203 [Bug] 更新4.30.0桌面版无法打开 · 0 of 1 met · 1 to check by hand

# Requirement Status Notes
1 Open normally after updating from 4.29.4 to 4.30.0 on Windows. 👀 Check by hand (runtime) Verify the packaged Windows updater flow launches the backend successfully; the change includes a Windows probe regression test, but the PR says it did not run a packaged installer.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src-tauri/src/backend/http.rs" line_range="201" />
<code_context>
+            }
+        };
+
+        let raw = unsafe { socket(family, SOCK_STREAM, IPPROTO_TCP) };
+        if raw == INVALID_SOCKET {
+            return None;
</code_context>
<issue_to_address>
**First probe falls back to slow connect**

When the managed-start preflight performs the process's first Winsock operation on a numeric loopback endpoint, `socket` fails with `WSANOTINITIALISED`, so `probe` returns `None` and `connect_probe` falls back to `TcpStream::connect_timeout`; the normal SYN retransmission delay blocks the managed start instead of using the fast probe.

Initialize Winsock before creating the raw socket so the probe can use its fast path.
</issue_to_address>

### Comment 2
<location path="src-tauri/src/backend/http.rs" line_range="239" />
<code_context>
+        };
+        let mut returned = 0u32;
+        unsafe {
+            WSAIoctl(
+                socket,
+                SIO_TCP_INITIAL_RTO,
</code_context>
<issue_to_address>
**Rejected RTO option stalls the probe**

When the OS or socket provider rejects `SIO_TCP_INITIAL_RTO`, `disable_syn_retransmissions` discards the `WSAIoctl` result, so `probe` continues with default SYN retransmissions; `wait_writable` reaches the probe timeout before the connection is reported, and the endpoint check refuses to start the backend.

Check the `WSAIoctl` result and handle failure without continuing the probe with SYN retransmissions enabled.
</issue_to_address>

### Comment 3
<location path="src-tauri/src/backend/http.rs" line_range="908" />
<code_context>
+        drop(listener);
+
+        let started = Instant::now();
+        let error = connect_probe(address, Duration::from_millis(5_000))
+            .expect_err("a closed loopback port must be reported as refused");
+        let elapsed = started.elapsed();
</code_context>
<issue_to_address>
**Windows regression passes on Linux**

When `cargo test` runs on the configured Ubuntu CI runner, the test `loopback_probe_reports_a_closed_port_without_waiting_for_syn_retransmissions` calls `connect_probe` at `http.rs:908`, but that function's Windows probe is behind `#[cfg(windows)]`. On the configured Ubuntu CI runner, the ordinary Linux connect path refuses quickly, so the test passes even if the Windows-specific fix is broken.

Add a Windows CI test run for this regression test.
</issue_to_address>

### Comment 4
<location path="src-tauri/src/backend/http.rs" line_range="914" />
<code_context>
+
+        assert_eq!(error.kind(), ErrorKind::ConnectionRefused, "{error}");
+        assert!(
+            elapsed < Duration::from_millis(1_000),
+            "a closed loopback port must not wait for the SYN retransmission budget: {elapsed:?}"
+        );
</code_context>
<issue_to_address>
**Slow probes still pass**

When a closed-port probe returns `ConnectionRefused` after 800–999 ms, the test `loopback_probe_reports_a_closed_port_without_waiting_for_syn_retransmissions` allows elapsed time under 1,000 ms at `http.rs:914`, while passing a 5,000 ms timeout at line 908. A probe that refuses after 900 ms passes the test but times out when the endpoint check uses its normal 800 ms budget.

Use the normal 800 ms probe timeout in the test and assert that the closed port is refused within that budget.
</issue_to_address>

Sourcery assessment

Approval pending. 4 findings to address first.

Blocking findings: src-tauri/src/backend/http.rs:201, src-tauri/src/backend/http.rs:239, src-tauri/src/backend/http.rs:908, src-tauri/src/backend/http.rs:914


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src-tauri/src/backend/http.rs Resolved
Comment thread src-tauri/src/backend/http.rs Resolved
Comment thread src-tauri/src/backend/http.rs Outdated
drop(listener);

let started = Instant::now();
let error = connect_probe(address, Duration::from_millis(5_000))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Windows regression passes on Linux

When cargo test runs on the configured Ubuntu CI runner, the test loopback_probe_reports_a_closed_port_without_waiting_for_syn_retransmissions calls connect_probe at http.rs:908, but that function's Windows probe is behind #[cfg(windows)]. On the configured Ubuntu CI runner, the ordinary Linux connect path refuses quickly, so the test passes even if the Windows-specific fix is broken.

Add a Windows CI test run for this regression test.

Prompt for AI agents
In `src-tauri/src/backend/http.rs` at line 908:

**Windows regression passes on Linux**

When `cargo test` runs on the configured Ubuntu CI runner, the test `loopback_probe_reports_a_closed_port_without_waiting_for_syn_retransmissions` calls `connect_probe` at `http.rs:908`, but that function's Windows probe is behind `#[cfg(windows)]`. On the configured Ubuntu CI runner, the ordinary Linux connect path refuses quickly, so the test passes even if the Windows-specific fix is broken.

Add a Windows CI test run for this regression test.

Comment thread src-tauri/src/backend/http.rs Resolved
Address the review on AstrBotDevs#205:

- Call WSAStartup once before the first raw socket. A probe can be the
  process's first Winsock user, and socket() would then fail with
  WSANOTINITIALISED and drop the preflight back to the slow path.
- Treat a rejected SIO_TCP_INITIAL_RTO as "raw probe unavailable" and fall
  back to TcpStream::connect_timeout, instead of waiting for a refusal that
  the default SYN retransmissions will not deliver inside the budget.
- Run the regression test on Windows only: the Linux connect path always
  refuses at once, so it cannot regress there. The test now uses the normal
  800 ms probe budget and asserts the refusal arrives well inside it.
@LuviaSeraphina

LuviaSeraphina commented Dec 2, 2026 •

Copy link
Copy Markdown
Author

All four points are addressed in bc10839:

  1. Winsock initialisation. probe now calls WSAStartup once (guarded by a OnceLock) before the first socket(), so a preflight that happens to be the process's first Winsock user still takes the fast path instead of falling back.
  2. Rejected RTO option. disable_syn_retransmissions now returns the WSAIoctl result. A rejection closes the raw socket and returns None, so connect_probe falls back to TcpStream::connect_timeout — the pre-change behaviour — instead of probing with SYN retransmissions still enabled and burning the budget.
  3. Windows-only regression test. The test is now #[cfg(windows)]: the Linux path always refuses at once, so a green on Ubuntu said nothing about this fix and was misleading.
  4. Budget. The test uses the normal 800 ms probe timeout and asserts the refusal arrives within 500 ms, so a probe that refuses after 900 ms now fails it.

Full suite on Windows 10 26H2 (build 26300.9974) is unchanged at 232 passed / 48 failed, and the 48 are the same environmental tempfile failures that main also has on this machine.

One gap I cannot close from this PR: check-rust.yml runs on ubuntu-latest, and the Windows build job builds installers without running cargo test, so this test does not execute in CI. I verified it locally on Windows.

@LuviaSeraphina

Copy link
Copy Markdown
Author

Windows verification update for bc10839: cargo test --manifest-path src-tauri/Cargo.toml --locked passed 280/280 (0 failures, 0 ignored) with a dedicated writable TEMP/TMP for the test process. This supersedes the earlier 232/280 run; no source or system permission changes were needed. The Windows loopback regression also passed when run separately, and cargo fmt --all -- --check passed. This is local test evidence, not a packaged 4.29.4 upgrade test or a CI result.

@zouyonghe

Copy link
Copy Markdown
Member

Thank you for investigating the Winsock behavior, benchmarking the loopback probe, and rerunning the Windows test suite. The reported drop from 2,043 ms to 14 ms for the individual check makes this worth pursuing as a startup performance improvement.

#207 has already merged the 5-second default for #203. Please update this branch from main and keep that default and the shared deadline for each probe.

  1. ensure_backend_ready() calls ping_backend() before the managed-start endpoint check. This PR speeds up the second check, so the first one can still wait about two seconds on a closed loopback port. Apply the Windows loopback fast path to both checks and measure time from Desktop launch to backend process creation. Keep standard TCP connect as the fallback when the fast path is unavailable and give it the remaining time. An inconclusive result should still block managed startup.

  2. The raw socket() call creates an inheritable handle. A child launched concurrently can inherit it and keep the connection alive. Please use WSASocketW with WSA_FLAG_NO_HANDLE_INHERIT so the handle is non-inheritable from creation.

Please verify the updated branch on Windows with both a closed port and an active listener, and include the cold-start timings. A focused Windows CI test would also cover the Winsock path that the current Ubuntu Rust job skips.

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.

[Bug] 更新4.30.0桌面版无法打开

2 participants