Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio backend performance: five superlinear paths in the routes and data layer (#8499)

Daniel Han87cd048077f8
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 4df402ed506..196b770b8b1 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -7092,6 +7092,15 @@ class LlamaCppBackend:
for _ in range(alen):
n = struct.unpack("<Q", f.read(8))[0]
raw = f.read(n)
+ # Only "<...>" / "[...]" entries survive delimiter_shaped_tokens, so skip
+ # the decode for the rest. UTF-8 is self-synchronising, so no multi-byte
+ # character starts with either byte and the first one settles it. The
+ # bytes are still read rather than seeked past: seeking would move the
+ # cursor differently on a short read, raise a different error on a bad
+ # length, and fail outright on a non-seekable stream. Decoding a
+ # six-figure vocabulary is the cost here, not reading it.
+ if raw[:1] != b"<" and raw[:1] != b"[":
+ continue
# A vocabulary holds arbitrary bytes; a marker is text, so undecodable
# entries are simply not markers.
try:
diff --git a/studio/backend/core/inference/web_access_policy.py b/studio/backend/core/inference/web_access_policy.py
index 2e0462608d1..3c28622df8d 100644
--- a/studio/backend/core/inference/web_access_policy.py
+++ b/studio/backend/core/inference/web_access_policy.py
@@ -8,11 +8,15 @@ from __future__ import annotations
import ipaddress
import re
import zlib
+from functools import lru_cache
from typing import Any
from urllib.parse import urlsplit
_DOMAIN_LABEL = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$")
_MAX_DOMAINS_PER_LIST = 100
+# A cache key holds the caller's raw strings for the life of the process, so only an entry
+# short enough to be a real domain is eligible; see normalize_website_policy.
+_MAX_CACHEABLE_DOMAIN_LEN = 253
# Most search engines stop honouring site: past a handful of OR terms.
_SITE_FILTER_LIMIT = 8
@@ -51,6 +55,27 @@ def normalize_domain(value: Any) -> str:
return ascii_domain
+@lru_cache(maxsize = 256)
+def _normalized_domain_tuple(raw_domains: tuple) -> tuple:
+ """``normalize_domain`` over an all-``str`` list, deduplicated, order preserved.
+
+ ``normalize_domain`` is a pure function of its argument (lowercase, IDNA encode,
+ validate), so the result for a given tuple of exact ``str`` domains is invariant and
+ safe to memoise. One restricted web search checks the same policy against every
+ candidate URL, which re-normalised both lists (up to 100 domains each) every time.
+ An invalid domain still raises from inside here, and ``lru_cache`` does not memoise
+ exceptions, so the same ``ValueError`` is raised on every call as before.
+ """
+ domains: list = []
+ seen: set = set()
+ for raw_domain in raw_domains:
+ domain = normalize_domain(raw_domain)
+ if domain not in seen:
+ seen.add(domain)
+ domains.append(domain)
+ return tuple(domains)
+
+
def normalize_website_policy(value: Any) -> dict[str, list[str]]:
if value is None:
return {"allowedDomains": [], "blockedDomains": []}
@@ -67,6 +92,16 @@ def normalize_website_policy(value: Any) -> dict[str, list[str]]:
raise ValueError(f"{key} must be a list")
if len(raw_domains) > _MAX_DOMAINS_PER_LIST:
raise ValueError(f"{key} supports at most {_MAX_DOMAINS_PER_LIST} domains")
+ # Exact ``str`` only: anything else can be unhashable and its error message carries
+ # the original repr. Over-long entries stay off the cached path too -- nameprep
+ # deletes characters such as U+00AD, so an arbitrarily long raw string can still
+ # normalise, and caching would pin a caller-sized string. Both paths agree.
+ if all(
+ type(raw_domain) is str and len(raw_domain) <= _MAX_CACHEABLE_DOMAIN_LEN
+ for raw_domain in raw_domains
+ ):
+ normalized[key] = list(_normalized_domain_tuple(tuple(raw_domains)))
+ continue
domains: list[str] = []
for raw_domain in raw_domains:
domain = normalize_domain(raw_domain)
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 25d2029bca0..a7e7a72dfa2 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -7,6 +7,7 @@ from __future__ import annotations
import time
import uuid
+from collections import deque
from typing import Annotated, Any, Dict, Literal, Optional, List, Union
from pydantic import (
@@ -1485,57 +1486,100 @@ class ChatCompletionRequest(BaseModel):
unconsumed tool_call; synth a random id only if none exists. A user
turn breaks the lookup.
"""
+ # Both passes below were a backwards rescan per tool result, O(n^2) for one assistant
+ # with n calls. Each is now one forward pass with an index -- the same search, since
+ # the backward walk never left the current user-delimited segment.
+ messages = self.messages
+ # The first pass only feeds the second, so with every tool_call_id present there is
+ # nothing to do (the common case).
+ for msg in messages:
+ if msg.role == "tool" and not msg.tool_call_id:
+ break
+ else:
+ return self
+
# Pre-mark explicit ids so a missing-id sibling can't steal a claimed one.
consumed: set[tuple[int, int]] = set()
- def _mark_consumed(start_idx: int, tool_call_id: str) -> None:
- for asst_idx in range(start_idx - 1, -1, -1):
- prev = self.messages[asst_idx]
- if prev.role == "user":
- break
- if prev.role != "assistant" or not prev.tool_calls:
+ # Newest assistant call per explicit id in this segment; within one assistant the
+ # first index wins, matching the old first-match-nearest-assistant walk. Only
+ # ``str`` ids are indexed: ``tool_call_id`` is a ``str``, so nothing else matches.
+ latest_by_id: dict = {}
+ for asst_idx, msg in enumerate(messages):
+ role = msg.role
+ if role == "user":
+ latest_by_id.clear()
+ elif role == "assistant":
+ if not msg.tool_calls:
continue
- for tc_idx, tc in enumerate(prev.tool_calls):
- if isinstance(tc, dict) and tc.get("id") == tool_call_id:
- consumed.add((asst_idx, tc_idx))
- return
-
- for tool_idx, msg in enumerate(self.messages):
- if msg.role == "tool" and msg.tool_call_id:
- _mark_consumed(tool_idx, msg.tool_call_id)
-
- for tool_idx, msg in enumerate(self.messages):
- if msg.role != "tool" or msg.tool_call_id:
- continue
- picked: str | None = None
- for asst_idx in range(tool_idx - 1, -1, -1):
- prev = self.messages[asst_idx]
- if prev.role != "assistant" or not prev.tool_calls:
- if prev.role == "user":
- break
- continue
- name_match = None
- fallback = None
- for tc_idx, tc in enumerate(prev.tool_calls):
- if (asst_idx, tc_idx) in consumed:
- continue
+ here: set = set()
+ for tc_idx, tc in enumerate(msg.tool_calls):
if not isinstance(tc, dict):
continue
tc_id = tc.get("id")
- if not tc_id:
+ if isinstance(tc_id, str) and tc_id not in here:
+ here.add(tc_id)
+ latest_by_id[tc_id] = (asst_idx, tc_idx)
+ elif role == "tool" and msg.tool_call_id:
+ claimed = latest_by_id.get(msg.tool_call_id)
+ if claimed is not None:
+ consumed.add(claimed)
+
+ # Assistants in this segment with an unclaimed call, oldest first, so the nearest is
+ # on top. A drained assistant never refills, so popping it is permanent and the walk
+ # past it happens once overall, not once per tool result. Each frame keeps its calls
+ # in order plus the same indexes bucketed by function name; one consumed out of turn
+ # is dropped when it reaches a queue front.
+ stack: list = []
+ for asst_idx, msg in enumerate(messages):
+ role = msg.role
+ if role == "user":
+ stack.clear()
+ continue
+ if role == "assistant":
+ if not msg.tool_calls:
+ continue
+ in_order: deque = deque()
+ by_name: dict = {}
+ for tc_idx, tc in enumerate(msg.tool_calls):
+ if (asst_idx, tc_idx) in consumed or not isinstance(tc, dict):
+ continue
+ if not tc.get("id"):
continue
function = tc.get("function")
function_name = function.get("name") if isinstance(function, dict) else None
- if msg.name and function_name == msg.name:
- name_match = (tc_id, asst_idx, tc_idx)
- break
- if fallback is None:
- fallback = (tc_id, asst_idx, tc_idx)
- chosen = name_match or fallback
- if chosen is not None:
- picked, a, t = chosen
- consumed.add((a, t))
- break
+ in_order.append(tc_idx)
+ # ``name`` is a ``str``, so only a ``str`` function name can match it.
+ if isinstance(function_name, str):
+ by_name.setdefault(function_name, deque()).append(tc_idx)
+ if in_order:
+ stack.append((asst_idx, msg.tool_calls, in_order, by_name))
+ continue
+ if role != "tool" or msg.tool_call_id:
+ continue
+ picked = None
+ while stack:
+ frame_idx, tool_calls, in_order, by_name = stack[-1]
+ while in_order and (frame_idx, in_order[0]) in consumed:
+ in_order.popleft()
+ if not in_order:
+ stack.pop()
+ continue
+ # Name match anywhere in this assistant, else its first remaining call,
+ # exactly as the old in-order scan did.
+ chosen = None
+ if msg.name:
+ named = by_name.get(msg.name)
+ if named is not None:
+ while named and (frame_idx, named[0]) in consumed:
+ named.popleft()
+ if named:
+ chosen = named.popleft()
+ if chosen is None:
+ chosen = in_order.popleft()
+ consumed.add((frame_idx, chosen))
+ picked = tool_calls[chosen].get("id")
+ break
if picked is None:
import secrets as _secrets
picked = f"call_{_secrets.token_hex(8)}"
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index e321a9d8ebb..4e1ee9ca67e 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -718,11 +718,13 @@ def _truncate_middle_messages(messages: list, keep_ratio: float):
tail = groups[-protected_tail:]
current_est = total_est
- kept_middle: list[list] = list(middle)
dropped = 0
- # Drop oldest-first until the estimate fits the target.
- while kept_middle and current_est > target_est:
- victim = kept_middle.pop(0)
+ # Drop oldest-first until the estimate fits the target. A cursor over ``middle``, not
+ # ``pop(0)`` on a copy: popping the front of a list shifts every remaining element.
+ first_kept = 0
+ while first_kept < len(middle) and current_est > target_est:
+ victim = middle[first_kept]
+ first_kept += 1
dropped += len(victim)
current_est -= sum(estimates[id(msg)] for msg in victim)
@@ -730,7 +732,7 @@ def _truncate_middle_messages(messages: list, keep_ratio: float):
return messages, 0
new_messages = head + anchor
- for grp in kept_middle:
+ for grp in middle[first_kept:]:
new_messages.extend(grp)
for grp in tail:
new_messages.extend(grp)
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index 2649783a9d3..2fa2b74f72c 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -3419,6 +3419,12 @@ async def upload_diffusion_dataset(
allowed = _DIFFUSION_DATASET_MEDIA_EXTS | _DIFFUSION_DATASET_TEXT_EXTS
# Validate every filename up front so a valid file ahead of a bad one is not left on disk when the 400 fires; the upload is all-or-nothing.
names: list[str] = []
+ # Indexes over `names` so the three batch-local duplicate checks below are hash
+ # lookups, not scans over every earlier filename (O(N^2) at the 1000-file cap). First
+ # / insertion order is kept, so each error still names the filename the scans picked.
+ seen_names: set = set()
+ first_name_by_casefold: dict = {}
+ media_names_by_stem_cf: dict = {}
for f in files:
# Normalise to a safe basename. Path.name does not split on a backslash on POSIX, so fold
# backslashes first or a Windows client's path is stored verbatim, ".." and all.
@@ -3433,7 +3439,7 @@ async def upload_diffusion_dataset(
# Reject an EXACT duplicate name within THIS batch: the same-name exemption below is for
# SEPARATE repeat uploads, while inside one batch the later replace would discard the earlier.
fname_cf = filename.casefold()
- if filename in names:
+ if filename in seen_names:
raise HTTPException(
status_code = 400,
detail = (
@@ -3468,7 +3474,11 @@ async def upload_diffusion_dataset(
None,
)
if clash is None:
- clash = next((n for n in names if _shares_sidecar(n)), None)
+ # Only a media name with this casefolded stem can share the sidecar.
+ clash = next(
+ (n for n in media_names_by_stem_cf.get(stem_cf, ()) if _shares_sidecar(n)),
+ None,
+ )
if clash is not None:
kind = "clip" if ext in _DIFFUSION_DATASET_CLIP_EXTS else "image"
raise HTTPException(
@@ -3483,10 +3493,8 @@ async def upload_diffusion_dataset(
# case: there 'Cat.png' and 'cat.png' are ONE destination, so the commit would replace the
# first staged part with the second while `uploaded` counted both. The same-name exemption
# above is for a SEPARATE repeat upload; on a case-sensitive filesystem both stay allowed.
- if any(n.casefold() == fname_cf for n in names) and _dataset_folder_is_case_insensitive(
- folder
- ):
- clash_cf = next(n for n in names if n.casefold() == fname_cf)
+ clash_cf = first_name_by_casefold.get(fname_cf)
+ if clash_cf is not None and _dataset_folder_is_case_insensitive(folder):
raise HTTPException(
status_code = 400,
detail = (
@@ -3495,6 +3503,12 @@ async def upload_diffusion_dataset(
"other. Rename one before uploading."
),
)
+ seen_names.add(filename)
+ first_name_by_casefold.setdefault(fname_cf, filename)
+ if ext in _DIFFUSION_DATASET_MEDIA_EXTS:
+ media_names_by_stem_cf.setdefault(Path(filename).stem.casefold(), []).append(
+ filename
+ )
names.append(filename)
# Stage each file to a temp name and move it in only once the whole batch is written, so a mid-batch failure leaves the dataset untouched, including any same-name file a direct write would truncate.
staged: list[tuple[Path, Path]] = [] # (temp, final)
diff --git a/studio/backend/tests/test_web_access_policy.py b/studio/backend/tests/test_web_access_policy.py
index 8b5f90544f6..be7c0787f8e 100644
--- a/studio/backend/tests/test_web_access_policy.py
+++ b/studio/backend/tests/test_web_access_policy.py
@@ -11,6 +11,7 @@ import pytest
from core.inference import tools
from core.inference.tool_loop_controller import is_tool_error
from core.inference.web_access_policy import (
+ _normalized_domain_tuple,
check_url_access,
normalize_website_policy,
scope_search_query,
@@ -90,6 +91,26 @@ def test_policy_normalizes_idna_deduplicates_and_rejects_urls():
normalize_website_policy({"allowedDomains": ["https://arxiv.org"]})
+def test_oversized_raw_domains_normalize_without_entering_the_cache():
+ # Nameprep deletes U+00AD, so 100k soft hyphens still normalise to a valid domain. The
+ # memo key is the caller's raw tuple, so caching one would pin it for the life of the
+ # process; it must normalise on the uncached path instead.
+ normalize_website_policy({}) # warm the empty-list key so the counts below are exact
+ padded = "a" + "\u00ad" * 100_000 + ".com"
+ before = _normalized_domain_tuple.cache_info().currsize
+ assert normalize_website_policy({"allowedDomains": [padded]}) == {
+ "allowedDomains": ["a.com"],
+ "blockedDomains": [],
+ }
+ assert _normalized_domain_tuple.cache_info().currsize == before
+ # A domain of a plausible length still takes the cached path.
+ assert normalize_website_policy({"allowedDomains": ["cached.example"]}) == {
+ "allowedDomains": ["cached.example"],
+ "blockedDomains": [],
+ }
+ assert _normalized_domain_tuple.cache_info().currsize == before + 1
+
+
def test_policy_is_injected_into_prompts_and_search_queries():
prompt = website_policy_prompt(ARXIV_ONLY)
assert "Only search or fetch" in prompt