Skip to content

Studio: add isolated multi-user workspaces - #10102

Closed
Imagineer99 wants to merge 138 commits into
unslothai:mainfrom
Imagineer99:feat/multi-tenant-workspaces
Closed

Imagineer99 wants to merge 138 commits into
unslothai:mainfrom
Imagineer99:feat/multi-tenant-workspaces

Conversation

@Imagineer99

@Imagineer99 Imagineer99 commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds opt-in, owner-managed multi-user support to Studio.

  • The owner creates accounts in Settings → Accounts; there is no public signup.
  • Studio issues a one-time setup code that expires after 60 minutes. The user enters it in the normal password field and must immediately choose a permanent password.
  • Each account gets a private workspace under UNSLOTH_STUDIO_HOME/workspaces/<stable-key> for chats, settings, credentials, uploads, projects, outputs, and runtime state.
  • Model downloads, caches, and compute remain shared to avoid duplicating large weights.
  • The existing unsloth owner keeps the legacy root layout and host-folder access. Managed users can browse only their workspace and deliberate shared model roots.

Isolation

The authenticated account is propagated through request and background-job context; storage roots are resolved from that context rather than by changing process-global environment variables.

The isolation pass covers galleries, tool sandboxes, MCP OAuth, local-model discovery, scans, recipes, RAG, training, exports, and API-usage state. Regenerating a setup code invalidates the previous code and unfinished first-login sessions.

Deliberate tradeoffs

  • Managed users currently sign in through the browser; the desktop shell remains owner-oriented.
  • There is no email invitation or recovery flow; recovery is owner-managed.
  • Deleting an account revokes access but retains its workspace for recovery. Secure deletion should be a separate explicit action.
  • Data is private per account, but model presence and hardware capacity are installation-wide.

Validation

  • Frontend: 6,245 tests, typecheck, production build, and ESLint passed.
  • Backend: 728 focused isolation/auth tests and 678 compatibility tests passed.
  • Playwright passed the full owner → setup code → forced password change → Alice/Bob isolation → deletion journey.
  • Labelled Playwright screenshots and facts
  • GitHub runner status

Review note

This is the current end-to-end implementation so the overall direction and UX can be reviewed together. Because the diff is large, I expect to extract it into smaller stacked PRs before merge.

I’m very open to changing the implementation, UX, desktop/browser split, or terminology based on feedback.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-02T14:57:33.485535Z c158487 New commits
ℹ️ 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.

@Imagineer99

Imagineer99 commented Aug 31, 2026 •

Copy link
Copy Markdown
Member Author

Playwright evidence — final rebased implementation

