From 1fb6020c14e0de02c66f29f55869f5d710ae6d90 Mon Sep 17 00:00:00 2001 From: Sam Minot Date: Sun, 22 Nov 2026 22:16:09 -0800 Subject: [PATCH 1/2] Fix what a whole-repo code review found; release 1.10.1 Security. A loaded checkpoint's SVG figure was served on the workspace's origin as it came, and the viewer handed the same bytes out as a blob, so a crafted figure opened in its own tab could run script there. Both paths now pass SVG through an allowlist sanitiser (packages/viewer lib/sanitizeSvg.ts), and the figure route sends nosniff on every figure and a CSP sandbox on SVG. Sessions. A checkpoint whose app_state is newer than the app now really opens read-only; it only said so. A save or points-transform with a path outside the data directory is refused with a 400 before anything changes, where it used to rename the session or rewrite the transform and then fail. A transform marks the session unsaved and bumps obsm:spatial when it is applied, not when a save finishes. SDS_CONTAINER_MEM_MB=0 no longer refuses every load. The in-process .zarr import captured its log by swapping sys.stdout, sys.stderr and the root logger's level for the whole API process, so other threads' output landed in its job log and two overlapping imports could leave the streams bound to a dead buffer. It now captures logging records from its own thread, from non-propagating loggers, and from zarr's I/O thread, and leaves the process streams alone. Shared guards raise domain errors that main.py maps to the same status codes and bodies, so the MCP tools no longer import fastapi or reverse-map status codes. The save validators moved to sessions/save_request.py, and the MCP save goes through them too. Analysis Workspace frontend. Lasso-labelling a region set a checkpoint already carries starts from the stored labels instead of erasing them (the path is not reachable from the serverless sidebar today). Cirro upload toasts fire on a change of state, not on every page load. The canvas control props derive from the viewer's own interfaces. Web app. Five unused exports are gone; the reports share GroupCard and useSaveFigure, and three spatial tasks share useSpatialTask. Stale comments about a tile route, a tile cache and a write lock held for a whole job are corrected. The SPA changes need the v1.10.1 tag after merge; the manifests are bumped to match. Co-Authored-By: Claude Opus 5.5 --- DESIGN.md | 2 +- DEVELOPMENT.md | 35 ++- backend/app/config.py | 14 +- backend/app/deps.py | 60 ++--- backend/app/imaging.py | 16 +- backend/app/main.py | 245 ++++-------------- backend/app/mcp/server.py | 38 +-- backend/app/mcp/vision.py | 12 +- backend/app/persistence/store.py | 2 +- backend/app/registry/base.py | 25 +- .../app/registry/custom/read_spatialdata.py | 3 +- backend/app/routers/snapshots.py | 2 +- backend/app/sessions/manager.py | 4 + backend/app/sessions/regions.py | 4 +- backend/app/sessions/save_request.py | 229 ++++++++++++++++ backend/app/sessions/session.py | 80 ++++-- backend/app/snapshots.py | 10 +- backend/app/transport/livelog.py | 85 ++++-- cirro-studio/package.json | 2 +- cirro-studio/src/app/library.ts | 4 +- cirro-studio/src/app/route.ts | 2 - cirro-studio/src/app/ui.tsx | 4 - cirro-studio/src/data/model.ts | 2 - cirro-studio/src/reports/CompareReport.tsx | 31 +-- .../src/reports/CompositionReport.tsx | 19 +- cirro-studio/src/reports/MarkersReport.tsx | 28 +- .../src/reports/NeighborhoodsReport.tsx | 83 +++--- cirro-studio/src/reports/NichesReport.tsx | 57 ++-- cirro-studio/src/reports/parts.tsx | 57 +++- cirro-studio/src/tasks/NeighborhoodsTask.tsx | 8 +- cirro-studio/src/tasks/NichesTask.tsx | 8 +- cirro-studio/src/tasks/SpatialGenesTask.tsx | 8 +- cirro-studio/src/tasks/useSpatialTask.ts | 12 + cirro-studio/src/workbench/workbench.ts | 5 - docs/CONTRACT.md | 6 +- frontend/package.json | 2 +- frontend/src/components/RegionsPanel.tsx | 2 +- frontend/src/data/apiSource.ts | 8 +- frontend/src/hooks/useSSE.ts | 26 +- frontend/src/store/cirroUploads.test.ts | 44 ++++ frontend/src/store/localRegions.test.ts | 99 +++++++ frontend/src/store/sessionStore.ts | 75 +++++- package-lock.json | 12 +- package.json | 2 +- packages/studio-ui/package.json | 2 +- .../studio-ui/src/canvas/CanvasControls.tsx | 47 +--- .../src/canvas/EmbeddingControls.tsx | 18 +- packages/viewer/package.json | 2 +- packages/viewer/src/data/checkpointSource.ts | 7 +- packages/viewer/src/index.ts | 1 + packages/viewer/src/lib/sanitizeSvg.test.ts | 122 +++++++++ packages/viewer/src/lib/sanitizeSvg.ts | 101 ++++++++ 52 files changed, 1148 insertions(+), 624 deletions(-) create mode 100644 backend/app/sessions/save_request.py create mode 100644 cirro-studio/src/tasks/useSpatialTask.ts create mode 100644 frontend/src/store/cirroUploads.test.ts create mode 100644 frontend/src/store/localRegions.test.ts create mode 100644 packages/viewer/src/lib/sanitizeSvg.test.ts create mode 100644 packages/viewer/src/lib/sanitizeSvg.ts diff --git a/DESIGN.md b/DESIGN.md index 2d98554..6d6221c 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -2670,7 +2670,7 @@ and stay retired. The hard requirement is that the agent can *see* a display, *reason* about a pattern, and then *act* on it (annotate/subset) in coordinates provably consistent with the pixels it saw. `view_display` renders through the §14 snapshot core -(`snapshots._render_figure`) and returns two content blocks: the PNG, and a metadata +(`snapshots.render_figure`) and returns two content blocks: the PNG, and a metadata JSON carrying a `pixel_to_world` affine (composing the deck viewport window, the PNG's y-down rows, `invert_x/y`, and — when the display renders in image-pixel space, §9.4 — the image's own `pixel_to_world`), the world window and corner coordinates, diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index e6f7dc4..566388b 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -89,8 +89,9 @@ backend/ FastAPI app holder, session lookup (get_session/get_writable_session — the read-only + edit-lock guard every mutating route goes through), the per-request client id (bind_client_id/CLIENT_ID), the read-lock/executor wrappers, the - image-render admission semaphore, and the business helpers shared by a - route and the MCP surface (default checkpoint path, var-name search) + image-render admission semaphore, and the var-name search a route shares + with the MCP surface. The session guards raise the session layer's own + errors (sessions/session.py), which main.py maps onto 404/403/423/503 app/registry/ base.py (abstract Function + contract envelope), library_fn.py (one reflection executor for squidpy/scanpy/spatialdata-io), custom/ (non-squidpy functions), library_catalog.yaml (opt-in library manifests), terms.yaml + dictionary.py @@ -102,7 +103,9 @@ backend/ FastAPI app app/sessions/ manager, session (queue/worker), presence (viewer list + per-session edit lock), adapter (routes to Function.execute), regions, shape_annotations (arrows/lines/boxes/polygons/ellipses/text -> sdata.shapes["annotations"]), - appstate, transform (points->global affine) + appstate, transform (points->global affine), + save_request (what a checkpoint save may be asked for: destination, name, + element/level/slot/figure selections — shared by the save route and MCP) app/schemas/ pydantic request-body schemas (annotations.py, kept in sync with packages/viewer/src/schemas/annotations.ts's zod schema) app/transport/ arrow (field -> Arrow IPC), tables (element inventory + dataframe page JSON), @@ -218,7 +221,7 @@ Component-level notes: [`backend/README.md`](backend/README.md), | Change the MCP assistant surface (tools, vision render, agent guidance) | `backend/app/mcp/server.py` (tools) + `vision.py` (render/coords/membership) + `agent.py` (presence/lock) + `guides/*.md` (guidance text); mounted in `main.py` | [DESIGN.md](DESIGN.md) §29 | | Change the checkpoint/persistence format | `backend/app/persistence/store.py` | [DESIGN.md](DESIGN.md) §3, §14.1, [docs/CHECKPOINT_FORMAT.md](docs/CHECKPOINT_FORMAT.md) | | Change which elements a save can leave out, which parts of a table it can leave out, at what resolution images are written, or how their sizes are estimated | `backend/app/persistence/store.py` (`select_elements`, `trim_pyramid`, `trim_table`, `element_size_mb`, `image_levels`, `table_slots`) + `sessions/appstate.py` (`prune_to_elements`, `prune_to_table_slots`) + `frontend/src/components/SaveCheckpointDialog.tsx` | below | -| Change where a save writes, what the file is named, or what the session is called | `backend/app/main.py` (`_validated_destination`, `_validated_name`) + `deps.py` (`default_save_path`) + `sessions/session.py` (`rename`, `_run_load`) + `frontend/src/components/SaveCheckpointDialog.tsx` (the checkpoint extension itself is in `frontend/src/lib/checkpointExt.ts`, kept out of the dialog so its lazy chunk stays split) | below | +| Change where a save writes, what the file is named, or what the session is called | `backend/app/sessions/save_request.py` (`validated_destination`, `validated_name`, `default_save_path`) + `sessions/session.py` (`rename`, `_run_load`) + `frontend/src/components/SaveCheckpointDialog.tsx` (the checkpoint extension itself is in `frontend/src/lib/checkpointExt.ts`, kept out of the dialog so its lazy chunk stays split) | below | | Change how rendered plot figures are stored, served or shown | `backend/app/persistence/store.py` (`_write_figures`, `read_figure`, `figure_index`) + `sessions/session.py` (`figure`, `figure_index`, `figures_to_persist`) + `frontend/src/lib/figures.ts` + `components/PlotGallery.tsx` / `FigureLightbox.tsx` / `PlotDetail.tsx` | below | | Change what the serverless viewer can read from a checkpoint | `backend/app/persistence/store.py` (`_write_viewer_sidecar`, the writer half) + `packages/viewer/src/data/checkpointSource.ts` (the reader half) — the two must move together | [DESIGN.md](DESIGN.md) §14.1–14.2, [docs/CHECKPOINT_FORMAT.md](docs/CHECKPOINT_FORMAT.md) §4 | | Change how a store without the sidecar (plain SpatialData) is read — which table, where images and boundaries sit, which cell each boundary belongs to, the default displays | `packages/viewer/src/data/plainSpatialData.ts` (its image placement ports `imaging.pixel_to_world`, its boundary placement `geometry.element_to_world`, its `cellIndexOf` `geometry.cell_index`, its displays `manager.auto_displays`; keep them agreeing) + `plainSpatialData.test.ts` | [docs/CHECKPOINT_FORMAT.md](docs/CHECKPOINT_FORMAT.md) §9 | @@ -325,7 +328,11 @@ still captured and delivered at completion — this only adds a live tap. The session worker sets an ambient sink (`livelog.job_target`) around a read-bootstrap job; `capture_log` (`registry/base.py`) tees each captured write to it, published as `job.log` (`{session_id, job_id, chunk}`). The custom `.zarr` reader runs in the worker -thread, so it publishes directly. Library readers (spatialdata-io Xenium/Visium/…) run +thread, so it publishes directly — and, sharing the API process with every other +session, captures only its own thread's logging records (`livelog.own_thread_logs`, tapping +the root logger and the ones that do not propagate to it, such as spatialdata's, and +admitting zarr's shared I/O thread, where a store read logs its progress), not +stdout/stderr: what the import prints or warns goes to the server console, not the job log. Library readers (spatialdata-io Xenium/Visium/…) run in the loky child, which can't reach the bus: `kernel.run_library_call` opens a `livelog.child_log_stream` (a `multiprocessing.Manager` queue + a drainer thread) for read calls, the child's `capture_log(sink=queue.put)` pushes lines onto it, and the @@ -340,15 +347,16 @@ these in per-job / per-load buffers (`sessionStore`) and renders them with `Ansi ### Where a save writes, and what the file calls itself -`POST /api/sessions/{id}/save` takes three destination fields, all validated at the -route boundary (`main._validated_destination` / `_validated_name`) so a bad one is a 400 -rather than a job that fails minutes into a multi-GB write: +`POST /api/sessions/{id}/save` takes three destination fields, all validated before the +job is queued (`sessions/save_request.py`: `validated_destination` / `validated_name`, run +by the route and by the MCP `save_checkpoint` tool alike) so a bad one is a 400 rather +than a job that fails minutes into a multi-GB write: - `folder` — a directory under `DATA_DIR`, created by the writer if it doesn't exist (`store._zip_from_dir` / `_save_zip` both `mkdir(parents=True)` before staging beside the destination). - `prefix` — the filename stem `-` is appended to, defaulting to the - session's current name. `deps.default_save_path(sess, folder, prefix)` is the single + session's current name. `save_request.default_save_path(sess, folder, prefix)` is the single seam that composes both; the points-transform route and the MCP `save_checkpoint` tool call it with neither and so keep the flat-in-`DATA_DIR` default. - `name` — the session name. `Session.rename` (run on the worker as the save job's @@ -393,7 +401,7 @@ container-level sharing. the table its shape and every field path, and `uns` holds the `spatialdata_attrs` without which it is not a valid SpatialData table. Nor is an `obsm` key a display draws from — `coords`/`obsm_key` are non-nullable in the schema, so unlike a coloring they have no -neutral form; `main._validated_slots` rejects both and the dialog locks the checkboxes to +neutral form; `save_request.validated_slots` rejects both and the dialog locks the checkboxes to match. Everything else, `X` included, can go. **Dropping `X`.** It is usually the largest thing in the file and the reason the control @@ -466,6 +474,13 @@ know: session and a checkpoint. `frontend/src/lib/figures.ts` holds the shared selectors (which format to display, which plots have a figure, byte totals) and `hooks/useFigure.ts` turns one into an object URL, revoked when the plot, format or component changes. + An SVG is cleaned on the way out of `getPlotFigure`, in both sources + (`packages/viewer/src/lib/sanitizeSvg.ts`, with `sanitizeSvg.test.ts`): the store may be + one somebody else chose — a live session serves a loaded checkpoint's figures verbatim — + and that object URL opened outside an `` is a document of the app's origin. Only an + allowlist of drawing elements, local `#id` references and embedded rasters survive, so a + matplotlib feature that writes an element outside the list needs the list extended, or + it will be missing from the copy the app shows and downloads. ## Local dev environment diff --git a/backend/app/config.py b/backend/app/config.py index dc3a2d0..0357e76 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -224,9 +224,10 @@ class Config: MAX_SESSIONS = int(os.environ.get("SDS_MAX_SESSIONS", "8")) - # Max image tiles/thumbnails composited at once. A zoom/pan burst asks for many - # tiles simultaneously, and each finest-level tile can realize a full multi-MB - # pyramid chunk; this caps the concurrent transient so the burst can't OOM. + # Max image thumbnails composited at once (deps.render_image; the thumbnail route + # is its only caller, the canvas compositing client-side). Each one realizes a whole + # coarsest pyramid level and an RGB composite of it; this caps the concurrent + # transient so several requested together can't OOM. # Scales with the CPU allocation by default (compositing is CPU-bound) rather than a # fixed small number, so a bigger deployment gets more parallelism without a config # change; override down via the env var on a memory-constrained container. @@ -294,8 +295,11 @@ class Config: LONG_RUNNING_S = float(os.environ.get("SDS_LONG_RUNNING_S", "120")) # watchdog threshold # Max time a read-only endpoint waits on the session read lock before giving up - # with a fast 503 instead of hanging. Reads block while a compute/plot job holds - # the write lock for its whole duration; behind a fronting proxy (e.g. CloudFront, + # with a fast 503 instead of hanging. A compute/plot job runs with no lock and takes + # the write lock only to commit its result, but reads still block for as long as that + # commit lasts, and adopting a new object (an import, a checkpoint load, a compute + # that returns a replacement) re-tiles its rasters under the lock, which can take + # minutes for a large store; behind a fronting proxy (e.g. CloudFront, # ~30s origin timeout) a longer block returns a 504 to the browser. Failing fast # under that limit turns the hang into a retryable 503 the frontend re-issues once # the job completes (via SSE). Keep comfortably below the proxy's timeout. diff --git a/backend/app/deps.py b/backend/app/deps.py index 4e357c5..364ff27 100644 --- a/backend/app/deps.py +++ b/backend/app/deps.py @@ -3,7 +3,9 @@ and every router module. Kept out of main.py so routers can import them without a circular dependency on the app object (main.py imports the routers, not vice versa). Session-scoped business logic shared between a route and the MCP surface (the -default checkpoint path, the var-name search) lives here too, for the same reason. +var-name search) lives here too, for the same reason. The session guards below are +that as well, so they raise the session layer's own errors (sessions/session.py), +which main.py maps onto HTTP statuses. """ import asyncio import contextlib @@ -14,6 +16,8 @@ from .config import config from .sessions.manager import SessionManager from .sessions.presence import PRESENCE +from .sessions.session import (SessionBusyError, SessionLockedError, SessionNotFoundError, + SessionReadOnlyError) # The process-wide manager, bound by lifespan once the registry is built. Public # (not underscore) because it is the canonical live-manager handle for out-of-request @@ -51,7 +55,7 @@ def bad_request(): def get_session(sid: str): s = get_manager().get(sid) if s is None: - raise HTTPException(404, "session not found") + raise SessionNotFoundError("session not found") return s @@ -63,7 +67,7 @@ def get_writable_session(sid: str): not just an unwired UI.""" s = get_session(sid) if s.read_only: - raise HTTPException(403, "session is read-only") + raise SessionReadOnlyError("session is read-only") claim_lock(sid) return s @@ -75,7 +79,7 @@ def claim_lock(sid: str): viewers writing at once.""" holder = PRESENCE.claim(sid, CLIENT_ID.get()) if holder is not None: - raise HTTPException(423, f"session is locked by {holder.name}") + raise SessionLockedError(f"session is locked by {holder.name}") # The calling browser client's id, bound per request from the X-SDS-Client-Id header @@ -98,24 +102,6 @@ async def in_executor(fn, *a): return await asyncio.get_running_loop().run_in_executor(None, fn, *a) -def default_save_path(sess, folder: str | None = None, prefix: str | None = None) -> str: - """Checkpoint path to use when the caller doesn't give one explicitly — shared by - the save/points-transform routes and the MCP save_checkpoint tool. The filename's - content-hash suffix is (re)computed from the written bytes on every save (see - `_save_zip`), so this only needs the checkpoint's clean base name - stripping any - hash (or extension) a previous save already appended keeps it from stacking a new - one on top. - - `folder` (a directory under DATA_DIR, relative to it or absolute) and `prefix` (the - filename stem the hash is appended to) are the Save dialog's destination fields; - without them the file lands flat in DATA_DIR under the session's name. Both are - validated at the route boundary (`main._validated_destination`) — a caller reaching - this directly must have checked them itself.""" - from .persistence.store import strip_content_hash, strip_checkpoint_ext, CHECKPOINT_EXT - stem = strip_content_hash(strip_checkpoint_ext(prefix or sess.name)) - return str(config.DATA_DIR / (folder or "") / f"{stem}{CHECKPOINT_EXT}") - - async def search_var_names(sess, q: str = "", limit: int = 50) -> list[str]: """Search the session's var_names (genes) — the color-by gene picker route and the MCP search_genes tool. adata can carry tens of thousands of genes, so match @@ -137,17 +123,21 @@ def _search(): async def read_locked(sess, fn, *a): """Run `fn(*a)` in the executor under the session's read lock — the shape every read-only endpoint needs to serve a field/manifest/preview off a session that a - queued job may be mutating concurrently. A compute/plot job holds the write lock for - its whole duration; rather than block past a fronting proxy's origin timeout (which - surfaces as a 504), give up after READ_LOCK_TIMEOUT_S with a retryable 503 the - frontend re-issues once the job completes.""" + queued job may be mutating concurrently. A compute/plot job computes with no lock + held and takes the write lock only to commit its result (`Session._run_call`), but a + commit can be long: adopting a read bootstrap's or a loaded checkpoint's object + re-tiles its rasters under the write lock (minutes for a large store), and a + close-with-save writes the whole checkpoint under it. Rather than block past a + fronting proxy's origin timeout (which surfaces as a 504), give up after + READ_LOCK_TIMEOUT_S with a retryable 503 (`SessionBusyError`) the frontend re-issues + once the lock is free.""" def _run(): # acquire_read reports the timeout as False rather than raising, so the 503 covers # ONLY the acquisition: a TimeoutError raised by fn itself (a slow network read, # say) is a different failure and must not be relabelled as lock contention the # client will retry forever. if not sess.lock.acquire_read(config.READ_LOCK_TIMEOUT_S): - raise HTTPException(503, "session busy: compute in progress, retry") + raise SessionBusyError("session busy: compute in progress, retry") try: return fn(*a) finally: @@ -155,18 +145,18 @@ def _run(): return await in_executor(_run) -# Global cap on concurrent image compositing. deck.gl fires a burst of tile requests on -# every zoom/pan, and each finest-level tile can realize a full multi-MB pyramid chunk; -# without this a burst decodes them all at once and spikes memory. Shared across sessions -# since RAM is a process-wide resource. +# Global cap on concurrent server-side image compositing. The only thing composited +# here is the thumbnail (routers/imaging.py; the canvas composites tiles in the browser), +# and each one decodes and composites a whole level of the image's pyramid; without +# this, several arriving together decode at once and spike memory. Shared across +# sessions since RAM is a process-wide resource. _IMAGE_RENDER_SEM = asyncio.Semaphore(config.IMAGE_RENDER_CONCURRENCY) async def render_image(sess, fn): - """Composite a tile/thumbnail under the render semaphore, refusing once RSS is past - the admission boundary so a zoom burst can't push an already-loaded container into - OOM. 503 lets the frontend keep its coarse base layer and retry as memory frees - (BitmapLayer just re-requests on the next viewport change).""" + """Composite an image thumbnail under the render semaphore, refusing once memory is + past the admission boundary so a render can't push an already-loaded container into + OOM. The 503 is retryable: the caller asks again once memory has freed.""" async with _IMAGE_RENDER_SEM: if get_manager().over_memory_boundary(): raise HTTPException(503, "image render deferred: memory boundary reached") diff --git a/backend/app/imaging.py b/backend/app/imaging.py index 2d79cfd..f4e872f 100644 --- a/backend/app/imaging.py +++ b/backend/app/imaging.py @@ -1,10 +1,12 @@ """Image serving for the canvas background (DESIGN §9.2). -Large sections (Xenium: ~34k x 14k px, multi-GB) can't ship as one image, so we -serve the SpatialData multiscale pyramid as WebP tiles: deck.gl requests only the -tiles visible at the current zoom, from the level whose native resolution matches -the screen. A single coarse thumbnail is still served as an always-present base -layer under the tiles. +Large sections (Xenium: ~34k x 14k px, multi-GB) can't ship as one image, so the +canvas composites client-side: the browser (Viv) reads the session's normalized +multiscale raster zarr chunk by chunk through the raw raster-store route, fetching +only what is visible at the current zoom. This module describes each image for that +client (`image_info`: dimensions, pyramid levels, channels, contrast domain), keeps +the cache of raw chunk bytes the route serves from, and renders the one image the +server still composites itself: a WebP thumbnail of the coarsest level. Two coordinate spaces have to be reconciled. The spot/cell coordinates in `obsm["spatial"]` may be in different units (e.g. Xenium microns) than the image's @@ -48,7 +50,7 @@ # reads one compressed chunk file per browser request; without this, panning back # over already-seen tiles re-reads each chunk (a syscall + read-lock round trip, and # a real disk read when WORK_DIR is not RAM-backed). Same (id(sdata), ...) keying as -# the tile cache, so evict_caches drops it on the same adoption/close boundary. +# _norm_cache, so evict_caches drops it on the same adoption/close boundary. # Byte-budgeted because these bytes live in the API process heap (counted in RSS); # guarded by a lock since reads run under the shared — hence concurrent — read lock. _raster_chunk_cache: "OrderedDict[tuple, bytes]" = OrderedDict() @@ -59,7 +61,7 @@ def evict_caches(sdata) -> None: """Drop every cache entry belonging to `sdata`. Call before a session's object is - released so a reused id() can't serve another image's cached norm/tiles/chunks.""" + released so a reused id() can't serve another image's cached norm or chunks.""" global _raster_chunk_bytes sid = id(sdata) with _norm_cache_lock: diff --git a/backend/app/main.py b/backend/app/main.py index 42f351d..21f3707 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -6,12 +6,14 @@ from fastapi.responses import JSONResponse, StreamingResponse from fastapi.staticfiles import StaticFiles -from .config import config, data_roots, within_data_dir +from .config import config, data_roots from .registry.introspect import REGISTRY from .registry.reader_paths import reader_namespace from .sessions.manager import SessionManager from .sessions.presence import PRESENCE, clean_name -from .sessions.session import SessionLoadingError +from .sessions import save_request +from .sessions.session import (SessionBusyError, SessionLoadingError, SessionLockedError, + SessionNotFoundError, SessionReadOnlyError) from .transport.sse import BUS from .transport import arrow from .transport import tables @@ -20,8 +22,7 @@ from . import datasets from . import deps from .deps import (get_session, get_writable_session, claim_lock, get_manager, in_executor, - read_locked, bad_request, bind_client_id, CLIENT_ID, - default_save_path, search_var_names) + read_locked, bad_request, bind_client_id, CLIENT_ID, search_var_names) from .routers import imaging as imaging_router, cirro as cirro_router from .routers import snapshots as snapshots_router, recipes as recipes_router from .mcp.server import mcp_server @@ -104,6 +105,22 @@ async def _session_still_loading(request: Request, exc: SessionLoadingError): and in routers/ — answers the same way.""" return JSONResponse(status_code=409, content={"detail": str(exc)}) + +# The refusals of the shared session guards (deps.get_session / get_writable_session / +# claim_lock / read_locked), which raise domain errors because the MCP surface calls +# them too. Each is answered as `{"detail": }` with the status below. +_SESSION_GUARD_STATUS = {SessionNotFoundError: 404, SessionReadOnlyError: 403, + SessionLockedError: 423, SessionBusyError: 503} + + +async def _session_guard_refused(request: Request, exc: Exception): + return JSONResponse(status_code=_SESSION_GUARD_STATUS[type(exc)], + content={"detail": str(exc)}) + + +for _guard_error in _SESSION_GUARD_STATUS: + app.add_exception_handler(_guard_error, _session_guard_refused) + # Self-contained route domains live in routers/ (imports above); the rest — sessions, # jobs, staging, plots, displays, subset/save, shape annotations, the data path, and # SSE — stay here where they share the session/job wiring. Shared helpers (get_session, @@ -371,6 +388,20 @@ async def redraw(sid: str, plot_id: str): return {"ok": True} +# A figure's bytes can come verbatim from a loaded checkpoint (`Session.figure` falls +# back to the store's own), and an SVG opened as a document on this origin would run any +# script it carries with the workspace's authority. `sandbox` gives such a document an +# opaque origin and no script; nosniff keeps the declared type. Only the SVG is +# sandboxed: a browser's PDF viewer does not run inside a sandboxed document. The SPA +# fetches the bytes instead and cleans an SVG itself (viewer `sanitizeSvg`) before it +# makes a blob URL of one. +_FIGURE_HEADERS = {"X-Content-Type-Options": "nosniff"} +_SVG_FIGURE_HEADERS = { + **_FIGURE_HEADERS, + "Content-Security-Policy": "sandbox; default-src 'none'; style-src 'unsafe-inline'", +} + + @app.get("/api/sessions/{sid}/plots/{plot_id}/figure") async def figure(sid: str, plot_id: str, fmt: str = "svg"): media = {"svg": "image/svg+xml", "pdf": "application/pdf", "png": "image/png"}.get(fmt) @@ -381,7 +412,8 @@ async def figure(sid: str, plot_id: str, fmt: str = "svg"): blob = get_session(sid).figure(plot_id, fmt) if blob is None: raise HTTPException(404, "figure not drawn") - return Response(content=blob, media_type=media) + return Response(content=blob, media_type=media, + headers=_SVG_FIGURE_HEADERS if fmt == "svg" else _FIGURE_HEADERS) # ---- displays -------------------------------------------------------------- @@ -459,194 +491,18 @@ async def list_third_party_licenses(): return acknowledgements.catalog() -def _validated_include(sess, include) -> dict[str, list[str]] | None: - """Check the save body's element selection against the session, raising 400 rather - than letting a bad name surface as a failed job. A facet absent from `include` keeps - that facet whole; a facet present keeps exactly the names listed, so `{"images": []}` - drops every image.""" - if include is None: - return None - from .registry.base import sdata_facets - if not isinstance(include, dict): - raise HTTPException(400, "include must be an object of facet -> element names") - facets = sdata_facets() - out: dict[str, list[str]] = {} - for facet, names in include.items(): - if facet not in facets: - raise HTTPException(400, f"unknown element facet '{facet}'") - if not isinstance(names, list): - raise HTTPException(400, f"include['{facet}'] must be a list of element names") - have = set(getattr(sess.sdata, facet, None) or {}) - missing = sorted(n for n in names if n not in have) - if missing: - raise HTTPException(400, f"unknown {facet} element(s): {', '.join(missing)}") - out[facet] = list(names) - kept = out.get("tables") - # Dropping the table the displays and every field path are resolved against would - # produce a checkpoint that reopens with nothing to show. - if kept is not None and sess.active_table_key is not None: - if sess.active_table_key not in kept: - raise HTTPException(400, "the active table must be included in the saved checkpoint") - # `select_elements` keeps the listed order, and a display names no table — it - # resolves against the first one. So a list that includes the active table but - # does not lead with it would hand the reopened checkpoint a different default - # table than the app_state written beside it describes. Reordering keeps both - # tables and costs nothing; the order carries no other meaning. - out["tables"] = [sess.active_table_key] + [n for n in kept if n != sess.active_table_key] - return out - - -def _validated_levels(sess, levels) -> dict[str, int] | None: - """Check the save body's per-image resolution choice — image name -> index of the - finest pyramid level to write, coarser levels always kept, so 0 writes the whole - pyramid. Levels a caller left at 0 are dropped here, so an all-0 request is - indistinguishable from no request at all and keeps the incremental fast path.""" - if not levels: - return None - if not isinstance(levels, dict): - raise HTTPException(400, "levels must be an object of image name -> level index") - from . import imaging - out: dict[str, int] = {} - for name, finest in levels.items(): - if name not in (getattr(sess.sdata, "images", None) or {}): - raise HTTPException(400, f"unknown images element '{name}'") - depth = len(imaging.image_levels(sess.sdata, name)) - if not isinstance(finest, int) or isinstance(finest, bool) or not 0 <= finest < depth: - raise HTTPException(400, f"levels['{name}'] must be an integer in 0..{depth - 1}") - if finest: - out[name] = finest - return out or None - - -def _validated_slots(sess, slots) -> dict[str, list[str]] | None: - """Check the save body's per-table slot selection — table name -> the slot paths to - write (`store.table_slot_paths`' vocabulary). A table absent from `slots` is written - whole; a table present keeps exactly the paths listed. Two things a selection may - not drop, because the resulting file would not open onto what it claims to hold: - the structurally required slots (`store.REQUIRED_TABLE_SLOTS`), and an `obsm` key a - display reads its coordinates or its embedding from — `coords` and `obsm_key` are - non-nullable in `app_state.schema.json`, so unlike a coloring they cannot be - neutralised.""" - if not slots: - return None - if not isinstance(slots, dict): - raise HTTPException(400, "slots must be an object of table name -> slot paths") - from .persistence import store - out: dict[str, list[str]] = {} - for name, paths in slots.items(): - adata = (getattr(sess.sdata, "tables", None) or {}).get(name) - if adata is None: - raise HTTPException(400, f"unknown tables element '{name}'") - if not isinstance(paths, list) or not all(isinstance(p, str) for p in paths): - raise HTTPException(400, f"slots['{name}'] must be a list of slot paths") - have = store.table_slot_paths(adata) - if unknown := sorted(set(paths) - set(have)): - raise HTTPException(400, f"unknown slot(s) in table '{name}': {', '.join(unknown)}") - if missing := [p for p in store.REQUIRED_TABLE_SLOTS if p not in paths]: - raise HTTPException( - 400, f"table '{name}' cannot be saved without: {', '.join(missing)}") - for key in _display_obsm_keys(sess) if name == sess.active_table_key else (): - if f"obsm/{key}" in have and f"obsm/{key}" not in paths: - raise HTTPException(400, f"obsm/{key} is used by a display and must be saved") - out[name] = list(paths) - return out - - -def _display_obsm_keys(sess) -> set[str]: - """The obsm keys the session's displays resolve against: an embedding's `obsm_key` - and a spatial display's `coords` (an `obsm:` field path).""" - keys = set() - for d in sess.app_state.get("displays", []): - enc = d.get("encoding") or {} - if key := enc.get("obsm_key"): - keys.add(key) - element, _, key = (enc.get("coords") or "").partition(":") - if element == "obsm" and key: - keys.add(key) - return keys - - -def _validated_figures(sess, figures) -> list[str] | None: - """Check the save body's figure selection: `null`/absent keeps every drawn plot's - figure, a list keeps exactly those plot ids (`[]` writes no figures at all). Ids that - aren't drawn plots are a client bug, not something to silently drop.""" - if figures is None: - return None - if not isinstance(figures, list) or not all(isinstance(p, str) for p in figures): - raise HTTPException(400, "figures must be a list of plot ids") - missing = sorted(set(figures) - sess.drawn_plot_ids()) - if missing: - raise HTTPException(400, f"no drawn plot(s) with id(s): {', '.join(missing)}") - return figures - - -def _validated_name(body) -> str | None: - """The save body's session name: what the checkpoint records as its own name - (`app_state["name"]`, adopted again when the file is reloaded) and what the live - session is renamed to. Absent leaves both alone.""" - name = body.get("name") - if name is None: - return None - if not isinstance(name, str) or not name.strip(): - raise HTTPException(400, "name must be a non-empty string") - return name.strip() - - -def _validated_destination(sess, body) -> tuple[str, bool]: - """Resolve the save body's destination to (path, hash_name). - - `path` is the verbatim escape hatch — written exactly as given, with no content-hash - suffix (the MCP save_checkpoint tool and the offline harness use it). The Save dialog - instead sends `folder` (a directory under DATA_DIR, created if it doesn't exist) and - `prefix` (the filename stem), which compose onto `default_save_path` and so keep the - hash suffix. A folder outside DATA_DIR or a prefix that isn't a plain filename is a - 400 here rather than a job that fails minutes into a multi-GB write.""" - explicit = body.get("path") - folder, prefix = body.get("folder"), body.get("prefix") - if explicit is not None and (folder is not None or prefix is not None): - raise HTTPException(400, "path cannot be combined with folder or prefix") - if explicit is not None: - if not isinstance(explicit, str) or not explicit.strip(): - raise HTTPException(400, "path must be a non-empty string") - return explicit, False - if folder is not None: - if not isinstance(folder, str): - raise HTTPException(400, "folder must be a string") - target = (config.DATA_DIR / folder).resolve() - if not within_data_dir(target): - raise HTTPException(400, "folder is outside the data directory") - if target.exists() and not target.is_dir(): - raise HTTPException(400, f"'{folder}' is not a directory") - if prefix is not None: - if not isinstance(prefix, str) or not prefix.strip(): - raise HTTPException(400, "prefix must be a non-empty string") - prefix = prefix.strip() - # One path component, and not dot-prefixed: the dataset scanner skips names - # starting with "." (it is how save staging hides itself), so such a checkpoint - # would never appear in the load picker. - if "/" in prefix or "\\" in prefix or prefix.startswith("."): - raise HTTPException(400, "prefix must be a filename with no path separators") - return default_save_path(sess, folder, prefix), True - - @app.post("/api/sessions/{sid}/save") async def save(sid: str, body: dict | None = None): + """Queue a checkpoint save. The body's destination, name and selections are checked + by `save_request` (shared with the MCP save_checkpoint tool); what it refuses is a + 400 here rather than a failed job.""" sess = get_writable_session(sid) - body = body or {} - name = _validated_name(body) - # The stem `prefix` falls back to is the session's name as it stands now; the rename - # lands on the worker together with the write (Session._run_save), so a save that - # never runs leaves both the name and the file alone. - path, hash_name = _validated_destination(sess, body) - include = _validated_include(sess, body.get("include")) - levels = _validated_levels(sess, body.get("levels")) - slots = _validated_slots(sess, body.get("slots")) - figures = _validated_figures(sess, body.get("figures")) - job_id = sess.enqueue_special("save", {"path": path, "hash_name": hash_name, - "name": name, "include": include, - "levels": levels, "slots": slots, - "figures": figures}) - return {"job_id": job_id, "path": path} + try: + payload = save_request.validated_payload(sess, body or {}) + except save_request.SaveRequestError as e: + raise HTTPException(400, str(e)) + job_id = sess.enqueue_special("save", payload) + return {"job_id": job_id, "path": payload["path"]} # ---- points -> global coordinate transform --------------------------------- @@ -671,7 +527,14 @@ async def set_points_transform(sid: str, body: dict): if not (isinstance(affine, list) and len(affine) == 6): raise HTTPException(400, "affine must be 6 floats [a, b, c, d, e, f]") explicit = body.get("path") - path = explicit or default_save_path(sess) + if explicit: + if not isinstance(explicit, str): + raise HTTPException(400, "path must be a string") + try: + save_request.require_save_path(explicit) + except save_request.SaveRequestError as e: + raise HTTPException(400, str(e)) + path = explicit or save_request.default_save_path(sess) job_id = sess.enqueue_special("set_transform", {"affine": affine, "path": path, "hash_name": not explicit}) return {"job_id": job_id, "path": path} diff --git a/backend/app/mcp/server.py b/backend/app/mcp/server.py index 58cdaf1..1adc63c 100644 --- a/backend/app/mcp/server.py +++ b/backend/app/mcp/server.py @@ -13,8 +13,8 @@ one POST, no SSE dependency, so it survives buffering proxies and is trivially testable. - The assistant participates in presence/locking as a first-class viewer - (mcp/agent.py); mutating tools surface the 423 "locked by " as a clean - error with the takeover hint. + (mcp/agent.py); mutating tools surface the edit-lock refusal ("locked by + ") as a clean error with the takeover hint. - Guidance for the agent (domain + app) ships as markdown in mcp/guides/, served by `read_guide` and indexed in the server instructions below. """ @@ -25,7 +25,6 @@ import time from pathlib import Path -from fastapi import HTTPException from mcp.server.fastmcp import FastMCP from mcp.server.fastmcp.utilities.types import Image from mcp.server.transport_security import TransportSecuritySettings @@ -35,11 +34,13 @@ from ..config import config, data_roots from ..registry.introspect import REGISTRY from ..registry.reader_paths import reader_namespace -from ..sessions.session import TERMINAL_JOB_STATUSES +from ..sessions import save_request +from ..sessions.session import (TERMINAL_JOB_STATUSES, SessionLockedError, + SessionNotFoundError, SessionReadOnlyError) from ..transport import tables from ..transport.sse import BUS from .. import deps -from ..deps import in_executor, read_locked, default_save_path, search_var_names +from ..deps import in_executor, read_locked, search_var_names GUIDES_DIR = Path(__file__).parent / "guides" GUIDE_TOPICS = { @@ -120,14 +121,15 @@ def _sess(session_id: str | None = None): def _writable(session_id: str | None = None): """The mutating-tool guard: same checks as the REST routes (read-only + edit - lock), with the HTTPException translated into an agent-actionable error.""" + lock), with the refusal translated into an agent-actionable error.""" try: return deps.get_writable_session(_sid(session_id)) - except HTTPException as e: - hint = (" — call set_active_session(session_id, take_control=True) to take the " - "edit lock (tell the user first; they keep watching read-only)" - if e.status_code == 423 else "") - raise RuntimeError(f"{e.detail}{hint}") + except SessionLockedError as e: + raise RuntimeError(f"{e} — call set_active_session(session_id, take_control=True) " + "to take the edit lock (tell the user first; they keep watching " + "read-only)") + except (SessionNotFoundError, SessionReadOnlyError) as e: + raise RuntimeError(str(e)) async def _await_job(sess, job_id: str, timeout_s: float) -> str: @@ -332,12 +334,14 @@ async def release_control() -> dict: async def save_checkpoint(session_id: str | None = None, path: str | None = None, wait: bool = True, timeout_s: float = 600) -> dict: """Save the session to a .zarr.zip checkpoint (reloadable via create_session). - Default path: / with a content-hash suffix.""" + Default path: / with a content-hash suffix. An explicit + path must be under the data dir.""" agent.bind_agent() sess = _writable(session_id) - target = path or default_save_path(sess) - job_id = sess.enqueue_special("save", {"path": target, "hash_name": not path}) - out = await _special_job_report(sess, job_id, wait, timeout_s, path=target) + # The same checks the save route applies; a refused request raises here. + payload = save_request.validated_payload(sess, {"path": path} if path else {}) + job_id = sess.enqueue_special("save", payload) + out = await _special_job_report(sess, job_id, wait, timeout_s, path=payload["path"]) if out["status"] == "completed": out["path"] = sess.store_path # the save may have appended the hash suffix return out @@ -353,8 +357,8 @@ async def close_session(session_id: str, save: bool = False) -> dict: else: try: deps.claim_lock(session_id) - except HTTPException as e: - raise RuntimeError(str(e.detail)) + except SessionLockedError as e: + raise RuntimeError(str(e)) # A failed save raises here with the session still open, and the assistant stays # attached to it. await in_executor(_mgr().close, session_id, save) diff --git a/backend/app/mcp/vision.py b/backend/app/mcp/vision.py index 6936d32..d1874ea 100644 --- a/backend/app/mcp/vision.py +++ b/backend/app/mcp/vision.py @@ -2,7 +2,7 @@ with an exact, machine-usable mapping between the PNG's pixels and the session's world coordinates. -Built on the snapshot render core (`snapshots._render_figure`), which already +Built on the snapshot render core (`snapshots.render_figure`), which already reproduces any spatial/embedding display — image compositing, palette-matched cells, boundary polygons — for a given viewport. This module adds what an *agent* needs on top of a human-facing figure: @@ -214,12 +214,12 @@ def render_view(session, display_id: str | None = None, viewport=None, viewport = display["viewport"] spec = {"display_id": display.get("id"), "viewport": viewport, "width_px": width_px, "height_px": height_px, "dpi": RENDER_DPI} - # _render_figure builds a bare (non-pyplot) Figure — no Gcf registration, so + # render_figure builds a bare (non-pyplot) Figure — no Gcf registration, so # nothing to close and concurrent renders can't corrupt shared figure state. - fig, render_meta = snapshots._render_figure(session, spec) + fig, render_meta = snapshots.render_figure(session, spec) ax = fig.axes[0] target, zoom = viewport["target"], float(viewport["zoom"]) - bbox = snapshots._window(target, zoom, width_px, height_px) + bbox = snapshots.viewport_window(target, zoom, width_px, height_px) # view -> world: identity unless the display renders in image-pixel space. kind, _, p2w, w2v = snapshots.view_frame(session, display) @@ -292,7 +292,7 @@ def px_to_world(px: float, py: float) -> list[float]: # ---- region membership (shared by inspect/annotate/subset) ---------------------- def cells_in_polygons(session, display: dict | None, polygons, space: str = "spatial") -> np.ndarray: """Boolean mask of active-table cells inside any of the polygon rings. - space='spatial': rings are world coordinates (reuses regions._membership, the + space='spatial': rings are world coordinates (reuses regions.membership, the same math the annotate endpoint applies). space='embedding': rings are embedding coordinates of the display's obsm components — resolved here because the backend annotate/subset endpoints only take embedding selections as cell_indices.""" @@ -300,7 +300,7 @@ def cells_in_polygons(session, display: dict | None, polygons, space: str = "spa adata = session.active_table() if space == "spatial": - return regions._membership(session.sdata, adata, {"polygons": polygons}) + return regions.membership(session.sdata, adata, {"polygons": polygons}) from matplotlib.path import Path as MplPath coords = snapshots.point_coords(session, (display or {}).get("encoding", {}), "embedding") diff --git a/backend/app/persistence/store.py b/backend/app/persistence/store.py index bea8240..acfce78 100644 --- a/backend/app/persistence/store.py +++ b/backend/app/persistence/store.py @@ -507,7 +507,7 @@ def select_elements(sdata, include: dict[str, list[str]] | None = None, selection just dropped. A name in `include` that the object does not have is a ValueError. The save route - has already rejected it with a 400 (`main._validated_include`), so reaching here + has already rejected it with a 400 (`save_request.validated_include`), so reaching here means a caller built the selection itself (the CLI, the MCP surface) — dropping the name instead would hand that caller a checkpoint quietly missing an element it asked for. diff --git a/backend/app/registry/base.py b/backend/app/registry/base.py index 9bcf13a..9c0dd1e 100644 --- a/backend/app/registry/base.py +++ b/backend/app/registry/base.py @@ -285,15 +285,34 @@ def getvalue(self): return _clean_log(super().getvalue()) +# zarr does a store's reads on one loop thread of its own (zarr.core.sync), and that +# is where it logs each group and array it opens — the only progress an in-process +# store read reports. +_STORE_IO_THREADS = ("zarr_io",) + + @contextlib.contextmanager -def capture_log(sink=None): +def capture_log(sink=None, *, process_wide: bool = True): """Capture everything the call logs/prints into a returned buffer. When a `sink` is given (or an ambient live-log target is set — see transport/livelog.py), each - write is also streamed to the client live.""" + write is also streamed to the client live. + + The default swaps sys.stdout/sys.stderr and taps the root logger unfiltered, which + is only sound where the call owns its process: a compute-pool child (kernel.py). A + call that runs in the API process on a session worker thread passes + `process_wide=False` and gets the records its own thread logs (the root's and + spatialdata's), with zarr's from its I/O thread, and nothing else — not what it or + a library prints or warns straight to stdout/stderr, which stays on the console + (livelog.own_thread_logs has the reasons).""" + from ..transport import livelog if sink is None: - from ..transport import livelog sink = livelog.current_sink() buf = _CaptureBuffer(sink) + if not process_wide: + with livelog.own_thread_logs(buf.write, logging.DEBUG, detached=True, + helper_threads=_STORE_IO_THREADS): + yield buf + return handler = logging.StreamHandler(buf) handler.setLevel(logging.DEBUG) root = logging.getLogger() diff --git a/backend/app/registry/custom/read_spatialdata.py b/backend/app/registry/custom/read_spatialdata.py index 9e4aa75..b155a96 100644 --- a/backend/app/registry/custom/read_spatialdata.py +++ b/backend/app/registry/custom/read_spatialdata.py @@ -62,7 +62,8 @@ def execute(self, params: dict, session) -> CallResult: store = params.get("store") if not store: return CallResult(status="failed", error="a store path is required") - with capture_log() as buf: + # Runs on the session worker thread in the API process, not in a pool child. + with capture_log(process_wide=False) as buf: try: sdata, extract_dir, _ = read_spatialdata_archive(store) except Exception as e: diff --git a/backend/app/routers/snapshots.py b/backend/app/routers/snapshots.py index 7862143..893382c 100644 --- a/backend/app/routers/snapshots.py +++ b/backend/app/routers/snapshots.py @@ -16,7 +16,7 @@ @contextlib.contextmanager def _snapshot_errors(): """Map a render's failure modes onto status codes, shared by save and preview — the - two run the same `_render_figure` and previously disagreed, the save endpoint letting + two run the same `render_figure` and previously disagreed, the save endpoint letting a bad `obsm_key` escape as a 500 where the preview answered 400. A read-lock timeout is the same retryable 503 every other read path returns (deps.read_locked).""" try: diff --git a/backend/app/sessions/manager.py b/backend/app/sessions/manager.py index bd3675c..a5a4e9d 100644 --- a/backend/app/sessions/manager.py +++ b/backend/app/sessions/manager.py @@ -534,6 +534,10 @@ def _check_capacity(self): raise RuntimeError(f"max concurrent sessions ({config.MAX_SESSIONS}) reached") def _check_admission(self, resident_mb: float): + # A non-positive limit disables memory accounting (see `_mem_fraction`); without + # this, `avail` would be negative and every load refused. + if config.CONTAINER_MEM_MB <= 0: + return avail = config.CONTAINER_MEM_MB - self._effective_mb() if resident_mb > avail: raise RuntimeError( diff --git a/backend/app/sessions/regions.py b/backend/app/sessions/regions.py index 1e35f18..8f3f61f 100644 --- a/backend/app/sessions/regions.py +++ b/backend/app/sessions/regions.py @@ -36,7 +36,7 @@ def _membership_from_indices(adata, cell_indices: list[int]) -> np.ndarray: return inside -def _membership(sdata, adata, payload: dict) -> np.ndarray: +def membership(sdata, adata, payload: dict) -> np.ndarray: """Boolean mask of cells whose coordinates fall inside any drawn ring. The lasso rings arrive in *world* space, so the cells are resolved into the same space by `transform.world_xy` — which key holds the coordinates, then the region element's @@ -82,7 +82,7 @@ def assign(session, payload: dict) -> list: cell_indices = payload.get("cell_indices") inside = (_membership_from_indices(adata, cell_indices) if cell_indices is not None - else _membership(session.sdata, adata, payload)) + else membership(session.sdata, adata, payload)) # obs categorical column, "unassigned" by default (single-label partition, §2) col = adata.obs.get(set_name) diff --git a/backend/app/sessions/save_request.py b/backend/app/sessions/save_request.py new file mode 100644 index 0000000..bc19d67 --- /dev/null +++ b/backend/app/sessions/save_request.py @@ -0,0 +1,229 @@ +"""What a checkpoint save may be asked for: the destination, the session name, and the +element / pyramid-level / table-slot / figure selections, each checked against the +session before the job is queued. Shared by the save route and the MCP save_checkpoint +tool, so it raises a plain `SaveRequestError` and imports nothing of fastapi; the route +maps that onto 400 (main.save). +""" +from pathlib import Path + +from ..config import config, within_data_dir + + +class SaveRequestError(ValueError): + """A save request the session cannot honour: a destination outside DATA_DIR, a name + that isn't one, or a selection naming something the session doesn't hold.""" + + +def require_save_path(path: str) -> None: + """Refuse a checkpoint target outside DATA_DIR. Run where a caller's verbatim path + enters (`validated_destination`, the points-transform route) so a bad one is refused + before a job is queued, and again by the save and set_transform jobs before they + touch the session — which is what keeps a refused job from leaving the session + renamed or its transform rewritten.""" + if not within_data_dir(Path(path).resolve()): + raise SaveRequestError("save path is outside the data directory") + + +def default_save_path(sess, folder: str | None = None, prefix: str | None = None) -> str: + """Checkpoint path to use when the caller doesn't give one explicitly — shared by + the save/points-transform routes and the MCP save_checkpoint tool. The filename's + content-hash suffix is (re)computed from the written bytes on every save (see + `_save_zip`), so this only needs the checkpoint's clean base name - stripping any + hash (or extension) a previous save already appended keeps it from stacking a new + one on top. + + `folder` (a directory under DATA_DIR, relative to it or absolute) and `prefix` (the + filename stem the hash is appended to) are the Save dialog's destination fields; + without them the file lands flat in DATA_DIR under the session's name. Both are + validated by `validated_destination` — a caller reaching this directly must have + checked them itself.""" + from ..persistence.store import strip_content_hash, strip_checkpoint_ext, CHECKPOINT_EXT + stem = strip_content_hash(strip_checkpoint_ext(prefix or sess.name)) + return str(config.DATA_DIR / (folder or "") / f"{stem}{CHECKPOINT_EXT}") + + +def validated_payload(sess, body: dict) -> dict: + """The save job's payload (`Session._run_save`) for a save request body, every field + checked — so a bad one is refused here rather than surfacing as a failed job. + + The stem `prefix` falls back to is the session's name as it stands now; the rename + lands on the worker together with the write, so a save that never runs leaves both + the name and the file alone.""" + name = validated_name(body) + path, hash_name = validated_destination(sess, body) + return {"path": path, "hash_name": hash_name, "name": name, + "include": validated_include(sess, body.get("include")), + "levels": validated_levels(sess, body.get("levels")), + "slots": validated_slots(sess, body.get("slots")), + "figures": validated_figures(sess, body.get("figures"))} + + +def validated_include(sess, include) -> dict[str, list[str]] | None: + """Check the save body's element selection against the session. A facet absent from + `include` keeps that facet whole; a facet present keeps exactly the names listed, so + `{"images": []}` drops every image.""" + if include is None: + return None + from ..registry.base import sdata_facets + if not isinstance(include, dict): + raise SaveRequestError("include must be an object of facet -> element names") + facets = sdata_facets() + out: dict[str, list[str]] = {} + for facet, names in include.items(): + if facet not in facets: + raise SaveRequestError(f"unknown element facet '{facet}'") + if not isinstance(names, list): + raise SaveRequestError(f"include['{facet}'] must be a list of element names") + have = set(getattr(sess.sdata, facet, None) or {}) + missing = sorted(n for n in names if n not in have) + if missing: + raise SaveRequestError(f"unknown {facet} element(s): {', '.join(missing)}") + out[facet] = list(names) + kept = out.get("tables") + # Dropping the table the displays and every field path are resolved against would + # produce a checkpoint that reopens with nothing to show. + if kept is not None and sess.active_table_key is not None: + if sess.active_table_key not in kept: + raise SaveRequestError("the active table must be included in the saved checkpoint") + # `select_elements` keeps the listed order, and a display names no table — it + # resolves against the first one. So a list that includes the active table but + # does not lead with it would hand the reopened checkpoint a different default + # table than the app_state written beside it describes. Reordering keeps both + # tables and costs nothing; the order carries no other meaning. + out["tables"] = [sess.active_table_key] + [n for n in kept if n != sess.active_table_key] + return out + + +def validated_levels(sess, levels) -> dict[str, int] | None: + """Check the save body's per-image resolution choice — image name -> index of the + finest pyramid level to write, coarser levels always kept, so 0 writes the whole + pyramid. Levels a caller left at 0 are dropped here, so an all-0 request is + indistinguishable from no request at all and keeps the incremental fast path.""" + if not levels: + return None + if not isinstance(levels, dict): + raise SaveRequestError("levels must be an object of image name -> level index") + from .. import imaging + out: dict[str, int] = {} + for name, finest in levels.items(): + if name not in (getattr(sess.sdata, "images", None) or {}): + raise SaveRequestError(f"unknown images element '{name}'") + depth = len(imaging.image_levels(sess.sdata, name)) + if not isinstance(finest, int) or isinstance(finest, bool) or not 0 <= finest < depth: + raise SaveRequestError(f"levels['{name}'] must be an integer in 0..{depth - 1}") + if finest: + out[name] = finest + return out or None + + +def validated_slots(sess, slots) -> dict[str, list[str]] | None: + """Check the save body's per-table slot selection — table name -> the slot paths to + write (`store.table_slot_paths`' vocabulary). A table absent from `slots` is written + whole; a table present keeps exactly the paths listed. Two things a selection may + not drop, because the resulting file would not open onto what it claims to hold: + the structurally required slots (`store.REQUIRED_TABLE_SLOTS`), and an `obsm` key a + display reads its coordinates or its embedding from — `coords` and `obsm_key` are + non-nullable in `app_state.schema.json`, so unlike a coloring they cannot be + neutralised.""" + if not slots: + return None + if not isinstance(slots, dict): + raise SaveRequestError("slots must be an object of table name -> slot paths") + from ..persistence import store + out: dict[str, list[str]] = {} + for name, paths in slots.items(): + adata = (getattr(sess.sdata, "tables", None) or {}).get(name) + if adata is None: + raise SaveRequestError(f"unknown tables element '{name}'") + if not isinstance(paths, list) or not all(isinstance(p, str) for p in paths): + raise SaveRequestError(f"slots['{name}'] must be a list of slot paths") + have = store.table_slot_paths(adata) + if unknown := sorted(set(paths) - set(have)): + raise SaveRequestError(f"unknown slot(s) in table '{name}': {', '.join(unknown)}") + if missing := [p for p in store.REQUIRED_TABLE_SLOTS if p not in paths]: + raise SaveRequestError( + f"table '{name}' cannot be saved without: {', '.join(missing)}") + for key in _display_obsm_keys(sess) if name == sess.active_table_key else (): + if f"obsm/{key}" in have and f"obsm/{key}" not in paths: + raise SaveRequestError(f"obsm/{key} is used by a display and must be saved") + out[name] = list(paths) + return out + + +def _display_obsm_keys(sess) -> set[str]: + """The obsm keys the session's displays resolve against: an embedding's `obsm_key` + and a spatial display's `coords` (an `obsm:` field path).""" + keys = set() + for d in sess.app_state.get("displays", []): + enc = d.get("encoding") or {} + if key := enc.get("obsm_key"): + keys.add(key) + element, _, key = (enc.get("coords") or "").partition(":") + if element == "obsm" and key: + keys.add(key) + return keys + + +def validated_figures(sess, figures) -> list[str] | None: + """Check the save body's figure selection: `null`/absent keeps every drawn plot's + figure, a list keeps exactly those plot ids (`[]` writes no figures at all). Ids that + aren't drawn plots are a client bug, not something to silently drop.""" + if figures is None: + return None + if not isinstance(figures, list) or not all(isinstance(p, str) for p in figures): + raise SaveRequestError("figures must be a list of plot ids") + missing = sorted(set(figures) - sess.drawn_plot_ids()) + if missing: + raise SaveRequestError(f"no drawn plot(s) with id(s): {', '.join(missing)}") + return figures + + +def validated_name(body) -> str | None: + """The save body's session name: what the checkpoint records as its own name + (`app_state["name"]`, adopted again when the file is reloaded) and what the live + session is renamed to. Absent leaves both alone.""" + name = body.get("name") + if name is None: + return None + if not isinstance(name, str) or not name.strip(): + raise SaveRequestError("name must be a non-empty string") + return name.strip() + + +def validated_destination(sess, body) -> tuple[str, bool]: + """Resolve the save body's destination to (path, hash_name). + + `path` is the verbatim escape hatch — written exactly as given, with no content-hash + suffix (the MCP save_checkpoint tool and the offline harness use it). The Save dialog + instead sends `folder` (a directory under DATA_DIR, created if it doesn't exist) and + `prefix` (the filename stem), which compose onto `default_save_path` and so keep the + hash suffix. A path or folder outside DATA_DIR, or a prefix that isn't a plain + filename, is refused here rather than as a job that fails minutes into a multi-GB + write.""" + explicit = body.get("path") + folder, prefix = body.get("folder"), body.get("prefix") + if explicit is not None and (folder is not None or prefix is not None): + raise SaveRequestError("path cannot be combined with folder or prefix") + if explicit is not None: + if not isinstance(explicit, str) or not explicit.strip(): + raise SaveRequestError("path must be a non-empty string") + require_save_path(explicit) + return explicit, False + if folder is not None: + if not isinstance(folder, str): + raise SaveRequestError("folder must be a string") + target = (config.DATA_DIR / folder).resolve() + if not within_data_dir(target): + raise SaveRequestError("folder is outside the data directory") + if target.exists() and not target.is_dir(): + raise SaveRequestError(f"'{folder}' is not a directory") + if prefix is not None: + if not isinstance(prefix, str) or not prefix.strip(): + raise SaveRequestError("prefix must be a non-empty string") + prefix = prefix.strip() + # One path component, and not dot-prefixed: the dataset scanner skips names + # starting with "." (it is how save staging hides itself), so such a checkpoint + # would never appear in the load picker. + if "/" in prefix or "\\" in prefix or prefix.startswith("."): + raise SaveRequestError("prefix must be a filename with no path separators") + return default_save_path(sess, folder, prefix), True diff --git a/backend/app/sessions/session.py b/backend/app/sessions/session.py index a4e13f1..7944dbc 100644 --- a/backend/app/sessions/session.py +++ b/backend/app/sessions/session.py @@ -12,11 +12,9 @@ import uuid from concurrent.futures import BrokenExecutor, ThreadPoolExecutor from contextlib import contextmanager -from pathlib import Path -from . import appstate +from . import appstate, save_request from .adapter import ADAPTER -from ..config import within_data_dir from ..registry.introspect import REGISTRY from ..registry.reader_paths import validate_reader_params from ..transport import livelog @@ -179,6 +177,26 @@ class SessionLoadingError(Exception): to 409).""" +# What the shared session guards (deps.py) refuse a request with. Raised as domain +# errors because those guards are also reached off-HTTP, by the MCP surface; main.py +# maps each onto its status once. None is a RuntimeError/KeyError/ValueError: routes +# catch those around the same calls to answer 400/404, and would relabel these. +class SessionNotFoundError(Exception): + """No live session has the requested id (404).""" + + +class SessionReadOnlyError(Exception): + """A mutation refused because the session is read-only (403).""" + + +class SessionLockedError(Exception): + """A mutation refused because another viewer holds the session's edit lock (423).""" + + +class SessionBusyError(Exception): + """A read that could not take the session's read lock in time (503, retryable).""" + + class Session: def __init__(self, sid, name, sdata, app_state, manager, parent_id=None, store_path=None, read_only=False): @@ -189,8 +207,9 @@ def __init__(self, sid, name, sdata, app_state, manager, parent_id=None, store_p self.manager = manager self.parent_id = parent_id self.store_path = store_path - # True for a session opened frozen (create_from_load(read_only=True)): every - # mutating route rejects it (deps.py::get_writable_session) so it stays a + # True for a session opened frozen (create_from_load(read_only=True)), or one + # whose checkpoint carries a newer app_state schema than this app (`_run_load`): + # every mutating route rejects it (deps.py::get_writable_session) so it stays a # read-only view of its checkpoint. self.read_only = read_only # True when the in-memory object matches its saved checkpoint: set on load @@ -670,13 +689,13 @@ def _run_call(self, job_id, kind, descriptor): if self.extract_dir: shutil.rmtree(self.extract_dir, ignore_errors=True) self.extract_dir = result.extract_dir - is_reimport = fn is not None and fn.effect_class == "read" + is_read_call = fn is not None and fn.effect_class == "read" # An imported store may itself be a checkpoint this app wrote (opened # via Import Data instead of the checkpoint loader): its attrs carry # the writing session's app_state, whose compute_history is the # provenance of the data. Carry those records into this session # instead of silently dropping them. - if is_reimport: + if is_read_call: self._adopt_import_history(new_object) # A reader's images/labels can be single-scale or huge-chunked; tile # them now so the canvas never realizes a multi-GB chunk per tile. @@ -687,14 +706,16 @@ def _run_call(self, job_id, kind, descriptor): # that happens to reuse a conventional image name, which would otherwise # be wrongly treated as "already known local" — leaving raster_stores[name] # pointing at the PREVIOUS dataset's cache dir. Force a from-scratch - # locality check for that case by passing no prior knowledge at all. - known_stores = {} if is_reimport else self.raster_stores - # A read bootstrap's rebuild can be lengthy (multi-GB); stream its - # progress over the same job.log channel `target` above already taps, - # so the import spinner keeps moving during this (write-lock-held) rebuild. + # locality check for every read call by passing no prior knowledge at + # all (the first bootstrap has none to pass anyway). + known_stores = {} if is_read_call else self.raster_stores + # A read call's rebuild (the first bootstrap or a re-import) can be + # lengthy (multi-GB); stream its progress over the same job.log channel + # `target` above already taps, so the import spinner keeps moving during + # this (write-lock-held) rebuild. progress = ((lambda message, pct=None: BUS.publish( "job.log", {"session_id": self.id, "job_id": job_id, "chunk": f"{message}\n"})) - if is_reimport else None) + if is_read_call else None) self._adopt_rasters(known_stores, progress) self.active_table_key = self._default_table_key() if not self.app_state["displays"]: @@ -929,15 +950,12 @@ def _hold_dropped_figures(self, keeping: dict[str, dict[str, bytes]]) -> None: if held.get(fmt) is None: held[fmt] = read_figure(self.extract_dir, pid, fmt) - def _save_and_finish(self, job_id: str, payload: dict, kind: str, - bump_fields: list | None = None) -> None: + def _save_and_finish(self, job_id: str, payload: dict, kind: str) -> None: """Shared completion tail for the checkpoint-writing jobs (save, set_transform): - validate the target path, write the checkpoint under the read lock (data reads - keep flowing during a multi-GB zip), then flip the saved-state bookkeeping and - publish the job's terminal event.""" - target = Path(payload["path"]).resolve() - if not within_data_dir(target): - raise ValueError("save path is outside the data directory") + write the checkpoint under the read lock (data reads keep flowing during a + multi-GB zip), then flip the saved-state bookkeeping and publish the job's + terminal event. The callers have already checked the target path + (`save_request.require_save_path`), before mutating anything.""" include, levels = payload.get("include"), payload.get("levels") slots = payload.get("slots") with self.lock.reading(): @@ -952,8 +970,6 @@ def _save_and_finish(self, job_id: str, payload: dict, kind: str, self.saved = True self._clear_dirty() self._jobs[job_id]["status"] = "completed" - if bump_fields: - appstate.bump_versions(self.app_state, bump_fields) BUS.publish("job.completed", {"session_id": self.id, "job_id": job_id, "kind": kind, "path": written, "data_versions": self.app_state["data_versions"]}) @@ -962,13 +978,23 @@ def _run_set_transform(self, job_id, payload): """Set the points->global transform on the active table's region element and persist to disk so it survives a session restart (§3.1 mutating job).""" from . import transform + # Before the affine is touched: a refused target leaves the transform as it was. + save_request.require_save_path(payload["path"]) with self.lock.writing(): region = transform.set_affine6(self.sdata, self.active_table(), payload["affine"]) if region: self.dirty_transforms.add(region) - self._save_and_finish(job_id, payload, "set_transform", bump_fields=["obsm:spatial"]) + # The affine is live from here whether or not the write below succeeds, so the + # session is unsaved and the coordinates clients hold are stale now. Bumping + # before the save reaches them either way: job.completed carries data_versions, + # and job.failed has clients refetch the session state that holds them. + self.saved = False + appstate.bump_versions(self.app_state, ["obsm:spatial"]) + self._save_and_finish(job_id, payload, "set_transform") def _run_save(self, job_id, payload): + # Before the rename: a refused target leaves the session named as it was. + save_request.require_save_path(payload["path"]) name = payload.get("name") # Also renames when only `app_state` lacks the name: a session that has never # been renamed still needs it recorded, or a file saved under a different prefix @@ -1051,6 +1077,12 @@ def report(message, pct=None): report("Building views…") if not self.app_state["displays"]: self.manager.auto_displays(self) + if newer: + # A file written by a later app carries app_state this one cannot + # migrate, so every mutating route has to refuse it + # (deps.get_writable_session reads this attribute, and so does the + # summary published below). + self.read_only = True self.status = "ready" self.error = None self._publish_summary() diff --git a/backend/app/snapshots.py b/backend/app/snapshots.py index f004b1e..d28e17d 100644 --- a/backend/app/snapshots.py +++ b/backend/app/snapshots.py @@ -256,7 +256,7 @@ def _shapes_element(session, enc: dict) -> str | None: return polygonal[0] if polygonal else None -def _window(target, zoom, width_px, height_px): +def viewport_window(target, zoom, width_px, height_px): """Axis-aligned window [x0,y0,x1,y1] in the view's coordinate space. deck's OrthographicView puts 2**zoom pixels per unit, so `n` output px span n/2**zoom units, centered on target.""" @@ -527,7 +527,7 @@ def _draw_minimap(fig, session, enc, element, pts, bbox, facecolor, dpi) -> bool # ---- the render core --------------------------------------------------------- -def _render_figure(session, spec: dict): +def render_figure(session, spec: dict): """Render into an in-memory matplotlib Figure. Returns (fig, render_meta). Deliberately never pyplot: pyplot's Gcf figure registry is process-global and @@ -569,7 +569,7 @@ def _render_figure(session, spec: dict): else: pts = xy - bbox = _window(target, zoom, width_px, height_px) + bbox = viewport_window(target, zoom, width_px, height_px) # mean inter-point spacing (full dataset bounds) -> world radius, matching # buildSpotLayer.estimateMeanSpacing + pointWorldRadius. @@ -651,7 +651,7 @@ def render_preview(session, spec: dict) -> bytes: """A low-cost PNG of the framing for the modal preview. Same core, no file writes and no embedded metadata.""" with session.lock.reading(config.READ_LOCK_TIMEOUT_S): - fig, _ = _render_figure(session, spec) + fig, _ = render_figure(session, spec) buf = io.BytesIO() fig.savefig(buf, format="png", dpi=fig.dpi) return buf.getvalue() @@ -695,7 +695,7 @@ def save_snapshot(session, spec: dict) -> dict: # across several multi-MB savefig calls stalls a pending compute commit for their whole # duration. with session.lock.reading(config.READ_LOCK_TIMEOUT_S): - fig, render_meta = _render_figure(session, spec) + fig, render_meta = render_figure(session, spec) meta = _metadata(session, spec, display, render_meta, formats) meta_json = json.dumps(meta) diff --git a/backend/app/transport/livelog.py b/backend/app/transport/livelog.py index d0105bb..5517aa3 100644 --- a/backend/app/transport/livelog.py +++ b/backend/app/transport/livelog.py @@ -11,7 +11,8 @@ * A read-bootstrap job (session worker thread) sets `job_target(...)`; the reader's `capture_log()` picks up the ambient sink and tees each write to a `job.log` event. Library readers run in the loky child, so `child_log_stream` - pipes their lines back to the parent over a Manager queue. + pipes their lines back to the parent over a Manager queue. A reader that runs in + the API process itself captures through `own_thread_logs`, like the load path. * The synchronous checkpoint-load path uses `forward_load_logs(load_id)`, which routes lines onto the existing `session.loading` channel (keyed by the client-minted nonce, since no session id exists yet). @@ -76,62 +77,90 @@ def emit(self, record): class _OwnThreadOnly(logging.Filter): - """Admit only records emitted by the thread that opened the load. The handler goes - on the ROOT logger, so with two loads in flight every record in the process would - otherwise be published to BOTH `load_id` channels — each client watching the other's - reader. Loads run one per session worker thread, so thread identity is the routing - key, matching how `_SINK` routes the job path per thread.""" - def __init__(self, thread_id: int): + """Admit only records emitted by the thread that opened the capture. The handler goes + on the ROOT logger, so with two reads in flight every record in the process would + otherwise be published to BOTH sinks — each client watching the other's reader. + Reads run one per session worker thread, so thread identity is the routing key, + matching how `_SINK` routes the job path per thread.""" + def __init__(self, thread_id: int, helper_threads: tuple[str, ...] = ()): super().__init__() self._thread_id = thread_id + self._helper_threads = helper_threads def filter(self, record): - return record.thread == self._thread_id + return record.thread == self._thread_id or record.threadName in self._helper_threads -# Guards the root level below, which is process-global while `forward_load_logs` is -# per-load. `_level_depth` counts the loads currently holding the INFO override and +# Guards the root level below, which is process-global while `own_thread_logs` is +# per-read. `_level_depth` counts the reads currently holding a level override and # `_level_prev` is the level the OUTERMOST one found: without the refcount, two -# overlapping loads each capture-and-restore, so the first to finish drops the level +# overlapping reads each capture-and-restore, so the first to finish drops the level # back and silences the second's live log — and if it captured after the second had -# already raised it, the root logger is left at INFO for the life of the process. +# already lowered it, the root logger is left lowered for the life of the process. _LEVEL_LOCK = threading.Lock() _level_depth = 0 _level_prev = logging.NOTSET @contextlib.contextmanager -def forward_load_logs(load_id: str | None): - """Forward this thread's root-logger records to the checkpoint-load progress channel - while the load runs, without redirecting stdout/stderr — the load keeps logging to the - console (Docker) as before, and also streams to the client. Safe to run concurrently - with other loads: each gets its own handler, records are routed by emitting thread, - and the root level is restored once the last load leaves.""" +def own_thread_logs(sink, level: int, fmt: str | None = None, *, detached: bool = False, + helper_threads: tuple[str, ...] = ()): + """Send this thread's root-logger records, one formatted line per `sink` call, for + the length of the block, without redirecting stdout/stderr: those are process-global, + so swapping them here in the API process would pull every other thread's output into + this read and, when two reads overlap, leave them bound to a finished read's buffer. + The console keeps what it had. Safe to run concurrently with other reads: each gets + its own handler, records are routed by emitting thread, and the root level — lowered + to `level` while any read needs it — is restored once the last one leaves. + + `detached` also taps the loggers that do not propagate to the root (spatialdata's + own, which is where a store read reports its progress, writes to a console handler + and stops there), at whatever level each already has. `helper_threads` names + threads a library runs this thread's work on, whose records are admitted too: they + are shared by every read in the process, so two overlapping reads see each other's + lines from them, which is the price of seeing any.""" global _level_depth, _level_prev - if not load_id: - yield - return - handler = _SinkHandler(_load_sink(load_id)) - handler.setFormatter(logging.Formatter("%(levelname)s %(name)s: %(message)s")) - handler.addFilter(_OwnThreadOnly(threading.get_ident())) + handler = _SinkHandler(sink) + handler.setLevel(level) + if fmt is not None: + handler.setFormatter(logging.Formatter(fmt)) + handler.addFilter(_OwnThreadOnly(threading.get_ident(), helper_threads)) root = logging.getLogger() - root.addHandler(handler) + tapped = [root] + if detached: + tapped += [named for named in logging.root.manager.loggerDict.values() + if isinstance(named, logging.Logger) and not named.propagate] + for logger in tapped: + logger.addHandler(handler) with _LEVEL_LOCK: if _level_depth == 0: _level_prev = root.level - if root.level == logging.NOTSET or root.level > logging.INFO: - root.setLevel(logging.INFO) + if root.level == logging.NOTSET or root.level > level: + root.setLevel(level) _level_depth += 1 try: yield finally: - root.removeHandler(handler) + for logger in tapped: + logger.removeHandler(handler) with _LEVEL_LOCK: _level_depth -= 1 if _level_depth == 0: root.setLevel(_level_prev) +@contextlib.contextmanager +def forward_load_logs(load_id: str | None): + """Forward this thread's root-logger records to the checkpoint-load progress channel + while the load runs (see `own_thread_logs`) — the load keeps logging to the console + (Docker) as before, and also streams to the client.""" + if not load_id: + yield + return + with own_thread_logs(_load_sink(load_id), logging.INFO, "%(levelname)s %(name)s: %(message)s"): + yield + + @contextlib.contextmanager def child_log_stream(sink): """For a reader that runs in the loky child (library readers): hand back a Manager diff --git a/cirro-studio/package.json b/cirro-studio/package.json index 05d68ec..d9e2387 100644 --- a/cirro-studio/package.json +++ b/cirro-studio/package.json @@ -1,7 +1,7 @@ { "name": "spatial-data-studio-cirro", "private": true, - "version": "1.10.0", + "version": "1.10.1", "type": "module", "scripts": { "dev": "vite", diff --git a/cirro-studio/src/app/library.ts b/cirro-studio/src/app/library.ts index 0ce0d11..5637e67 100644 --- a/cirro-studio/src/app/library.ts +++ b/cirro-studio/src/app/library.ts @@ -1,6 +1,6 @@ // The project as the app presents it: four stages a spatial study moves through, with // each SpatialData store and the versions saved on it gathered into one spatial dataset. -import type { CatalogItem, DatasetRecord, ImageItem, RunItem, StoreItem, VersionItem } from '../data/model'; +import type { CatalogItem, ImageItem, RunItem, StoreItem, VersionItem } from '../data/model'; import { itemKey } from '../data/model'; import { datasetRef, parseCirroRef } from '../stack/cirroRef'; import type { CatalogState } from './catalog'; @@ -143,5 +143,3 @@ export function ancestry(entity: SpatialEntity, version: VersionItem | null): st for (let at = version; at; at = byRef.get(at.parent) ?? null) chain.unshift(refOfItem(at)); return [entity.baseRef, ...chain]; } - -export const datasetOf = (state: Pick, item: CatalogItem): DatasetRecord | undefined => state.byId.get(item.datasetId); diff --git a/cirro-studio/src/app/route.ts b/cirro-studio/src/app/route.ts index a66d83d..f658f4b 100644 --- a/cirro-studio/src/app/route.ts +++ b/cirro-studio/src/app/route.ts @@ -96,8 +96,6 @@ export function navigate(update: Record, { replace = fals listeners.forEach((l) => l()); } -export const hrefFor = (update: Record) => target(update).toString(); - const sameAddress = (a: string, b: string) => { const sorted = (s: string) => [...new URLSearchParams(s)].map((p) => p.join('=')).sort().join('&'); return sorted(a) === sorted(b); diff --git a/cirro-studio/src/app/ui.tsx b/cirro-studio/src/app/ui.tsx index 8e17864..5e27ac6 100644 --- a/cirro-studio/src/app/ui.tsx +++ b/cirro-studio/src/app/ui.tsx @@ -115,7 +115,3 @@ export const STAGE_ICONS: Record = { /** A stage's tint as an inline style, for elements that read `--c`. */ export const tint = (cssVar: string) => ({ '--c': `var(${cssVar})` }) as CSSProperties; - -export function Spinner({ label }: { label: string }) { - return ; -} diff --git a/cirro-studio/src/data/model.ts b/cirro-studio/src/data/model.ts index 3518597..81023d8 100644 --- a/cirro-studio/src/data/model.ts +++ b/cirro-studio/src/data/model.ts @@ -28,8 +28,6 @@ export interface DatasetRecord { credit?: Partial; } -export type ItemKind = 'image' | 'run' | 'store' | 'version'; - interface ItemBase { // `/`, unique within a collection. key: string; diff --git a/cirro-studio/src/reports/CompareReport.tsx b/cirro-studio/src/reports/CompareReport.tsx index a040fda..3a369f7 100644 --- a/cirro-studio/src/reports/CompareReport.tsx +++ b/cirro-studio/src/reports/CompareReport.tsx @@ -8,14 +8,13 @@ import { formatCount } from '../app/ui'; import { BarList } from '../charts/BarList'; import { TissueThumb, type Paint } from '../charts/TissueThumb'; import { SIGNIFICANCE, Volcano } from '../charts/Volcano'; -import { describeError } from '../cirro/session'; import { SIZE_PRESETS } from '../figures/layout'; import { keepFigure } from '../figures/spec'; import { useDisplays } from '../item/displayState'; import { readGroups } from '../tasks/data'; import { FORMATS, ResultTable, type Column, type GroupSpec } from '../tasks/parts'; import { storeOf } from '../workbench/workbench'; -import { DownloadCsv, FullTable, GENE_SET_SIZE, geneValues, pct, ScoreGenes, Section, showOnTissue, Stats, useMatrix, useTissue } from './parts'; +import { DownloadCsv, FullTable, GENE_SET_SIZE, geneValues, pct, ScoreGenes, Section, showOnTissue, Stats, useMatrix, useSaveFigure, useTissue } from './parts'; import type { ReportProps } from './ReportView'; import { geneTestsOf, readResultTable } from './store'; @@ -80,25 +79,15 @@ export default function CompareReport({ result, table, wb, handle, unit, width } }; }, [wb.key, handle, result, a, b]); - const [figure, setFigure] = useState<'saving' | 'saved' | null>(null); - const [problem, setProblem] = useState(null); - const saveFigure = async () => { - setFigure('saving'); - setProblem(null); - try { - await keepFigure(wb.key, handle.tableKey, { - title: result.meta.title, - caption: `Genes compared between ${a.label} (${formatCount(a.size)} ${unit}s) and ${b.label} (${formatCount(b.size)}): Wilcoxon rank-sum, Benjamini–Hochberg adjusted. Dashed lines: adjusted p = ${cutoffs.padj} and |log2 fold change| = ${cutoffs.logfc}.`, - created_by: session?.displayName ?? '', - view: { kind: 'chart', chart: { type: 'volcano', result: [...result.path, 'table'].join('/'), labels: SIGNIFICANCE.labels, ...cutoffs } }, - width_mm: SIZE_PRESETS.single.widthMm, - }); - setFigure('saved'); - } catch (e) { - setFigure(null); - setProblem(describeError(e)); - } - }; + const { state: figure, problem, run: saveFigure } = useSaveFigure(async () => { + await keepFigure(wb.key, handle.tableKey, { + title: result.meta.title, + caption: `Genes compared between ${a.label} (${formatCount(a.size)} ${unit}s) and ${b.label} (${formatCount(b.size)}): Wilcoxon rank-sum, Benjamini–Hochberg adjusted. Dashed lines: adjusted p = ${cutoffs.padj} and |log2 fold change| = ${cutoffs.logfc}.`, + created_by: session?.displayName ?? '', + view: { kind: 'chart', chart: { type: 'volcano', result: [...result.path, 'table'].join('/'), labels: SIGNIFICANCE.labels, ...cutoffs } }, + width_mm: SIZE_PRESETS.single.widthMm, + }); + }); const tableColumns: Column[] = [ { key: 'gene', label: 'Gene' }, { key: 'logfc', label: 'log2FC', format: FORMATS.num }, diff --git a/cirro-studio/src/reports/CompositionReport.tsx b/cirro-studio/src/reports/CompositionReport.tsx index dca58b7..69562fc 100644 --- a/cirro-studio/src/reports/CompositionReport.tsx +++ b/cirro-studio/src/reports/CompositionReport.tsx @@ -3,20 +3,19 @@ // (log2 observed over expected, with a chi-square test of each pair) as a heatmap; and // every pair's counts. The Composition view draws the same sections live, and keeps them // as this report. -import { useMemo, useState, type ReactNode } from 'react'; +import { useMemo, type ReactNode } from 'react'; import { MIN_EXPECTED, testComposition, type CrossTable } from '../analysis/composition'; import { useStudio } from '../app/studio'; import { formatCount } from '../app/ui'; import { Heatmap } from '../charts/Heatmap'; import { StackedBars } from '../charts/StackedBars'; import { SIGNIFICANCE } from '../charts/Volcano'; -import { describeError } from '../cirro/session'; import { SIZE_PRESETS } from '../figures/layout'; import { keepFigure, type ChartSpec } from '../figures/spec'; import { useDisplays } from '../item/displayState'; import { useColorKey } from '../item/useColorField'; import { FORMATS, ResultTable, type Column } from '../tasks/parts'; -import { DownloadCsv, NO_COLOR, pct, Section, Stats } from './parts'; +import { DownloadCsv, NO_COLOR, pct, Section, Stats, useSaveFigure } from './parts'; import type { ReportProps } from './ReportView'; import { matrixOf } from './store'; @@ -126,19 +125,7 @@ export function CompositionSections({ table, colors, column, across, leftOut, un /** Keep a chart over this result as a figure, and say once it is kept. */ function SaveFigure({ save }: { save: () => Promise }) { - const [state, setState] = useState<'saving' | 'saved' | null>(null); - const [problem, setProblem] = useState(null); - const run = async () => { - setState('saving'); - setProblem(null); - try { - await save(); - setState('saved'); - } catch (e) { - setState(null); - setProblem(describeError(e)); - } - }; + const { state, problem, run } = useSaveFigure(save); return ( {problem && {problem}} diff --git a/cirro-studio/src/reports/MarkersReport.tsx b/cirro-studio/src/reports/MarkersReport.tsx index e1bee11..c8ca1f9 100644 --- a/cirro-studio/src/reports/MarkersReport.tsx +++ b/cirro-studio/src/reports/MarkersReport.tsx @@ -5,13 +5,13 @@ import { useEffect, useMemo, useState } from 'react'; import type { GeneTest } from '../analysis/rankGenes'; import { formatCount, plural } from '../app/ui'; import { DotPlot } from '../charts/DotPlot'; -import { TissueThumb, type Paint, type Tissue } from '../charts/TissueThumb'; +import type { Paint, Tissue } from '../charts/TissueThumb'; import { useDisplays } from '../item/displayState'; import { useColorKey } from '../item/useColorField'; import { readGroups } from '../tasks/data'; import { FORMATS, ResultTable, type Column } from '../tasks/parts'; import type { Workbench } from '../workbench/workbench'; -import { DownloadCsv, FullTable, GENE_SET_SIZE, geneValues, NO_COLOR, pct, ScoreGenes, Section, showOnTissue, Stats, useMatrix, useTissue } from './parts'; +import { DownloadCsv, FullTable, GENE_SET_SIZE, geneValues, GroupCard, NO_COLOR, pct, ScoreGenes, Section, showOnTissue, Stats, useMatrix, useTissue } from './parts'; import type { ReportProps } from './ReportView'; import { geneTestsOf } from './store'; @@ -25,7 +25,6 @@ export type MarkersSummary = { const SHOWN_MARKERS = 5; // More columns than this and the dot plot stops being read at a glance. const MAX_DOT_GENES = 80; -const THUMB_W = 132; const TABLE_COLUMNS: Column[] = [ { key: 'gene', label: 'Gene' }, { key: 'score', label: 'Score', format: FORMATS.num }, { key: 'logfc', label: 'log2FC', format: FORMATS.num }, { key: 'padj', label: 'Adj. p', format: FORMATS.p }, @@ -34,7 +33,7 @@ const TABLE_COLUMNS: Column[] = [ // The table shows a group at a time; its file holds every group's, one after another. const CSV_COLUMNS: Column[] = [{ key: 'group', label: 'Group' }, ...TABLE_COLUMNS]; -function GroupCard({ wb, handle, column, label, size, total, color, tests, significant, tissue, member, unit }: { +function MarkersCard({ wb, handle, column, label, size, total, color, tests, significant, tissue, member, unit }: { wb: Workbench; handle: ReportProps['handle']; column: string; label: string; size: number; total: number; color: string; tests: GeneTest[]; significant: GeneTest[]; tissue: Tissue | null; member: ((c: number) => boolean) | null; unit: string; @@ -52,18 +51,9 @@ function GroupCard({ wb, handle, column, label, size, total, color, tests, signi const set = significant.slice(0, GENE_SET_SIZE).map((t) => t.gene); const shown = nearest.slice(0, SHOWN_MARKERS); return ( -
-
- -

{label}

- {plural(size, [unit, `${unit}s`])} · {((100 * size) / Math.max(total, 1)).toFixed(1)}% -
-
-
- {tissue && paint ? - :
} -
{gene ? `${gene}, log1p` : `Where its ${unit}s are`}
-
+ Genelog2FCHere · others @@ -82,7 +72,7 @@ function GroupCard({ wb, handle, column, label, size, total, color, tests, signi ))} -
+ )}>

