Skip to content

Studio: refuse keyless access to a cross-site browser request - #9683

Merged
danielhanchen merged 15 commits into
mainfrom
danielhanchen/keyless-cross-site-followup
Aug 27, 2026
Merged

danielhanchen merged 15 commits into
mainfrom
danielhanchen/keyless-cross-site-followup

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 25, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #9102, which merged before this landed. The keyless feature is on main now; this closes a gap in its browser rule and adds the adversarial coverage.

The gap

Origin does not identify a browser. No engine attaches it to a same-origin GET, nor to a cross-site GET issued in no-cors mode, and only Chromium withholds a no-cors fetch aimed at http://127.0.0.1:<port>, through Private Network Access. Firefox and Safari have not shipped it, so there the request arrives.

Measured against a live server on current main (8e06238e5), replaying the exact shapes those engines emit:

shape scope=off scope=inference scope=full
cross-site no-cors GET /v1/models 401 200 200
cross-site no-cors POST /v1/unload 401 401 400, reached the handler
cross-site cors GET, carries Origin 401 401 401
Studio's own same-origin GET 401 200 200

The response is opaque to the page, so this is not a read primitive. It is a blind request primitive and an "is Unsloth Studio running here" oracle, and under full it reaches management handlers, where only FastAPI's JSON body requirement stops the POSTs. The guards from #9102 are what hold the line: GET /api/auth/api-keys still answers 403 through _require_a_credential_of_its_own.

The fix

Read Sec-Fetch-Site. The browser sets it on every request whatever the mode, and a page cannot forge it, because the Sec- prefix makes it a forbidden header name. Only cross-site and same-site are refused. same-origin is Studio's own page and none is the user typing the URL, so both stay admitted.

Absence stays admitted, and has to: curl, the OpenAI SDKs and Safari before 16.4 send no Sec-Fetch-* at all, and serving them is the point of the setting. That also means the header is only there to be read where the transport is a potentially trustworthy URL, so this narrows full, which is loopback-only, more tightly than plain-HTTP LAN inference. It never widens either.

After the fix every browser row above is 401, the same-origin row is unchanged, and a 63-case end-to-end run over curl-shaped requests is byte-identical to before.

Tests

New file, so nothing #9102 owns is touched. 15 tests covering what the merged suite asserts only at the predicate layer, only in one direction, or not at all:

  • scope=off refused through the security dependency, not only through scope_covers
  • GET/PUT /api/settings/keyless-api-access and _require_ui_session_for_keyless, which had no test at all. This is the self-promotion question: a keyless caller must not be able to widen its own scope
  • a real credential never stops working. Valid key and valid session across all three scopes and eight transports, including the ones keyless itself is refused on, asserting they authenticate as themselves rather than through either keyless scheme, since a downgrade would silently take away tools an existing API client already had. Mutation-checked: dropping the APPROVED_DUMMY_BEARERS clause from the dependency fails it with api_key was downgraded to keyless on loopback/inference
  • inference from a public bind and a public peer
  • management routes under inference
  • root_path and trailing slash driven through keyless_request_allowed, not just scope_covers
  • the dynamic GET /v1/models/ prefix pinned to the one handler it can reach. It admits every non-empty suffix rather than an exact pair, so the safety argument rests on route topology; this fails the day a second GET /models/... route is registered
  • a session JWT naming an unknown subject
  • asgi_request_is_keyless called directly. The duplicate-header rule has three implementations and only one was covered
  • every _hosted_mode_forbidden flag, including lan_access_is_colab and lan_access_secure_launch
  • the full denials with _remote_connector_active cleared. In the merged suite it is left True, so the wildcard-bind and LAN denials pass even if _full_scope_transport_allowed is deleted
  • the revoke-after-admission race from @Imagineer99's review on Studio: add secure keyless localhost and private-LAN API access #9102, pinned directly, since their reproducer can no longer run on this head

Verification

  • Full backend suite as Backend CI runs it: 30498 passed, 155 skipped. The one failure, test_tool_result_fits_window, fails identically on plain main and is unrelated
  • Frontend: typecheck clean, 4892 tests pass, biome check error free. The middle commit annotates the cloudflareUrl trigger dependency, which was the one Biome error the feature shipped with
  • Ruff clean on both changed Python files

Still open from the #9102 review, not changed here

keyless_transport_allowed returns True on the LAN branch before it consults _public_tunnel_active, so an active tunnel disables keyless for loopback but not for the LAN listener. Not exploitable through Studio's own tunnel, which targets http://localhost:<port> and so presents a loopback peer, but the #9102 description says keyless is disabled "even for localhost until that exposure stops" and the code does less than that. Left alone as a product call. Separately, _names_a_session and bearer_names_a_session have no callers anywhere in the repo.

Added during review: DNS rebinding

Codex raised a P1 on the same-origin branch, and it was right. I reproduced it at the previous head before changing anything: scope full, GET /api/chat/threads with Host: evil.example:8888 and Sec-Fetch-Site: same-origin was admitted.

DNS rebinding produces every local signal the transport checks read. A page on evil.example whose record is re-pointed at 127.0.0.1 keeps its own origin, so the fetch is same-origin: no Origin, Sec-Fetch-Site: same-origin, and a loopback peer on a loopback socket. Unlike the no-cors case above, the response is readable by the page.

This predates the branch, since a same-origin GET carries no Origin and the existing rule never fired either. But same-origin is a positive signal this branch introduces, so the check belongs with it.

_host_authority_is_direct closes it. A direct client addresses the socket by literal address or localhost; only a rebound page sends a domain, because the browser sends the name the page was served from. Absent Host stays admitted, since the merged suite and HTTP/1.0 callers send none and no browser omits it. Bracketed IPv6 junk such as [::1]evil.example is rejected rather than parsed, matching what _host_header_is_loopback already does for the bootstrap path.