Captured by studio/frontend/e2e/multi-user-workspaces.spec.ts from the final PR head 02ee3f4f4d97aa2646083bad643b596263a964ce, against a fresh isolated UNSLOTH_STUDIO_HOME on the same Studio server. (The head includes pre-commit.ci's formatting-only follow-up.)

The scenario passed in 24.6s and asserts more than the screenshots show: the old setup code is rejected after regeneration, first login is forced through password setup, Alice sees Alice private launch plan, and Bob receives an empty thread list.

1. Normal username + password login

Studio login with username and password

2. Owner creates Alice; setup code is shown once

Owner account creation with one-time setup code

3. Account actions are compact and secondary

Managed account actions menu

4. Regeneration warns that the old code/session will stop working

Setup code regeneration confirmation

5. The setup code is entered as the first password, then Alice chooses her own

Forced first-login password setup

6. Owner sees account readiness without exposed credentials

Owner account list with ready workspaces

7. Same server, isolated workspaces

Alice sees her private chat Bob sees no Alice chat
Alice private workspace Bob isolated empty workspace

8. Destructive account action has a clear confirmation and retention copy

Delete managed account confirmation

Machine-checked Playwright facts
  • Login has an explicit username field.
  • Accounts exercised: unsloth, alice, bob.
  • Setup uses the normal password field and expires in 60 minutes.
  • A setup code is shown once; regeneration invalidates the previous code.
  • Alice thread titles: Alice private launch plan.
  • Bob thread titles: none.
  • Every step ran against the same server process.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

TrainingBackend.__init__ snapshotted current_workspace_subject() into
_active_workspace_subject, and owns_workspace() compared it with ==. The
singleton is built lazily by get_training_backend() in whichever request
context first touches it, so the idle backend was pinned to that account
(or to the legacy owner when warmed from the lifespan).

Every other account then got 404 from /api/train/progress and
/api/train/metrics, a silently ignored reset_training, and a permanent
"idle" status, before it had ever started a run.

Use None as the unclaimed sentinel and accept it in owns_workspace, which
is what DiffusionTrainingService already does. A real start still stamps
the owning subject in start_training_subprocess, so a second account still
cannot see or stop another account's live or just-finished run.
_request_sync called start_auto_sync() unconditionally. For the legacy
account that took the legacy branch and spawned a second worker, which
holds the process-global _worker_lock for its entire lifetime and is never
stopped. Every later worker then blocked on that lock.

In the suite the first test to enqueue a sync leaked a worker that starved
the rest, producing three 330s pytest-timeout hangs in
test_rag_linked_folders.py, plus a UNIQUE constraint failure on
rag_job_leases where the leaked worker raced a test's own lease insert.

The legacy account already has a worker started by the lifespan, which is
what the original comment says, so only managed workspaces need the lazy
start. tests/test_rag_linked_folders.py goes from three hangs to 86 passed
in 22s.
Usernames may contain dots (^[a-z0-9][a-z0-9._-]*$), and the key kept them,
so the account con.txt produced the directory con.txt-<digest>. Windows
resolves a reserved device name followed by any extension back to the
device, exactly as NUL.txt and NUL.tar.gz resolve to NUL, so its base name
is CON and the directory cannot be created. The same holds for prn, aux,
nul, com1-9 and lpt1-9 followed by a dot.

Fold dots into the separator so the key is always a single component
ending in the digest, which can never equal a device name. Usernames still
map to distinct keys because the digest hashes the original value, so a.b
and a-b share a readable prefix but not a key.

Worth changing now rather than later: the key is the on-disk directory
name, so altering it after installs have managed workspaces would strand
them.
hub/services/datasets/local.py replaced the module constants
DATASET_UPLOAD_DIR and LOCAL_DATASETS_ROOT with functions, which is the
right move because the constants captured a path at import time. Eight
monkeypatch sites still targeted the removed names and raised
AttributeError at setup.

Patch dataset_uploads_root / recipe_datasets_root instead, which are still
module-level in local.py, so the tests keep isolating without
reintroducing import-time capture. Two of the three affected modules live
under hub/tests/, which the backend CI test selection does not collect, so
those failures were latent.

Also drop the dead model_config.outputs_root patch, since scan_trained_models
now resolves through resolve_output_dir and the storage_roots patch on the
line above is the whole seam; and re-anchor the write-lock ordering
assertion, whose literal cleanup_orphaned_runs() became a per-workspace
run_in_workspace call. The ordering it guards still holds.
The import-hoist lint job fails on it as a BLOCKER: added but never used.
ManagedUserListResponse and CreatedManagedUserResponse are the two the
route handlers actually reference.
OwnerServerAccessSections held a skeleton until fetchCurrentAccount()
resolved and replaced the whole panel with an error if it rejected. The
settings-tab browser smoke drives the panel without an authenticated
session, so /api/auth/me failed, the error branch rendered, and the LAN
address rows were never present: the Remote and LAN tab went from 131
elements at the merge base to 5.

Draw the sections unless the role comes back definitively non-admin, and
remember the answer so switching between the API Keys and Remote and LAN
tabs does not refetch. This is presentation only. Every route behind these
controls is independently gated by _require_install_admin, so drawing them
before the role is known grants a managed account nothing.

tests/studio/playwright_settings_tabs.py now reports 131 elements again
and exits 0.
@danielhanchen

Copy link
Copy Markdown
Member

I pushed six commits to this branch. Two are real production bugs, the rest clear the red CI. I also ran a fairly wide simulation pass; numbers and method below so you can check my working.

Differential test result

Same pytest invocation as studio-backend-ci.yml, run in two worktrees of one clone, same venv, same machine:

merge base 1d2679f4f this branch before after these commits
failed 3 18 3
errors 0 9 0
passed 35823 35823 35850
wall 11m35s 18m46s 11m25s

The three remaining failures are the identical set that already fails on the merge base (test_offload_planner_seam, test_mcp_training_start_guard which is FastMCP drift, test_conversation_archive), so they are not yours.

The two production bugs

1. An idle TrainingBackend claimed the first caller's workspace. __init__ snapshotted current_workspace_subject() and owns_workspace() compared with ==, but get_training_backend() builds the singleton lazily in whichever request context touches it first. Every other account then got 404 from /api/train/progress and /api/train/metrics, a silently ignored reset_training, and a permanent idle status, before ever starting a run. DiffusionTrainingService already had this right with a None unclaimed sentinel, so I matched it. A started run still stamps its owner, so the isolation you built is unchanged. This is what the 9 test_training_status_terminal failures were pointing at.

2. _request_sync spawned a second linked-folder worker for the legacy account. That worker holds the process-global _worker_lock for its whole lifetime and is never stopped, so every later worker blocked on it. That was the three 330s timeouts in test_rag_linked_folders.py and the rag_job_leases UNIQUE failure, where the leaked worker raced the test's own lease insert. Your comment on that line already says the legacy account has a startup worker, so I limited the lazy start to managed subjects. That file goes from three hangs to 86 passed in 22s.

For the record, the rag_job_leases PRIMARY KEY (kind, job_id) is fine as is. rag.db is already per workspace, so it is effectively subject scoped and needs no migration.

One cross-platform bug

Usernames may contain dots and the workspace key kept them, so account con.txt mapped to directory con.txt-<digest>. Windows resolves a reserved device name followed by any extension back to the device, exactly as NUL.txt and NUL.tar.gz resolve to NUL, so its base name is CON and the directory cannot be created. Same for prn, aux, nul, com1-9, lpt1-9. I fold dots into the separator so the key is always one component ending in the digest. Distinct usernames still get distinct keys because the digest hashes the original value. Worth doing now rather than after anyone has managed workspaces on disk.

What I verified

  • Backwards compatibility. I built a populated single-user install with merge-base code (chats, settings, encrypted credentials, an external scan folder, dataset uploads, RAG, outputs, exports, galleries), then upgraded in place to this branch. 18/18 checks: nothing moved, nothing changed content, nothing migrated under workspaces/, the credential still decrypts, the external scan folder is still visible to the owner, and is_admin promoted correctly. The owner keeping the historical root layout is the thing that makes this safe, and it holds.
  • Browsers. The multi-user journey passes on chromium, firefox and webkit, each with its own backend and UNSLOTH_STUDIO_HOME. That covers Chrome and Edge via Chromium and Safari's engine via WebKit, though WebKit is not branded Safari. They cannot share one backend because the spec rotates the owner bootstrap password, which is worth knowing if you ever add engines to CI. playwright.config.ts has no projects, so I selected engines with --browser; adding a projects block would make this a one-liner in CI.
  • Windows path budget. workspaces/<key>/ costs up to 57 characters. Worst realistic managed path I could construct is 193 of the 260 MAX_PATH budget, and Studio opts into neither longPathAware nor \\?\ prefixing. Fine today, but managed users have less headroom than the owner, who is unaffected. User-named run and export directories are unbounded and could cross it, which was already true before this PR.
  • Frontend: typecheck, 6245/6245 unit tests, build, and the settings-tab smoke all pass.

Still red, not mine to decide

npm provenance fails on [email protected] arriving as a transitive install-script dependency of the new @playwright/test. That job wants an explicit maintainer and version sign-off, so I left it to you.

Not fixed, flagged only

While reviewing I found isolation gaps beyond the six Codex raised. I deliberately did not touch them since they are design calls on your PR, but the highest-signal ones: the /p preview routes carry no auth dependency and resolve in the owner's outputs_root(), so a managed user whose run name collides with an owner run gets an unauthenticated link to the owner's checkpoint; the keyless guard _require_a_credential_of_its_own was not extended to the four new account endpoints, so with keyless enabled an unauthenticated caller resolves to unsloth and passes require_admin; loop.run_in_executor does not copy the ContextVar, so the run-event SSE in chat_generation_runs.py and research_runs.py polls the owner's studio.db while the to_thread call on the next line polls the caller's; and video generation starts on a raw thread, so a managed user's clip lands in the owner's gallery. Happy to write any of these up properly or send them as a follow-up if useful.

Nice feature. The account layer and the setup-code handling in particular look well built.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 3 commits September 1, 2026 02:35
My earlier commit stopped _request_sync from lazily starting a worker for the
legacy account. That was the wrong layer. start_auto_sync already refuses to
spawn when this workspace's thread is alive and unstopped, so the call was
already a no-op on a healthy server, and skipping it only removed a self-heal
path: if the lifespan worker never started because rag was unavailable at boot
or the post-warm stood down, or if the worker died, a legacy sync would sit
pending until the next restart.

The leak is a test artifact. Several tests drive folder_sync._worker directly
without registering it as _thread, so start_auto_sync sees no live worker and
spawns a second one, which then holds the process-global _worker_lock for its
whole lifetime and starves every later worker.

Restore the unconditional call and contain it in the suite: an autouse fixture
stops any worker a test started, and neutralises the lazy start except where
start_auto_sync is itself under test, marked with real_auto_sync. These are
reconciliation state-machine tests that call reconcile_folder and _worker
explicitly, so a background worker consuming the queue first is exactly the
race that made them flaky.

tests/test_rag_linked_folders.py: 104 passed, no timeouts.
The module-level cache I added outlived the account it was read for. Signing
out is an SPA navigation rather than a reload, so after a managed account
opened Settings and the owner then signed in, the owner was shown the
"only the installation owner can change this" card and could not reach Remote,
LAN or keyless access until a hard refresh. The mirror case showed a managed
account controls that 403 on every read.

Refetch per mount. One /api/auth/me per tab switch is cheaper than a
cross-account correctness hazard. The optimistic draw, which is what restores
the merge-base behaviour the settings-tab smoke checks, is unaffected.

Also log the failed role lookup instead of swallowing it silently, so a
genuinely broken /api/auth/me is diagnosable rather than leaving every account
looking at owner controls.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…r PR unslothai#10102

The four new /api/auth/users endpoints only required an admin subject, and a
keyless caller resolves to the owner admin, so an unauthenticated request could
list accounts, mint a setup code and delete an account. They now carry
_require_a_credential_of_its_own like the other credential-bearing routes.

Deleting an account left its workspace in place, and workspace_key is derived
from the username, so recreating the name inherited the previous holder's chats
and encrypted provider keys. The directory is now moved aside on delete.

/api/shutdown, /api/llama/update and /api/llama/backend act on the whole
install, so they take a new require_install_admin dependency.

resolve_export_write_dir passed absolute paths through for every subject, which
is a write primitive into any directory the backend can reach. It stays open
for the owner and is held to the account's own exports root otherwise.
studio.db is per account now, but the memos in front of it are process global,
so within the TTL one account's VRAM budget, model memory, auto-switch and
embedding model settings were served to the next caller. They are now keyed by
workspace subject, as is the OpenAI model catalog cache, whose scan includes
scan-folder models that are private per account.

install_latest_transformers_route mutates the shared runtime, so it takes
require_install_admin.
…#10102

The video generate worker and the workspace-delete collector ran on bare
threads, which lose the ContextVar, so they resolved the owner's gallery and
sandbox instead of the caller's. Both now bind the calling subject.

The two SSE event waits use loop.run_in_executor, which does not copy context
either, so the pool thread waited on the owner's studio.db while the snapshot
beside it read the caller's. They go through copy_context().run.

MCP session keys were (url, headers, scope), and scope carries client-chosen
session ids, so two accounts presenting the same one shared a live stdio child.
The subject is appended to the key.
@danielhanchen

Copy link
Copy Markdown
Member

Second pass on this one, focused only on things I could reproduce. Pushed 4 commits (45f72b4..2eabf96).

The chain that worried me most

_authenticate_without_credential resolves a keyless caller to the owner admin, and the four new /api/auth/users endpoints only checked require_admin. On an install with no password set that meant an unauthenticated request could list accounts, mint a setup code for one, or delete one. Combined with the second item below it is a cross-account read: delete a target account, recreate the username, inherit the workspace, log in with the setup code you were just handed.

  • Account management now also depends on _require_a_credential_of_its_own, matching change_password and logout.
  • delete_managed_user moves the workspace to <key>-deleted-<timestamp> instead of leaving it for the next holder of the name. Files are kept for recovery, just not inherited.

The rest

  • resolve_export_write_dir passed absolute paths through for every subject. Kept open for the owner, since that is what [Bug] GGUF export unnecessarily copies finished GGUF files to .unsloth directory in C: drive, regardless of the local source/destination addresses set by the user. This also causes WinError 112 on systems low on free space on drive C: #6082 asked for, and held to the account's own exports root otherwise.
  • /api/shutdown, /api/llama/update, /api/llama/backend and install_latest_transformers act on the whole install, so they take a new require_install_admin.
  • The memos in front of studio.db are process global: VRAM budget, model memory, auto switch, embedding model settings and the OpenAI catalog cache all served one account's value to the next for the length of the TTL. Keyed by subject now.
  • The video generate worker and the workspace-delete collector ran on bare threads, which drop the ContextVar, so they wrote the owner's gallery and swept the owner's sandbox. Both bind the calling subject. The video one binds inside the existing functools.partial rather than via workspace_thread, so the worker target and kwargs keep the shape test_video_backend.py asserts.
  • Both SSE event waits use loop.run_in_executor, which does not copy context either, so the pool thread waited on the owner's studio.db while the snapshot beside it read the caller's. Now copy_context().run.
  • MCP session keys were (url, headers, scope) and scope carries client-chosen session ids, so two accounts presenting the same one shared a live stdio child. Subject appended, not prepended, because close_stdio_sessions matches on k[0]/k[1].

What I measured

Full backend suite at head: 2 failed, 35855 passed, 233 skipped. Both failures (test_offload_planner_seam, test_mcp_training_start_guard) fail identically at the merge base, so the set is unchanged. ruff, verify_import_hoist.py, enforce_kwargs_spacing.py and ast.parse on every changed file are clean.

Single user is unaffected. workspace_root() returns studio_root() for the owner, the 62 storage roots are byte-identical to base for that subject, and a populated legacy install seeded with merge-base code and upgraded in place passes 18/18 checks including the partially-migrated auth_user.is_admin case. The 168 inference test modules are identical base vs head.

Still open, your call

Not fixed because they are design decisions on your PR rather than clear bugs:

  • The TrainingBackend workspace claim is set in start_training_subprocess and never released, so after the first run ends other accounts still see idle/404 for a backend nobody is using.
  • ResearchSupervisor and the chat-generation lease sweeper run against the owner's DB regardless of who queued the work.
  • chat_generation_runs_db keeps a process-global _schema_ready flag while the DB path is now per workspace.
  • _shutdown_subprocess has call sites with no owns_workspace guard.
  • /api/lan-access/port has no admin gate.
  • The /p preview routes bind no subject, and the preview signature is identical across subjects.

Happy to take any of those in a follow-up if you want them in this PR rather than after.

@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: e6977d455c

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

"unsloth_chat_active_preset",
"unsloth_chat_active_preset_source",
"unsloth_chat_system_prompts",
];

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 Clear per-model configurations when switching accounts

