Repository navigation
Studio: add isolated multi-user workspaces - #10102
Imagineer99 wants to merge 138 commits into
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
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.
|
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 resultSame pytest invocation as
The three remaining failures are the identical set that already fails on the merge base ( The two production bugs1. An idle 2. For the record, the One cross-platform bugUsernames may contain dots and the workspace key kept them, so account What I verified
Still red, not mine to decide
Not fixed, flagged onlyWhile 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 Nice feature. The account layer and the setup-code handling in particular look well built. |
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.
…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.
|
Second pass on this one, focused only on things I could reproduce. Pushed 4 commits ( The chain that worried me most
The rest
What I measuredFull backend suite at head: Single user is unaffected. Still open, your callNot fixed because they are design decisions on your PR rather than clear bugs:
Happy to take any of those in a follow-up if you want them in this PR rather than after. |
There was a problem hiding this comment.
💡 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", | ||
| ]; |
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
| # A spawn starts with the legacy ContextVar default. Bind the account before | ||
| # any dynamic output/cache/database path is resolved. | ||
| _bind_worker_workspace(config) |
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| _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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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]] = {} |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| # 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
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.
There was a problem hiding this comment.
💡 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(); |
There was a problem hiding this comment.
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 👍 / 👎.
| if resident_text_model_is_foreign(): | ||
| return InferenceStatusResponse( |
There was a problem hiding this comment.
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]] = {} |
There was a problem hiding this comment.
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 👍 / 👎.
|
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.
There was a problem hiding this comment.
💡 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() |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
💡 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".
| 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; | ||
| } |
There was a problem hiding this comment.
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 👍 / 👎.
| if _hub_cache_entry_is_hidden_from_this_account(resolved_child): | ||
| continue |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
💡 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), |
There was a problem hiding this comment.
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()] |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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".
| run_in_workspace( | ||
| receipt.subject, | ||
| self._sink, | ||
| receipt, |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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 👍 / 👎.









Summary
Adds opt-in, owner-managed multi-user support to Studio.
UNSLOTH_STUDIO_HOME/workspaces/<stable-key>for chats, settings, credentials, uploads, projects, outputs, and runtime state.unslothowner 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
Validation
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.