Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
35 changes: 25 additions & 10 deletions DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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),
Expand Down Expand Up @@ -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 |
Expand Down Expand Up @@ -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
Expand All @@ -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 `-<content hash>` 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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 `<img>` 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

Expand Down
14 changes: 9 additions & 5 deletions backend/app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
60 changes: 25 additions & 35 deletions backend/app/deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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


Expand All @@ -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

Expand All @@ -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
Expand All @@ -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
Expand All @@ -137,36 +123,40 @@ 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:
sess.lock.release_read()
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")
Expand Down
Loading
Loading