When Alice signs out and Bob signs in through the same SPA, this purge omits unsloth_model_configs. The origin-wide store in features/model-picker/model-config/per-model-config.ts is therefore reused by Bob and contains model-keyed chatTemplateOverride, llamaExtraArgs, context, GPU, and quantization settings; loading the same model silently applies Alice's configuration to Bob's inference and can expose Alice's custom template or invalidate Bob's results. Include this key in the account-scoped purge and reset any hydrated readers during the transition.

Useful? React with 👍 / 👎.

# is given, so an absolute path was a read of another account's private
# checkpoint, exportable and pushable from there. Before ownership is
# assigned and before the worker spawns.
_reject_uncontained_local_path(request.checkpoint_path, "export")

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 Contain custom imatrix inputs for managed exports

Apply this containment policy to ExportGGUFRequest.imatrix_path as well. After a managed caller loads an allowed checkpoint, /export/gguf forwards that caller-controlled path unchanged to the export subprocess, where the GGUF exporter opens it as the importance-matrix input; an absolute path to another workspace's private calibration matrix is therefore readable and usable in the caller's exported model even though the checkpoint path itself is confined. Reject uncontained local imatrix paths before dispatching the worker.

Useful? React with 👍 / 👎.


Single-user installs are unaffected: the only account there is the owner.
"""
return is_installation_owner(subject)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reject private GGUF image URLs for managed callers

Apply this private-host policy to multimodal URLs sent to the local GGUF backend. For a managed caller using a loaded vision GGUF, _preflight_image_for_switch() deliberately permits remote URLs and _openai_messages_for_gguf_chat() forwards each image_url unchanged to the local llama-server, which fetches the image from the backend host; a request can therefore name a loopback or LAN URL and make the server probe or ingest an internal image despite the restriction enforced for provider and MCP destinations. Validate and pin every hop before forwarding, or require data URLs for managed accounts.

Useful? React with 👍 / 👎.

Deletion quiesces what is running, which is a point-in-time answer. A request
that authenticated a moment earlier and then paused before reaching the code
that starts work is invisible to that sweep: it resumes afterwards, opens the
account's databases under the same username-derived pathnames, and recreates
the directory the retirement just renamed away. If the name has since been
recreated, those writes land in the new account's workspace.

So bind a generation as well as a subject. delete_managed_user bumps the
account's generation before the sweep, and workspace_root refuses a binding
older than the bump. That one function builds every per-account root, so it is
the single place a stale request stops. Nothing that never bound explicitly is
affected, the legacy owner included, and a binding taken after the deletion is
current, so a recreated account works normally.

The refusal is a RetiredWorkspaceError, answered as 401 rather than a 500: the
credential the request presented genuinely no longer exists.
@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: b776c81b8d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

that has its own token still uses it.
"""
return not via_api_key
return not via_api_key and is_installation_owner(current_subject)

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 Apply ambient-token policy to audio download plans