request before after
Host: evil.example:8888, Sec-Fetch-Site: same-origin admitted refused
Host: localhost.evil.example:8888 admitted refused
Host: 127.0.0.1:8888 (curl, SDK) admitted admitted
Host: localhost:8888 admitted admitted
no Host header admitted admitted

One narrow cost worth naming: reaching Studio keylessly through a private hostname such as studio.internal:8888 now needs a key. That is fail-closed, and the right default for a setting that removes authentication.

Origin is not enough to tell that a browser started a request. No engine
attaches it to a same-origin GET, nor to a cross-site GET issued in no-cors
mode, and a no-cors fetch aimed at http://127.0.0.1:<port> really does arrive:
only Chromium withholds it, through Private Network Access, which Firefox and
Safari have not shipped. Against a live server on the current head, a request
shaped exactly the way those two emit it was served the model list keylessly
under inference, and reached the management handlers under full.

Sec-Fetch-Site says who initiated the request, on every request whatever the
mode, and a page cannot forge it: the Sec- prefix makes it a forbidden header
name. Only cross-site and same-site are refused. same-origin is Studio's own
page and none is the user typing the URL, so both stay admitted.

Absence stays admitted too, and has to: curl, the OpenAI SDKs and Safari before
16.4 send no Sec-Fetch-* at all, and serving them is the point of the setting.
That also means the header is only there to be read where the transport is a
potentially trustworthy URL, so this narrows full scope, which is loopback-only,
more tightly than plain-HTTP LAN inference. It never widens either.

Adds the adversarial suite the feature was missing, in its own file so the
existing test budget is untouched: scope=off refused through the security
dependency rather than only through scope_covers, the settings route that grants
the scope refusing to let a keyless caller widen it, public bind and public peer,
management routes under inference, root_path and trailing slash driven end to
end, the dynamic /v1/models/ prefix pinned to the one handler it can reach, a
session JWT naming an unknown subject, the ASGI twin of the header rules, every
hosted-mode flag, the full-scope denials with the tunnel flag cleared so they are
not over-determined, and the revoke-after-admission race from the review, pinned
directly since the original reproducer can no longer run on this head.
biome check reports useExhaustiveDependencies on the effect that reloads keyless
settings: cloudflareUrl is in the dependency list but never read in the body.
That is deliberate. It is there so a tunnel appearing or going away re-fetches
exposure from the backend and the warning copy stays current. Annotated the way
the rest of the frontend annotates a trigger dependency, so the file is clean.
The setting adds an admission path and must never take one away. A working key
or session has to keep authenticating on every scope and on every transport,
including the ones keyless itself is refused on: public bind, active tunnel,
Colab, --secure, and the browser shapes the Sec-Fetch-Site rule now rejects. A
usable bearer is resolved before any scope or transport check runs, so nothing
in the gating can reach it, and this holds that shape in place.

It also asserts the credential authenticates as itself rather than through
either keyless scheme. That is not cosmetic: the middleware classifies a
key-bearing request as non-keyless precisely so an existing API client keeps its
own tool policy, and a downgrade would quietly take away tools it already had.
Removing the APPROVED_DUMMY_BEARERS clause from the dependency fails this test
with "api_key was downgraded to keyless on loopback/inference".

Revoked and expired keys are re-checked at the widest scope in the same test, so
the two directions cannot drift apart.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 3d38694cc1

ℹ️ 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-only pass. The helper docstring said the same thing twice about why
Origin cannot identify a browser, and the test docstrings pointed at "the PR",
which named nothing a reader could open once #9102 merged.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

DNS rebinding produces every local signal the transport checks read. A page on
evil.example whose record is re-pointed at 127.0.0.1 keeps its own origin, so the
fetch is same-origin: no Origin header, Sec-Fetch-Site: same-origin, and a
loopback peer on a loopback socket. Reproduced at the previous head, scope full,
GET /api/chat/threads with Host: evil.example:8888 admitted, and unlike the
no-cors case the response is readable by the page.

This predates the branch, since a same-origin GET carries no Origin and the
existing rule never fired either, but same-origin is a positive signal this
branch introduced, so the check belongs with it.

Host is what still differs: a direct client addresses the socket by literal
address or localhost, and only a rebound page sends a domain, because the browser
sends the name the page was served from. Absent Host stays admitted, since the
merged suite and HTTP/1.0 callers send none and no browser omits it. Bracketed
IPv6 junk such as [::1]evil.example is rejected rather than parsed, matching what
_host_header_is_loopback already does for the bootstrap path.

Costs a private hostname such as studio.internal:8888 its keyless access, which
is fail-closed and the right default for a setting that removes authentication.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: a0e37a22f7

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

pre-commit-ci Bot and others added 2 commits August 25, 2026 11:33
Final comment-only pass. The helper docstring restated the attack twice, and two
comments still said "the PR" where #9102 is merged and the reader has nothing to
open.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 47689693fc

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

Copy link
Copy Markdown
Member Author

CI status, since the red checks here are misleading.

Every red check on this PR is cancelled, not failure. On the current head: 32 cancelled, 12 success, 1 neutral, and gh pr checks renders cancelled as "fail". Something is clearing the org Actions queue repo-wide; I re-ran the cancelled runs once and they were cancelled again without a replacement, so re-running is not the answer.

I replicated this branch onto a staging repo, cut from fresh main and merged with this head, to get honest signal. Result: 16 success, 1 skipped, one failure, and that failure is not from this branch:

test_checked_in_file_reads_name_an_encoding
  ['tests/studio/playwright_declared_polls.py:210: write_text()']

That file is on main unchanged and is not touched by this PR. It makes Repo tests (CPU), and so Backend CI, red on every open PR. Fixed separately in #9698.

So the only genuine failure reachable from here is a pre-existing one with a fix already open. Nothing on this branch is failing.

