Skip to content

Studio: refuse downloads when bandwidth settings cannot be read - #17645

Merged
danielhanchen merged 1 commit into
unslothai:mainfrom
RioPlay:fix/studio-download-limit-read-failure
Nov 14, 2026
Merged

danielhanchen merged 1 commit into
unslothai:mainfrom
RioPlay:fix/studio-download-limit-read-failure

Conversation

@RioPlay

@RioPlay RioPlay commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

A temporary settings-read error can make Studio start a download without its saved bandwidth limit. This PR prevents that specific failure; it does not throttle normal Xet downloads or claim to fix their responsiveness problems.

Before and after

Before: the settings getter catches a read exception and returns None. The download lifecycle interprets that as an intentionally disabled limit, so a configured cap can silently disappear.

With this patch: an unreadable setting stops the download with a sanitized error and retry guidance. Initial transport selection returns HTTP 503. If a later read fails during launch or a transport retry, no downloader is spawned and the job claim is released so the operation can be retried after recovery.

When settings can be read: the configured limit, intentionally disabled limit, normal transport selection, and existing oversized-file Xet exception retain their prior behavior. This patch does not change Xet concurrency, memory budgets, or native transfer pacing.

Reproduction and regression checks

The committed tests simulate a settings-read exception and check transport selection, prevention of worker creation, claim cleanup, sanitized errors, and recovery. They also check that a normal read returns the configured limit. No private logs or model download are needed.

From the repository root, with backend test dependencies installed:

PYTHONPATH=studio/backend python -m pytest -q studio/backend/tests/test_download_speed_limit.py

Local result at 56ac0e00d6: 37 passed. This is a local result, not a claim that upstream CI has passed.

Desktop test procedure and observations

With the patched production modules installed:

  1. In a separate process importing the installed modules, inject a settings-read exception. Transport selection returns 503, no worker starts, and normal reads recover after the injected failure is removed. This fault was not injected into the running desktop app.
  2. In Studio, resume a GGUF download using HTTP with an 8 Mbit/s cap for about 45 seconds, interact with the download panel, then cancel. The panel remains responsive and cancellation completes.
  3. Download the same variant through uncapped Xet into a fresh folder on the same drive for about six minutes. Progress passes halfway. Overall computer responsiveness degrades and intermittent connectivity dropouts are reported in another app, without a full lockup. Separate short HTTPS probes continue succeeding; those probes do not measure the other app's existing connection and do not disprove the reported dropouts. The download was stopped before completion.

The earlier unpatched experience involved more severe lockups and connectivity problems that stopped after the Studio-spawned Python processes were terminated. That is a reported observation, not a matched baseline run. The patched test still showed degradation. Differences in cache state, duration, transport, and bandwidth settings mean the change in severity cannot be attributed to this patch.

Interpretation and remaining scope

A 1 Gbit/s transfer is at most 125 MB/s before protocol overhead. Network traffic approaching link capacity therefore does not, by itself, establish that the disk's transfer-rate limit was exceeded. Passive disk counters showed queued I/O, but no disk benchmark was performed and the cause of the responsiveness degradation remains unresolved.

There is no evidence that the settings-read failure or a bypassed saved cap caused the original incident. This PR fixes the independently reproducible bandwidth-policy failure. Investigation of Xet-related slowdowns and intermittent connectivity remains separate.

Follow-up to #16819; related to #15603. No personal logs, local paths, machine identifiers, or configuration databases are attached.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 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-14T08:19:55.836591Z 56ac0e0 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.

@danielhanchen danielhanchen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thank you for the PR! The goal of this PR is to stop a configured download speed limit from silently disappearing when the settings database cannot be read. As a summary, this PR makes the speed limit getter raise a dedicated error instead of returning "no limit", turns that into a 503 at transport selection, and leaves no worker spawned and the job claim released when a later read fails.

I reproduced the bug on the merge base: with an 8 Mbit/s cap saved and the settings read raising, transport selection picked Xet and the worker was spawned without UNSLOTH_DOWNLOAD_SPEED_LIMIT_MBPS. On this branch both refuse. All 9 new tests fail on the base and pass here.

Reviewers Severity Finding
1/1 Medium The new error also reaches GET /api/settings/download-speed-limit, which now returns an unhandled 500 instead of the retry message
1/1 Medium GET /api/studio/download-transport-capabilities now returns 500, which drops the whole capabilities object the download UI reads, not just speed_limited
1/1 Low The underlying read error is no longer logged anywhere, so a locked database leaves no trace in the server log

The fork does not allow maintainer edits, so here are the changes for the two files outside this diff.

studio/backend/routes/settings.py (also import DownloadSpeedLimitUnavailableError):

    try:
        return DownloadSpeedLimitResponse(mbps = get_download_speed_limit_mbps())
    except DownloadSpeedLimitUnavailableError as exc:
        raise HTTPException(status_code = 503, detail = str(exc)) from None