Apply this owner-only ambient-token policy to routes/inference.py::audio_download_plan as well. When a managed caller omits LoadRequest.hf_token, that route passes None to native_audio_download_plan(), whose HfApi(token=None) falls back to the backend's cached/process Hugging Face credential. Naming one of the owner's private audio repositories therefore returns its file names, revisions, and sizes in the download plan; managed callers should pass an explicit account-owned token or an anonymous-auth sentinel.

Useful? React with 👍 / 👎.

Comment on lines +3687 to +3689
# A spawn starts with the legacy ContextVar default. Bind the account before
# any dynamic output/cache/database path is resolved.
_bind_worker_workspace(config)

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 Contain TensorBoard paths in the MLX worker

On Apple Silicon, a managed training request with enable_tensorboard=true can supply an absolute tensorboard_dir: _run_mlx_training() forwards that raw value to SummaryWriter(log_dir=...), unlike the regular worker path that passes it through resolve_tensorboard_dir(). Binding the workspace here therefore does not prevent the MLX worker from creating event files in another account's workspace or any other host directory writable by the backend; normalize and contain this path before starting the MLX writer.

Useful? React with 👍 / 👎.

bypass_permissions is an ordinary request field, so a managed account could
set it and get python and terminal with the safety analysis, the command
blocklist and the resource caps all switched off, running as the backend OS
user. Moving the working directory under the account's workspace is not a
boundary once those are the things being disabled: an absolute path reads any
file the server can reach, another workspace or auth.db included.