@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed studio/backend/utils/keyless_api_access.py on main has no Sec-Fetch-Site or Host authority check, so cross-site no-cors and rebound same-origin requests still reach keyless admission, and the same-origin rebinding case is closed here too. Will get this reviewed.

…sence

The rule this branch added admits a request that carries no `Sec-Fetch-Site`, on
the docstring's claim that the header "is set on every request whatever the mode".
That is not what the spec says and not what browsers do. Fetch Metadata is attached
only to a *potentially trustworthy* URL, and Secure Contexts spells that set as
`127.0.0.0/8` and `::1/128`. Any other spelling that still reaches a loopback
listener arrives with no Fetch Metadata at all, and absence-means-not-a-browser
then reads a hostile page as curl.

Measured against a live server, Chromium 151 / Firefox 153 / WebKit 26.5:

| dialled from a cross-site page | Host seen        | Sec-Fetch-Site | before |
| ------------------------------ | ---------------- | -------------- | ------ |
| `[::ffff:127.0.0.1]:<port>`    | `[::ffff:7f00:1]`| absent, all 3  | ADMITTED |
| `[::ffff:7f00:1]:<port>`       | `[::ffff:7f00:1]`| absent, all 3  | ADMITTED |
| `0.0.0.0:<port>`               | `0.0.0.0`        | absent         | ADMITTED |
| `localhost.:<port>`            | `localhost.`     | absent on WebKit | ADMITTED |
| `127.0.0.1:<port>` (control)   | `127.0.0.1`      | cross-site     | refused |

`_normalized_ip` un-maps the IPv4-mapped forms, which is right for the socket
addresses it was written for and wrong for an authority off the wire: it undoes
exactly the distinction the browser is drawing. The authority is now parsed here
and matched as written, refusing IPv4-mapped IPv6, the unspecified addresses, and
a trailing-dot `localhost` (Secure Contexts lists it, but WebKit's check is a
plain string compare and it sends nothing there).

`none` is no longer admitted. Its comment said "the user typing the URL, which no
page can cause" -- true of a page, false of a server. `none` is computed before
the redirect chain is walked, so an attacker 302 from a navigation the user started
lands here still saying `none`; Firefox and WebKit both delivered it. Nobody types
an API route into an address bar.

A repeated `Host` or `Sec-Fetch-Site` is refused rather than resolved. Both
predicates read `Headers.get()`, which takes the first value; h11 rejects a
repeated `Host` but httptools passes both through, and neither rejects a repeated
`Sec-Fetch-Site`. `asgi_request_is_keyless` already fails closed on a repeated
`Authorization` a hundred lines below, so this now matches the file's own rule.

Also fixes a drift the strengthened twin test caught: `asgi_request_is_keyless`
hand-rolled `partition(" ")` while the dependency uses FastAPI's parser, and they
disagreed on `Authorization: bearer  not-needed` -- keyless to every route, and
not-keyless to `KeylessToolPolicyMiddleware`, which is what clamps the tool grant.
That one shape reached keyless admission with an unclamped tool policy. Both now
share the parser.

Malformed authorities are refused: the port suffix must be numeric, brackets must
close, and the literal must parse. `localhost:garbage`, `127.0.0.1:80@evil`,
`127.0.0.1%evil.example`, `::1]` and `127.0.0.1:<port>/../evil` all reached the app
through both uvicorn parsers and were admitted.

UI side, the panel stopped agreeing with the backend. `keylessBaseEligible` short
circuits on `exposure === "private_lan"`, which is computed from the RESOLVED
address, so `unsloth studio -H box.local` rendered a copyable
`Bearer not-needed` curl against a URL the new rule answers 401 on, and
`_has_keyless_lan_url` resolved the name and reported it eligible. Both now require
a literal. The LAN panel still shows the hostname URL -- the UI works there on a
session -- it just no longer claims keyless does.

Verification, all before/after on the same tree:

- raw-socket matrix over the real predicate behind real uvicorn, both parsers,
  both scopes: 27 expectation failures -> 0. All 11 legitimate client shapes
  (curl, OpenAI/Anthropic/LM Studio/Ollama SDKs, HTTP/1.0 without Host, `[::1]`,
  Studio's own same-origin page) still admitted.
- closed loop, hostile page in all three engines against the real predicate:
  10 hostile requests admitted -> 0, same-origin still admitted.
- backend suite as Backend CI runs it: failure set byte-identical to the merge
  base (387 ids either side, 0 new), +18 passed.
- frontend: 4893 tests pass, typecheck clean, biome error free. Ruff clean.

Known residual, now pinned by a test rather than assumed away: on the plain-HTTP
private-LAN limb no URL is potentially trustworthy, so no engine sends
`Sec-Fetch-*` there and that predicate is structurally inert. `Origin` and the
authority rule are what carry the LAN limb. Narrowing it further would take away
the private-LAN inference the setting exists to provide.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Follow-up commit bac1aa63f. I went back at this branch with real browsers and a raw-socket harness rather than synthetic requests, and the headline rule had a hole big enough to matter.

What was wrong

The docstring claimed Sec-Fetch-Site "is set on every request whatever the mode". It is not. Fetch Metadata is only attached to a potentially trustworthy URL, and Secure Contexts spells that set as 127.0.0.0/8 and ::1/128. Any other spelling that still reaches a loopback listener arrives with no Fetch Metadata at all — and "absent means not a browser" then reads a hostile page as curl.

Measured against a live server from a cross-site page, Chromium 151 / Firefox 153 / WebKit 26.5:

dialled from a hostile page Host the server sees Sec-Fetch-Site on 47689693f
http://[::ffff:127.0.0.1]:PORT [::ffff:7f00:1] absent, all three engines ADMITTED
http://[::ffff:7f00:1]:PORT [::ffff:7f00:1] absent, all three engines ADMITTED
http://0.0.0.0:PORT 0.0.0.0 absent ADMITTED
http://localhost.:PORT localhost. absent on WebKit only ADMITTED
http://127.0.0.1:PORT (control) 127.0.0.1 cross-site refused

All of those reach a listener bound on 127.0.0.1 with a 127.0.0.1 peer, so request_is_loopback passes too. The cause is that _normalized_ip un-maps IPv4-mapped IPv6 — correct for the socket addresses it was written for, wrong for an authority off the wire, because it undoes exactly the distinction the browser is drawing. Chromium's IPAddress::IsLoopback never calls IsIPv4MappedIPv6; Firefox's function is literally named IsLoopBackAddressWithoutIPv6Mapping.

Three more, same commit:

  • none was admitted. Its comment said "the user typing the URL, which no page can cause" — true of a page, false of a server. none is computed before the redirect chain is walked (spec §4.1, deliberate per Sending Sec-Fetch-Site: none after redirects from directly user-initiated requests w3c/webappsec-fetch-metadata#39), so an attacker 302 from a navigation the user started lands still saying none. Reproduced in Firefox and WebKit. Control held: the same target reached by clicking a link inside the attacker page arrives cross-site.
  • Repeated Host / Sec-Fetch-Site took the first value. h11 rejects a repeated Host, httptools passes both through, and neither rejects a repeated Sec-Fetch-Site. asgi_request_is_keyless already fails closed on a repeated Authorization a hundred lines below.
  • The two credential implementations had drifted. asgi_request_is_keyless hand-rolled partition(" ") while the dependency uses FastAPI's parser. They disagreed on Authorization: bearer not-needed (doubled space): keyless to every route, and not-keyless to KeylessToolPolicyMiddleware, which is what clamps the tool grant. That one shape reached keyless admission carrying an unclamped tool policy. Pre-existing; the strengthened twin test caught it.

What changed

The authority is now parsed here and matched as written, refusing IPv4-mapped IPv6, the unspecified addresses, a trailing-dot localhost, and a malformed authority (non-numeric port, unclosed bracket, 127.0.0.1:80@evil, 127.0.0.1%evil.example, ::1], 127.0.0.1:PORT/../evil — all of which reached the app through both uvicorn parsers and were admitted). none is out. Repeats are refused. Both twins share FastAPI's parser.

UI side, the panel had stopped agreeing with the backend: keylessBaseEligible short-circuits on exposure === "private_lan", which is computed from the resolved address, so unsloth studio -H box.local rendered a copyable Bearer not-needed curl against a URL this branch answers 401 on, and _has_keyless_lan_url resolved the name and reported it eligible. Both now require a literal. The LAN panel still shows the hostname URL — the UI works there on a session — it just no longer claims keyless does.

Verification

Before/after on the same tree, everything scripted:

  • Raw-socket matrix over the real predicate behind real uvicorn, both parsers, both scopes: 27 expectation failures -> 0. All 11 legitimate client shapes still admitted (curl by IP and by localhost, OpenAI / Anthropic / LM Studio / Ollama SDK shapes, HTTP/1.0 without Host, [::1], Studio's own same-origin page).
  • Closed loop, a hostile page driven in all three engines against the real predicate: 10 hostile requests admitted -> 0, and same-origin still admitted.
  • Backend suite as Backend CI runs it: failure set byte-identical to the merge base — 387 ids either side, 0 new — and +18 passed.
  • Frontend: 4893 tests pass, typecheck clean, biome check error free. Ruff clean on all changed Python.
  • Cross-platform: the adversarial suite runs on ubuntu-latest, macos-15 and windows-latest in staging.

Compatibility

Nothing changes for an install that leaves the setting off, which is every existing install: keyless_request_allowed returns at the off check before these predicates are reached. Every first-party component was audited and is unaffected — the Tauri app addresses 127.0.0.1 and carries a real bearer, both CLIs always send a bearer, MCP has its own mandatory token, the two backend self-calls hard-code 127.0.0.1 with internal keys, and the Vite dev proxy rewrites Host. No schema, default or migration is touched.

Residual, now pinned by a test rather than assumed away

On the plain-HTTP private-LAN limb no URL is potentially trustworthy, so no engine sends Sec-Fetch-* there and _browser_initiated_elsewhere is structurally inert. Origin and the authority rule carry that limb. Narrowing it further would take away the private-LAN inference the setting exists to provide, so it is documented and asserted in both directions instead.

Also worth stating plainly, since the original description called the cost narrow: same-site refusal means a page on another localhost port loses keyless, a same-machine reverse proxy that preserves Host loses it, and UNSLOTH_STUDIO_URL pointed at a named remote loses it. All fail closed, all correct, none previously named.

@danielhanchen

Copy link
Copy Markdown
Member Author

Cross-platform, on real runners in staging. The adversarial suite passes on all three, and the address-family probe explains why the bypass mattered where it did.

Adversarial suite, Python 3.12: ubuntu-latest 18 passed, macos-15 18 passed, windows-latest 18 passed.

Does a non-trustworthy loopback spelling actually reach a listener bound on 127.0.0.1?

connect target Linux macOS 15 Windows
127.0.0.1 reached reached reached
localhost reached reached reached
0.0.0.0 reached, peer 127.0.0.1 reached, peer 127.0.0.1 refused, WSAEADDRNOTAVAIL
::ffff:127.0.0.1 reached, peer 127.0.0.1 reached, peer 127.0.0.1 refused, WSAEADDRNOTAVAIL
::ffff:7f00:1 reached, peer 127.0.0.1 reached, peer 127.0.0.1 refused, WSAEADDRNOTAVAIL
::127.0.0.1 (v4-compat) unreachable unreachable unreachable

So the IPv4-mapped and unspecified bypasses were live on Linux and macOS and never reachable on Windows, which matches the documented connect() behaviour there. The fix refuses all of them on every platform regardless, and it is pure ipaddress string parsing with no socket or platform dependency, so there is nothing OS-specific in the rule itself.

Worth recording because it cuts the other way too: on Linux and macOS the peer address for every one of those is plain 127.0.0.1, so request_is_loopback was satisfied and the socket checks could never have caught this. The authority was the only place it was visible.

Being an address rather than a name was not enough. The authority rule accepted
every literal, so on a loopback transport `Host: 8.8.8.8:8888` was admitted under
`full` and served management responses.

The socket checks only ever see the hop that connected. An SSH forward or a reverse
proxy in front of a loopback bind makes both ASGI endpoints loopback while the page's
own origin, and therefore `Host`, is the public address it was served from. That
authority is the only place the difference is visible, which is the same reason the
IPv4-mapped case needed fixing.

`full` is loopback-only by construction -- `_full_scope_transport_allowed` already
demands a loopback bind and a loopback peer -- so its authority must be loopback too,
and nothing legitimate reaches a loopback-only server by typing a routable address.
`inference` may additionally be reached across the private LAN, so it takes the same
networks `lan_access_settings` admits and nothing wider.

Spelled with the repo's existing `_private_non_loopback` rather than `is_private`,
which means "not globally reachable" and so counts the documentation ranges as private
(203.0.113.5 reports is_private=True). CGNAT and the doc ranges are outside
`_PRIVATE_LAN_NETWORKS`, so both are refused, matching what the socket checks already
enforce for the LAN limb.

Before and after, on a loopback transport:

| Host                | full        | inference   |
| ------------------- | ----------- | ----------- |
| 127.0.0.1, ::1, 127.0.0.2, localhost | admitted -> admitted | admitted -> admitted |
| absent              | admitted -> admitted | admitted -> admitted |
| 192.168.1.5, fd00::1 | admitted -> REFUSED | admitted -> admitted |
| 8.8.8.8, 2001:db8::1 | admitted -> REFUSED | admitted -> REFUSED |
| 100.64.0.1 (CGNAT)   | admitted -> REFUSED | admitted -> REFUSED |

Also runs the repo formatter over the three files, which is what `pre-commit.ci` was
red on: the hook adjusts kwarg spacing and the test file had drifted.

Verified: keyless, LAN, desktop-auth and off-event-loop suites 170 passed; the
raw-socket matrix over the real predicate behind real uvicorn is 0 expectation
failures on both parsers and both scopes; full backend suite as Backend CI runs it
has 0 new failures against the merge base (385 vs 387).
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The LAN panel decides whether to print `Bearer not-needed` through
`_has_keyless_lan_url`, which had its own copy of the authority test, and the copy
went through `_normalized_ip`. That un-maps IPv4-mapped IPv6, which is the one thing
the mapped form is refused for, so a launch on `::ffff:192.168.1.24` was advertised
as keyless-eligible while admission refused the mapped authority. Reproduced before
changing anything:

| URL / Host                      | panel said | admission said |
| ------------------------------- | ---------- | -------------- |
| `192.168.1.24:8888`             | eligible   | admitted       |
| `[::ffff:192.168.1.24]:8888`    | eligible   | REFUSED        |
| `[::ffff:c0a8:118]:8888`        | eligible   | REFUSED        |

Adding a second mapped-literal check next to the first is what produced the drift,
so both ends now answer through one `keyless_authority_address_allowed`, and the
panel parses the literal as written instead of normalising it. It takes an
already-parsed address so the caller keeps responsibility for parsing the spelling
faithfully, which is the part that has to stay honest.

Same shape as the `asgi_request_is_keyless` split earlier on this branch: two copies
of a rule that must agree will eventually not.

Verified: keyless, LAN, desktop-auth and off-event-loop suites 171 passed; panel and
admission agree on every literal spelling tested, including loopback, private v4/v6,
mapped, CGNAT, public and a hostname; full backend suite has 0 new failures against
the merge base (385 vs 387).
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 26, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The guard asked whether a base LOOKS like an address. Every one of these is a well
formed literal, and admission refuses all of them, so the panel kept advertising a
copy-paste `Bearer not-needed` command that answers 401. Reproduced before changing
anything, at scope=inference with exposure=private_lan:

| base                              | panel said | admission says |
| --------------------------------- | ---------- | -------------- |
| `[::ffff:192.168.1.24]:8888`      | eligible   | refused        |
| `[::ffff:c0a8:118]:8888`          | eligible   | refused        |
| `[::]:8888`, `0.0.0.0:8888`       | eligible   | refused        |
| `8.8.8.8:8888`                    | eligible   | refused        |

The public case was not in the report and is the same defect.

Third time this guard has been wrong, each time because it tested something adjacent
to the real question: first `exposure` short-circuited the host test, then syntax
stood in for the address class, and `isPrivateLanHost` unwrapped `::ffff:` -- which is
the one thing admission refuses the mapped form for. So the pure logic moves to
`keyless-example-eligibility.ts`, mirroring `keyless_authority_address_allowed`, and
the unwrapping is gone.

Its own module because the old test could only scrape the component source: importing
`usage-examples.tsx` drags react and shiki into a unit test. Now the table itself is
pinned, not the presence of a guard, and it mirrors the backend test by name so the
two are changed together.

Verified: 4 new frontend tests pass, 4896 frontend tests pass overall, typecheck
clean, biome error free (warning parity with the existing test files); backend
keyless, LAN, desktop-auth and off-event-loop suites 171 passed.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 26, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 39b47c3599

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

The new eligibility module declared its own copies, and they were wrong in both
directions: the invented union carried a "loopback" member that does not exist and
was missing "network", which does. `Tauri Linux debug build` caught it:

    usage-examples.tsx(705,45): error TS2345: Argument of type
    'KeylessApiAccessExposure | null' is not assignable to parameter of type
    'KeylessExposure | null'. Type '"network"' is not assignable to
    'KeylessExposure | null'.

Redeclaring a type to avoid an import is the same mistake as the duplicated address
rule this module exists to remove, so it now imports both from
`../api/keyless-api-access`.

Worth noting for the next change here: `tsc --noEmit -p tsconfig.json` passes on the
broken version. `npm run build` runs `tsc -b`, which resolves project references and
is what actually fails, so that is the check to run.

No behaviour change -- "network" exposure falls through to the authority rule exactly
as before, and only "colab" and "public_url" are refused up front.

Verified: npm run build succeeds, 4896 frontend tests pass, biome error free, backend
keyless and LAN suites pass.
@danielhanchen

Copy link
Copy Markdown
Member Author

CI status on eebcc25eb, since two checks were red and only one of them was mine.

Tauri Linux debug build was mine, and is fixed. The eligibility module I added last commit declared its own copies of the keyless scope and exposure types, and they were wrong in both directions: the invented union carried a loopback member that does not exist and was missing network, which does.

usage-examples.tsx(705,45): error TS2345: Argument of type
'KeylessApiAccessExposure | null' is not assignable to parameter of type
'KeylessExposure | null'. Type '"network"' is not assignable to 'KeylessExposure | null'.

Both types now come from ../api/keyless-api-access. No behaviour change: network exposure falls through to the authority rule exactly as before, and only colab and public_url are refused up front.

Worth recording for anyone touching this next: tsc --noEmit -p tsconfig.json passes on the broken version. npm run build runs tsc -b, which resolves project references, and that is what fails. Run the build, not the bare typecheck.

pre-commit.ci is not this branch. The ruff-format-with-kwargs hook reports "938 files reformatted" across files this PR never touches (unsloth/kernels/fp8.py, unsloth/models/qwen3.py, studio/backend/hub/routes/datasets.py), then skips its push with "a conflict occurred when applying fixes to the pr".

I ran the same hook against a pristine checkout of origin/main: 469 files reformatted there too. So the check cannot be green for any PR right now, and the larger number here is branch staleness on top of it. The three Python files this PR does touch are format-stable under the hook, verified by running it on them and getting no diff.

Everything else: npm run build succeeds, 4896 frontend tests pass, biome error free, backend keyless/LAN/desktop-auth suites pass, and the full backend suite has a byte-identical failure set to the merge base. Cross-platform staging CI is green on ubuntu-latest, macos-15 and windows-latest.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 26, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: eebcc25ebc

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

The pre-commit hook pins ruff 0.6.9, which wraps a long assert differently
from newer ruff, so the file was not format-stable in CI.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 26, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 26, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 2841d21f80

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

Comments and docstrings only, no code change.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 26, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: b00ebee265

ℹ️ 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 0aab674 into main Aug 27, 2026
3 of 45 checks passed
@danielhanchen
danielhanchen deleted the danielhanchen/keyless-cross-site-followup branch August 27, 2026 03:33
Souravrajvi0 added a commit to Souravrajvi0/unsloth that referenced this pull request Aug 27, 2026
… moves

Source-inspection contracts still pointed at openai_chat_completions after
unslothai#9187 split produce_openai_chat_completions out, and at strings that unslothai#7880
and unslothai#9683 moved. Point them at the live sites and defer PEP 604 unions in
the new kv-cache estimate tests.
mahiatlinux added a commit that referenced this pull request Aug 27, 2026
)

* Studio: add Chat settings to disable or ease GGUF auto-compaction

Local GGUF chats always opted into truncate_oldest, then compacted at the
prompt budget with a 25% extra trim (or a full checkpoint reset). Settings
now let you turn that off, switch to a sliding window, and choose how much
extra room a rolling compaction takes. Compaction still keys off the
configured context length, not free VRAM.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: honor Chat compaction settings over process defaults

Send checkpoint/error overflow fields from Studio so Chat settings override
UNSLOTH_CONTEXT_POLICY and UNSLOTH_CONTEXT_OVERFLOW. Refuse checkpoint-origin
sticky boundaries when a request forces rolling, and route search_conversation
from the same effective policy as the fitter.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* honor zero compaction headroom

* test zero-headroom rolling compaction

* preserve server compaction policy by default

* test server policy inheritance

* mark studio-owned tool history

* keep studio tool history on the fitted path

* isolate studio tool history provenance

* test compaction after local tool use

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* complete locale settings translations

* fix sanitized catalog guard coverage

* run pip cache guard on workflow changes

* set utf-8 for pip cache guard reads

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* mark studio tool history in token counts

* reset boundaries when context policy changes

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* mark studio tool history from replayed calls

Hosted server builtins such as web_search are dropped during OpenAI
serialization, so ownership must be derived from the calls that actually
go on the wire. Mixed hosted-plus-local history can then keep the
studio_tool_history marker and stay on the compaction path.

* align prune contract test with token-count history builder

The send and count paths both prune through pruneOutboundHistory into
survivingMessages; the source contract still expected the old
outboundMessages name on the count path.

* align sticky and token-count harnesses with current compaction APIs

Recall fixtures store rolling-shaped truncation records, so pin CONTEXT_POLICY
to rolling when faking studio_db. Recount and prune harnesses follow the
renamed token-count builder, a tighter setActiveThreadId slice, and the
send-path prune call rather than the earlier count-path copy.

* test(studio): follow main's chat-completions extract and VRAM/keyless moves

Source-inspection contracts still pointed at openai_chat_completions after
#9187 split produce_openai_chat_completions out, and at strings that #7880
and #9683 moved. Point them at the live sites and defer PEP 604 unions in
the new kv-cache estimate tests.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* drop the duplicate workflow guard entry this pr added

tests/studio/test_pip_cache_naming.py was already listed at line 141 of
.github/workflows/workflow-trigger-lint.yml, so the Workflow guard suites
step collected it twice. The trailing newline it also removed goes back.

* keep the eviction bite for requests that chose no compaction setting

fit_rolling_context gated the 5% floor on each eviction bite on `headroom > 0`,
but keeps_boundary = False zeroes the headroom for every threadless API request
and incognito chat. Those callers send no new field, so they were handed the
"no extra trim" behaviour anyway: on a 201-message transcript at
context_length 1100 eviction fell from 12 messages to 2.

Gate it on the requested ratio instead, so only a caller that actually asked
for no extra trim gives the floor up.

* replay a rolling boundary where the fit cannot start an epoch

_sticky_compaction_boundary rejected any boundary whose recorded policy differed
from the process policy, in both directions. The rolling-to-checkpoint direction
is only unsafe where fit_checkpoint_context would read the boundary as an epoch
already in force and skip the reset's recall, and that needs _can_reset_epoch.

Threads it refuses -- a template that cannot render tools, --disable-tools, no
conversation archive -- compact through fit_rolling_context and record a rolling
boundary, so on a checkpoint-default server every later turn discarded it and the
boundary slid again. Measured on a stored boundary of 6: base restored 6, this
branch returned 0.

Each call site now computes _can_reset_epoch once and hands the same value to the
boundary read and to the fit.

* declare studio_tool_history on the token-count request

refreshContextUsage forwards the marker, but ChatCountTokensRequest only carried
it through extra = "allow", which coerces nothing. A client sending the JSON
string "false" reached _only_studio_tool_history as a truthy value and moved the
count onto the Unsloth tool path the completion never takes, so the context-usage
bar priced a different prompt. The model's own bypass_permissions field is
declared for the same reason.

* restore the constraint the renamed tool-history helper documented

Renaming _only_studio_memory_tool_history to _only_studio_tool_history replaced
its docstring with three lines that say what the marker is and no longer say why
the strict route exists: a replayed tool pair read as a client contract sends the
turn to the llama-server passthrough, which runs no context fit, so the epoch,
the carried-forward block and the automatic recall are gone one turn after the
compaction that created them. Put that back, and match the sentence case the rest
of the file and the api.ts field comments use.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* keep a rolling boundary off the checkpoint replay branch

A request that may not reset still takes the checkpoint REPLAY branch in
_fit_context under a checkpoint policy, so the rolling-origin boundary the
previous commit restored reached fit_checkpoint_context and read as an epoch
already in force. The fit returned checkpoint_started false, and
_archive_and_recall reads that as "already recalled" and injected nothing.
Measured at context_length 1800 with a stored boundary of 30: the reply lost the
archived turns the rolling fallback would have pulled back.

_sticky_compaction_state now returns the depth and whether a checkpoint reset
recorded it, mixed provenance across surviving rows counting as rolling since
min(boundaries) may pick either row. _fit_context takes that as
sticky_is_checkpoint and enters the replay branch only for a real epoch;
otherwise the count stays on the rolling fitter, which reports no
checkpoint_started and still recalls.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* discard a boundary cut with more extra trim than the request asks for

Phase one of fit_rolling_context re-applies the saved boundary before anything
else and returns as soon as the result fits, so an already-compacted chat that
moved from 25% extra room down to 10%, 5% or none replayed the deeper cut and
never reached the phase that reads the new ratio. Lowering the setting did
nothing at all, and the history the client had re-sent stayed dropped.

The persisted truncation now carries boundary_headroom_ratio beside
boundary_messages and boundary_anchor, written through one _boundary_metadata
helper so the three cannot drift apart. _sticky_compaction_state refuses a
rolling boundary recorded under a larger ratio than this request wants; a larger
request needs no refusal, since phase two moves the boundary out by itself. Rows
saved before the ratio existed carry no key and replay as they did, and a
checkpoint reset ignores headroom so its depth is never refused over it.

* refuse a replayed boundary on any change of extra trim, not just a cut

The previous commit only refused a boundary recorded under MORE headroom than
the request asked for, on the reasoning that phase two would widen a shallower
one by itself. It does not: phase one re-applies the saved count and phase two
runs only when the result still does not fit, so a shallower boundary that
already fits is just as inert. Measured on a 121-message transcript at
context_length 1600, a stored boundary of 86 gave dropped 86 under both 0.05 and
0.25, so raising the setting did nothing either.

Compare for equality instead. With the 5%-origin boundary of 86 above, a request
at 0.05 still replays it and a request at 0.25 recomputes to 94.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: mahiatlinux <[email protected]>
danielhanchen pushed a commit that referenced this pull request Aug 27, 2026
)