studio/backend/main.py, studio_download_transport_capabilities:

    try:
        speed_limited = get_download_speed_limit_mbps() is not None
    except DownloadSpeedLimitUnavailableError:
        speed_limited = True  # unknown policy: preflight as limited, the start itself refuses
    return {**caps, "speed_limited": speed_limited}

If these are not applied here, I will carry them in a follow-up PR together with two tests that cover the endpoints.

See inline comments for details and suggested fixes.

except Exception as exc: # noqa: BLE001 - an unreadable db reports no limit, not a 500
logger.debug("download speed limit read failed (%s)", exc)
return None
except Exception: # noqa: BLE001 - an unreadable policy must not remove the limit

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[1/1 reviewers] The original exception is discarded with from None and nothing logs it, so a locked or corrupt settings database never reaches the server log. Keeping the sanitized message for the client but logging the cause locally helps with diagnosis (this also needs from loggers import get_logger and logger = get_logger(__name__) back at the top of the module):

Suggested change
except Exception: # noqa: BLE001 - an unreadable policy must not remove the limit
except Exception as exc: # noqa: BLE001 - an unreadable policy must not remove the limit
logger.warning("download speed limit read failed (%s)", exc)

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 56ac0e00d6

ℹ️ 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 a30e49b into unslothai:main Nov 14, 2026
danielhanchen added a commit that referenced this pull request Nov 14, 2026
…when the limit cannot be read (#17741)

Follow-up to #17645, which made the download speed limit getter raise
`DownloadSpeedLimitUnavailableError` when the settings database cannot
be read. Two other readers of that getter were not updated and turned
the new error into an unhandled 500:

- `GET /api/settings/download-speed-limit` now answers 503 with the same
sanitized retry message the download start uses.
- `GET /api/studio/download-transport-capabilities` keeps answering,
with `speed_limited: true` when the limit cannot be read. Before this
change, a 500 here dropped the whole capabilities object the download
dialog reads (Xet availability included), not just the limit flag. The
download start still refuses on its own, so reporting "limited" only
makes the preflight assume HTTP.
- The getter logs the underlying read error as a warning again, so a
locked database still shows up in the server log while the client
message stays sanitized.

When the setting can be read, nothing changes: all 37 existing tests in
`test_download_speed_limit.py` behave the same on main and on this
branch.

### Tests

- Two new tests, `test_unreadable_limit_is_a_503_on_the_settings_route`
and `test_unreadable_limit_keeps_capabilities_answering_as_limited`,
fail on main and pass here.
- `studio/backend/tests/test_download_speed_limit.py`: 39 passed.
- I ran all 84 download / settings / transport / hf test files in
`studio/backend/tests` on both main and this branch, and this branch
adds no failures.
danielhanchen added a commit that referenced this pull request Nov 14, 2026
… of racing the drainer (#17782)

## Problem


`studio/backend/tests/test_orchestrator_switch_waits.py::test_worker_crash_mid_frame_cannot_block_the_shutdown_deadline`
failed three times today on PRs that do not touch the orchestrator
(#17645, #17743 and #17776), all with the same signature:

```
tests/test_orchestrator_switch_waits.py:385: assert runner.exitcode == 0
E   AssertionError: assert 1 == 0
  File ".../test_orchestrator_switch_waits.py", line 366, in crash_after_drain
    assert proc.exitcode == 1
```

The worker in that test does `replies.put(<1 MiB frame>)` and then
`assert replies._reader.poll(30)` on its own end of the reply pipe
before crashing. But the code under test, `_shutdown_subprocess` ->
`_drain_unread_replies`, starts a drainer thread that reads that same
pipe. When the drainer gets the whole frame first, the worker's poll
finds nothing and waits its full 30 s, while the parent's
`proc.join(30)` expires first and sees `exitcode is None`.
`test_forced_shutdown_does_not_read_an_interrupted_queue_frame` polls
the same pipe from the parent and has the same race.

The orchestrator is fine. The tests depended on thread scheduling.

## Fix

A helper, `_write_partial_frame`, writes a length header claiming the
whole 1 MiB frame plus the first 32 KiB of it straight to the pipe, then
the worker crashes (or sleeps, for the interrupted-writer test). This is
less than one pipe buffer, so the write never blocks. Any reader is left
inside a partial frame every time, which is the state both tests mean to
set up. The interrupted-writer test now waits on a `wrote` event instead
of polling the shared pipe. On Windows, where `PipeConnection` has no
raw write, the helper falls back to the old `put`.

## Tests

- Reproduced the CI failure on main by adding `time.sleep(1)` in the
worker before its poll: `assert 1 == 0`, the same error as CI. With the
same delays added around the new partial write, both tests still pass.
- `test_orchestrator_switch_waits.py`: 14 passed, three times under `-n
8`.
- Both tests ran 30 times on 10 concurrent loops, base and head. Both
passed every time locally, so the flake is not reproducible here without
the forced delay above.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants