From dad8faa760a141999fb2cdd930c28fed02f6f05b Mon Sep 17 00:00:00 2001 From: Net Zhang Date: Tue, 22 Sep 2026 10:11:29 -0400 Subject: [PATCH 1/2] Serialize and cache the cuML availability check Two Streamlit script runs resolving the auto backend at the same moment imported cuML concurrently; the second importer could see a partially initialized package, get an ImportError, and be reported as "cuML not available", so one run projected on sklearn while the other used the GPU. We now guard the import with a lock and cache a successful result, log import failures instead of swallowing them, and tag the projection, KMeans and embedding log banners with the Streamlit session and thread ids so duplicate runs can be attributed. Also give the cuML UMAP subprocess unique temp files per call: two concurrent runs in one process shared PID-named files, and the first run's cleanup deleted the second run's output, which then fell back to sklearn with "subprocess failed (rc=0)". Refs #49 Co-Authored-By: Claude Fable 5.1 --- apps/embed_explore/components/sidebar.py | 6 ++-- apps/precalculated/components/sidebar.py | 5 +-- shared/lib/session.py | 29 ++++++++++++++++++ shared/utils/backend.py | 39 +++++++++++++++++++++--- shared/utils/clustering.py | 9 ++++-- 5 files changed, 77 insertions(+), 11 deletions(-) create mode 100644 shared/lib/session.py diff --git a/apps/embed_explore/components/sidebar.py b/apps/embed_explore/components/sidebar.py index 511d88b..acedf66 100644 --- a/apps/embed_explore/components/sidebar.py +++ b/apps/embed_explore/components/sidebar.py @@ -20,6 +20,7 @@ ) from shared.utils.backend import check_cuda_available, resolve_backend, is_oom_error from shared.utils.logging_config import get_logger +from shared.lib.session import session_tag logger = get_logger(__name__) @@ -59,6 +60,7 @@ def render_embedding_section() -> Tuple[bool, Optional[str], Optional[str], int, # Handle embedding execution if embed_button and image_dir and os.path.isdir(image_dir): + logger.info(f"EMBEDDING START: {image_dir} ({session_tag()})") with StreamlitProgressContext(st.empty(), "Embedding complete!") as progress: try: embeddings, valid_paths = EmbeddingService.generate_embeddings( @@ -150,7 +152,7 @@ def _run_projection(embeddings, valid_paths, reduction_method, dim_reduction_bac actual_backend = resolve_backend(dim_reduction_backend, "reduction") logger.info("=" * 60) - logger.info("PROJECTION START") + logger.info(f"PROJECTION START ({session_tag()})") logger.info(f"Device: {device_info} (CUDA: {'Yes' if cuda_available else 'No'})") logger.info(f"Backend: {actual_backend} (requested: {dim_reduction_backend})") @@ -211,7 +213,7 @@ def _run_kmeans(embeddings, n_clusters, clustering_backend, n_workers, seed): """Run KMeans on already-extracted embeddings and add labels to df_plot.""" try: actual_backend = resolve_backend(clustering_backend, "clustering") - logger.info(f"KMeans: k={n_clusters}, backend={actual_backend}") + logger.info(f"KMeans: k={n_clusters}, backend={actual_backend} ({session_tag()})") with st.spinner(f"Running KMeans (k={n_clusters})..."): labels = ClusteringService.run_kmeans_only_safe( diff --git a/apps/precalculated/components/sidebar.py b/apps/precalculated/components/sidebar.py index 162f6cf..a22a4ad 100644 --- a/apps/precalculated/components/sidebar.py +++ b/apps/precalculated/components/sidebar.py @@ -18,6 +18,7 @@ from shared.components.clustering_controls import render_projection_controls, render_kmeans_controls from shared.utils.backend import check_cuda_available, resolve_backend, is_oom_error from shared.utils.logging_config import get_logger +from shared.lib.session import session_tag logger = get_logger(__name__) @@ -618,7 +619,7 @@ def _run_projection(filtered_df, reduction_method, dim_reduction_backend, seed): actual_backend = resolve_backend(dim_reduction_backend, "reduction") logger.info("=" * 60) - logger.info("PROJECTION START") + logger.info(f"PROJECTION START ({session_tag()})") logger.info(f"Device: {device_info} (CUDA: {'Yes' if cuda_available else 'No'})") logger.info(f"Backend: {actual_backend} (requested: {dim_reduction_backend})") @@ -679,7 +680,7 @@ def _run_kmeans(embeddings, n_clusters, clustering_backend, n_workers, seed): """Run KMeans on already-extracted embeddings and add labels to df_plot.""" try: actual_backend = resolve_backend(clustering_backend, "clustering") - logger.info(f"KMeans: k={n_clusters}, backend={actual_backend}") + logger.info(f"KMeans: k={n_clusters}, backend={actual_backend} ({session_tag()})") with st.spinner(f"Running KMeans (k={n_clusters})..."): labels = ClusteringService.run_kmeans_only_safe( diff --git a/shared/lib/session.py b/shared/lib/session.py new file mode 100644 index 0000000..91a1555 --- /dev/null +++ b/shared/lib/session.py @@ -0,0 +1,29 @@ +"""Streamlit session identification for log lines. + +Streamlit can execute the same script twice for one interaction (a duplicated +click event, or a second browser tab), which shows up in the log as doubled +"PROJECTION START" banners with no way to tell the runs apart (#49). Tagging +long-running steps with the session id makes duplicates attributable. +""" + +import threading +from typing import Optional + + +def current_session_id() -> Optional[str]: + """Streamlit session id of the running script, or None outside Streamlit.""" + try: + from streamlit.runtime.scriptrunner import get_script_run_ctx + ctx = get_script_run_ctx(suppress_warning=True) + except Exception: # streamlit missing or API moved: never break logging + return None + return getattr(ctx, "session_id", None) if ctx else None + + +def session_tag() -> str: + """Short, log-friendly tag such as ``session=1a2b3c4d thread=139872`` + (``session=none`` outside Streamlit). The thread id tells two concurrent + script runs of one session apart from one run logging twice.""" + sid = current_session_id() + session = f"session={sid[:8]}" if sid else "session=none" + return f"{session} thread={threading.get_ident()}" diff --git a/shared/utils/backend.py b/shared/utils/backend.py index 7af37a3..5beac10 100644 --- a/shared/utils/backend.py +++ b/shared/utils/backend.py @@ -10,6 +10,7 @@ """ import importlib.util +import threading from typing import Tuple, Optional from shared.utils.logging_config import get_logger @@ -29,6 +30,12 @@ # Cache CUDA availability to avoid repeated checks _cuda_check_cache: Optional[Tuple[bool, str]] = None +# cuML availability: the real import is slow (tens of seconds cold) and not +# safe to run from two threads at once, so it happens under a lock and a +# success is cached. Only True is cached: a transient failure must not stick. +_cuml_check_lock = threading.Lock() +_cuml_available_cache: Optional[bool] = None + def check_cuda_available() -> Tuple[bool, str]: """ @@ -72,15 +79,37 @@ def check_cuda_available() -> Tuple[bool, str]: return _cuda_check_cache +def _import_cuml() -> None: + """Perform the real cuML import (factored out so tests can stub it).""" + import cuml # noqa: F401 + + def check_cuml_available() -> bool: - """Check if cuML is available (actual import, for runtime use).""" + """Check if cuML is available (actual import, for runtime use). + + Serialized with a lock: two Streamlit script runs resolving the backend + at the same moment would otherwise import cuML concurrently, and the + second importer can see a partially initialized package and get an + ImportError, which used to be reported as "cuML not available" (#49). + A successful import is cached so later calls return instantly. + """ + global _cuml_available_cache + if not HAS_CUML_PACKAGE: return False - try: - import cuml + if _cuml_available_cache: + return True + + with _cuml_check_lock: + if _cuml_available_cache: # another thread finished while we waited + return True + try: + _import_cuml() + except ImportError as e: + logger.warning(f"cuML is installed but failed to import ({e}); using CPU backends") + return False + _cuml_available_cache = True return True - except ImportError: - return False def resolve_backend(backend: str, operation: str = "general") -> str: diff --git a/shared/utils/clustering.py b/shared/utils/clustering.py index 4115ef5..095ad0b 100644 --- a/shared/utils/clustering.py +++ b/shared/utils/clustering.py @@ -4,6 +4,7 @@ import subprocess import tempfile import time +import uuid import numpy as np from shared.utils.logging_config import get_logger @@ -315,9 +316,13 @@ def _run_cuml_umap_subprocess(embeddings: np.ndarray, seed: Optional[int]) -> np n_neighbors = min(15, max(2, n_samples - 1)) # Use /dev/shm for fast IPC when available, else /tmp + # Unique per call, not per process: two concurrent runs in one Streamlit + # process (#49) would otherwise share the same files, and the first run's + # cleanup deletes the second run's output ("subprocess failed (rc=0)"). shm_dir = "/dev/shm" if os.path.isdir("/dev/shm") else tempfile.gettempdir() - input_path = os.path.join(shm_dir, f"cuml_umap_in_{os.getpid()}.npy") - output_path = os.path.join(shm_dir, f"cuml_umap_out_{os.getpid()}.npy") + run_id = f"{os.getpid()}_{uuid.uuid4().hex[:8]}" + input_path = os.path.join(shm_dir, f"cuml_umap_in_{run_id}.npy") + output_path = os.path.join(shm_dir, f"cuml_umap_out_{run_id}.npy") np.save(input_path, embeddings) seed_arg = str(seed) if seed is not None else "" From d77ec94deb7b4396fcb558e4967879220adff07c Mon Sep 17 00:00:00 2001 From: Net Zhang Date: Tue, 22 Sep 2026 10:38:19 -0400 Subject: [PATCH 2/2] Keep the newest run alive when a click is duplicated Show a spinner while the compute backend is resolved (the first cuML probe of a session imports cuML, which can take several seconds with no feedback), log every Project to 2D / Run KMeans click with its session and thread ids, and flag runs in flight so a duplicate is visible in the log. The duplicate is never refused: Streamlit stops the older script run at its next Streamlit call once a newer one exists, so refusing the newer run left no projection running at all. --- apps/embed_explore/components/sidebar.py | 29 +++++++++++++++++++----- apps/precalculated/components/sidebar.py | 29 +++++++++++++++++++----- shared/lib/session.py | 28 ++++++++++++++++++++++- 3 files changed, 73 insertions(+), 13 deletions(-) diff --git a/apps/embed_explore/components/sidebar.py b/apps/embed_explore/components/sidebar.py index acedf66..8690758 100644 --- a/apps/embed_explore/components/sidebar.py +++ b/apps/embed_explore/components/sidebar.py @@ -20,7 +20,7 @@ ) from shared.utils.backend import check_cuda_available, resolve_backend, is_oom_error from shared.utils.logging_config import get_logger -from shared.lib.session import session_tag +from shared.lib.session import is_running, session_tag, single_run logger = get_logger(__name__) @@ -121,7 +121,15 @@ def render_projection_section(): dim_reduction_backend, seed = render_projection_controls() if st.button("Project to 2D", type="primary"): - _run_projection(embeddings, valid_paths, reduction_method, dim_reduction_backend, seed) + # Streamlit stops the older script run at its next st call once a + # newer one exists, so the newest run must always proceed: never + # refuse it (#49). Just make a duplicate visible in the log. + logger.info(f"Project to 2D clicked ({session_tag()})") + if is_running("projection_running"): + logger.warning(f"Duplicate projection request in this session; " + f"Streamlit will stop the earlier run ({session_tag()})") + with single_run("projection_running"): + _run_projection(embeddings, valid_paths, reduction_method, dim_reduction_backend, seed) def render_kmeans_section(): @@ -142,14 +150,22 @@ def render_kmeans_section(): clustering_backend, n_workers, seed = render_kmeans_controls() if st.button("Run KMeans", type="primary"): - _run_kmeans(embeddings, n_clusters, clustering_backend, n_workers, seed) + logger.info(f"Run KMeans clicked ({session_tag()})") + if is_running("kmeans_running"): + logger.warning(f"Duplicate KMeans request in this session; " + f"Streamlit will stop the earlier run ({session_tag()})") + with single_run("kmeans_running"): + _run_kmeans(embeddings, n_clusters, clustering_backend, n_workers, seed) def _run_projection(embeddings, valid_paths, reduction_method, dim_reduction_backend, seed): """Run dim reduction and create the 2D scatter plot dataframe.""" try: - cuda_available, device_info = check_cuda_available() - actual_backend = resolve_backend(dim_reduction_backend, "reduction") + # The first cuML probe of a session imports cuML (seconds, cold); show + # feedback so the button never looks dead and invites a second click. + with st.spinner("Checking compute backend..."): + cuda_available, device_info = check_cuda_available() + actual_backend = resolve_backend(dim_reduction_backend, "reduction") logger.info("=" * 60) logger.info(f"PROJECTION START ({session_tag()})") @@ -212,7 +228,8 @@ def _run_projection(embeddings, valid_paths, reduction_method, dim_reduction_bac def _run_kmeans(embeddings, n_clusters, clustering_backend, n_workers, seed): """Run KMeans on already-extracted embeddings and add labels to df_plot.""" try: - actual_backend = resolve_backend(clustering_backend, "clustering") + with st.spinner("Checking compute backend..."): + actual_backend = resolve_backend(clustering_backend, "clustering") logger.info(f"KMeans: k={n_clusters}, backend={actual_backend} ({session_tag()})") with st.spinner(f"Running KMeans (k={n_clusters})..."): diff --git a/apps/precalculated/components/sidebar.py b/apps/precalculated/components/sidebar.py index a22a4ad..f463179 100644 --- a/apps/precalculated/components/sidebar.py +++ b/apps/precalculated/components/sidebar.py @@ -18,7 +18,7 @@ from shared.components.clustering_controls import render_projection_controls, render_kmeans_controls from shared.utils.backend import check_cuda_available, resolve_backend, is_oom_error from shared.utils.logging_config import get_logger -from shared.lib.session import session_tag +from shared.lib.session import is_running, session_tag, single_run logger = get_logger(__name__) @@ -556,7 +556,15 @@ def render_projection_section(): dim_reduction_backend, seed = render_projection_controls() if st.button("Project to 2D", type="primary"): - _run_projection(filtered_df, reduction_method, dim_reduction_backend, seed) + # Streamlit stops the older script run at its next st call once a + # newer one exists, so the newest run must always proceed: never + # refuse it (#49). Just make a duplicate visible in the log. + logger.info(f"Project to 2D clicked ({session_tag()})") + if is_running("projection_running"): + logger.warning(f"Duplicate projection request in this session; " + f"Streamlit will stop the earlier run ({session_tag()})") + with single_run("projection_running"): + _run_projection(filtered_df, reduction_method, dim_reduction_backend, seed) def render_kmeans_section(): @@ -609,14 +617,22 @@ def render_kmeans_section(): clustering_backend, n_workers, seed = render_kmeans_controls() if st.button("Run KMeans", type="primary"): - _run_kmeans(embeddings, n_clusters, clustering_backend, n_workers, seed) + logger.info(f"Run KMeans clicked ({session_tag()})") + if is_running("kmeans_running"): + logger.warning(f"Duplicate KMeans request in this session; " + f"Streamlit will stop the earlier run ({session_tag()})") + with single_run("kmeans_running"): + _run_kmeans(embeddings, n_clusters, clustering_backend, n_workers, seed) def _run_projection(filtered_df, reduction_method, dim_reduction_backend, seed): """Run dim reduction and create the 2D scatter plot dataframe.""" try: - cuda_available, device_info = check_cuda_available() - actual_backend = resolve_backend(dim_reduction_backend, "reduction") + # The first cuML probe of a session imports cuML (seconds, cold); show + # feedback so the button never looks dead and invites a second click. + with st.spinner("Checking compute backend..."): + cuda_available, device_info = check_cuda_available() + actual_backend = resolve_backend(dim_reduction_backend, "reduction") logger.info("=" * 60) logger.info(f"PROJECTION START ({session_tag()})") @@ -679,7 +695,8 @@ def _run_projection(filtered_df, reduction_method, dim_reduction_backend, seed): def _run_kmeans(embeddings, n_clusters, clustering_backend, n_workers, seed): """Run KMeans on already-extracted embeddings and add labels to df_plot.""" try: - actual_backend = resolve_backend(clustering_backend, "clustering") + with st.spinner("Checking compute backend..."): + actual_backend = resolve_backend(clustering_backend, "clustering") logger.info(f"KMeans: k={n_clusters}, backend={actual_backend} ({session_tag()})") with st.spinner(f"Running KMeans (k={n_clusters})..."): diff --git a/shared/lib/session.py b/shared/lib/session.py index 91a1555..b75eabe 100644 --- a/shared/lib/session.py +++ b/shared/lib/session.py @@ -7,7 +7,8 @@ """ import threading -from typing import Optional +from contextlib import contextmanager +from typing import Iterator, Optional def current_session_id() -> Optional[str]: @@ -27,3 +28,28 @@ def session_tag() -> str: sid = current_session_id() session = f"session={sid[:8]}" if sid else "session=none" return f"{session} thread={threading.get_ident()}" + + +def is_running(flag_key: str) -> bool: + """True while a long-running action marked with :func:`single_run` is in flight.""" + import streamlit as st + return bool(st.session_state.get(flag_key, False)) + + +@contextmanager +def single_run(flag_key: str) -> Iterator[None]: + """Mark a long-running action in session state for its duration. + + A duplicated click starts a second script run of the same session while + the first is still executing (#49); session state is shared between them, + so the second run can see the flag and log the duplicate. It must not + refuse to run: Streamlit stops the *older* run at its next Streamlit call + once a newer one exists, so refusing the newer run leaves nothing running. + The flag is always cleared, including when Streamlit stops the run. + """ + import streamlit as st + st.session_state[flag_key] = True + try: + yield + finally: + st.session_state[flag_key] = False