* Studio: add Chat settings to disable or ease GGUF auto-compaction

Local GGUF chats always opted into truncate_oldest, then compacted at the
prompt budget with a 25% extra trim (or a full checkpoint reset). Settings
now let you turn that off, switch to a sliding window, and choose how much
extra room a rolling compaction takes. Compaction still keys off the
configured context length, not free VRAM.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: honor Chat compaction settings over process defaults

Send checkpoint/error overflow fields from Studio so Chat settings override
UNSLOTH_CONTEXT_POLICY and UNSLOTH_CONTEXT_OVERFLOW. Refuse checkpoint-origin
sticky boundaries when a request forces rolling, and route search_conversation
from the same effective policy as the fitter.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* honor zero compaction headroom

* test zero-headroom rolling compaction

* preserve server compaction policy by default

* test server policy inheritance

* mark studio-owned tool history

* keep studio tool history on the fitted path

* isolate studio tool history provenance

* test compaction after local tool use

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* complete locale settings translations

* fix sanitized catalog guard coverage

* run pip cache guard on workflow changes

* set utf-8 for pip cache guard reads

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* mark studio tool history in token counts

* reset boundaries when context policy changes

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* mark studio tool history from replayed calls

Hosted server builtins such as web_search are dropped during OpenAI
serialization, so ownership must be derived from the calls that actually
go on the wire. Mixed hosted-plus-local history can then keep the
studio_tool_history marker and stay on the compaction path.