{significant.length ? <>{plural(significant.length, ['gene is', 'genes are'])} higher here. The strongest, {top.gene}, is in {pct(top.fracA)} of its {unit}s and {pct(top.fracB)} of the others. @@ -95,7 +85,7 @@ function GroupCard({ wb, handle, column, label, size, total, color, tests, signi )} {gene && } -

+ ); } @@ -198,7 +188,7 @@ export default function MarkersReport({ result, table, wb, handle, unit, width } const code = at?.get(g); const member = codes && code !== undefined ? (c: number) => codes.codes[c] === code : null; return ( - ); })} diff --git a/cirro-studio/src/reports/NeighborhoodsReport.tsx b/cirro-studio/src/reports/NeighborhoodsReport.tsx index 89dac62..a162fbe 100644 --- a/cirro-studio/src/reports/NeighborhoodsReport.tsx +++ b/cirro-studio/src/reports/NeighborhoodsReport.tsx @@ -5,11 +5,10 @@ // every pair. import { useEffect, useMemo, useState } from 'react'; import { useStudio } from '../app/studio'; -import { formatCount, plural } from '../app/ui'; +import { formatCount } from '../app/ui'; import { BarList } from '../charts/BarList'; import { Heatmap } from '../charts/Heatmap'; import { TissueThumb, type Paint, type Tissue } from '../charts/TissueThumb'; -import { describeError } from '../cirro/session'; import { SIZE_PRESETS } from '../figures/layout'; import { keepFigure } from '../figures/spec'; import { useDisplays } from '../item/displayState'; @@ -17,7 +16,7 @@ import { useColorKey } from '../item/useColorField'; import { readGroups } from '../tasks/data'; import { ResultTable, type Column } from '../tasks/parts'; import { storeOf } from '../workbench/workbench'; -import { DownloadCsv, FullTable, NO_COLOR, pct, Section, showOnTissue, Stats, useTissue } from './parts'; +import { DownloadCsv, FullTable, GroupCard, NO_COLOR, pct, Section, showOnTissue, Stats, useSaveFigure, useTissue } from './parts'; import type { ReportProps } from './ReportView'; import { matrixOf, readResultTable } from './store'; @@ -42,7 +41,6 @@ const SHOWN_PAIRS = 10; // How many groups a card names on each side, and lists among its cells' neighbors. const NAMED = 2; const SHOWN_NEIGHBORS = 4; -const THUMB_W = 132; const PAIR_THUMB_W = 200; // The heatmap's squares stop growing at this size, and the chart at the width they need. const HEAT_CELL = 26; @@ -60,7 +58,7 @@ const PAIR_COLUMNS: Column[] = [ ]; const listed = (items: string[]) => (items.length < 2 ? items.join('') : `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`); -function GroupCard({ label, groups, index, size, total, colors, z, shares, tissue, paint, unit }: { +function NeighborsCard({ label, groups, index, size, total, colors, z, shares, tissue, paint, unit }: { label: string; groups: string[]; index: number; size: number; total: number; colors: string[]; z: Float64Array; shares: Float64Array | null; tissue: Tissue | null; paint: Paint | null; unit: string; }) { @@ -73,33 +71,22 @@ function GroupCard({ label, groups, index, size, total, colors, z, shares, tissu const named = (js: number[]) => listed(js.map((j) => `${groups[j]} (z ${fmtZ(z[index * n + j])})`)); const neighbors = shares && groups.map((_, j) => j).sort((x, y) => shares[y] - shares[x]).slice(0, SHOWN_NEIGHBORS); return ( -
-
- -