Clamped in execute_tool, which is the one function every tool loop reaches the
tools through, so no loop or route can be updated and miss it. Clamped rather
than refused, so a managed account keeps its tools and keeps the sandbox. The
owner is unchanged, which is what a single-user install has always done.
@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: 52ab91b13f

ℹ️ 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 +33462 to +33464
if request.base_repo:
# Fetched the same way, under a separate identifier.
_reject_private_hub_repo_without_an_account_token(request.base_repo, request.hf_token)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Contain local diffusion base repositories

Apply _reject_uncontained_local_path to request.base_repo as well. For a managed caller, _reject_private_hub_repo_without_an_account_token explicitly returns early for path-shaped identifiers because it assumes containment was already enforced, but only model_path receives that check. Since DiffusionBackend accepts a local pipeline directory as the companion base, a caller can supply another workspace's absolute path here and have its VAE, text encoders, and other weights loaded by the backend.

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 d14ca13, and on the video load and both download plans as well. The reasoning is exactly right: the credential helper returns early for a path-shaped value because containment is supposed to own that case, so applying it to model_path alone left base_repo with neither check. Both backends read a local base repo's pipeline components, so that was a load of another workspace's VAE and text encoders past the guard.

Comment on lines +275 to +277
if request.base_repo:
# The base repo is fetched the same way and is a separate identifier.
_reject_private_hub_repo_without_an_account_token(request.base_repo, request.hf_token)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Contain local video base repositories

Apply the local-path containment check to request.base_repo, not only to request.model_path. When a managed caller supplies an absolute companion-pipeline path, this credential helper deliberately skips it as local, while the video backend accepts local base repositories and reads their pipeline components. This allows loading model data from another account's workspace despite the new model-path guard.

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 d14ca13, together with the image half, which had the same gap. Containment now runs on base_repo at /video/load and /video/download-plan, beside the model_path check.

Comment on lines +33455 to +33459
_reject_uncontained_local_path(request.model_path, "load")
# And the same credential rule the video load already applies. A Hub id is
# deliberately allowed through the containment check above, but
# DiffusionBackend.load_pipeline normalises a missing token to None, and
# huggingface_hub then sends the installation's implicit login, so a managed

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 Enforce the token policy on image download plans

Apply this managed-account credential check to diffusion_download_plan before it calls planner.download_plan. When a managed caller omits hf_token, the planner passes None through its Hugging Face metadata and file-size probes, which can fall back to the backend's cached/process credential; naming an owner-private image repository can therefore return its exact dependency files, revisions, and sizes even though the subsequent /images/load request is rejected here.

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.

Already closed at head, in 3d29b16, which landed alongside the video plan fix and covers /images/download-plan the same way: containment plus the credential question on model_path and base_repo, before validate_load_request or planner.download_plan reads anything. The plan and the load now refuse the identical pick.

# cache is shared by design, so a private dataset one account fetched with its
# own token is on disk for the whole box; this is what tells its downloader
# apart from an account that merely read the repository name off the inventory.
_dataset_downloaders: dict[str, set[str]] = {}

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 Persist private dataset access grants

Do not keep the only proof of private-dataset ownership in this process-local dictionary. After a server restart, _dataset_downloaders is empty, so caller_may_read_cached_dataset rejects the managed account that originally downloaded the dataset—even when the request carries that account's valid Hub token—and /cached hides it while cached format previews refuse its rows. This makes legitimately downloaded private datasets unusable from cache after every restart, particularly when Studio is offline; persist the grant per workspace or authorize the supplied credential before denying access.

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 d14ca13, and thank you for this one: it is the only item in this review that is a regression for the legitimate user rather than a gap against an attacker, which makes it the one most likely to have shipped unnoticed. The account that paid for a private dataset with its own token lost its cached rows on the next restart, and offline there was no Hub call left to recover them.

The grant is now written into that account's own studio.db, so it survives a restart and is not readable from another workspace. forget_workspace clears it explicitly rather than relying on the retirement rename, since that rename is allowed to fail and a grant left behind is one a namesake reads back. A grant that cannot be written is not fatal: the next download re-earns it.

Comment on lines +1325 to +1331
# Before anything is reserved or torn down. The worker runs as the same OS
# user, so repository code it loads reaches every account's files.
_reject_remote_code_from_a_managed_account(request.trust_remote_code)
_reject_wandb_without_an_account_token(
request.enable_wandb, getattr(request, "wandb_token", None)
)
_reject_ambient_s3_for_a_managed_account(request.s3_config)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Authorize cached datasets before training from them

Add a managed-account authorization check for dataset_local_path and dataset_snapshot_path alongside these new start guards. Later, _preflight_hf_dataset_request trusts either caller-controlled cache hint when training_dataset_cache_pin finds a matching shared-cache layout and returns before the anonymous Hub verification; the worker then receives that snapshot path unchanged. A managed caller who knows or enumerates another account's private dataset repository and snapshot path can therefore train on its cached rows without possessing its Hub token.

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 d14ca13. Correct that the pin was the hole: dataset_local_path and dataset_snapshot_path are both caller-supplied, and a match against the shared-cache layout returned before the anonymous Hub verification, so the worker got the snapshot path unchanged.

Both pin returns now ask caller_may_read_cached_dataset, which is the same question the dataset listing and preview routes ask, so training cannot reach rows those two would refuse. The offline branch gets it too, since that is where there is no Hub call to fall back on.

danielhanchen and others added 6 commits September 2, 2026 09:27
The Hub cache one is the load-path hole. A cache snapshot lives under
cache_root(), so it satisfied the generic "inside an Unsloth data root" test
and returned from containment before the credential question was ever asked.
The path is predictable and the folder browser hands it over, so a managed
account could name another account's private weights and have them loaded.
The repository identity is now recovered first, ahead of that test.

The rest are the same question asked where it was missing. Both download-plan
routes read the target's checkpoint names and pipeline config, so an absolute
path from another workspace came back described as a plan even though the load
would refuse it. tmp_root is keyed on workspace_key like the persistent roots,
so unstructured seed chunks were inherited by a recycled name. Recipe provider
and MCP endpoints reach Data Designer verbatim and it connects to them, so
they get the private-address policy the saved providers already have. And the
folder browser no longer lists cache directories whose repository this account
could not load, which is what supplied the path in the first place.
Thirteen tests each read a function's source and asserted that a guard call
appears in it. They pin something worth pinning, since a guard dropped from a
route is invisible until somebody reports it, but as thirteen copies of one
assertion they drifted apart and broke twice when a formatter moved an anchor
they matched on.

One parametrised table instead, with the same fragments and the same coverage.
Ordering properties stay as their own tests: "the guard runs before the
fallible work" is a different claim and a substring cannot express it.
Comments and docstrings only, on the lines this branch added. Every twenty-line
rationale that survived is the same fact in one or two lines, and nothing that
names a concrete failure was dropped: the reason a guard sits where it does,
the reason a sentinel is False rather than None, and the ordering constraints
are all still stated.

Verified with comment_tools.py check --strip-docstrings, which compares a
code-only signature of each file: 18 of 18 unchanged.
…estart

base_repo took the credential check but not containment, and the credential
helper returns early for a path-shaped value precisely because containment is
supposed to own that case. Both backends accept a local pipeline directory as
the companion base and read its components, so an absolute path there loaded
another workspace's weights past the model_path guard. Contained now on both
loads and both download plans.

The dataset grant was worse than an isolation gap, it was a regression for the
legitimate case: the only record of who downloaded a private dataset lived in a
process dictionary, so after a restart the account that fetched it with its own
token was refused its own cached rows, and offline there was no Hub call left
to recover it. The grant is now written into that account's own studio.db.
Retirement clears it explicitly rather than relying on the rename, which is
allowed to fail.

Training pinned the cache from two caller-supplied hints and returned before
Hub verification, so naming another account's private dataset and its snapshot
path trained on rows this account never had a token for. Both pin paths, online
and offline, now ask the same question the dataset routes ask.

@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: 742b7b29b9

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

// clearing the incoming account's keys would take them straight back out.
if (isOwner) releaseLegacyQuarantine();
if (!changed) return false;
announceAccountChange();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reset pending chat media on account changes

When Alice attaches audio, signs out without sending, and Bob signs in through the same SPA, this event does not reset useChatRuntimeStore, which retains Alice's raw pendingAudioBase64 and filename. The newly mounted composer has no visible audio attachment, but extractAudioBase64() in chat-adapter.ts falls back to that runtime value, so Bob's next message can silently submit Alice's recording under Bob's session. Add an account-change reset for pending chat media and other account-owned runtime state.