* align prune contract test with token-count history builder

The send and count paths both prune through pruneOutboundHistory into
survivingMessages; the source contract still expected the old
outboundMessages name on the count path.

* align sticky and token-count harnesses with current compaction APIs

Recall fixtures store rolling-shaped truncation records, so pin CONTEXT_POLICY
to rolling when faking studio_db. Recount and prune harnesses follow the
renamed token-count builder, a tighter setActiveThreadId slice, and the
send-path prune call rather than the earlier count-path copy.

* test(studio): follow main's chat-completions extract and VRAM/keyless moves

Source-inspection contracts still pointed at openai_chat_completions after
#9187 split produce_openai_chat_completions out, and at strings that #7880
and #9683 moved. Point them at the live sites and defer PEP 604 unions in
the new kv-cache estimate tests.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* drop the duplicate workflow guard entry this pr added

tests/studio/test_pip_cache_naming.py was already listed at line 141 of
.github/workflows/workflow-trigger-lint.yml, so the Workflow guard suites
step collected it twice. The trailing newline it also removed goes back.

* keep the eviction bite for requests that chose no compaction setting

fit_rolling_context gated the 5% floor on each eviction bite on `headroom > 0`,
but keeps_boundary = False zeroes the headroom for every threadless API request
and incognito chat. Those callers send no new field, so they were handed the
"no extra trim" behaviour anyway: on a 201-message transcript at
context_length 1100 eviction fell from 12 messages to 2.

