diff --git a/apps/embed_explore/components/sidebar.py b/apps/embed_explore/components/sidebar.py index 511d88b..8690758 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 is_running, session_tag, single_run 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( @@ -119,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(): @@ -140,17 +150,25 @@ 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("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})") @@ -210,8 +228,9 @@ 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") - logger.info(f"KMeans: k={n_clusters}, backend={actual_backend}") + 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})..."): labels = ClusteringService.run_kmeans_only_safe( diff --git a/apps/precalculated/components/sidebar.py b/apps/precalculated/components/sidebar.py index 162f6cf..f463179 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 is_running, session_tag, single_run logger = get_logger(__name__) @@ -555,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(): @@ -608,17 +617,25 @@ 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("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})") @@ -678,8 +695,9 @@ 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") - logger.info(f"KMeans: k={n_clusters}, backend={actual_backend}") + 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})..."): labels = ClusteringService.run_kmeans_only_safe( diff --git a/shared/lib/session.py b/shared/lib/session.py new file mode 100644 index 0000000..b75eabe --- /dev/null +++ b/shared/lib/session.py @@ -0,0 +1,55 @@ +"""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 contextlib import contextmanager +from typing import Iterator, 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()}" + + +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 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 ""