Skip to content

Desktop: keep probing the announced backend port instead of discarding it - #8211

Merged
danielhanchen merged 5 commits into
mainfrom
dh/desktop-port-verify-retry
Aug 9, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
dh/desktop-port-verify-retry

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Symptom

The desktop app hangs on the "Nearly done..." splash and eventually fails with:

The Unsloth backend did not start within 300 seconds.

The backend is up and serving the whole time. Reported on 0.1.526-beta, Windows 11, CPU-only.

Root cause

The backend announces its port once, on a TAURI_PORT= stdout line, and validate_candidate_port in process.rs probed it exactly once:

if !valid {
    warn!("Ignoring unverified TAURI_PORT candidate {}", port);
    return;
}

That line arrives while the backend is still importing torch. probe_owned_backend_state gives each request LOCAL_HTTP_TIMEOUT, which is 2 s. If the backend cannot answer inside that window, the only announcement it will ever make is discarded and the window keeps waiting for a backend on the port it originally requested, which the backend has already reported it could not bind. Nothing retries, so it waits out the full BACKEND_START_DEADLINE.

From the reporter's log, with 8888 held by an unrelated process so the backend moved to 8889:

16:51:56 [backend] Port 8888 is already in use by ssh.exe (PID 5092).
16:51:56 [backend] Unsloth Studio will use port 8889 instead.
16:51:59 [backend] TAURI_PORT=8889
16:52:01 [WARN]    Ignoring unverified TAURI_PORT candidate 8889
16:56:37 [error]   The Unsloth backend did not start within 300 seconds

The backend's own log for 16:52:01 records the probe that lost:

{"event": "request_completed", "path": "/api/liveness", "process_time_ms": 2156.02}

2156 ms against a 2000 ms budget. This is a race, not a hard failure. Three healthy runs in the same log validated in 735 ms, 792 ms and 2295 ms. The fast path wins it most of the time and loses it on a cold start, which is why it looks intermittent.

Note the port fallback itself is working correctly and is not the bug. The same fallback happens in every healthy run in these logs. What is wrong is discarding the announcement after one attempt.

Fix

Retry until the backend answers or BACKEND_START_DEADLINE passes, instead of giving the slowest moment of startup a single attempt. The deadline is the one the window is already waiting on, so this cannot extend a hang, only avoid one.

The loop bails early if the generation changes or another path claims the port, so a restarted backend does not leave an old probe running. The re-check binds its MutexGuard to a single statement rather than a match arm, keeping the future Send for tauri::async_runtime::spawn.

The rejection warning now carries the attempt count, so a genuine "wrong port announced" case still reports and is distinguishable from this race.

Why it surfaced now

Two conditions have to coincide: the requested port must already be taken, so the backend has to announce a different one; and that announcement must land during a slow patch of startup.

Anything that makes the first backend start colder makes the second more likely. A fresh package upgrade does exactly that, and in this log the run that failed is the one immediately after a successful desktop_backend_version_outdated repair, where torch warm took 99 s. The repair itself completed cleanly.

Related hazard, not addressed here

Worth a separate look. In the same diagnostics, runtime_health reports port=8888 status=healthy service=Unsloth UI Backend, but 8888 is held by ssh.exe. That machine is forwarding 8888 to a remote host that is also running Unsloth, so a health probe on the requested port can be answered by a different Unsloth instance. validate_candidate_port calls probe_owned_backend_state with require_desktop_secret: false, so identity rests on the service name rather than on the desktop secret. That did not cause this hang, but adopting someone else's backend is a worse failure than waiting for your own.

Testing

No Rust toolchain on the machine this was written on, so this relies on the Tauri CI build for compilation. tokio is already a direct dependency with features = ["full"], so tokio::time::sleep needs no manifest change. No test or doc asserted the old single-probe behaviour or the warning text. Brace and paren balance across process.rs verified against origin/main.