Gate it on the requested ratio instead, so only a caller that actually asked
for no extra trim gives the floor up.

* replay a rolling boundary where the fit cannot start an epoch

_sticky_compaction_boundary rejected any boundary whose recorded policy differed
from the process policy, in both directions. The rolling-to-checkpoint direction
is only unsafe where fit_checkpoint_context would read the boundary as an epoch
already in force and skip the reset's recall, and that needs _can_reset_epoch.

Threads it refuses -- a template that cannot render tools, --disable-tools, no
conversation archive -- compact through fit_rolling_context and record a rolling
boundary, so on a checkpoint-default server every later turn discarded it and the
boundary slid again. Measured on a stored boundary of 6: base restored 6, this
branch returned 0.

Each call site now computes _can_reset_epoch once and hands the same value to the
boundary read and to the fit.

* declare studio_tool_history on the token-count request

refreshContextUsage forwards the marker, but ChatCountTokensRequest only carried
it through extra = "allow", which coerces nothing. A client sending the JSON
string "false" reached _only_studio_tool_history as a truthy value and moved the
count onto the Unsloth tool path the completion never takes, so the context-usage
bar priced a different prompt. The model's own bypass_permissions field is
declared for the same reason.

* restore the constraint the renamed tool-history helper documented

Renaming _only_studio_memory_tool_history to _only_studio_tool_history replaced
its docstring with three lines that say what the marker is and no longer say why
the strict route exists: a replayed tool pair read as a client contract sends the
turn to the llama-server passthrough, which runs no context fit, so the epoch,
the carried-forward block and the automatic recall are gone one turn after the
compaction that created them. Put that back, and match the sentence case the rest
of the file and the api.ts field comments use.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* keep a rolling boundary off the checkpoint replay branch

