Skip to content

Studio: add a token usage allowance with a one-time override - #16500

Open
debojyoti-dev wants to merge 89 commits into
unslothai:mainfrom
debojyoti-dev:feat/token-usage-limit-16486
Open

debojyoti-dev wants to merge 89 commits into
unslothai:mainfrom
debojyoti-dev:feat/token-usage-limit-16486

Conversation

@debojyoti-dev

@debojyoti-dev debojyoti-dev commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Adds an optional, disabled-by-default token allowance for Studio. Once the period's cap is used up, new requests return HTTP 429 until the reset; a reply that is already running finishes. A one-time override lets one more request through per period.

Fixes #16486

Behavior

  • One cap with a daily, weekly or monthly reset at local midnight (Monday for weekly, the 1st for monthly) in the browser's timezone.
  • Counted from Studio's request monitor, which already sees every inference request: each finished request writes one usage row. API-key requests keep their existing usage receipts; Studio session requests (chats, scheduled tasks, previews, titles, durable runs, provider and OpenAI subscription chats) go to a small separate table, so API usage stats are unchanged.
  • Saving, editing, forking or deleting chats neither charges nor refunds anything; only requests count.
  • A request that reports no usage (stopped early, or a backend without stats) is estimated from what it generated (reply, reasoning, tool arguments) at 4 characters per token.
  • The override is refunded when its request fails or is cancelled before generating anything (for example no model loaded), and kept once any output was produced.
  • Only the Studio UI can change the allowance or grant the override; API keys cannot. Enabling it requires the API usage monitor, which is never silently re-enabled.

Limits

Already-admitted requests may finish beyond the cap, and tokens are not an exact money or energy budget. Estimates apply only where a backend reports no usage. A request in flight when Studio crashes is not charged. External Data Recipes providers called outside Unsloth's API are not covered.

Tests

tests/test_token_limit*.py cover receipts, estimates, override refunds (HTTP, durable runs, scheduled tasks) and route admission; the broad backend selection (216 files) has no failure that main does not also have. Frontend tests, TypeScript, locale parity and the production build pass.

Adds an optional cap on the tokens all chats and API requests can use per
day, week or month (unslothai#16486).

- Usage comes from a new token_usage_ledger table in studio.db. Triggers on
  chat_messages copy each assistant reply's token counts into it (same
  fallbacks as the Profile stats), so deleting or rewriting a chat does not
  hand tokens back. Fork copies are skipped and existing history is
  backfilled once. API-key requests are read from api_usage_events.
- One cap for everything, or separate caps for local models and for API
  keys plus external providers. Total counting charges the full context of
  each reply; incremental counting charges only prompt tokens the previous
  reply in the chat had not seen, plus the completion.
- The check runs once per incoming request (chat completions, completions,
  responses, messages and durable chat runs), before generation, so a reply
  that crosses the cap still finishes and the next request gets a 429.
- One override per pool per period lets exactly one more request through.
- An optional password locks every change, including turning the limit off.
  Changes and overrides need a UI session, never an API key.
- Settings > Profile gets a Token usage limit section, and the chat header
  shows a warning at 80% and the override dialog once the cap is reached.
danielhanchen added a commit that referenced this pull request Nov 3, 2026
…he stop (#16525)

## Summary


`studio/backend/tests/test_inference_worker_shutdown_exit.py::test_shutdown_exit_still_relays_the_mirrored_stderr_tail`
(added in #16338) fails intermittently in `(Python 3.13, g-r)`. In the
last 30 PRs it hit #16495, #16496, #16498, #16500 and #16509:

```
assert "the last line before shutdown" in result.stderr
E   assert 'the last line before shutdown' in ''
```

That is a real product bug, not a flaky test. The worker can drop its
last stderr lines when it exits, which are the lines the parent reports
when a worker dies.

**Cause.** `_tail_sink_to_stderr`, the mirror pump thread, decided it
was done from two separate steps: a read that came back empty, then a
check that `stop` was set. If the pump is descheduled between those two
steps, the worker writes its last lines to the sink and calls
`stop_worker_stderr_mirror()` in the gap. The pump then sees "empty
read, and stop is set", exits, and never relays them.

I instrumented the stop sequence in a child that runs the test's exact
script, 900 times on 24 threads. On a failing run:
- the sink held all 1720 bytes at stop time;
- the pump made exactly one read, which returned empty and was logged
after the stop;
- it emitted 0 bytes, and both threads ended cleanly within 4 ms.

So nothing timed out and nothing was cut off; the lines were simply
never read.

## Change

`studio/backend/utils/worker_stderr.py`, `_tail_sink_to_stderr`: the
pump records `stop.is_set()` before each read and only finishes on an
empty read that began after the stop was set. Bytes written before
`stop.set()` are therefore always read. Nothing else changes: the poll
interval, compaction, the relay, the join timeouts, and what a live
worker mirrors.

`studio/backend/tests/test_inference_worker_shutdown_exit.py`: new
`test_the_pump_reads_once_more_after_an_empty_read_that_raced_the_stop`.
It drives the pump with a reader whose first read returns empty and sets
`stop` in that same call, so the race is forced deterministically rather
than left to scheduling.

## Testing

| check | main | this branch |
|---|---|---|
| instrumented child, 300 / 600 / 900 parallel runs | 1 lost the whole
tail in each batch | 0 of 900 |
| new deterministic test | fails (`b'' == b'the last line before
shutdown\n'`) | passes |
| `test_shutdown_exit_still_relays_the_mirrored_stderr_tail`, `--count
40 -n 16` | 1 failed of 40 | 240 of 240 passed (`--count 80 -n 16`,
three times) |

- `test_inference_worker_shutdown_exit.py` and
`test_inference_worker_stderr_tail.py`: 77 passed.
@danielhanchen danielhanchen added >3000# affects UI# edge case# new-feature# security# Moves a security boundary: sandbox, allowlist, permission or network guard labels Nov 3, 2026
@danielhanchen danielhanchen self-assigned this Nov 3, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 3, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 3, 2026
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Nov 3, 2026
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Nov 3, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 3, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@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 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: 6d5a7f7658

ℹ️ 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 +35319 to +35323
def _sf_settle_streamed_passes():
# A later pass's failure must not lose the passes that already reported.
_stats = _sf_stats_holder.get("stats")
if _stats:
_monitor_usage(

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 Settle reported tool passes before returning on disconnect

When a streaming safetensors tool run detects a client disconnect through request.is_disconnected(), it finishes the monitor and returns without calling this helper. Previously completed turns may already have populated _sf_stats_holder, but updating _sf_seen_stats does not apply their usage to the monitor. Consequently, the terminal receipt replaces known token counts with character estimates, potentially substantially undercharging the allowance. An isolated execution with 1,600 reported tokens produced a 20-token receipt. Apply the settlement before the disconnect branch's early finish, as the exception handlers already do.

Useful? React with 👍 / 👎.

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.

Fixed in c1ddf30: the disconnect exit now settles the usage earlier passes reported before marking the row cancelled, like the other four exits.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

affects UI# edge case# new-feature# security# Moves a security boundary: sandbox, allowlist, permission or network guard >3000#

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Global Token Usage Guardrail

2 participants