I have not reproduced the hang deterministically. It needs the requested port occupied plus a backend slow enough to miss the 2 s window, and the fix is aimed at the mechanism the logs show rather than at a reproduction.

…g it

The backend announces its port once, on a TAURI_PORT stdout line. That line
arrives while it is still importing torch, and validate_candidate_port probed
exactly once with a 2 s per-request budget. When the backend could not answer
in time the only announcement was dropped, and the window went on waiting for
a backend on the port the backend had already reported it could not bind,
until BACKEND_START_DEADLINE expired 300 s later.

Seen on a CPU-only Windows machine where 8888 was taken and the backend moved
to 8889:

  16:51:59 [backend] TAURI_PORT=8889
  16:52:01 [WARN] Ignoring unverified TAURI_PORT candidate 8889
  16:56:37 [error] The Unsloth backend did not start within 300 seconds

The backend was up the whole time. Its own log for that second records
/api/liveness taking 2156 ms against the 2000 ms LOCAL_HTTP_TIMEOUT. Healthy
runs on the same machine validated in 735 ms, 792 ms and 2295 ms, so this is a
race the fast path wins most of the time and loses on a cold start.

Retry until the backend answers or BACKEND_START_DEADLINE passes, rather than
giving the slowest moment of startup a single attempt. The loop stops early if
the generation changes or another path claims the port, so a restarted backend
does not leave an old probe running.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d044b505e4

ℹ️ 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".

Comment thread studio/src-tauri/src/process.rs Outdated
// announcement left the window waiting out BACKEND_START_DEADLINE on the
// port the backend had already reported it could not bind. Keep probing
// until the backend answers or that same deadline passes.
let deadline = std::time::Instant::now() + BACKEND_START_DEADLINE;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reuse the watchdog's absolute startup deadline

When TAURI_PORT is emitted some time after the process starts, this creates a fresh 300-second deadline rather than using the deadline started by start_watchdog. A retry can therefore succeed after the watchdog has emitted server-start-timeout; the frontend timeout handler has already set startingRef.current = false and entered the error state, while its later server-port handler does not restore the running state. On sufficiently slow cold starts this leaves a healthy, validated backend running behind a persistent error screen, so the retry loop should share the process-start deadline (or receive its remaining duration) instead of restarting it here.

Useful? React with 👍 / 👎.

A probe is a liveness request plus a desktop-login request, each up to
LOCAL_HTTP_TIMEOUT, aimed at a backend that is by definition busy. Retrying at
a flat 2 s would have put roughly 90 requests into a 100 s torch import, adding
load to the slow start being waited on.

Double from 250 ms to a 5 s cap instead. The common race, where the backend is
a few hundred ms from ready, now resolves in about 2.2 s rather than 4 s, and
the long waits cost far less: about 18 probes rather than 26 across a 100 s
import, and 46 rather than 75 if the backend never answers at all.
@danielhanchen

Copy link
Copy Markdown
Member Author

Added bounded exponential backoff between probes, after a look at what a probe actually costs.

One probe is fetch_liveness plus desktop_login_route_compatible, each up to LOCAL_HTTP_TIMEOUT, aimed at a backend that is by definition busy. Retrying at a flat 2 s would have put roughly 90 requests into a 100 s torch import, which adds load to the slow start it is waiting on.

Doubling from 250 ms to a 5 s cap is better on both axes (approximate model, probe cost 2 s):

scenario flat 2 s 250 ms to 5 s
backend ready 0.2 s after the first probe fails (the reported bug) 2 probes, 4.0 s 2 probes, 2.2 s
cold torch import, ready 100 s in 26 probes 18 probes
never ready, port open but hung 75 probes 46 probes
never ready, port closed 150 probes 64 probes

Faster where it matters and 30 to 57 percent fewer requests in every long wait. Resource cost otherwise is one tokio task holding a few Arc clones and a String, bounded by BACKEND_START_DEADLINE, which is the deadline the window was already waiting on.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 41a1e90637

ℹ️ 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".

…ation

Port validation started its own 300 s clock when the TAURI_PORT line arrived,
which is well after the process starts: 23 s later in the report that prompted
this. So the retry loop could outlive the watchdog, and a validation that
succeeded in that gap emitted server-port after server-start-timeout had
already put the window in an error state. The frontend's server-port handler
sets the api base but does not clear backendError or startingRef, so that
combination leaves a healthy validated backend behind a permanent error screen.

Capture the deadline once at spawn and pass it to both. It is taken before
start_watchdog spawns its thread, so validation can only ever end at or before
the timeout it must not outlive.
@danielhanchen

Copy link
Copy Markdown
Member Author

Good catch on the deadline, that one is real and I have fixed it in b9288ea.

Verified rather than assumed, since it depends on the frontend half being true as well:

  • start_watchdog starts its clock at spawn (let started = Instant::now() inside the spawned thread, then while started.elapsed() < BACKEND_START_DEADLINE).
  • validate_candidate_port was starting a fresh clock when the TAURI_PORT line arrived. In the report that prompted this PR that line came 23 s after spawn, so the retry loop could outlive the watchdog by that much.
  • The frontend half holds too. server-start-timeout sets startingRef.current = false, startTimedOutRef.current = true and setBackendError(...). A later server-port sets portRef, clears startTimedOutRef and calls setApiBase, but never clears backendError or restores startingRef. So a validated backend really would sit behind a permanent error screen.

Fix is the first of your two suggestions: capture the deadline once at spawn and pass it to both, rather than recomputing it. It is taken immediately before start_watchdog spawns its thread, so start_deadline <= watchdog deadline by construction and validation can only ever end at or before the timeout it must not outlive. Threaded through read_output_stream since that is where the announcement is parsed.

Worth noting separately: the frontend's inability to recover from a late server-port is still latent for any other path that could emit one. I have left it alone here because the timeout message is deliberate and this PR no longer produces that ordering, but it may deserve its own look.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b9288eab6f

ℹ️ 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".

