# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# QC2 @ CHALMERS CALIBRATION TOOLKIT
# (c) 2026 Chalmers University of Technology and Project Contributors
# ──────────────────────────────────────────────────────────────────────────
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ──────────────────────────────────────────────────────────────────────────
# CONTRIBUTORS list:
#
# Matteo Robbiati, robbiati@chalmers.se
# Axel Andersson, axean@chalmers.se
# Yanchen Lin, linya@chalmers.se
# ══════════════════════════════════════════════════════════════════════════
"""
Routing layer for the bragi_quantum.gui archive server.
Defines the session value type (``SessionBundle`` + ``_make_bundles``), the
FastAPI dependencies and error handlers, and two ``APIRouter`` factories whose
routes resolve their target from the live ``Archive`` on ``app.state``:
session_router() /session/{key}/... per-session replot API
GET /health -> liveness + paths
GET /steps -> node step summaries
GET /step/{i}/element/{name}/plots -> available plot names
POST /plot -> PNG bytes
GET /report -> rendered HTML report
pipeline_router() /pipeline/{run_ts}/... cross-session whole-pipeline view
The app itself (lifespan, routers, static mounts) is assembled in
``archive.py``; the pipeline/QoI domain logic lives in ``pipeline.py``.
"""
from __future__ import annotations
import json
import logging
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
from pydantic import BaseModel, Field
from bragi_quantum.gui import comments, replay
from bragi_quantum.gui.figure_quantize import quantize_figure_json
from bragi_quantum.gui.pipeline import (
_build_pipeline_data,
_chronological,
_collect_qoi_names,
_list_node_pngs,
_pipeline_start_config,
_pipeline_timing_summary,
_pipeline_timing_table,
_render_qoi_plot_png,
_render_timing_bar_png,
_render_timing_pie_png,
_resolve_node_dir,
)
from bragi_quantum.gui.rendering.html_rendering import (
create_html_rendering,
create_whole_pipeline_html,
)
from bragi_quantum.gui.timeline import Timeline
from bragi_quantum.gui.vendor_js_assets import plotly_asset_url
logger = logging.getLogger(__name__)
_MAX_COMMENT_CHARS = 20_000
[docs]
class CommentBody(BaseModel):
text: str = Field(..., min_length=1, max_length=_MAX_COMMENT_CHARS)
[docs]
class PlotRequest(BaseModel):
step_index: int = Field(..., ge=0)
element: str
plot_name: str = "main"
# Re-tune analysis-category parameters before re-fitting (the reanalysis
# path). Keys must be analysis fields; other fields are rejected.
overrides: dict[str, Any] | None = None
# How many elements the frontend currently has selected together (e.g. a
# marquee multi-select), so an analysis can skip an expensive per-element
# plot when it'd be rendered N times at once. Defaults to 1 (just this
# element) for callers that don't track a selection.
n_selected_elements: int = Field(default=1, ge=1)
[docs]
@dataclass(frozen=True)
class SessionBundle:
key: str
session_root: Path
title: str
step_count: int
total_steps: int
timeline: list[dict[str, Any]]
@property
def tl(self) -> Timeline:
"""The timeline as a value object (start config, qubits, node steps…)."""
return Timeline(self.timeline)
@property
def routes_prefix(self) -> str:
return f"/session/{self.key}"
@property
def start_ts(self) -> str:
return self.tl.start_ts
def _sanitize_key_part(value: str) -> str:
part = re.sub(r"[^a-zA-Z0-9_-]+", "-", value.strip())
part = part.strip("-")
return part or "run"
def _make_bundles(session_roots: list[Path]) -> list[SessionBundle]:
bundles: list[SessionBundle] = []
used_keys: set[str] = set()
for index, root in enumerate(session_roots, start=1):
resolved = Path(root).resolve()
segments = Timeline.load(resolved).split_runs()
many_runs_in_same_folder = len(segments) > 1
for run_idx, segment in enumerate(segments, start=1):
title, step_count = segment.title(resolved.name)
run_name = (segment.start_config.get("session_options") or {}).get(
"run_name"
)
base_key = resolved.name or f"session-{index}"
if many_runs_in_same_folder:
run_key_part = _sanitize_key_part(str(run_name or f"run-{run_idx}"))
base_key = f"{base_key}-{run_idx}-{run_key_part}"
title = f"{title} · run {run_idx}/{len(segments)}"
key = base_key
suffix = 2
while key in used_keys:
key = f"{base_key}-{suffix}"
suffix += 1
used_keys.add(key)
bundles.append(
SessionBundle(
key=key,
session_root=resolved,
title=title,
step_count=step_count,
total_steps=len(segment.steps),
timeline=segment.steps,
)
)
return bundles
# --------------------------------------------------------------------------- #
# Route dependencies + error handling #
# #
# Routes carry the entity in the path (``/session/{key}``, ``/pipeline/{run_ts}``)
# and resolve it against the live ``Archive`` on ``app.state`` — so the route #
# table is static and discovery only ever mutates the archive's dicts. #
# --------------------------------------------------------------------------- #
[docs]
def get_bundle(key: str, request: Request) -> SessionBundle:
bundle = request.app.state.archive.bundle(key)
if bundle is None:
raise HTTPException(status_code=404, detail=f"unknown session {key!r}")
return bundle
[docs]
def get_run(run_ts: str, request: Request) -> list[SessionBundle]:
return request.app.state.archive.run(run_ts)
def _replay_error_handler(_request: Request, exc: Exception) -> JSONResponse:
"""Any ``ReplayError`` bubbling out of a handler is a 404 (missing data)."""
return JSONResponse(status_code=404, content={"detail": str(exc)})
def _plot_render_error_handler(_request: Request, exc: Exception) -> JSONResponse:
"""A failed re-fit/render is a 500 that still lists the analysis fields read."""
logger.exception("plot re-fit/render failed")
return JSONResponse(
status_code=500,
content={
"detail": str(exc),
"analysis_fields": getattr(exc, "analysis_fields", []),
},
)
def _fallback_handler(_request: Request, exc: Exception) -> JSONResponse:
logger.exception("unhandled error in bragi_quantum.gui request")
return JSONResponse(status_code=500, content={"detail": str(exc)})
[docs]
def session_router() -> APIRouter:
"""Per-session replot API, resolved by ``{key}`` against the archive."""
router = APIRouter(prefix="/session/{key}")
@router.get("/health")
def health(bundle: SessionBundle = Depends(get_bundle)) -> dict[str, Any]:
return {
"ok": True,
"session_root": str(bundle.session_root),
"n_steps": len(bundle.timeline),
"node_steps": len(bundle.tl.node_steps),
"session_key": bundle.key,
}
@router.get("/steps")
def steps(bundle: SessionBundle = Depends(get_bundle)) -> list[dict[str, Any]]:
return [replay.step_summary(s) for s in bundle.tl.node_steps]
@router.get("/step/{step_index}/element/{element}/plots")
def list_plots(
step_index: int,
element: str,
bundle: SessionBundle = Depends(get_bundle),
) -> dict[str, Any]:
step = replay.find_step(bundle.timeline, step_index)
names = replay.list_plots_for_element(
step, element, session_root=bundle.session_root
)
return {"step_index": step_index, "element": element, "plots": names}
@router.get("/step/{step_index}/params")
def step_params(
step_index: int,
bundle: SessionBundle = Depends(get_bundle),
) -> dict[str, Any]:
"""Analysis-category parameters that can be re-tuned for this step."""
step = replay.find_step(bundle.timeline, step_index)
return {
"step_index": step_index,
"fields": replay.analysis_fields_for_step(step),
}
@router.post("/plot")
def plot(
req: PlotRequest,
request: Request,
bundle: SessionBundle = Depends(get_bundle),
) -> Response:
step = replay.find_step(bundle.timeline, req.step_index)
figure_json, analysis_fields = replay.render_figure_json(
step,
req.element,
req.plot_name,
session_root=bundle.session_root,
overrides=req.overrides,
n_selected_elements=req.n_selected_elements,
)
if request.app.state.archive.traffic_saver:
figure_json = quantize_figure_json(figure_json)
# A plotly figure ({data, layout}) rendered interactively by plotly.js,
# plus the analysis fields its fit and rendering read. The figure JSON
# is spliced in as-is rather than re-parsed.
return Response(
content=(
f'{{"figure": {figure_json}, '
f'"analysis_fields": {json.dumps(analysis_fields)}}}'
),
media_type="application/json",
headers={"Cache-Control": "private, max-age=3600"},
)
@router.get("/report")
def report(bundle: SessionBundle = Depends(get_bundle)) -> HTMLResponse:
html = create_html_rendering(
qubits=bundle.tl.qubits,
couplers=bundle.tl.couplers,
session_root_path=bundle.session_root,
session_timeline=bundle.timeline,
replot_endpoint_override=bundle.routes_prefix,
plotly_src=plotly_asset_url(),
)
return HTMLResponse(content=html)
return router
[docs]
def pipeline_router() -> APIRouter:
"""Cross-session whole-pipeline view for one run, resolved by ``{run_ts}``.
A single router serves every run's pipeline (``/pipeline/{run_ts}/…``); the
run's bundles are resolved from the archive, so there is no per-run route
registration and no OpenAPI operation-id juggling.
"""
router = APIRouter(prefix="/pipeline/{run_ts}")
def _bundle_or_404(session: str, request: Request) -> SessionBundle:
bundle = request.app.state.archive.bundle(session)
if bundle is None:
raise HTTPException(status_code=404, detail=f"unknown session {session!r}")
return bundle
@router.get("")
def pipeline_page() -> HTMLResponse:
return HTMLResponse(
content=create_whole_pipeline_html(),
headers={"Cache-Control": "no-store"},
)
@router.get("/data")
def pipeline_data(
bundles: list[SessionBundle] = Depends(get_run),
) -> dict[str, Any]:
# Chronological session order (first session first) → correct arrows.
return _build_pipeline_data(_chronological(bundles))
@router.get("/start-config")
def pipeline_start_config(
bundles: list[SessionBundle] = Depends(get_run),
) -> dict[str, Any]:
return _pipeline_start_config(bundles)
@router.get("/qois")
def pipeline_qois(
bundles: list[SessionBundle] = Depends(get_run),
) -> dict[str, Any]:
return _collect_qoi_names(bundles)
@router.get("/qoi-plot")
def pipeline_qoi_plot(
name: str,
mode: str = "absolute",
bundles: list[SessionBundle] = Depends(get_run),
) -> Response:
png = _render_qoi_plot_png(bundles, name, mode=mode)
return Response(
content=png,
media_type="image/png",
headers={"Cache-Control": "no-store"},
)
@router.get("/timing")
def pipeline_timing(
bundles: list[SessionBundle] = Depends(get_run),
) -> dict[str, Any]:
return _pipeline_timing_summary(_chronological(bundles))
@router.get("/timing-table")
def pipeline_timing_table(
bundles: list[SessionBundle] = Depends(get_run),
) -> dict[str, Any]:
return _pipeline_timing_table(_chronological(bundles))
@router.get("/timing-chart")
def pipeline_timing_chart(
kind: str = "bar",
bundles: list[SessionBundle] = Depends(get_run),
) -> Response:
png = (
_render_timing_pie_png(bundles)
if kind == "pie"
else _render_timing_bar_png(bundles)
)
return Response(
content=png,
media_type="image/png",
headers={"Cache-Control": "no-store"},
)
@router.get("/node-plots")
def pipeline_node_plots(
session: str, step: int, request: Request
) -> dict[str, Any]:
bundle = _bundle_or_404(session, request)
node_step = replay.find_step(bundle.timeline, step)
node_dir = _resolve_node_dir(node_step, bundle.session_root)
plots = _list_node_pngs(node_dir) if node_dir else []
return {"session": session, "step": step, "plots": plots}
def _comment_target(session: str, step: int, request: Request) -> tuple[Path, str]:
"""The node's output folder (where comments are saved) and its title."""
bundle = _bundle_or_404(session, request)
node_step = replay.find_step(bundle.timeline, step)
node_dir = _resolve_node_dir(node_step, bundle.session_root)
if node_dir is None:
raise HTTPException(status_code=404, detail="node output folder not found")
return node_dir, str(node_step.get("node_name") or node_dir.name)
@router.get("/comments")
def list_comments(session: str, step: int, request: Request) -> dict[str, Any]:
node_dir, _ = _comment_target(session, step, request)
return {"comments": comments.load_comments(node_dir)}
@router.post("/comments")
def add_comment(
session: str, step: int, body: CommentBody, request: Request
) -> dict[str, Any]:
node_dir, title = _comment_target(session, step, request)
saved = comments.add_comment(
node_dir, title, body.text.strip(), comments.current_author()
)
return {"comments": saved}
@router.put("/comments/{comment_id}")
def edit_comment(
comment_id: str, session: str, step: int, body: CommentBody, request: Request
) -> dict[str, Any]:
node_dir, title = _comment_target(session, step, request)
saved = comments.edit_comment(node_dir, title, comment_id, body.text.strip())
if saved is None:
raise HTTPException(status_code=404, detail="no such comment")
return {"comments": saved}
@router.delete("/comments/{comment_id}")
def delete_comment(
comment_id: str, session: str, step: int, request: Request
) -> dict[str, Any]:
node_dir, title = _comment_target(session, step, request)
saved = comments.delete_comment(node_dir, title, comment_id)
if saved is None:
raise HTTPException(status_code=404, detail="no such comment")
return {"comments": saved}
@router.get("/png")
def pipeline_png(
session: str, step: int, name: str, request: Request, preview: bool = False
) -> FileResponse:
bundle = _bundle_or_404(session, request)
node_step = replay.find_step(bundle.timeline, step)
node_dir = _resolve_node_dir(node_step, bundle.session_root)
if node_dir is None:
raise HTTPException(status_code=404, detail="node output folder not found")
# Guard against path traversal: the requested file must resolve to a
# plain .png sitting directly inside the node folder.
if not name.endswith(".png") or "/" in name or "\\" in name:
raise HTTPException(status_code=400, detail="invalid file name")
target = (node_dir / name).resolve()
if target.parent != node_dir.resolve() or not target.is_file():
raise HTTPException(status_code=404, detail=f"no such plot: {name}")
# Traffic-saver mode, and callers asking for ``preview`` (the feed's
# thumbnails), swap in the half-resolution preview that
# bragi_quantum.experiments saves next to the full image.
preview_file = target.with_name(f"{target.stem}_preview.png")
use_preview = preview or request.app.state.archive.traffic_saver
if use_preview and preview_file.is_file():
target = preview_file
return FileResponse(
target,
media_type="image/png",
headers={"Cache-Control": "private, max-age=3600"},
)
return router
def _register_common_middleware(app: FastAPI) -> None:
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["*"],
)
# Pages and figure JSON are large and highly compressible (PNG is skipped
# by default); this matters most over slow port-forwarded connections.
app.add_middleware(GZipMiddleware, minimum_size=1024, compresslevel=5)