Useful? React with 👍 / 👎.

Comment on lines +16725 to +16726
if resident_text_model_is_foreign():
return InferenceStatusResponse(

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 Apply resident-model redaction to model listings

When another account has loaded a private local text checkpoint, this guard hides it from /api/inference/status, but authenticated callers can still retrieve it through routes/models.py::list_models. That route appends inference_backend.models keys directly and uses llama_backend.model_identifier as the response ID, exposing the other account's absolute workspace path and model identity. Apply the same resident_text_model_is_foreign() policy to the model-listing endpoints before returning resident entries.

Useful? React with 👍 / 👎.

# The snapshot lands in the install-wide cache and /audio/stt/load carries no Hub
# credential, so this is what tells a private repo's own downloader apart from an
# account that merely learned its name.
_STT_MODEL_DOWNLOADERS: dict[str, set[str]] = {}

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 Persist private STT download grants

When a managed account downloads a private custom Whisper repository, _STT_MODEL_DOWNLOADERS is the only evidence that the cached snapshot belongs to that account. After a backend restart this dictionary is empty, and /audio/stt/load carries no Hub token, so _reject_private_stt_model_from_another_account() performs an anonymous check and rejects the legitimate downloader; the already-downloaded model is unusable from cache, especially offline. Persist the grant per workspace or authorize a request-supplied account token before denying the load.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member

The direction and the isolation model look right, and the per-subject storage roots in studio/backend/auth/storage.py are the part I want to keep. Agreed on splitting it: could you land the workspace-key plus storage-root layer first, then the accounts UI and the per-route gates on top?

Twelve reported items, six distinct bugs, so they are fixed as classes.

The grant that dies with the process was reported twice, for datasets and now
for dictation models: the account that downloaded a private repo with its own
token was refused its own cached copy after a restart, and offline there was no
Hub call left to re-earn it. Both now use one durable per-workspace store.

Two more caller-supplied paths reached a worker verbatim, the importance-matrix
input and the MLX TensorBoard directory, the latter bypassing the resolver the
non-MLX path already used. The audio download plan asked for no token, so it
answered for an owner-private repo on the installation's login. The model
listing published the identity, and for a local checkpoint the absolute path,
that the status route already redacts.

Image URLs on the local GGUF path are fetched by llama-server FROM THE BACKEND
HOST, which makes them the same outbound request providers and MCP targets are
policed for. Policed once, where every image part crosses.

The browser purge is now inverted. An allowlist missed four stores in one round
(downloads, per-model configs, recipe databases, pending chat media) and would
have kept missing them, so every key this app owns is cleared unless it is
listed as chrome, the account-scoped IndexedDB databases are deleted, and an
account change reloads the document rather than resetting the stores somebody
remembered to enumerate. The cross-tab guard compared the storage event against
localStorage, which the event has already updated, so it never fired once.

And the password-change step no longer re-notifies with default_username, which
is the owner: for a managed user's first login that moved the browser marker to
the owner and released the quarantined legacy data into their session.
_retire_workspace_directory held seven copies of the same five lines: a lazy
import, one call, a warning. Eight of those registries were reported one at a
time, over eight rounds, because nothing in the code said out loud that a
per-account registry has to be retired with the account. The table says it, and
it is the one place a new one gets added.

Still imported by name at call time, so a reduced install where one of those
modules will not import can still delete an account, and still never fatal for
the same reason. That trade turns a typo or a rename into a logged warning
nobody reads while the state it should have cleared is inherited by the next
holder of the name, so a test resolves every entry to a real callable.

@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: 064fe71fb2

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

def tmp_root() -> Path:
return Path(tempfile.gettempdir()) / "unsloth-studio"
root = Path(tempfile.gettempdir()) / "unsloth-studio"
subject = current_workspace_subject()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Fence every per-account root against stale bindings

When a request authenticates before its account is deleted, note_workspace_retired() makes only workspace_root() reject the stale binding; tmp_root() reads the subject directly and therefore bypasses that fence. For example, an unstructured-seed preview can pause after producing plaintext chunks, survive the deletion sweep because it is not a registered workspace job, and then recreate the retired username-derived temporary tree and write its parquet cache after the tombstone has been cleared, allowing a recreated account name to inherit predecessor state. Call assert_workspace_binding_current() here and in project_workspaces_root(), which has the same direct-subject bypass.

Useful? React with 👍 / 👎.

Two ways a deleted account's workspace directory came back with the name still
released, so the next holder of a reusable username opened it.

The retirement asked whether the account still had running jobs after the
rename. Those probes open the account's own research_runs.db and rag.db, and
both create their parent on connect, so the question rebuilt the tree and then
answered that nothing had rebuilt it. Clearing the durable grants did the same
through studio.db. Both now run before the rename, where the write lands in the
tree that is about to be moved and still does its job if the rename fails, which
is the case grant clearing exists for. The post-rename check is now path
existence alone, with no database opens, so a root that is back is one something
else rebuilt.

The other way is a worker that carries its subject as data and binds its
workspace at execution rather than at dispatch. Dispatched before the deletion
and run after it, it binds at the current generation, so the fence does not catch
it, and it recreates the directory after a retirement that had already succeeded
and cleared the tombstone. Which workers can do that is not an enumerable set, so
create_managed_user now retires whatever is on disk under the name's keys instead
of trusting the tombstone alone.
…rney

The transition logic depends on three platform behaviours a storage fake cannot
answer: localStorage.key enumerating a key nobody listed, a same-document
removeItem firing no storage event while a cross-document write fires one that
already reads back as the new value, and deleteDatabase making progress with a
live connection open. The spec pins all three, and it is cheap enough to sit in
the job that already has a backend 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: d6615cb000

ℹ️ 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 +246 to +250
for (const key of storedKeys()) {
if (!ACCOUNT_SCOPED_STORAGE_PREFIXES.some((prefix) => key.startsWith(prefix))) continue;
const value = readItem(key);
if (value !== null) held[key] = value;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve every legacy store before the first managed login

When a managed account is the first to sign in after an upgrade, this loop preserves only the explicitly listed key families, but purgeAccountScopedBrowserState() subsequently deletes every other app key and both recipe IndexedDB databases. Consequently, pre-account owner data such as unsloth_model_configs, recipes, execution rows, and generated datasets is permanently lost rather than restored when the installation owner later signs in; quarantine all account-scoped keys and databases, or migrate them into owner-namespaced storage before purging.

Useful? React with 👍 / 👎.

Comment on lines +2153 to +2154
if _hub_cache_entry_is_hidden_from_this_account(resolved_child):
continue

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 Apply private-repo filtering to every cache inventory

This access check is applied only while constructing /browse-folders; a managed account can still call /api/models/cached-gguf, /api/models/cached-models, or their /api/hub equivalents, whose scanners iterate every shared-cache repository without an authorization predicate and return private repo_id, cache_path, and sometimes load_id values. Thus another account's private repository names and exact snapshot paths remain enumerable even though this browser view hides them; filter all shared-cache inventory rows through the caller's repository-access policy as well.

Useful? React with 👍 / 👎.

…provide

state_for_tests and reset_registry_for_tests replaced four copies of
monkeypatch.setattr(search_images, "_registry", {}), which is correct for setup
and lost something nobody was asking for: monkeypatch put the original dict back
afterwards, so entries a test seeded never outlived it. The seam clears at setup
only, and the registry is one in-memory bucket per account for the life of the
process, so a seeded entry survived into whatever xdist scheduled next on that
worker. That test's clear then took a non-empty snapshot, and the replaying half
of a concurrent retry saw unreaped image ids and reaped as well.

That reproduces exactly, without threads or load, by running
test_a_replay_finishes_a_reap_the_original_clear_died_before_running before
test_the_replay_bit_comes_from_the_clear_transaction: two reaps at head, both
pass at the merge base. In a full run it needed the default xdist distribution to
put them on one worker in that order, which is why it read as intermittent.

Cleared after every test rather than at the four call sites, so a test added
later cannot reintroduce it, and only when the module is already imported so the
suites that never load it pay nothing.

@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: c158487f80

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

current_subject: str = Depends(get_current_subject),
# Owner only: this picks the executable the shared inference backend launches,
# and a managed account's workspace is writable by that account.
current_subject: str = Depends(require_install_admin),

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 Gate the llama.cpp path read for managed accounts

Apply the same installation-admin dependency to GET /api/settings/llama-cpp-path, which still accepts every authenticated managed account. Its response includes the configured absolute path, resolved_binary, and controlling environment-variable name, so when llama.cpp is installed under the owner's home or another private host directory, a managed caller can disclose those host paths even though the corresponding write and the analogous Hugging Face cache read are owner-only.

Useful? React with 👍 / 👎.

return os.path.normpath(os.path.abspath(os.path.expanduser(p)))

raw_roots = [studio_root(), outputs_root(), exports_root(), cache_root()]
raw_roots = [workspace_root(), outputs_root(), exports_root(), cache_root()]

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 Scope export-size cache entries by authorization

In a multi-account server, _EXPORT_SIZE_CACHE is keyed only by the model identifier and is consulted before hf_token is used. If one account requests /api/models/export-size for a private or gated Hub repository with its own token, a later managed account can request the same repository without credentials and receive the cached weight size, parameter count, and source instead of the Hub denying the lookup; key this memo by an authorization/token fingerprint or reauthorize before serving a hit.

Useful? React with 👍 / 👎.

@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: c158487f80

ℹ️ 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 +240 to +243
run_in_workspace(
receipt.subject,
self._sink,
receipt,

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 Fence queued receipts against account recreation

When an API-usage receipt remains queued while its managed account is deleted and recreated—particularly while the writer is retrying a busy database—this call creates a fresh workspace binding at execution time, after the deletion generation was bumped. The old receipt can therefore be written into the successor account's studio.db, where profile statistics expose the predecessor's model identifier and usage totals. The deletion sweep clears API-monitor entries but does not drain or invalidate this writer queue, so receipts need to retain and verify their admission generation or be purged during retirement.

Useful? React with 👍 / 👎.

clear_grants(_GRANT_KIND, subject)


def caller_may_read_cached_dataset(repo_id: Optional[str]) -> bool:

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 Apply cached-dataset authorization to local options

Apply this access policy to hub/routes/datasets.py::get_local_dataset_options. A managed caller who knows a private repository ID or its predictable shared-cache path can currently call /api/hub/datasets/local-options; local_dataset_options() resolves that cache and reads its dataset_info/snapshot metadata to return the private config and split names without invoking caller_may_read_cached_dataset(). This bypasses the authorization already used by the cached inventory and format-preview paths.

Useful? React with 👍 / 👎.

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