A request that may not reset still takes the checkpoint REPLAY branch in
_fit_context under a checkpoint policy, so the rolling-origin boundary the
previous commit restored reached fit_checkpoint_context and read as an epoch
already in force. The fit returned checkpoint_started false, and
_archive_and_recall reads that as "already recalled" and injected nothing.
Measured at context_length 1800 with a stored boundary of 30: the reply lost the
archived turns the rolling fallback would have pulled back.

_sticky_compaction_state now returns the depth and whether a checkpoint reset
recorded it, mixed provenance across surviving rows counting as rolling since
min(boundaries) may pick either row. _fit_context takes that as
sticky_is_checkpoint and enters the replay branch only for a real epoch;
otherwise the count stays on the rolling fitter, which reports no
checkpoint_started and still recalls.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* discard a boundary cut with more extra trim than the request asks for

Phase one of fit_rolling_context re-applies the saved boundary before anything
else and returns as soon as the result fits, so an already-compacted chat that
moved from 25% extra room down to 10%, 5% or none replayed the deeper cut and
never reached the phase that reads the new ratio. Lowering the setting did
nothing at all, and the history the client had re-sent stayed dropped.

The persisted truncation now carries boundary_headroom_ratio beside
boundary_messages and boundary_anchor, written through one _boundary_metadata
helper so the three cannot drift apart. _sticky_compaction_state refuses a
rolling boundary recorded under a larger ratio than this request wants; a larger
request needs no refusal, since phase two moves the boundary out by itself. Rows
saved before the ratio existed carry no key and replay as they did, and a
checkpoint reset ignores headroom so its depth is never refused over it.

* refuse a replayed boundary on any change of extra trim, not just a cut

The previous commit only refused a boundary recorded under MORE headroom than
the request asked for, on the reasoning that phase two would widen a shallower
one by itself. It does not: phase one re-applies the saved count and phase two
runs only when the result still does not fit, so a shallower boundary that
already fits is just as inert. Measured on a 121-message transcript at
context_length 1600, a stored boundary of 86 gave dropped 86 under both 0.05 and
0.25, so raising the setting did nothing either.

Compare for equality instead. With the 5%-origin boundary of 86 above, a request
at 0.05 still replays it and a request at 0.25 recomputes to 94.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: mahiatlinux <[email protected]>
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