Comment thread studio/src-tauri/src/process.rs Outdated
Comment on lines +1464 to +1467
if ok {
break true;
}
if std::time::Instant::now() >= deadline {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Check the deadline before accepting a successful probe

The new absolute deadline is still consulted only after an unsuccessful probe. If TAURI_PORT arrives after the 300-second deadline, or a probe begins just before it and succeeds afterward, this branch accepts the port and emits server-port even though the watchdog may already have emitted server-start-timeout; the timeout handler in use-tauri-backend.ts has stopped the startup loop, so the later port does not restore the running state. Check the deadline before starting/accepting every probe (and cap the sleep/request to the remaining time).

Useful? React with 👍 / 👎.

The deadline was only consulted after a failed probe, so a success could still
be emitted past it by two routes: the TAURI_PORT line itself arriving late, and
a probe that starts just under the deadline but finishes over it. The watchdog
does not kill a timed-out backend, so both are reachable on a slow start, and
either one puts server-port after server-start-timeout, which strands the
window in an error state it has no handler to leave.

Check before each probe and again before accepting one, and cap the sleep to
the time left. A port verified too late is now dropped with its own message
rather than reported as unverified, and an announcement that arrives after the
deadline says so instead of claiming zero attempts.
@danielhanchen

Copy link
Copy Markdown
Member Author

Right again, and more subtle than the first one. Fixed in 2e764b0.

The deadline was only consulted after a failed probe, so if ok { break true } could accept past it by two routes:

  1. the TAURI_PORT line itself arriving after the deadline, which is reachable because the watchdog does not kill a timed-out backend, so it keeps running and keeps printing
  2. a probe that starts just under the deadline and finishes over it, which is easy given a probe costs up to two LOCAL_HTTP_TIMEOUT requests

Either one puts server-port after server-start-timeout, which is the same stranded error screen the previous commit was meant to close.

Now checked before each probe and again before accepting one, with the sleep capped to the remaining time via saturating_duration_since.

I also split the failure logging, because the single message would have been untrue in both new cases. A port verified too late now says so rather than reporting as unverified, and an announcement that arrives after the deadline says that instead of claiming zero attempts.

One part of the suggestion I did not take: capping the per-request timeout to the remaining time. With the pre-probe and pre-accept checks, an over-running probe is discarded rather than emitted, so correctness no longer depends on it. The only cost is a few seconds of work thrown away on the last attempt, and I would rather not have this call site diverge from the shared LOCAL_HTTP_TIMEOUT semantics for that. Happy to add it if you disagree.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2e764b09cc

ℹ️ 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".

Comment on lines +1475 to +1476
if std::time::Instant::now() < deadline {
break true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Make timeout and port claim mutually exclusive

When a probe succeeds just before deadline, this check accepts it, but the async task can then be descheduled or wait for the state mutex until the watchdog has observed proc.port == None and emitted server-start-timeout. Validation can subsequently assign the port and emit server-port, reproducing the persistent error state because use-tauri-backend.ts does not clear backendError in that handler. The fresh evidence in this revision is that the new clock check remains separated from the later state claim; record timeout versus port acceptance atomically in the shared state so only one event can win.

Useful? React with 👍 / 👎.

…he window

Checking the clock and claiming the port were still two steps with a gap. A
probe could succeed just inside the deadline and then be descheduled, or wait
on the state mutex, long enough for the watchdog to observe port == None and
commit to server-start-timeout; validation would then assign the port and emit
server-port on top of it, which is the stranded error screen again.

Make the two outcomes mutually exclusive in the state they already share. The
watchdog sets start_timed_out while still holding the mutex it used to decide,
and port validation refuses to claim when that flag is set. Both generation
bumps clear it alongside the other per-start fields, so a restart starts clean.
@danielhanchen

Copy link
Copy Markdown
Member Author

Correct, and this is the one that actually closes the class rather than fencing off another instance of it. Fixed in 14cacf2.

The clock check and the port claim were still two steps with a gap. A probe could succeed just inside the deadline and then be descheduled, or block on the state mutex, long enough for the watchdog to observe port == None and commit to server-start-timeout. Validation would then assign the port and emit server-port on top of it.

Worth noting the reverse ordering was already safe: the watchdog re-checks proc.port.is_some() under the lock before emitting, so a validation that wins the lock first already makes it stand down. Only this direction was open.

So the fix is to give the other direction the same protection, in the state they already share:

  • the watchdog sets start_timed_out while still holding the mutex it used to decide, rather than deciding under the lock and emitting after releasing it
  • port validation adds proc.start_timed_out to the condition it already evaluates under that same mutex before assigning proc.port
  • both generation bumps clear it alongside the other per-start fields, so a restart starts clean

Exactly one of the two outcomes can now reach the window, by construction rather than by timing.

One honest edge I left alone: if shutdown is set between the watchdog's claim and its emit, the flag stays set without a timeout being emitted, so a late validation still declines to claim. That only happens while the app is tearing the backend down, where the port is moot and the next start resets the flag, so I did not add a third path to unwind it.

This is the third finding in a row on the same seam, and they were all downstream of one thing: the retry loop gave validate_candidate_port a lifetime the rest of the startup machinery assumed it did not have. The deeper fix is that use-tauri-backend.ts cannot recover from a late server-port at all, which is what makes every one of these orderings fatal instead of merely untidy. I am keeping that out of this PR since it is a frontend behaviour change, but it is the thing that would make this structurally impossible rather than guarded.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 14cacf2aca

ℹ️ 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 eb892d6 into main Aug 9, 2026
42 of 46 checks passed
@danielhanchen
danielhanchen deleted the dh/desktop-port-verify-retry branch August 9, 2026 12:56
danielhanchen added a commit that referenced this pull request Aug 9, 2026
…g it (#8211)

* Desktop: keep probing the announced backend port instead of discarding it

The backend announces its port once, on a TAURI_PORT stdout line. That line
arrives while it is still importing torch, and validate_candidate_port probed
exactly once with a 2 s per-request budget. When the backend could not answer
in time the only announcement was dropped, and the window went on waiting for
a backend on the port the backend had already reported it could not bind,
until BACKEND_START_DEADLINE expired 300 s later.

Seen on a CPU-only Windows machine where 8888 was taken and the backend moved
to 8889:

  16:51:59 [backend] TAURI_PORT=8889
  16:52:01 [WARN] Ignoring unverified TAURI_PORT candidate 8889
  16:56:37 [error] The Unsloth backend did not start within 300 seconds

The backend was up the whole time. Its own log for that second records
/api/liveness taking 2156 ms against the 2000 ms LOCAL_HTTP_TIMEOUT. Healthy
runs on the same machine validated in 735 ms, 792 ms and 2295 ms, so this is a
race the fast path wins most of the time and loses on a cold start.

Retry until the backend answers or BACKEND_START_DEADLINE passes, rather than
giving the slowest moment of startup a single attempt. The loop stops early if
the generation changes or another path claims the port, so a restarted backend
does not leave an old probe running.

* Desktop: back off between port-verification probes

A probe is a liveness request plus a desktop-login request, each up to
LOCAL_HTTP_TIMEOUT, aimed at a backend that is by definition busy. Retrying at
a flat 2 s would have put roughly 90 requests into a 100 s torch import, adding
load to the slow start being waited on.

Double from 250 ms to a 5 s cap instead. The common race, where the backend is
a few hundred ms from ready, now resolves in about 2.2 s rather than 4 s, and
the long waits cost far less: about 18 probes rather than 26 across a 100 s
import, and 46 rather than 75 if the backend never answers at all.

* Desktop: share one start deadline between the watchdog and port validation

Port validation started its own 300 s clock when the TAURI_PORT line arrived,
which is well after the process starts: 23 s later in the report that prompted
this. So the retry loop could outlive the watchdog, and a validation that
succeeded in that gap emitted server-port after server-start-timeout had
already put the window in an error state. The frontend's server-port handler
sets the api base but does not clear backendError or startingRef, so that
combination leaves a healthy validated backend behind a permanent error screen.

Capture the deadline once at spawn and pass it to both. It is taken before
start_watchdog spawns its thread, so validation can only ever end at or before
the timeout it must not outlive.

* Desktop: check the start deadline before accepting a validated port

The deadline was only consulted after a failed probe, so a success could still
be emitted past it by two routes: the TAURI_PORT line itself arriving late, and
a probe that starts just under the deadline but finishes over it. The watchdog
does not kill a timed-out backend, so both are reachable on a slow start, and
either one puts server-port after server-start-timeout, which strands the
window in an error state it has no handler to leave.

Check before each probe and again before accepting one, and cap the sleep to
the time left. A port verified too late is now dropped with its own message
rather than reported as unverified, and an announcement that arrives after the
deadline says so instead of claiming zero attempts.

* Desktop: let only one of the start timeout and the port claim reach the window

Checking the clock and claiming the port were still two steps with a gap. A
probe could succeed just inside the deadline and then be descheduled, or wait
on the state mutex, long enough for the watchdog to observe port == None and
commit to server-start-timeout; validation would then assign the port and emit
server-port on top of it, which is the stranded error screen again.

Make the two outcomes mutually exclusive in the state they already share. The
watchdog sets start_timed_out while still holding the mutex it used to decide,
and port validation refuses to claim when that flag is set. Both generation
bumps clear it alongside the other per-start fields, so a restart starts clean.
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