{label}

- {plural(size, [unit, `${unit}s`])} · {pct(size / Math.max(total, 1))} -
-
-
- {tissue && paint ? - :
} -
Where its {unit}s are
-
- {neighbors && ( - - - - {neighbors.map((j) => ( - - - - - - ))} - -
Its {unit}s' neighborsSharez
{groups[j]}{j === index && (itself)}{fmtShare(shares[j])}{fmtZ(z[index * n + j])}
- )} -
+ + Its {unit}s' neighborsSharez + + {neighbors.map((j) => ( + + {groups[j]}{j === index && (itself)} + {fmtShare(shares[j])} + {fmtZ(z[index * n + j])} + + ))} + + + )}>

{!Number.isFinite(own) ? <>Too few {unit}s to tell whether they keep together. : own >= Z_NOTABLE ? <>Keeps together (z {fmtZ(own)}). @@ -108,7 +95,7 @@ function GroupCard({ label, groups, index, size, total, colors, z, shares, tissu {beside.length ? <>Sits next to {named(beside)} more than chance : <>Sits next to no other group more than chance} {avoids.length ? <>; avoids {named(avoids)}. : <>, and avoids none.}

-
+
); } @@ -191,25 +178,15 @@ export default function NeighborhoodsReport({ result, table, wb, handle, unit, w const [picked, setPicked] = useState(null); const pair = picked ?? together[0] ?? apart[0] ?? null; - const [figure, setFigure] = useState<'saving' | 'saved' | null>(null); - const [problem, setProblem] = useState(null); - const saveFigure = async () => { - setFigure('saving'); - setProblem(null); - try { - await keepFigure(wb.key, handle.tableKey, { - title: result.meta.title, - caption: `z-scores of how often each pair of ${column} groups are neighbors (each ${unit}'s ${neighbors} nearest on the tissue) against ${formatCount(permutations)} shuffles of the labels: red, more often than chance; blue, less.`, - created_by: session?.displayName ?? '', - view: { kind: 'chart', chart: { type: 'heatmap', result: [...result.path, 'table'].join('/') } }, - width_mm: SIZE_PRESETS.single.widthMm, - }); - setFigure('saved'); - } catch (e) { - setFigure(null); - setProblem(describeError(e)); - } - }; + const { state: figure, problem, run: saveFigure } = useSaveFigure(async () => { + await keepFigure(wb.key, handle.tableKey, { + title: result.meta.title, + caption: `z-scores of how often each pair of ${column} groups are neighbors (each ${unit}'s ${neighbors} nearest on the tissue) against ${formatCount(permutations)} shuffles of the labels: red, more often than chance; blue, less.`, + created_by: session?.displayName ?? '', + view: { kind: 'chart', chart: { type: 'heatmap', result: [...result.path, 'table'].join('/') } }, + width_mm: SIZE_PRESETS.single.widthMm, + }); + }); const rows = useMemo((): PairRow[] => groups.flatMap((from, i) => groups.map((to, j) => ({ from, to, z: z[i * n + j], count: counts?.[i * n + j] ?? NaN, share: shares?.[i * n + j] ?? NaN, @@ -289,7 +266,7 @@ export default function NeighborhoodsReport({ result, table, wb, handle, unit, w : `Whether each group's ${unit}s keep together (its z-score with itself), and the groups its ${unit}s' neighbors belong to most: their share of all its neighbors, and how far that is from chance.`}>
{groups.map((g, i) => ( - ))}
diff --git a/cirro-studio/src/reports/NichesReport.tsx b/cirro-studio/src/reports/NichesReport.tsx index 0c218df..d64f7a3 100644 --- a/cirro-studio/src/reports/NichesReport.tsx +++ b/cirro-studio/src/reports/NichesReport.tsx @@ -3,11 +3,10 @@ // words and bars), and the full table of mixes. import { Fragment, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { useStudio } from '../app/studio'; -import { formatCount, plural } from '../app/ui'; +import { formatCount } from '../app/ui'; import { BarList } from '../charts/BarList'; import { Heatmap } from '../charts/Heatmap'; -import { TissueThumb, type Paint, type Tissue } from '../charts/TissueThumb'; -import { describeError } from '../cirro/session'; +import type { Paint, Tissue } from '../charts/TissueThumb'; import { SIZE_PRESETS } from '../figures/layout'; import { keepFigure } from '../figures/spec'; import { useDisplays } from '../item/displayState'; @@ -15,7 +14,7 @@ import { useColorKey } from '../item/useColorField'; import { useSize } from '../lib/useSize'; import { readGroups } from '../tasks/data'; import { ResultTable, type Column } from '../tasks/parts'; -import { DownloadCsv, FullTable, NO_COLOR, pct, Section, showOnTissue, Stats, useTissue } from './parts'; +import { DownloadCsv, FullTable, GroupCard, NO_COLOR, pct, Section, showOnTissue, Stats, useSaveFigure, useTissue } from './parts'; import type { ReportProps } from './ReportView'; export type NichesSummary = { @@ -46,7 +45,6 @@ const DISTINCT = 1.5; const SHOWN_GROUPS = 5; // A group under this share of a niche gets no bar: it would be a sliver labelled "<1%". const BAR_MIN = 0.01; -const THUMB_W = 132; // The heatmap's label room and largest square (its own limits): it is drawn no wider than // they need, so it doesn't trail empty space. const HEAT_LABEL_W = 110; @@ -78,19 +76,10 @@ function NicheCard({ label, size, total, color, mix, overall, groups, groupColor .map((s) => ({ ...s, ratio: s.share / overall[s.group] })) .sort((a, b) => b.ratio - a.ratio)[0]; return ( -
-
- -

{label}

- {plural(size, [unit, `${unit}s`])} · {((100 * size) / Math.max(total, 1)).toFixed(1)}% -
-
-
- {tissue && paint ? - :
} -
Where its {unit}s are
-
- {/* Sized by the card, not by the bars drawn at its last width, or it couldn't narrow. */} + {width > 0 && ( ({ label: groups[s.group], value: s.share, color: groupColor(groups[s.group]), note: pct(s.share) }))} /> )}
- + )}>

{describeMix(mix, groups)}{' '} {distinct && distinct.ratio >= DISTINCT ? <>{groups[distinct.group]} is {distinct.ratio.toFixed(1)}× as common here as across all {unit}s. : <>No group is much more common here than across all {unit}s.}

-
+ ); } @@ -170,25 +159,15 @@ export default function NichesReport({ result, table, wb, handle, unit, width }: [niches, current, nicheColors], ); - const [figure, setFigure] = useState<'saving' | 'saved' | null>(null); - const [problem, setProblem] = useState(null); - const saveFigure = async () => { - setFigure('saving'); - setProblem(null); - try { - await keepFigure(wb.key, handle.tableKey, { - title: result.meta.title, - caption: `Each row is a niche, found by k-means over every ${unit}'s neighborhood: the ${unit} and its ${neighbors} nearest. A square is the average share of a ${column} group in that niche's neighborhoods.`, - created_by: session?.displayName ?? '', - view: { kind: 'chart', chart: { type: 'heatmap', result: [...result.path, 'table'].join('/') } }, - width_mm: (groups.length > 12 ? SIZE_PRESETS.double : SIZE_PRESETS.single).widthMm, - }); - setFigure('saved'); - } catch (e) { - setFigure(null); - setProblem(describeError(e)); - } - }; + const { state: figure, problem, run: saveFigure } = useSaveFigure(async () => { + await keepFigure(wb.key, handle.tableKey, { + title: result.meta.title, + caption: `Each row is a niche, found by k-means over every ${unit}'s neighborhood: the ${unit} and its ${neighbors} nearest. A square is the average share of a ${column} group in that niche's neighborhoods.`, + created_by: session?.displayName ?? '', + view: { kind: 'chart', chart: { type: 'heatmap', result: [...result.path, 'table'].join('/') } }, + width_mm: (groups.length > 12 ? SIZE_PRESETS.double : SIZE_PRESETS.single).widthMm, + }); + }); const heatW = Math.min(width - 2, Math.max(320, HEAT_LABEL_W + groups.length * HEAT_CELL + 10)); const tableRows = useMemo(() => niches.map((niche, i) => ({ diff --git a/cirro-studio/src/reports/parts.tsx b/cirro-studio/src/reports/parts.tsx index 5b3e36d..99c485a 100644 --- a/cirro-studio/src/reports/parts.tsx +++ b/cirro-studio/src/reports/parts.tsx @@ -1,13 +1,13 @@ // What the reports share: the header that says what was run and when, the tiles of -// summary numbers, sections, the folded full table and its CSV download, the tissue they -// draw thumbnails of, and the actions that reach back into the data (color the tissue, -// score a gene set). +// summary numbers, sections, the folded full table and its CSV download, the card of one +// group, the tissue they draw thumbnails of, and the actions that reach back into the data +// (color the tissue, score a gene set) or keep a chart as a figure. import { useEffect, useState, type ReactNode } from 'react'; import { downloadBlob, type CheckpointHandle, type ExpressionMatrix } from '@cirrobio/spatial-viewer'; import { geneIndex } from '../analysis/matrix'; import { LENS_PARAM, navigate } from '../app/route'; -import { formatCount, formatDate, RemoveButton } from '../app/ui'; -import { tissueOf, type Tissue } from '../charts/TissueThumb'; +import { formatCount, formatDate, plural, RemoveButton } from '../app/ui'; +import { TissueThumb, tissueOf, type Paint, type Tissue } from '../charts/TissueThumb'; import { describeError } from '../cirro/session'; import { updateEncoding } from '../item/displayState'; import { freeName, readCoords, readMatrix } from '../tasks/data'; @@ -23,6 +23,8 @@ export const GENE_SET_SIZE = 25; // A group's color when its column no longer has it. export const NO_COLOR = '#8a93a3'; +const GROUP_THUMB_W = 132; + /** A share as a whole percentage; a share too small to round to 1% says so. */ export const pct = (v: number) => (v > 0 && v < 0.01 ? '<1%' : `${Math.round(100 * v)}%`); @@ -106,6 +108,51 @@ export function DownloadCsv({ name, rows, columns }: { name: s ); } +/** Keeping a chart over a result as a figure: whether it is being kept or has been, and why it couldn't be. */ +export function useSaveFigure(save: () => Promise) { + const [state, setState] = useState<'saving' | 'saved' | null>(null); + const [problem, setProblem] = useState(null); + const run = async () => { + setState('saving'); + setProblem(null); + try { + await save(); + setState('saved'); + } catch (e) { + setState(null); + setProblem(describeError(e)); + } + }; + return { state, problem, run }; +} + +/** One group of a report: its color, name and size, where it is on the tissue beside + * `detail`, and under them whatever the report says of it. `share` comes formatted: the + * reports round it differently. */ +export function GroupCard({ label, color, size, share, unit, tissue, paint, thumbLabel = `Where ${label} is`, caption, detail, children }: { + label: string; color: string; size: number; share: string; unit: string; tissue: Tissue | null; paint: Paint | null; + thumbLabel?: string; caption?: string; detail: ReactNode; children: ReactNode; +}) { + return ( +
+
+ +

{label}

+ {plural(size, [unit, `${unit}s`])} · {share} +
+
+
+ {tissue && paint ? + :
} +
{caption ?? `Where its ${unit}s are`}
+
+ {detail} +
+ {children} +
+ ); +} + // A report's view is the lens `report:`. export const REPORT_LENS = 'report:'; diff --git a/cirro-studio/src/tasks/NeighborhoodsTask.tsx b/cirro-studio/src/tasks/NeighborhoodsTask.tsx index 8adbea6..8e1ad27 100644 --- a/cirro-studio/src/tasks/NeighborhoodsTask.tsx +++ b/cirro-studio/src/tasks/NeighborhoodsTask.tsx @@ -3,9 +3,7 @@ // data and opens as its report. import { useState } from 'react'; import { ENRICHMENT_PERMUTATIONS, SPATIAL_NEIGHBOURS } from '../analysis/defaults'; -import { useStudio } from '../app/studio'; import { describeError } from '../cirro/session'; -import { useDisplays } from '../item/displayState'; import type { NeighborhoodsSummary } from '../reports/NeighborhoodsReport'; import { openReport } from '../reports/parts'; import { keepResult, storableNames, type KeptTable } from '../reports/store'; @@ -13,17 +11,15 @@ import { readCoords, readGroups } from './data'; import { ColumnSelect, JobStatus } from './parts'; import type { TaskProps } from './TaskPanel'; import { useJob } from './useJob'; +import { useSpatialTask } from './useSpatialTask'; const MAX_GROUPS = 60; export default function NeighborhoodsTask({ wb, unit }: TaskProps) { - const handle = wb.handle!; - const { session } = useStudio(); - const displays = useDisplays(wb.key, wb.handle); + const { handle, session, coords } = useSpatialTask(wb); const [column, setColumn] = useState(''); const [problem, setProblem] = useState(null); const job = useJob(); - const coords = displays.spatial?.encoding.coords ?? 'obsm:spatial'; const run = async () => { setProblem(null); diff --git a/cirro-studio/src/tasks/NichesTask.tsx b/cirro-studio/src/tasks/NichesTask.tsx index 54ee983..ba23471 100644 --- a/cirro-studio/src/tasks/NichesTask.tsx +++ b/cirro-studio/src/tasks/NichesTask.tsx @@ -4,9 +4,7 @@ // run is kept with the data and opens as its report. import { useState } from 'react'; import { NICHE_COUNT, NICHE_NEIGHBOURS } from '../analysis/defaults'; -import { useStudio } from '../app/studio'; import { describeError } from '../cirro/session'; -import { useDisplays } from '../item/displayState'; import type { NichesSummary } from '../reports/NichesReport'; import { openReport } from '../reports/parts'; import { keepResult, storableNames } from '../reports/store'; @@ -14,11 +12,10 @@ import { freeName, readCoords, readGroups } from './data'; import { ColumnSelect, JobStatus, writeObsColumn } from './parts'; import type { TaskProps } from './TaskPanel'; import { useJob } from './useJob'; +import { useSpatialTask } from './useSpatialTask'; export default function NichesTask({ wb, unit }: TaskProps) { - const handle = wb.handle!; - const { session } = useStudio(); - const displays = useDisplays(wb.key, wb.handle); + const { handle, session, coords } = useSpatialTask(wb); const taken = handle.fields.obs.map((f) => f.name); const [column, setColumn] = useState(''); const [count, setCount] = useState(NICHE_COUNT); @@ -26,7 +23,6 @@ export default function NichesTask({ wb, unit }: TaskProps) { const [name, setName] = useState(() => freeName('niche', taken)); const [problem, setProblem] = useState(null); const job = useJob(); - const coords = displays.spatial?.encoding.coords ?? 'obsm:spatial'; const run = async () => { setProblem(null); diff --git a/cirro-studio/src/tasks/SpatialGenesTask.tsx b/cirro-studio/src/tasks/SpatialGenesTask.tsx index 77e4a0b..bb8846a 100644 --- a/cirro-studio/src/tasks/SpatialGenesTask.tsx +++ b/cirro-studio/src/tasks/SpatialGenesTask.tsx @@ -6,11 +6,9 @@ import { useState } from 'react'; import { MORAN_MIN_CELLS, SPATIAL_NEIGHBOURS } from '../analysis/defaults'; import { geneIndex } from '../analysis/matrix'; import { PATTERN_GRID, PATTERN_MIN_CORRELATION, PATTERN_MIN_GENES, spatialPatterns } from '../analysis/patterns'; -import { useStudio } from '../app/studio'; import { tissueOf } from '../charts/TissueThumb'; import { SIGNIFICANCE } from '../charts/Volcano'; import { describeError } from '../cirro/session'; -import { useDisplays } from '../item/displayState'; import type { MoranSummary } from '../reports/MoranReport'; import { openReport } from '../reports/parts'; import { GENE_TEST_COLUMN, keepResult, type KeptTable } from '../reports/store'; @@ -18,17 +16,15 @@ import { readCoords, readMatrix } from './data'; import { JobStatus } from './parts'; import type { TaskProps } from './TaskPanel'; import { useJob } from './useJob'; +import { useSpatialTask } from './useSpatialTask'; // How many of the strongest spatially variable genes are grouped into patterns. const PATTERN_GENES = 60; export default function SpatialGenesTask({ wb, unit }: TaskProps) { - const handle = wb.handle!; - const { session } = useStudio(); - const displays = useDisplays(wb.key, wb.handle); + const { handle, session, coords } = useSpatialTask(wb); const [problem, setProblem] = useState(null); const job = useJob(); - const coords = displays.spatial?.encoding.coords ?? 'obsm:spatial'; const run = async () => { setProblem(null); diff --git a/cirro-studio/src/tasks/useSpatialTask.ts b/cirro-studio/src/tasks/useSpatialTask.ts new file mode 100644 index 0000000..191427c --- /dev/null +++ b/cirro-studio/src/tasks/useSpatialTask.ts @@ -0,0 +1,12 @@ +// What a task that reads cell positions starts from: the opened store, who is signed in +// (kept with its result), and the positions the tissue is drawn from. +import { useStudio } from '../app/studio'; +import { useDisplays } from '../item/displayState'; +import type { Workbench } from '../workbench/workbench'; + +export function useSpatialTask(wb: Workbench) { + const handle = wb.handle!; + const { session } = useStudio(); + const displays = useDisplays(wb.key, wb.handle); + return { handle, session, coords: displays.spatial?.encoding.coords ?? 'obsm:spatial' }; +} diff --git a/cirro-studio/src/workbench/workbench.ts b/cirro-studio/src/workbench/workbench.ts index 75a3feb..0b3baf8 100644 --- a/cirro-studio/src/workbench/workbench.ts +++ b/cirro-studio/src/workbench/workbench.ts @@ -254,8 +254,3 @@ export async function saveDraft(key: string, req: SaveRequest, onProgress?: (fra return { ...result, key: workbenchKey({ datasetId: result.datasetId, path: LAYER_MANIFEST, kind: 'version' }) }; }); } - -/** Forget an opened stack, so opening it again reads it afresh. */ -export function closeWorkbench(key: string) { - benches.delete(key); -} diff --git a/docs/CONTRACT.md b/docs/CONTRACT.md index abb9e9b..6876e78 100644 --- a/docs/CONTRACT.md +++ b/docs/CONTRACT.md @@ -72,7 +72,7 @@ ui_schema widget values: `checkbox|number|text|select|multitext|obs_key|obs_cate | PUT | `/api/sessions/{id}/pending/{stepId}` | `{params}` | `{ok:true}` | | DELETE | `/api/sessions/{id}/history/{entryId}` | — | `{ok:true}` (delete a compute/plot history entry, incl. discarding a pending step; queued/running entries can't be deleted) | | POST | `/api/sessions/{id}/plots/{plotId}/redraw` | — | `{ok:true}` | -| GET | `/api/sessions/{id}/plots/{plotId}/figure?fmt=svg\|pdf\|png` | — | figure bytes (image/svg+xml, application/pdf, or image/png — the raster copy consumed by the MCP assistant's `view_plot`). Served from this session's render, or read back from the checkpoint it was loaded from; **404** when neither has it (`SessionState.figures` says which plots do, without a fetch) | +| GET | `/api/sessions/{id}/plots/{plotId}/figure?fmt=svg\|pdf\|png` | — | figure bytes (image/svg+xml, application/pdf, or image/png — the raster copy consumed by the MCP assistant's `view_plot`). Served from this session's render, or read back from the checkpoint it was loaded from, with `X-Content-Type-Options: nosniff`, and for an SVG `Content-Security-Policy: sandbox; default-src 'none'; style-src 'unsafe-inline'` so one opened as a document cannot run script on the app's origin; **404** when neither has it (`SessionState.figures` says which plots do, without a fetch) | | PUT | `/api/sessions/{id}/displays/{displayId}` | `DisplaySpec` | `{ok:true}` | | POST | `/api/sessions/{id}/displays` | `DisplaySpec` (no id) | `DisplaySpec` (with id) — lazily add a display (e.g. an `embedding_canvas` for a dataset/obsm gained after session creation) | | POST | `/api/sessions/{id}/subset` | `{polygons:[[[x,y]...]] \| cell_indices:[int], coordinate_system?, invert?:bool}` | `{job_id}` (queued; the child session arrives via a `session.created` SSE event and the parent is closed — `session.removed` with `reason:"subset"`). Polygon vertices are canvas **world** coordinates (`obsm['spatial']` space); the backend maps them into a coordinate system and queries there. `coordinate_system` overrides which system that is — by default it is derived from the object (DESIGN §8.2), never taken from the hash-ordered `coordinate_systems` list. `invert:true` keeps the cells OUTSIDE the region. `cell_indices` (in place of `polygons`) subsets by explicit table rows — the embedding view's client-resolved selection, filtered via `match_sdata_to_table` | @@ -81,9 +81,9 @@ ui_schema widget values: `checkbox|number|text|select|multitext|obs_key|obs_cate | POST | `/api/sessions/{id}/shape-annotations` | `ShapeAnnotation` (no id) | `{job_id}` (create one shape) | | PUT | `/api/sessions/{id}/shape-annotations/{shapeId}` | `ShapeAnnotation` | `{job_id}` (replace one shape's geometry/style) | | DELETE | `/api/sessions/{id}/shape-annotations/{shapeId}` | — | `{job_id}` | -| POST | `/api/sessions/{id}/save` | `{folder?, prefix?, name?, path?, include?, levels?, slots?, figures?}` | `{job_id, path}` (queued save). `folder` is a directory under `DATA_DIR` (relative to it or absolute, created if absent) and `prefix` the filename stem the `-` suffix is appended to (default: the session's current name) — **400** for a folder outside `DATA_DIR`, or a prefix that is blank, dot-prefixed or holds a path separator. `name` renames the session and is recorded in the file as `app_state.name`, which a later load adopts in place of the filename; **400** if blank. `path` is the verbatim escape hatch — written as given, no hash suffix — and **400** if combined with `folder`/`prefix`. `figures` is the list of drawn-plot ids whose rendered figures the file should carry — omit for all of them, `[]` for none; **400** for an id that isn't a drawn plot | +| POST | `/api/sessions/{id}/save` | `{folder?, prefix?, name?, path?, include?, levels?, slots?, figures?}` | `{job_id, path}` (queued save). `folder` is a directory under `DATA_DIR` (relative to it or absolute, created if absent) and `prefix` the filename stem the `-` suffix is appended to (default: the session's current name) — **400** for a folder outside `DATA_DIR`, or a prefix that is blank, dot-prefixed or holds a path separator. `name` renames the session and is recorded in the file as `app_state.name`, which a later load adopts in place of the filename; **400** if blank. `path` is the verbatim escape hatch — written as given, no hash suffix — and **400** if it resolves outside `DATA_DIR` or is combined with `folder`/`prefix`. `figures` is the list of drawn-plot ids whose rendered figures the file should carry — omit for all of them, `[]` for none; **400** for an id that isn't a drawn plot | | GET | `/api/sessions/{id}/points-transform` | — | `{affine:[a,b,c,d,e,f], element}` (points→global affine of the active table's region element) | -| POST | `/api/sessions/{id}/points-transform` | `{affine:[a,b,c,d,e,f], path?}` | `{job_id, path}` (sets the affine and persists to disk) | +| POST | `/api/sessions/{id}/points-transform` | `{affine:[a,b,c,d,e,f], path?}` | `{job_id, path}` (sets the affine and persists to disk); **400** for a `path` that resolves outside `DATA_DIR` | | POST | `/api/sessions/{id}/snapshot` | `{viewport:{target,zoom}, width_px, height_px, dpi, formats:["pdf"\|"png"], label?, display_id?, include_minimap?}` | `{status,name,formats,rasterized_points}` — renders + writes `.figure.{pdf,png,thumb.png,json}` in DATA_DIR; 400 on an unrenderable spec, 503 (retryable) if a compute holds the write lock past `READ_LOCK_TIMEOUT_S` | | POST | `/api/sessions/{id}/snapshot/preview` | same as snapshot | `image/png` bytes — a low-res preview of the framing; writes nothing; same 400/503 as the save above | | GET | `/api/snapshots` | — | `{snapshots:[{name,base,label,created,kind,dataset,formats,output,thumbnail_url,metadata}]}` | diff --git a/frontend/package.json b/frontend/package.json index e00d3ba..96310ca 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "spatial-data-studio-frontend", "private": true, - "version": "1.10.0", + "version": "1.10.1", "type": "module", "scripts": { "dev": "vite", diff --git a/frontend/src/components/RegionsPanel.tsx b/frontend/src/components/RegionsPanel.tsx index aef2950..bce1e8e 100644 --- a/frontend/src/components/RegionsPanel.tsx +++ b/frontend/src/components/RegionsPanel.tsx @@ -92,7 +92,7 @@ export default function RegionsPanel() { try { if (isLocal) { if (source && regionCellIndices) { - applyLocalRegion({ + await applyLocalRegion({ source, cellIndices: regionCellIndices, nCells: sessionState?.fields.n_obs ?? 0, diff --git a/frontend/src/data/apiSource.ts b/frontend/src/data/apiSource.ts index 3d810bb..2efd845 100644 --- a/frontend/src/data/apiSource.ts +++ b/frontend/src/data/apiSource.ts @@ -2,7 +2,7 @@ // DataSource interface, so the same canvas can be pointed at a checkpoint instead. import { useMemo } from 'react'; import { loadOmeZarr } from '@vivjs/loaders'; -import type { DataSource, ImageLoader } from '@cirrobio/spatial-viewer'; +import { sanitizeSvg, type DataSource, type ImageLoader } from '@cirrobio/spatial-viewer'; import { getElements, getFieldData, getFigureUrl, getImageInfo, getImageThumbnailUrl, getShapesGeoArrow, searchVarNames, @@ -33,7 +33,11 @@ export function createApiSource(sessionId: string): DataSource { }); if (res.status === 404) return null; if (!res.ok) throw new Error(`figure fetch failed: ${res.status} ${res.statusText}`); - return res.blob(); + // A figure the session did not draw itself comes verbatim from the checkpoint it + // loaded, so an SVG is cleaned for the same reason the checkpoint source cleans + // one: the blob URL made from it is a same-origin document once opened in a tab. + if (format !== 'svg') return res.blob(); + return new Blob([sanitizeSvg(await res.text())], { type: 'image/svg+xml' }); }, async openImageLoader(element): Promise { diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts index 623bfec..0f7081c 100644 --- a/frontend/src/hooks/useSSE.ts +++ b/frontend/src/hooks/useSSE.ts @@ -64,7 +64,8 @@ export function useSSE(enabled = true): void { // data_versions already update instantly from the event payload, so delaying the // catch-up refetch by one tick is invisible to the user — but it collapses a // back-to-back batch (a recipe's N queued steps, or run-all) into one request - // instead of N, each of which would otherwise queue behind the next step's write lock. + // instead of N, each of which can land on another step's commit and wait for its + // write lock. const refreshTimer = useRef | null>(null); function scheduleRefresh(sessionId: string) { if (refreshTimer.current) clearTimeout(refreshTimer.current); @@ -135,13 +136,15 @@ export function useSSE(enabled = true): void { } }, - // Show the row immediately from the event itself. A refetch here can't do it: - // GET /api/sessions takes the session read lock, which blocks until the - // already-running job releases the write lock — so the row would only appear - // once the job finished. Insert on queued, flip to running on started, and let - // the terminal events below refetch to reconcile the full record (the write - // lock is released by then). Job tracking is scoped to the active session so - // another session's activity never spins this viewer's UI. + // Show the row immediately from the event itself rather than from a refetch. + // GET /api/sessions/{id} takes the session read lock: a job computes without + // the write lock and takes it only to commit, but whatever holds it when the + // refetch arrives — an earlier job's commit (minutes when it adopts and re-tiles + // an object), a save, a checkpoint load — makes that read wait, then 503 and + // retry. The event is already here. Insert on queued, flip to running on + // started, and let the terminal events below refetch to reconcile the full + // record. Job tracking is scoped to the active session so another session's + // activity never spins this viewer's UI. 'job.queued': (data) => { const d = data as JobQueuedEvent; if (d.session_id !== activeSession()) return; @@ -178,9 +181,10 @@ export function useSSE(enabled = true): void { if (d.session_id !== activeSession()) return; updateDataVersions(d.data_versions); // Flip the row to its terminal status from the event, not the refetch below: - // in a back-to-back queue (recipe / run-all) this job's completion refetch - // blocks on the read lock behind the NEXT job's write lock, so without this - // the finished row would keep showing "running" until the whole batch drains. + // that refetch is debounced, and in a back-to-back queue (recipe / run-all) + // the read it makes can still wait on the read lock behind a later step's + // commit — so without this the finished row would keep showing "running" + // after it ended. if (d.kind === 'compute') setEntryStatus(d.job_id, 'completed'); // Save runs as a background job with no visible result; confirm it finished. if (d.kind === 'save') { diff --git a/frontend/src/store/cirroUploads.test.ts b/frontend/src/store/cirroUploads.test.ts new file mode 100644 index 0000000..ca933cf --- /dev/null +++ b/frontend/src/store/cirroUploads.test.ts @@ -0,0 +1,44 @@ +// @vitest-environment happy-dom (lib/presence reads localStorage at import) +import { describe, it, expect, vi } from 'vitest'; + +vi.mock('../api', () => ({ + ApiError: class ApiError extends Error { status = 500; }, + getCirroUploads: vi.fn(), +})); + +import { useAppStore } from './sessionStore'; +import * as api from '../api'; +import type { CirroUpload } from '../api'; + +const upload = (id: number, state: CirroUpload['state'], error: string | null = null): CirroUpload => + ({ id, dataset_name: `dataset ${id}`, state, error }); + +const refreshWith = async (uploads: CirroUpload[]) => { + (api.getCirroUploads as ReturnType).mockResolvedValue({ uploads }); + await useAppStore.getState().refreshCirroUploads(); +}; +const messages = () => useAppStore.getState().notifications.map((n) => n.message); + +// The backend keeps settled uploads listed, so the rows a freshly loaded page reads are +// history. One sequence rather than separate cases: "has loaded once" is module state. +describe('refreshCirroUploads', () => { + it('announces only the changes this page watched happen', async () => { + await refreshWith([upload(1, 'completed'), upload(2, 'failed', 'boom'), upload(3, 'uploading')]); + expect(messages()).toEqual([]); + expect(useAppStore.getState().cirroUploads).toHaveLength(3); + + // An upload that was mid-flight at load still reports when it lands. + await refreshWith([upload(1, 'completed'), upload(2, 'failed', 'boom'), upload(3, 'completed')]); + expect(messages()).toEqual(['Uploaded to Cirro as "dataset 3".']); + + // Unchanged rows stay quiet on every later refresh. + await refreshWith([upload(1, 'completed'), upload(2, 'failed', 'boom'), upload(3, 'completed')]); + expect(messages()).toHaveLength(1); + + // One started after load that had already failed by the time its first read + // came back was still watched, and still reports. + await refreshWith([upload(1, 'completed'), upload(2, 'failed', 'boom'), upload(3, 'completed'), + upload(4, 'failed', 'no space')]); + expect(messages()).toEqual(['Uploaded to Cirro as "dataset 3".', 'Cirro upload failed: no space']); + }); +}); diff --git a/frontend/src/store/localRegions.test.ts b/frontend/src/store/localRegions.test.ts new file mode 100644 index 0000000..41fbf79 --- /dev/null +++ b/frontend/src/store/localRegions.test.ts @@ -0,0 +1,99 @@ +// @vitest-environment happy-dom (lib/presence reads localStorage at import) +import { describe, it, expect, beforeEach } from 'vitest'; +import { makeTable, Schema, Table } from 'apache-arrow'; +import type { DataSource, LocalCategorical } from '@cirrobio/spatial-viewer'; + +import { useAppStore } from './sessionStore'; +import type { RegionSet } from '../types'; + +// The two members labelling touches, behaving as the checkpoint source does: a local +// column, once installed, shadows the stored one of the same name. +function checkpointLike(stored: Record) { + const local = new Map(); + const source = { + kind: 'checkpoint', + setLocalColumn: (path: string, column: LocalCategorical) => { local.set(path, column); }, + getFieldData: async (path: string) => { + const column = local.get(path) ?? stored[path]; + if (!column) throw new Error(`no such column: ${path}`); + const table = makeTable({ code: column.codes }); + return new Table(new Schema(table.schema.fields, new Map([ + ['kind', 'categorical'], + ['categories', JSON.stringify(column.categories)], + ])), table.batches); + }, + } as unknown as DataSource; + return { source, local }; +} + +const tumorSet: RegionSet = { + id: 'set-1', name: 'tissue', obs_column: 'tissue', + categories: [ + { label: 'tumor', color: '#ff0000', n_cells: 2 }, + { label: 'stroma', color: '#00ff00', n_cells: 2 }, + ], +}; + +const openSession = (regions: RegionSet[], obs: string[]) => { + // Switching sessions is what clears the module-scope local columns between cases. + useAppStore.getState().setActiveSessionId(null); + useAppStore.getState().setActiveSessionId('sess'); + useAppStore.setState({ + sessionState: { + fields: { obs: obs.map((name) => ({ name, kind: 'categorical' })), n_obs: 5 }, + app_state: { regions }, + data_versions: {}, + } as never, + }); +}; +const regionSets = () => useAppStore.getState().sessionState?.app_state.regions ?? []; +const label = (source: DataSource, cellIndices: number[], category: string, obsColumn = 'tissue') => + useAppStore.getState().applyLocalRegion({ + source, cellIndices, nCells: 5, obsColumn, category, color: '#0000ff', + }); + +describe('applyLocalRegion', () => { + beforeEach(() => openSession([tumorSet], ['tissue'])); + + it('keeps the labels a stored region set already carries', async () => { + const { source, local } = checkpointLike({ + 'obs:tissue': { categories: ['tumor', 'stroma'], codes: Int32Array.of(0, 0, 1, 1, -1) }, + }); + await label(source, [1, 2], 'necrosis'); + + const column = local.get('obs:tissue'); + // The stored levels keep their positions; the cell with no level joins "unlabelled". + expect(column?.categories).toEqual(['tumor', 'stroma', 'unlabelled', 'necrosis']); + expect(Array.from(column?.codes ?? [])).toEqual([0, 3, 3, 1, 2]); + expect(regionSets()).toEqual([{ + ...tumorSet, + categories: [ + { label: 'tumor', color: '#ff0000', n_cells: 1 }, + { label: 'necrosis', color: '#0000ff', n_cells: 2 }, + { label: 'stroma', color: '#00ff00', n_cells: 1 }, + ], + }]); + expect(useAppStore.getState().sessionState?.data_versions['obs:tissue']).toBe(1); + + // A second label builds on the first rather than re-reading the store. + await label(source, [0], 'necrosis'); + expect(Array.from(local.get('obs:tissue')?.codes ?? [])).toEqual([3, 3, 3, 1, 2]); + }); + + it('adds no unlabelled level to a stored column with every cell labelled', async () => { + const { source, local } = checkpointLike({ + 'obs:tissue': { categories: ['tumor', 'stroma'], codes: Int32Array.of(0, 0, 1, 1, 1) }, + }); + await label(source, [4], 'tumor'); + expect(local.get('obs:tissue')?.categories).toEqual(['tumor', 'stroma']); + expect(Array.from(local.get('obs:tissue')?.codes ?? [])).toEqual([0, 0, 1, 1, 0]); + }); + + it('starts a new column with every other cell unlabelled', async () => { + const { source, local } = checkpointLike({}); + await label(source, [3], 'margin', 'drawn'); + expect(local.get('obs:drawn')?.categories).toEqual(['unlabelled', 'margin']); + expect(Array.from(local.get('obs:drawn')?.codes ?? [])).toEqual([0, 0, 0, 1, 0]); + expect(regionSets().map((r) => r.obs_column)).toEqual(['tissue', 'drawn']); + }); +}); diff --git a/frontend/src/store/sessionStore.ts b/frontend/src/store/sessionStore.ts index 51032c0..e5af9c7 100644 --- a/frontend/src/store/sessionStore.ts +++ b/frontend/src/store/sessionStore.ts @@ -1,6 +1,7 @@ import { create } from 'zustand'; import { ApiError, + arrowToColorSource, defaultFill, defaultStroke, fetchWhenIdle, @@ -46,6 +47,27 @@ const UNLABELLED = 'unlabelled'; // the canvas reads it back through the data source like any other column. const localRegionColumns = new Map(); +// A column the store already holds, as the starting point for labelling into it. Its +// levels keep their order (and so their palette colours); a cell with no level — a +// pandas categorical stores a missing value as code -1 — joins "unlabelled", which is +// added only when such a cell exists. +function seedFromStoredColumn(stored: LocalCategorical): LocalCategorical { + const categories = [...stored.categories]; + const codes = Int32Array.from(stored.codes); + let unlabelled = categories.indexOf(UNLABELLED); + for (let i = 0; i < codes.length; i++) { + if (codes[i] >= 0 && codes[i] < stored.categories.length) continue; + if (unlabelled < 0) unlabelled = categories.push(UNLABELLED) - 1; + codes[i] = unlabelled; + } + return { categories, codes }; +} + +// Whether the upload rows have been read once. The first read is the baseline: the +// backend keeps settled uploads listed, so what it returns is this browser's history, +// not news. +let cirroUploadsLoaded = false; + // A job's status lands in whichever collection holds it; these narrow the shared // status union so setEntryStatus can update the right record type without a cast. const HIST_STATUSES = ['pending', 'queued', 'running', 'completed', 'failed', 'cancelled'] as const; @@ -196,8 +218,9 @@ interface AppStore { updateDisplay: (display: DisplaySpec) => void; addDisplay: (display: DisplaySpec) => void; // Optimistically show a submitted compute/plot as queued straight from the - // job.queued event — a refetch can't do this because the read won't return until - // the (already-running) job frees the write lock (it 503s and retries until then). + // job.queued event — the event is in hand, while a refetch is a round trip whose + // read waits (503s and retries) for as long as a commit, a save or a load holds + // the session's write lock. addQueuedEntry: ( effectClass: 'compute' | 'plot', base: { id: string; namespace: string; function: string; params: Record }, @@ -273,7 +296,9 @@ interface AppStore { // Label cells entirely in the browser (serverless viewer). Writes a local // categorical column onto the data source and mirrors it into the session state // the pickers and legend read, so the result is indistinguishable from a - // backend-assigned region set — except that it lives only in this tab. + // backend-assigned region set — except that it lives only in this tab. Async + // because the first label into a column the store already holds reads that column, + // so the labels it carries are kept rather than shadowed by an empty one. applyLocalRegion: (args: { source: DataSource; cellIndices: number[]; @@ -281,7 +306,7 @@ interface AppStore { obsColumn: string; category: string; color: string; - }) => void; + }) => Promise; setRegionCellIndices: (idx: number[] | null) => void; addDrawVertex: (pt: [number, number]) => void; addDrawPolygon: (ring: [number, number][]) => void; @@ -679,17 +704,34 @@ export const useAppStore = create((set, get) => ({ setRegionCellIndices: (idx) => set({ regionCellIndices: idx }), hiddenCells: null, setHiddenCells: (cells) => set({ hiddenCells: cells && cells.size ? cells : null }), - applyLocalRegion: ({ source, cellIndices, nCells, obsColumn, category, color }) => + applyLocalRegion: async ({ source, cellIndices, nCells, obsColumn, category, color }) => { + const setLocalColumn = source.setLocalColumn?.bind(source); + if (!setLocalColumn) return; + const path = `obs:${obsColumn}`; + const sessionId = get().activeSessionId; + // The local column shadows the stored one of the same name from its first label + // on, so a column the checkpoint already carries (an existing region set is the + // default target) has to be the starting point — starting empty would wipe every + // category it holds off the canvas and out of the region registry. Read before + // any shadow is installed, which is the only time the source still returns the + // stored column. + let stored: LocalCategorical | undefined; + if (!localRegionColumns.has(path) + && get().sessionState?.fields.obs.some((f) => f.name === obsColumn)) { + const column = arrowToColorSource(await source.getFieldData(path)); + // The maps are per-session and were cleared if the session changed meanwhile. + if (get().activeSessionId !== sessionId) return; + if (column?.kind === 'categorical') stored = seedFromStoredColumn(column); + } set((s) => { - if (!s.sessionState || !source.setLocalColumn) return {}; - const path = `obs:${obsColumn}`; + if (!s.sessionState) return {}; const regions = s.sessionState.app_state.regions ?? []; const existing = regions.find((r) => r.obs_column === obsColumn); - // Categories carry an explicit "unlabelled" level at code 0 so cells outside - // every lasso stay visible (and greyed) rather than dropping out of the - // colouring. Re-labelling a cell overwrites its previous category. - const previous = localRegionColumns.get(path); + // A column started here carries an explicit "unlabelled" level at code 0 so + // cells outside every lasso stay visible (and greyed) rather than dropping out + // of the colouring. Re-labelling a cell overwrites its previous category. + const previous = localRegionColumns.get(path) ?? stored; const categories = previous ? [...previous.categories] : [UNLABELLED]; let code = categories.indexOf(category); if (code < 0) { @@ -701,7 +743,7 @@ export const useAppStore = create((set, get) => ({ if (i >= 0 && i < codes.length) codes[i] = code; } localRegionColumns.set(path, { categories, codes }); - source.setLocalColumn(path, { categories, codes }); + setLocalColumn(path, { categories, codes }); // Recount every category from the codes, so re-labelling over an earlier // selection reports the truth rather than accumulating. @@ -744,7 +786,8 @@ export const useAppStore = create((set, get) => ({ }, }, }; - }), + }); + }, addDrawVertex: (pt) => set((s) => ({ drawRing: [...s.drawRing, pt] })), addDrawPolygon: (ring) => set((s) => ({ drawPolygons: [...s.drawPolygons, ring] })), commitDrawRegion: () => @@ -936,8 +979,12 @@ export const useAppStore = create((set, get) => ({ const previous = new Map(get().cirroUploads.map((u) => [u.id, u.state])); try { const { uploads } = await getCirroUploads(); + // Only a change this page watched happen is announced — otherwise every page + // load would repeat the outcome of every past upload. + const announce = cirroUploadsLoaded; + cirroUploadsLoaded = true; for (const u of uploads) { - if (previous.get(u.id) === u.state) continue; + if (!announce || previous.get(u.id) === u.state) continue; if (u.state === 'completed') { get().pushNotification({ kind: 'info', message: `Uploaded to Cirro as "${u.dataset_name}".` }); } else if (u.state === 'failed') { diff --git a/package-lock.json b/package-lock.json index 83b7abb..cce983e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "spatial-data-studio", - "version": "1.10.0", + "version": "1.10.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "spatial-data-studio", - "version": "1.10.0", + "version": "1.10.1", "workspaces": [ "packages/viewer", "packages/studio-ui", @@ -22,7 +22,7 @@ }, "cirro-studio": { "name": "spatial-data-studio-cirro", - "version": "1.10.0", + "version": "1.10.1", "dependencies": { "@cirrobio/api-client": "0.13.39", "@cirrobio/sdk": "0.13.39", @@ -82,7 +82,7 @@ }, "frontend": { "name": "spatial-data-studio-frontend", - "version": "1.10.0", + "version": "1.10.1", "dependencies": { "@cirrobio/spatial-viewer": "*", "@cirrobio/studio-ui": "*", @@ -11389,7 +11389,7 @@ }, "packages/studio-ui": { "name": "@cirrobio/studio-ui", - "version": "1.10.0", + "version": "1.10.1", "license": "SEE LICENSE IN LICENSE.md", "peerDependencies": { "@cirrobio/spatial-viewer": "*", @@ -11401,7 +11401,7 @@ }, "packages/viewer": { "name": "@cirrobio/spatial-viewer", - "version": "1.10.0", + "version": "1.10.1", "license": "SEE LICENSE IN LICENSE.md", "dependencies": { "hyparquet": "^1.28.2", diff --git a/package.json b/package.json index 3685cc2..64633c5 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "spatial-data-studio", "private": true, - "version": "1.10.0", + "version": "1.10.1", "workspaces": [ "packages/viewer", "packages/studio-ui", diff --git a/packages/studio-ui/package.json b/packages/studio-ui/package.json index 9499ea0..34ab7eb 100644 --- a/packages/studio-ui/package.json +++ b/packages/studio-ui/package.json @@ -1,6 +1,6 @@ { "name": "@cirrobio/studio-ui", - "version": "1.10.0", + "version": "1.10.1", "private": true, "description": "Spatial Data Studio's own controls (the canvas display settings and the pickers they use) and its Google Analytics page views, shared by the Studio app and Spatial Data Studio for Cirro.", "license": "SEE LICENSE IN LICENSE.md", diff --git a/packages/studio-ui/src/canvas/CanvasControls.tsx b/packages/studio-ui/src/canvas/CanvasControls.tsx index f5ae8d0..d5c9f8a 100644 --- a/packages/studio-ui/src/canvas/CanvasControls.tsx +++ b/packages/studio-ui/src/canvas/CanvasControls.tsx @@ -10,63 +10,24 @@ import DualRangeField, { rangeDigits, rangeStep } from './DualRangeField'; import ColorRangeControls from './ColorRangeControls'; import { CATEGORY_SWATCHES, CHANNEL_COLORS, SPATIAL_ENCODING_DEFAULTS, ZOOM_LIMITS, - type Channel, type ColorRange, type ObsField, type SpatialDisplaySpec, + type SpatialCanvasControls, } from '@cirrobio/spatial-viewer'; -interface CanvasControlsProps { - display: SpatialDisplaySpec; - obsFields: ObsField[]; - layers: string[]; - hasX: boolean; - colorByName: string; - legendVisible: boolean; - updateEncoding: (patch: Partial) => void; - // Categorical levels + effective hex color for the per-category color controls; - // null unless the current color-by field is categorical (within the level cap). - categoryColorItems: { label: string; color: string }[] | null; - hasCategoryOverrides: boolean; - setCategoryColor: (label: string, color: string) => void; - resetCategoryColors: () => void; - colorRange: ColorRange | null; - setColorLimits: (limits: [number, number] | null) => void; - showPoints: boolean; +// What the mounted canvas supplies, plus the setters and placement the host adds. +type CanvasControlsProps = SpatialCanvasControls & { setShowPoints: (v: boolean) => void; - showImage: boolean; setShowImage: (v: boolean) => void; - invertX: boolean; setInvertX: (v: boolean) => void; - invertY: boolean; setInvertY: (v: boolean) => void; - background: 'light' | 'dark'; setBackground: (v: 'light' | 'dark') => void; - showLegend: boolean; setShowLegend: (v: boolean) => void; - showMinimap: boolean; setShowMinimap: (v: boolean) => void; - renderMode: 'points' | 'points+shapes'; setRenderMode: (v: 'points' | 'points+shapes') => void; - shapeSets: string[]; - shapesElement: string | null; setShapesElement: (v: string) => void; - imageSets: string[]; - imageElement: string | null; - setImageElement: (v: string | null) => void; - channels: Channel[]; - setChannel: (index: number, patch: Partial<{ visible: boolean; name: string; color: string; contrastLimits: [number, number] }>) => void; - maxVisibleReached: boolean; panelCollapsed: boolean; setPanelCollapsed: (v: boolean) => void; docked?: boolean; - zoom: number; - onZoom: (delta: number) => void; - onFit: () => void; - onEditTransform?: () => void; - // False when this viewer can't change the session (read-only snapshot, or another - // viewer holds the edit lock): everything else here is a display setting that stays - // on this screen, but the transform editor writes to the session and its checkpoint. - canEdit: boolean; - editBlockedReason: string | null; -} +}; type DisplayTab = 'layers' | 'cells' | 'image'; diff --git a/packages/studio-ui/src/canvas/EmbeddingControls.tsx b/packages/studio-ui/src/canvas/EmbeddingControls.tsx index cf13aa3..bc29745 100644 --- a/packages/studio-ui/src/canvas/EmbeddingControls.tsx +++ b/packages/studio-ui/src/canvas/EmbeddingControls.tsx @@ -4,24 +4,14 @@ import ColorRangeControls from './ColorRangeControls'; import CanvasSettingsShell from './CanvasSettingsShell'; import LegendControls from './LegendControls'; import PointStyleControls from './PointStyleControls'; -import type { ColorRange, EmbeddingDisplaySpec, ObsField, ObsmField } from '@cirrobio/spatial-viewer'; +import type { EmbeddingCanvasControls } from '@cirrobio/spatial-viewer'; -interface Props { - display: EmbeddingDisplaySpec; - obsFields: ObsField[]; - hasX: boolean; - layers: string[]; - obsmFields: ObsmField[]; - colorByName: string; - legendVisible: boolean; - updateEncoding: (patch: Partial) => void; - colorRange: ColorRange | null; - setColorLimits: (limits: [number, number] | null) => void; +// What the mounted canvas supplies, plus the placement the host adds. +type Props = EmbeddingCanvasControls & { panelCollapsed: boolean; setPanelCollapsed: (v: boolean) => void; docked?: boolean; - onFit: () => void; -} +}; // One row of the X/Y/Z axis pickers: which component of the selected obsm array // to plot on that axis. diff --git a/packages/viewer/package.json b/packages/viewer/package.json index d442fd0..1f5111c 100644 --- a/packages/viewer/package.json +++ b/packages/viewer/package.json @@ -1,6 +1,6 @@ { "name": "@cirrobio/spatial-viewer", - "version": "1.10.0", + "version": "1.10.1", "description": "Host-agnostic WebGL spatial/embedding canvases and the .zarr.zip checkpoint reader from Spatial Data Studio.", "license": "SEE LICENSE IN LICENSE.md", "sideEffects": false, diff --git a/packages/viewer/src/data/checkpointSource.ts b/packages/viewer/src/data/checkpointSource.ts index 1708c40..9561905 100644 --- a/packages/viewer/src/data/checkpointSource.ts +++ b/packages/viewer/src/data/checkpointSource.ts @@ -23,6 +23,7 @@ import { } from '../types'; import { applyAffineXy } from '../canvas/imageAffine'; import { afterThisTask } from '../lib/afterThisTask'; +import { sanitizeSvg } from '../lib/sanitizeSvg'; import { SHAPE_ANNOTATIONS_ELEMENT } from '../lib/shapeAnnotations'; import type { ShapeAnnotation } from '../schemas/annotations'; import type { FileMetaData } from 'hyparquet'; @@ -616,7 +617,11 @@ export async function openCheckpointStore( async getPlotFigure(plotId: string, format: FigureFormat): Promise { if (!sidecar.figures?.[plotId]?.[format]) return null; const bytes = await readBytes(root, `viewer/figures/${plotId}/${format}`); - return new Blob([bytes], { type: FIGURE_MEDIA_TYPES[format] }); + // The store may be one somebody else chose (`?checkpoint=`), and an SVG blob + // is a same-origin document as soon as its URL is opened outside an . Cleaned + // here so the display and the download are both handed the safe copy. + const body = format === 'svg' ? sanitizeSvg(new TextDecoder().decode(bytes)) : bytes; + return new Blob([body], { type: FIGURE_MEDIA_TYPES[format] }); }, async getExpressionMatrix(onProgress) { diff --git a/packages/viewer/src/index.ts b/packages/viewer/src/index.ts index 8a3f883..19f44aa 100644 --- a/packages/viewer/src/index.ts +++ b/packages/viewer/src/index.ts @@ -70,6 +70,7 @@ export { useArrowPositions, type ScatterPositions } from './canvas/useArrowPosit // ---- Snapshots (PNG capture + the saved-figure contract) --------------------- export { downloadCanvasPng, plotCanvas } from './lib/canvasCapture'; export { downloadBlob } from './lib/download'; +export { sanitizeSvg } from './lib/sanitizeSvg'; export { formatCreated, type Snapshot, type SnapshotExportParams, type SnapshotFormat, } from './lib/snapshots'; diff --git a/packages/viewer/src/lib/sanitizeSvg.test.ts b/packages/viewer/src/lib/sanitizeSvg.test.ts new file mode 100644 index 0000000..6db31f8 --- /dev/null +++ b/packages/viewer/src/lib/sanitizeSvg.test.ts @@ -0,0 +1,122 @@ +// @vitest-environment happy-dom +import { describe, it, expect } from 'vitest'; +import { sanitizeSvg } from './sanitizeSvg'; + +// The shape of what matplotlib's SVG backend writes: a doctype, RDF metadata, a CDATA-free +// style block, clip paths and glyphs in referenced by local id, a hatch pattern, +// an embedded raster, and Gouraud shading's gradient + filter. +const MATPLOTLIB = ` + + + + + + + Matplotlib v3.11.0, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + axis + + + + + + + + +`; + +const parse = (text: string) => new DOMParser().parseFromString(text, 'image/svg+xml'); +// Every element with its attributes, in document order — what the figure draws with. +const drawn = (text: string) => Array.from(parse(text).getElementsByTagName('*'), (element) => + [element.tagName, ...Array.from(element.attributes, (a) => `${a.name}=${a.value}`).sort()].join(' ')); + +describe('sanitizeSvg', () => { + it('leaves a matplotlib figure as it was drawn', () => { + const cleaned = sanitizeSvg(MATPLOTLIB); + expect(drawn(cleaned)).toEqual(drawn(MATPLOTLIB)); + expect(cleaned).toContain('*{stroke-linejoin: round; stroke-linecap: butt}'); + expect(cleaned).toContain('Matplotlib v3.11.0'); + expect(cleaned).not.toContain(' { + const cleaned = sanitizeSvg(` + + + + + alert(2) + alert(3) + + + + + + + + + + + + +`); + + for (const gone of ['script', 'alert', 'evil.example', 'javascript:', 'foreignObject', 'iframe', + 'xml-stylesheet', '@import', 'onload', 'onclick', 'OnMouseOver', 'animate', ' { + const cleaned = sanitizeSvg(` + + + + +`); + expect(cleaned).not.toContain('evil.example'); + const document = parse(cleaned); + expect(document.getElementById('escaped-url')).toBeNull(); + expect(document.getElementById('escaped-import')).toBeNull(); + expect(document.getElementById('image-set')?.getAttribute('style')).toBeNull(); + expect(document.getElementById('quoted')?.getAttribute('clip-path')).toBe('url("#c")'); + expect(document.getElementById('quoted')?.getAttribute('fill')).toBe('url( #g)'); + }); + + it('refuses what is not an SVG document', () => { + expect(() => sanitizeSvg('')).toThrow(/not a well-formed SVG/); + expect(() => sanitizeSvg('')) + .toThrow(/not a well-formed SVG/); + expect(() => sanitizeSvg('')).toThrow(/not a well-formed SVG/); + }); +}); diff --git a/packages/viewer/src/lib/sanitizeSvg.ts b/packages/viewer/src/lib/sanitizeSvg.ts new file mode 100644 index 0000000..572a03f --- /dev/null +++ b/packages/viewer/src/lib/sanitizeSvg.ts @@ -0,0 +1,101 @@ +// An SVG read out of a store somebody else chose is shown from a same-origin blob URL. +// As an it is inert, but the same URL opened as a document ("open image in new +// tab") is a page of this origin, and any script in it would run with the app's +// storage and its Cirro session. So nothing that can run script, or reach outside the +// file, survives the reading. +// +// An allowlist rather than a list of known-bad names: it covers the drawing elements +// matplotlib writes (and the gradients, patterns and filters it uses for shading and +// hatches), and everything else in the SVG namespace — script, foreignObject, the +// animation elements that can rewrite an href, whatever is added to SVG next — goes. + +const SVG_NS = 'http://www.w3.org/2000/svg'; +const XLINK_NS = 'http://www.w3.org/1999/xlink'; + +const SVG_ELEMENTS = new Set([ + 'svg', 'g', 'defs', 'symbol', 'use', 'a', 'switch', + 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'image', + 'text', 'tspan', 'textPath', + 'clipPath', 'mask', 'pattern', 'marker', 'linearGradient', 'radialGradient', 'stop', + 'filter', 'style', 'title', 'desc', 'metadata', +]); +// The filter primitives (feColorMatrix, feComposite, ...) — matplotlib's Gouraud shading. +const FILTER_PRIMITIVE = /^fe[A-Z][A-Za-z]*$/; + +// The only link targets kept: another node of the same file, and — on alone — +// a raster embedded in it. Not `data:image/svg+xml`, which is a second document. +const LOCAL_REFERENCE = /^\s*#/; +const EMBEDDED_RASTER = /^\s*data:image\/(png|jpeg|gif|webp);base64,/i; +// A CSS `url(...)` to anything but a node of the same file, a stylesheet import, or +// `image-set()`, which takes an address as a bare string. A backslash is refused +// outright: CSS escapes can spell any of those (`\75 rl(`), and no figure needs one. +// The lookahead excludes quotes and spaces so that backtracking over the optional +// ones before it cannot make a quoted `url("#id")` look external. +const EXTERNAL_CSS = /\\|image-set\(|@import|url\(\s*['"]?\s*(?![#\s'"])/i; + +const PROCESSING_INSTRUCTION = 7; + +function isKeptElement(element: Element): boolean { + if (element.namespaceURI === SVG_NS) { + return SVG_ELEMENTS.has(element.localName) || FILTER_PRIMITIVE.test(element.localName); + } + // The RDF/Dublin Core description matplotlib writes sits in in its own + // namespaces and is never rendered. Anywhere else a foreign element has no business + // in a figure, and XHTML — where