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.

fix(studio): coalesce concurrent keyless-settings reads to stop SQLite thundering herd (#9911)

Adarsh D4b52ff56b742
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index c5abd62c339..5e39b899e1f 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -3827,7 +3827,6 @@ def fork_chat_thread(
if src is None:
conn.rollback()
return None
- # Verify branch msg belongs to source thread.
branch_row = conn.execute(
"SELECT * FROM chat_messages WHERE thread_id = ? AND id = ?",
(source_thread_id, branch_message_id),
@@ -3835,7 +3834,6 @@ def fork_chat_thread(
if branch_row is None:
conn.rollback()
return None
- # Walk ancestry from branch msg back to root via parent_id chain.
ancestry: list[sqlite3.Row] = []
cursor_row = branch_row
seen: set[str] = set()
@@ -3850,7 +3848,6 @@ def fork_chat_thread(
(source_thread_id, parent),
).fetchone()
ancestry.reverse() # root .. branch msg
- # Map old msg id -> new msg id for parent_id rewriting.
id_map: dict[str, str] = {row["id"]: id_factory() for row in ancestry}
src_dict = dict(src)
conn.execute(
@@ -4382,10 +4379,11 @@ def compare_and_set_app_setting(key: str, expected: Any, value: Any) -> bool:
conn.close()
-def upsert_app_settings(settings: dict[str, Any]) -> dict[str, Any]:
+def upsert_app_settings(settings: dict[str, Any], *, read_back: bool = True) -> dict[str, Any]:
if not settings:
return {}
conn = get_connection()
+ committed = False
try:
now = datetime.now(timezone.utc).isoformat()
conn.executemany(
@@ -4399,10 +4397,17 @@ def upsert_app_settings(settings: dict[str, Any]) -> dict[str, Any]:
[(key, json.dumps(value), now) for key, value in settings.items()],
)
conn.commit()
+ committed = True
+ if not read_back:
+ return settings
rows = conn.execute("SELECT key, value_json FROM app_settings ORDER BY key").fetchall()
return {row["key"]: _json_loads(row["value_json"], None) for row in rows}
finally:
- conn.close()
+ try:
+ conn.close()
+ except Exception:
+ if not committed or read_back:
+ raise
def upsert_app_setting_map_entry(
diff --git a/studio/backend/tests/test_keyless_api_access.py b/studio/backend/tests/test_keyless_api_access.py
index 382965903ba..9cd98877338 100644
--- a/studio/backend/tests/test_keyless_api_access.py
+++ b/studio/backend/tests/test_keyless_api_access.py
@@ -6,6 +6,8 @@ from __future__ import annotations
import asyncio
import secrets
import threading
+import time
+from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone
from pathlib import Path
from types import SimpleNamespace
@@ -40,7 +42,6 @@ from utils.keyless_api_access import (
)
-# Keep this security matrix compact enough for the PR test-line budget.
# fmt: off
@pytest.fixture(autouse = True)
def isolated_auth_db(tmp_path, monkeypatch):
@@ -141,7 +142,7 @@ def test_settings_are_immediate_and_fail_closed(monkeypatch):
assert get_keyless_api_tools_enabled() is False
set_keyless_api_access("full", tools = True)
- monkeypatch.setattr(studio_db, "get_app_setting",
+ monkeypatch.setattr(studio_db, "get_app_settings",
lambda *_a, **_k: (_ for _ in ()).throw(OSError("db unavailable")))
_reset_scope_cache()
assert (get_keyless_api_access_scope(), get_keyless_api_tools_enabled()) == ("off", False)
@@ -174,6 +175,520 @@ def test_stale_refresh_cannot_reopen_a_closed_scope(monkeypatch):
assert observed == [("off", False)]
+def test_concurrent_stale_cache_misses_coalesce_into_one_sqlite_read(monkeypatch):
+ import utils.keyless_api_access as keyless
+
+ set_keyless_api_access("inference", tools = False)
+ _reset_scope_cache()
+
+ clock = [0.0]
+ monkeypatch.setattr(keyless.time, "monotonic", lambda: clock[0])
+ real_read = keyless._read_settings
+ call_count = 0
+ count_lock = threading.Lock()
+ release = threading.Event()
+ n_threads = 25
+ entered = threading.Barrier(n_threads + 1)
+
+ def counted_read():
+ nonlocal call_count
+ with count_lock:
+ call_count += 1
+ assert release.wait(timeout = 10)
+ return real_read()
+
+ monkeypatch.setattr(keyless, "_read_settings", counted_read)
+
+ results = [None] * n_threads
+
+ def worker(i):
+ entered.wait(timeout = 10)
+ results[i] = keyless._settings()
+
+ threads = [threading.Thread(target = worker, args = (i,)) for i in range(n_threads)]
+ for t in threads:
+ t.start()
+ entered.wait(timeout = 10)
+ time.sleep(0.2) # let followers queue
+ clock[0] = keyless._SETTINGS_CACHE_TTL_S + 1.0
+ release.set()
+ for t in threads:
+ t.join(timeout = 10)
+
+ assert call_count == 1
+ assert results.count(("inference", False)) == 1
+ assert results.count(("off", False)) == n_threads - 1
+
+
+def test_concurrent_keyless_checks_through_the_real_entrypoint_stay_bounded(monkeypatch):
+ import utils.keyless_api_access as keyless
+ from utils.keyless_api_access import asgi_request_is_keyless
+
+ set_keyless_api_access("inference", tools = False)
+ keyless._cached_settings = (
+ time.monotonic() - keyless._SETTINGS_CACHE_TTL_S - 1,
+ "inference",
+ False,
+ )
+
+ real_read = keyless._read_settings
+ call_count = 0
+ count_lock = threading.Lock()
+ release = threading.Event()
+
+ def counted_read():
+ nonlocal call_count
+ with count_lock:
+ call_count += 1
+ assert release.wait(timeout = 10)
+ return real_read()
+
+ monkeypatch.setattr(keyless, "_read_settings", counted_read)
+
+ scope = asgi_scope(path = "/v1/models")
+ n_requests = 20
+ pool_workers = 4
+
+ with ThreadPoolExecutor(max_workers = pool_workers) as pool:
+ futures = [pool.submit(asgi_request_is_keyless, scope) for _ in range(n_requests)]
+ time.sleep(0.2) # fill the pool
+ late_future = pool.submit(asgi_request_is_keyless, scope)
+ release.set()
+ results = [f.result(timeout = 10) for f in futures]
+ late_result = late_future.result(timeout = 10)
+
+ assert call_count == 1
+ assert results.count(True) == 1
+ assert results.count(False) == n_requests - 1
+ assert isinstance(late_result, bool)
+
+
+def test_async_stale_cache_miss_broadcasts_one_refresh_result(monkeypatch):
+ import utils.keyless_api_access as keyless
+
+ set_keyless_api_access("inference", tools = True)
+ _reset_scope_cache()
+
+ owner_started = threading.Event()
+ release_owner = threading.Event()
+ real_once = keyless._settings_once
+ call_count = 0
+ count_lock = threading.Lock()
+
+ def counted_once():
+ nonlocal call_count
+ with count_lock:
+ call_count += 1
+ return real_once()
+
+ def delayed_read():
+ owner_started.set()
+ assert release_owner.wait(timeout = 10)
+ return "inference", True
+
+ monkeypatch.setattr(keyless, "_settings_once", counted_once)
+ monkeypatch.setattr(keyless, "_read_settings", delayed_read)
+
+ async def exercise():
+ cancelled = asyncio.create_task(keyless._settings_async())
+ requests = [asyncio.create_task(keyless._settings_async()) for _ in range(100)]
+ try:
+ for _ in range(100):
+ if owner_started.is_set():
+ break
+ await asyncio.sleep(0.01)
+ assert owner_started.is_set()
+ await asyncio.sleep(0.1)
+ assert call_count == 1
+ cancelled.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await cancelled
+ finally:
+ release_owner.set()
+ results = await asyncio.gather(*requests)
+ assert [result[:2] for result in results] == [("inference", True)] * 100
+ assert len({result[2] for result in results}) == 1
+ assert call_count == 1
+
+ asyncio.run(exercise())
+
+
+def test_slow_refresh_does_not_exhaust_the_anyio_worker_pool(monkeypatch):
+ import anyio.to_thread
+ import utils.keyless_api_access as keyless
+ from starlette.concurrency import run_in_threadpool
+
+ set_keyless_api_access("inference", tools = False)
+ keyless._cached_settings = (
+ time.monotonic() - keyless._SETTINGS_CACHE_TTL_S - 1,
+ "inference",
+ False,
+ )
+
+ owner_started = threading.Event()
+ release_owner = threading.Event()
+ real_read = keyless._read_settings_from_db
+ real_once = keyless._settings_once
+ once_count = 0
+ count_lock = threading.Lock()
+
+ def delayed_read():
+ owner_started.set()
+ assert release_owner.wait(timeout = 10)
+ return real_read()
+
+ def counted_once():
+ nonlocal once_count
+ with count_lock:
+ once_count += 1
+ return real_once()
+
+ monkeypatch.setattr(keyless, "_read_settings", delayed_read)
+ monkeypatch.setattr(keyless, "_settings_once", counted_once)
+
+ async def exercise():
+ limiter = anyio.to_thread.current_default_thread_limiter()
+ original_tokens = limiter.total_tokens
+ limiter.total_tokens = 4
+
+ observed = []
+
+ async def downstream(scope, *_args):
+ observed.append(scope["state"][KEYLESS_ADMISSION_STATE_KEY])
+
+ middleware = KeylessToolPolicyMiddleware(downstream)
+ requests = [
+ asyncio.create_task(middleware(asgi_scope(), lambda: None, lambda _message: None))
+ for _ in range(4)
+ ]
+ try:
+ for _ in range(100):
+ if owner_started.is_set():
+ break
+ await asyncio.sleep(0.01)
+ assert owner_started.is_set()
+ assert once_count == 1
+
+ unrelated = asyncio.create_task(run_in_threadpool(lambda: "available"))
+ assert await asyncio.wait_for(unrelated, timeout = 1) == "available"
+ finally:
+ release_owner.set()
+ await asyncio.gather(*requests)
+ limiter.total_tokens = original_tokens
+ assert observed == [True] * 4
+ assert once_count == 1
+
+ asyncio.run(exercise())
+
+
+def test_failed_refresh_does_not_reuse_permissive_stale_settings(monkeypatch):
+ import utils.keyless_api_access as keyless
+
+ set_keyless_api_access("inference", tools = True)
+ keyless._cached_settings = (
+ time.monotonic() - keyless._SETTINGS_CACHE_TTL_S - 1,
+ "inference",
+ True,
+ )
+ refresh_started = threading.Event()
+ release_refresh = threading.Event()
+
+ def failed_read():
+ refresh_started.set()
+ assert release_refresh.wait(timeout = 10)
+ raise OSError("db unavailable")
+
+ monkeypatch.setattr(keyless, "_read_settings_from_db", failed_read)
+
+ async def exercise():
+ observed = []
+
+ async def downstream(scope, *_args):
+ observed.append(scope["state"][KEYLESS_ADMISSION_STATE_KEY])
+
+ middleware = KeylessToolPolicyMiddleware(downstream)
+ requests = [
+ asyncio.create_task(middleware(asgi_scope(), lambda: None, lambda _message: None))
+ for _ in range(2)
+ ]
+ try:
+ for _ in range(100):
+ if refresh_started.is_set() and keyless._settings_refresh_inflight is not None:
+ break
+ await asyncio.sleep(0.01)
+ assert refresh_started.is_set()
+ finally:
+ release_refresh.set()
+ await asyncio.gather(*requests)
+ assert observed == [False, False]
+
+ asyncio.run(exercise())
+
+
+def test_async_settings_tasks_do_not_retain_closed_event_loops(monkeypatch):
+ import gc
+ import weakref
+ import utils.keyless_api_access as keyless
+
+ loop_refs = []
+
+ async def immediate_settings():
+ return "off", False, 0
+
+ monkeypatch.setattr(keyless, "_refresh_settings_async", immediate_settings)
+
+ async def read_settings():
+ loop_refs.append(weakref.ref(asyncio.get_running_loop()))
+ assert (await keyless._settings_async())[:2] == ("off", False)
+
+ for _ in range(3):
+ asyncio.run(read_settings())
+ gc.collect()
+
+ assert all(ref() is None for ref in loop_refs)
+
+
+def test_scope_write_preserves_tools_during_an_inflight_refresh(monkeypatch):
+ import utils.keyless_api_access as keyless
+
+ set_keyless_api_access("full", tools = True)
+ _reset_scope_cache()
+
+ owner_started = threading.Event()
+ release_owner = threading.Event()
+ real_read = keyless._read_settings_from_db
+ read_count = 0
+ count_lock = threading.Lock()
+
+ def delayed_first_read():
+ nonlocal read_count
+ with count_lock:
+ read_count += 1
+ first = read_count == 1
+ if first:
+ owner_started.set()
+ assert release_owner.wait(timeout = 10)
+ return real_read()
+
+ monkeypatch.setattr(keyless, "_read_settings_from_db", delayed_first_read)
+ reader = threading.Thread(target = keyless._settings)
+ reader.start()
+ try:
+ assert owner_started.wait(timeout = 10)
+ set_keyless_api_access("inference")
+ finally:
+ release_owner.set()
+ reader.join(timeout = 10)
+
+ assert not reader.is_alive()
+ assert get_keyless_api_access_settings() == ("inference", True)
+
+
+def test_scope_write_aborts_when_preserved_tools_cannot_be_read(monkeypatch):
+ import utils.keyless_api_access as keyless
+
+ set_keyless_api_access("full", tools = True)
+ monkeypatch.setattr(
+ keyless,
+ "_read_settings_from_db",
+ lambda: (_ for _ in ()).throw(OSError("db unavailable")),
+ )
+
+ with pytest.raises(OSError, match = "db unavailable"):
+ set_keyless_api_access("inference")
+
+ assert get_keyless_api_access_settings() == ("full", True)
+
+
+def test_disable_without_tools_does_not_depend_on_a_preservation_read(monkeypatch):
+ import utils.keyless_api_access as keyless
+
+ set_keyless_api_access("full", tools = True)
+ monkeypatch.setattr(
+ keyless,
+ "_read_settings_from_db",
+ lambda: (_ for _ in ()).throw(OSError("db unavailable")),
+ )
+
+ assert set_keyless_api_access("off") == ("off", False)
+ assert get_keyless_api_access_settings() == ("off", False)
+
+
+def test_keyless_write_has_no_fallible_post_commit_read(monkeypatch):
+ import storage.studio_db as studio_db
+ import utils.keyless_api_access as keyless
+
+ real_get_connection = studio_db.get_connection
+ result_read_attempted = False
+
+ class GuardedConnection:
+ def __init__(self, connection):
+ self.connection = connection
+
+ def __getattr__(self, name):
+ return getattr(self.connection, name)
+
+ def execute(self, sql, *args):
+ nonlocal result_read_attempted
+ if "SELECT key, value_json FROM app_settings ORDER BY key" in " ".join(sql.split()):
+ result_read_attempted = True
+ raise RuntimeError("result read failed after commit")
+ return self.connection.execute(sql, *args)
+
+ def close(self):
+ self.connection.close()
+ raise RuntimeError("close failed after commit")
+
+ monkeypatch.setattr(
+ studio_db,
+ "get_connection",
+ lambda: GuardedConnection(real_get_connection()),
+ )
+
+ assert set_keyless_api_access("inference", tools = True) == ("inference", True)
+ assert result_read_attempted is False
+ monkeypatch.setattr(studio_db, "get_connection", real_get_connection)
+ keyless._reset_scope_cache()
+ assert get_keyless_api_access_settings() == ("inference", True)
+
+
+def test_committed_disable_is_fail_closed_before_cache_publication(monkeypatch):
+ import storage.studio_db as studio_db
+ import utils.keyless_api_access as keyless
+
+ set_keyless_api_access("inference", tools = True)
+ keyless._cached_settings = (
+ time.monotonic() - keyless._SETTINGS_CACHE_TTL_S - 1,
+ "inference",
+ True,
+ )
+
+ refresh_started = threading.Event()
+ release_refresh = threading.Event()
+ write_committed = threading.Event()
+ release_writer = threading.Event()
+ real_read = keyless._read_settings
+ real_upsert = studio_db.upsert_app_settings
+
+ def delayed_read():
+ refresh_started.set()
+ assert release_refresh.wait(timeout = 10)
+ return real_read()
+
+ def delayed_upsert(settings, **kwargs):
+ result = real_upsert(settings, **kwargs)
+ write_committed.set()
+ assert release_writer.wait(timeout = 10)
+ return result
+
+ monkeypatch.setattr(keyless, "_read_settings", delayed_read)
+ monkeypatch.setattr(studio_db, "upsert_app_settings", delayed_upsert)
+ refresh_result = []
+ refresh = threading.Thread(target = lambda: refresh_result.append(keyless._settings()))
+ writer = threading.Thread(target = set_keyless_api_access, args = ("off",),
+ kwargs = {"tools": False})
+ refresh.start()
+ assert refresh_started.wait(timeout = 10)
+ writer.start()
+ try:
+ assert write_committed.wait(timeout = 10)
+ release_refresh.set()
+ refresh.join(timeout = 10)
+ assert refresh_result == [("off", False)]
+ assert asgi_request_is_keyless(asgi_scope(path = "/v1/models")) is False
+ assert get_keyless_api_tools_enabled() is False
+ finally:
+ release_writer.set()
+ writer.join(timeout = 10)
+ if refresh.is_alive():
+ release_refresh.set()
+ refresh.join(timeout = 10)
+
+ assert not writer.is_alive() and not refresh.is_alive()
+ assert get_keyless_api_access_settings() == ("off", False)
+
+
+def test_middleware_rechecks_a_setting_changed_during_classification(monkeypatch):
+ import utils.keyless_api_access as keyless
+
+ set_keyless_api_access("inference", tools = True)
+ classification_started = threading.Event()
+ release_classification = threading.Event()
+ real_classifier = keyless.asgi_request_is_keyless
+
+ def delayed_classifier(scope, settings):
+ admitted = real_classifier(scope, settings)
+ classification_started.set()
+ assert release_classification.wait(timeout = 10)
+ return admitted
+
+ monkeypatch.setattr(keyless, "asgi_request_is_keyless", delayed_classifier)
+
+ async def exercise():
+ observed = []
+
+ async def downstream(scope, *_args):
+ observed.append(scope["state"][KEYLESS_ADMISSION_STATE_KEY])
+
+ request = asyncio.create_task(KeylessToolPolicyMiddleware(downstream)(
+ asgi_scope(), lambda: None, lambda _message: None))
+ try:
+ for _ in range(100):
+ if classification_started.is_set():
+ break
+ await asyncio.sleep(0.01)
+ assert classification_started.is_set()
+ await asyncio.to_thread(set_keyless_api_access, "off", tools = False)
+ finally:
+ release_classification.set()
+ await request
+ assert observed == [False]
+
+ asyncio.run(exercise())
+
+
+def test_middleware_linearizes_admission_before_a_concurrent_disable():
+ set_keyless_api_access("inference", tools = True)
+ publication_started = threading.Event()
+ writer_done = threading.Event()
+ committed_before_publication = []
+
+ class PublicationGate(dict):
+ def setdefault(self, key, default = None,):
+ if key == "state":
+ publication_started.set()
+ committed_before_publication.append(writer_done.wait(timeout = 0.2))
+ return super().setdefault(key, default)
+
+ scope = PublicationGate(asgi_scope())
+
+ def disable():
+ assert publication_started.wait(timeout = 10)
+ set_keyless_api_access("off", tools = False)
+ writer_done.set()
+
+ writer = threading.Thread(target = disable)
+ writer.start()
+
+ async def exercise():
+ observed = []
+
+ async def downstream(request_scope, *_args):
+ observed.append(request_scope["state"][KEYLESS_ADMISSION_STATE_KEY])
+
+ await KeylessToolPolicyMiddleware(downstream)(scope, lambda: None, lambda _message: None)
+ return observed
+
+ try:
+ assert asyncio.run(exercise()) == [True]
+ finally:
+ writer.join(timeout = 10)
+
+ assert not writer.is_alive()
+ assert committed_before_publication == [False]
+ assert get_keyless_api_access_settings() == ("off", False)
+
+
def test_overlapping_writes_publish_in_commit_order(monkeypatch):
import storage.studio_db as studio_db
@@ -182,8 +697,8 @@ def test_overlapping_writes_publish_in_commit_order(monkeypatch):
second_committed = threading.Event()
real_upsert = studio_db.upsert_app_settings
- def delayed_upsert(settings):
- result = real_upsert(settings)
+ def delayed_upsert(settings, **kwargs):
+ result = real_upsert(settings, **kwargs)
if settings[KEYLESS_API_ACCESS_SETTING_KEY] == "full":
first_committed.set()
assert release_first.wait(timeout = 10)
diff --git a/studio/backend/utils/keyless_api_access.py b/studio/backend/utils/keyless_api_access.py
index 906c2a57780..c6806fad4c4 100644
--- a/studio/backend/utils/keyless_api_access.py
+++ b/studio/backend/utils/keyless_api_access.py
@@ -26,8 +26,10 @@ matches the ASGI accepting address and port. Signing in to Unsloth is unaffected
from __future__ import annotations
+import asyncio
import threading
import time
+import weakref
from typing import Any, Optional
KEYLESS_API_ACCESS_SETTING_KEY = "keyless_api_access_scope"
@@ -82,6 +84,10 @@ _cached_settings: Optional[tuple[float, str, bool]] = None
_settings_generation = 0
_cache_lock = threading.Lock()
_write_lock = threading.Lock()
+_settings_refresh_inflight: Optional[object] = None
+_settings_write_inflight: Optional[object] = None
+_async_settings_tasks = weakref.WeakKeyDictionary()
+_async_settings_pending_tasks: set[asyncio.Task] = set()
def _reset_scope_cache() -> None:
@@ -91,20 +97,26 @@ def _reset_scope_cache() -> None:
_cached_settings = None
-def _read_settings() -> tuple[str, bool]:
- try:
- from storage.studio_db import get_app_setting
- scope = _coerce_scope(get_app_setting(KEYLESS_API_ACCESS_SETTING_KEY, None))
- tools = _coerce_bool(get_app_setting(KEYLESS_API_TOOLS_SETTING_KEY, None))
- except Exception:
- return KEYLESS_SCOPE_OFF, False
+def _read_settings_from_db() -> tuple[str, bool]:
+ from storage.studio_db import get_app_settings
+
+ values = get_app_settings([KEYLESS_API_ACCESS_SETTING_KEY, KEYLESS_API_TOOLS_SETTING_KEY])
+ scope = _coerce_scope(values.get(KEYLESS_API_ACCESS_SETTING_KEY))
+ tools = _coerce_bool(values.get(KEYLESS_API_TOOLS_SETTING_KEY))
return (
scope or DEFAULT_KEYLESS_API_ACCESS_SCOPE,
DEFAULT_KEYLESS_API_TOOLS_ENABLED if tools is None else tools,
)
-def _settings() -> tuple[str, bool]:
+def _read_settings() -> tuple[str, bool]:
+ try:
+ return _read_settings_from_db()
+ except Exception:
+ return KEYLESS_SCOPE_OFF, False
+
+
+def _settings_once() -> tuple[str, bool, bool, int]:
"""Read the persisted scope and tool grant; anything unreadable counts as off.
Unlike a normal setting these remove an authentication requirement, so a damaged
@@ -113,25 +125,91 @@ def _settings() -> tuple[str, bool]:
holding the old answer when the setting is turned off, and publishing it would
keep the server open for the rest of the TTL. The generation counter dates each
read against the writes, so only a read that still describes the DB is published.
+
+ One caller refreshes SQLite; async followers retry without worker tokens; sync
+ followers fail closed.
"""
- global _cached_settings
- now = time.monotonic()
- with _cache_lock:
- cached = _cached_settings
- if cached is not None and now - cached[0] < _SETTINGS_CACHE_TTL_S:
- return cached[1], cached[2]
- generation = _settings_generation
- scope, tools = _read_settings()
- with _cache_lock:
- if generation != _settings_generation:
+ global _cached_settings, _settings_refresh_inflight
+ owner_marker: Optional[object] = None
+ try:
+ now = time.monotonic()
+ with _cache_lock:
+ if _settings_write_inflight is not None:
+ return KEYLESS_SCOPE_OFF, False, False, _settings_generation
+ cached = _cached_settings
+ if cached is not None and now - cached[0] < _SETTINGS_CACHE_TTL_S:
+ return cached[1], cached[2], False, _settings_generation
+ if _settings_refresh_inflight is not None:
+ return KEYLESS_SCOPE_OFF, False, True, _settings_generation
+ owner_marker = _settings_refresh_inflight = object()
+ generation = _settings_generation
+
+ scope, tools = _read_settings()
+ with _cache_lock:
+ if _settings_write_inflight is not None:
+ return KEYLESS_SCOPE_OFF, False, False, _settings_generation
+ if generation == _settings_generation:
+ _cached_settings = (time.monotonic(), scope, tools)
published = _cached_settings
- if published is not None:
- return published[1], published[2]
- else:
- _cached_settings = (now, scope, tools)
+ published_generation = _settings_generation
+ if published is not None:
+ return published[1], published[2], False, published_generation
+ return scope, tools, False, published_generation
+ finally:
+ if owner_marker is not None:
+ with _cache_lock:
+ if _settings_refresh_inflight is owner_marker:
+ _settings_refresh_inflight = None
+
+
+def _settings() -> tuple[str, bool]:
+ scope, tools, _pending, _generation = _settings_once()
return scope, tools
+async def _settings_async() -> tuple[str, bool, int]:
+ return await asyncio.shield(_async_settings_task())
+
+
+async def _refresh_settings_async() -> tuple[str, bool, int]:
+ from starlette.concurrency import run_in_threadpool
+ while True:
+ scope, tools, pending, generation = await run_in_threadpool(_settings_once)
+ if not pending:
+ return scope, tools, generation
+ await asyncio.sleep(0.01)
+
+
+def _async_settings_task() -> asyncio.Task:
+ loop = asyncio.get_running_loop()
+ with _cache_lock:
+ task_ref = _async_settings_tasks.get(loop)
+ task = task_ref() if task_ref is not None else None
+ if task is None or task.done():
+ task = loop.create_task(_refresh_settings_async())
+ _async_settings_tasks[loop] = weakref.ref(task)
+ _async_settings_pending_tasks.add(task)
+ task.add_done_callback(
+ lambda completed, loop_ref = weakref.ref(loop): _release_async_settings_task(
+ completed, loop_ref
+ )
+ )
+ return task
+
+
+def _release_async_settings_task(task: asyncio.Task, loop_ref: weakref.ReferenceType) -> None:
+ try:
+ task.exception()
+ except asyncio.CancelledError:
+ pass
+ with _cache_lock:
+ _async_settings_pending_tasks.discard(task)
+ loop = loop_ref()
+ task_ref = _async_settings_tasks.get(loop) if loop is not None else None
+ if task_ref is not None and task_ref() is task:
+ del _async_settings_tasks[loop]
+
+
def get_keyless_api_access_scope() -> str:
return _settings()[0]
@@ -148,30 +226,51 @@ def get_keyless_api_tools_enabled() -> bool:
def set_keyless_api_access(value: Any, *, tools: Any = None) -> tuple[str, bool]:
"""Persist which routes are served without a key, and whether tools come with them."""
- global _cached_settings, _settings_generation
+ global _cached_settings, _settings_generation, _settings_write_inflight
scope = _coerce_scope(value)
if scope is None:
raise ValueError(f"Keyless API access scope must be one of: {', '.join(KEYLESS_SCOPES)}.")
with _write_lock:
- allow_tools = get_keyless_api_tools_enabled() if tools is None else _coerce_bool(tools)
- if allow_tools is None:
- raise ValueError("Keyless tool access must be true or false.")
- # tools are meaningless without a scope, and leaving them ticked would surprise
- # whoever turns keyless back on later
- allow_tools = allow_tools and scope != KEYLESS_SCOPE_OFF
-
- from storage.studio_db import upsert_app_settings
-
- upsert_app_settings(
- {
- KEYLESS_API_ACCESS_SETTING_KEY: scope,
- KEYLESS_API_TOOLS_SETTING_KEY: allow_tools,
- }
- )
+ write_marker = object()
+ upsert_started = False
with _cache_lock:
- _settings_generation += 1
- _cached_settings = (time.monotonic(), scope, allow_tools)
- return scope, allow_tools
+ _settings_write_inflight = write_marker
+ try:
+ if scope == KEYLESS_SCOPE_OFF:
+ allow_tools = False
+ else:
+ allow_tools = _read_settings_from_db()[1] if tools is None else _coerce_bool(tools)
+ if allow_tools is None:
+ raise ValueError("Keyless tool access must be true or false.")
+ # tools are meaningless without a scope, and leaving them ticked would surprise
+ # whoever turns keyless back on later
+ allow_tools = allow_tools and scope != KEYLESS_SCOPE_OFF
+
+ from storage.studio_db import upsert_app_settings
+
+ upsert_started = True
+ upsert_app_settings(
+ {
+ KEYLESS_API_ACCESS_SETTING_KEY: scope,
+ KEYLESS_API_TOOLS_SETTING_KEY: allow_tools,
+ },
+ read_back = False,
+ )
+ with _cache_lock:
+ _settings_generation += 1
+ _cached_settings = (time.monotonic(), scope, allow_tools)
+ return scope, allow_tools
+ except Exception:
+ # The write may have committed, so fail closed.
+ if upsert_started:
+ with _cache_lock:
+ _settings_generation += 1
+ _cached_settings = (time.monotonic(), KEYLESS_SCOPE_OFF, False)
+ raise
+ finally:
+ with _cache_lock:
+ if _settings_write_inflight is write_marker:
+ _settings_write_inflight = None
def access_exposure(app_state: Any) -> Optional[str]:
@@ -491,7 +590,10 @@ def keyless_transport_allowed(request: Any, scope: str) -> bool:
def keyless_request_allowed(request: Any) -> bool:
"""Whether the route and transport are eligible for keyless authentication."""
- scope = get_keyless_api_access_scope()
+ return _keyless_request_allowed_for_scope(request, get_keyless_api_access_scope())
+
+
+def _keyless_request_allowed_for_scope(request: Any, scope: str) -> bool:
if scope == KEYLESS_SCOPE_OFF:
return False
asgi_scope = getattr(request, "scope", {})
@@ -538,12 +640,19 @@ class KeylessToolPolicyMiddleware:
return
from starlette.concurrency import run_in_threadpool
- admitted = await run_in_threadpool(asgi_request_is_keyless, asgi_scope)
- asgi_scope.setdefault("state", {})[KEYLESS_ADMISSION_STATE_KEY] = admitted
+ scope, tools, generation = await _settings_async()
+ settings = (scope, tools)
+ admitted = await run_in_threadpool(asgi_request_is_keyless, asgi_scope, settings)
+ with _cache_lock:
+ if _settings_write_inflight is not None or generation != _settings_generation:
+ settings = (KEYLESS_SCOPE_OFF, False)
+ admitted = False
+ # Publish under the lock to linearize admission with writes.
+ asgi_scope.setdefault("state", {})[KEYLESS_ADMISSION_STATE_KEY] = admitted
if not admitted:
await self.app(asgi_scope, receive, send)
return
- if await run_in_threadpool(get_keyless_api_tools_enabled):
+ if settings[1]:
await self.app(asgi_scope, receive, send)
return
from state.tool_policy import tools_force_disabled
@@ -552,7 +661,7 @@ class KeylessToolPolicyMiddleware:
await self.app(asgi_scope, receive, send)
-def asgi_request_is_keyless(asgi_scope) -> bool:
+def asgi_request_is_keyless(asgi_scope, settings: Optional[tuple[str, bool]] = None) -> bool:
"""Whether this ASGI request is admitted by the setting rather than by a credential.
Middleware-side twin of ``auth.authentication.admitted_without_credential``, reading
@@ -565,7 +674,12 @@ def asgi_request_is_keyless(asgi_scope) -> bool:
request = Request(asgi_scope)
except Exception:
return False
- if not keyless_request_allowed(request):
+ allowed = (
+ keyless_request_allowed(request)
+ if settings is None
+ else _keyless_request_allowed_for_scope(request, settings[0])
+ )
+ if not allowed:
return False
authorization = [
bytes(value).decode("latin-1")