# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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:
#
# Axel Andersson, axean@chalmers.se
# Matteo Robbiati, robbiati@chalmers.se
# Yanchen Lin, linya@chalmers.se
# ══════════════════════════════════════════════════════════════════════════
"""The archive browser server.
``Archive`` owns the live state for a directory of timestamped run folders —
the session-bundle map, per-run bundle lists and the qubit/text search indexes — plus
the lock that guards them. A background thread (started by the app's lifespan)
periodically calls :meth:`Archive.discover`, the *only* writer, so the route
handlers are pure readers and the route table never changes at runtime: every
session/pipeline route carries its id in the path and resolves it here.
"""
from __future__ import annotations
import dataclasses
import datetime
import logging
import re
import socket
import sys
import threading
import webbrowser
from contextlib import asynccontextmanager
from pathlib import Path
import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from bragi_quantum.gui import replay, server
from bragi_quantum.gui.rendering.archive_rendering import (
POLL_INTERVAL_SECONDS,
build_archive_html,
)
from bragi_quantum.gui.rendering.html_rendering import (
create_html_rendering,
create_multi_session_html,
)
from bragi_quantum.gui.vendor_js_assets import assets_router, plotly_asset_url
logger = logging.getLogger(__name__)
_TS_RE = re.compile(r"^\d{8}_\d{6}(_.+)?$")
_SESSION_TS_RE = re.compile(r'"timestamp"\s*:\s*"([^"]+)"')
def _read_session_start_ts(timeline: Path) -> str:
"""Return the ISO start timestamp from the first entry of a session timeline.
Reads only the first 512 bytes to stay fast and avoid non-standard JSON
(Infinity/NaN) that appears later in the file.
"""
try:
with open(timeline, encoding="utf-8") as f:
head = f.read(512)
m = _SESSION_TS_RE.search(head)
return m.group(1) if m else ""
except OSError:
return ""
# --------------------------------------------------------------------------- #
# Qubit search index (derived purely from the on-disk session timelines) #
# --------------------------------------------------------------------------- #
def _canonical_qubit(token: str) -> str | None:
"""Canonicalize a qubit token to ``q<n>`` (no leading zeros), or ``None``.
Accepts ``q05``, ``Q5``, ``5`` and ``qubit:q05`` so matching is robust to
zero-padding (``q05`` and ``q5`` compare equal).
"""
t = token.strip().lower()
t = t.removeprefix("qubit:")
t = t.removeprefix("q")
if not t.isdigit():
return None
return f"q{int(t)}"
[docs]
def build_qubit_index(bundles) -> dict[str, set[str]]:
"""Map each run-folder name to the set of qubits measured in it.
A run's measured qubits are the union of every node step's ``target_qubits``
(the dataset-derived elements that actually produced data).
"""
index: dict[str, set[str]] = {}
for bundle in bundles:
run_name = bundle.session_root.parent.name
qubits = index.setdefault(run_name, set())
for step in bundle.timeline:
if step.get("kind") != "node":
continue
for element in step.get("target_qubits") or []:
canonical = _canonical_qubit(str(element))
if canonical is not None:
qubits.add(canonical)
return index
[docs]
def build_text_index(bundles) -> dict[str, set[str]]:
"""Map each run-folder name to the text terms it can be found by.
Terms are read straight off each session's raw timeline (mirroring
``build_qubit_index``, no ``Timeline``/``SessionBundle`` properties
needed): the session directory name, the run's sanitized display name,
the orchestrator's recorded name(s), the session id / template name, and
every node step's name. Case is preserved — matching (in/against
:func:`archive_search`) decides case-sensitivity, not the index.
"""
index: dict[str, set[str]] = {}
for bundle in bundles:
run_name = bundle.session_root.parent.name
terms = index.setdefault(run_name, set())
terms.add(bundle.session_root.name)
# Same slice archive_rendering.py uses for the sidebar's run title.
sanitized = run_name[16:] if len(run_name) > 15 else ""
if sanitized:
terms.add(sanitized)
start_config = next(
(s for s in bundle.timeline if s.get("kind") == "start_config"), {}
)
for value in (
start_config.get("run_name"),
(start_config.get("session_options") or {}).get("run_name"),
start_config.get("session_id"),
start_config.get("template_name"),
):
if value:
terms.add(str(value))
for step in bundle.timeline:
if step.get("kind") != "node":
continue
node_name = step.get("node_name")
if node_name:
terms.add(str(node_name))
return index
def _compile_search_pattern(
text: str, *, case_sensitive: bool, whole_word: bool, use_regex: bool
) -> re.Pattern[str]:
"""Build one matcher from a query fragment, mirroring the session log
search's own case/whole-word/regex toggles (see log-searcher-filter.js's
``buildLogSearchRegex``) so the two searches behave the same way. Raises
``re.error`` on an invalid pattern — callers decide how to surface that.
"""
pattern = text if use_regex else re.escape(text)
if whole_word:
pattern = rf"\b(?:{pattern})\b"
flags = 0 if case_sensitive else re.IGNORECASE
return re.compile(pattern, flags)
[docs]
def archive_search(
q: str,
qubit_index: dict[str, set[str]],
text_index: dict[str, set[str]] | None = None,
*,
case_sensitive: bool = False,
whole_word: bool = False,
use_regex: bool = False,
) -> dict:
"""Resolve an archive search query to the run ids that match it.
Two modes:
* Plain (the default): the query is split into whitespace/comma-separated
tokens. A token that's a qubit reference (``q05``, ``5``, ``qubit:q5``,
...) requires the run to have measured it; any other token is matched
as a substring against the run's name, session names and step names —
*every* token must match (AND semantics), same as the qubit-only
matching this replaces. ``case_sensitive``/``whole_word`` refine that
substring match.
* ``use_regex``: the whole (stripped) query is one regular expression,
tested against each run's combined searchable text — no token
splitting, same "one pattern, no AND-ing" behaviour as the session log
search's regex mode.
Returns ``{"names": [...]}`` (newest first), or ``{"names": None}`` when
the query is empty after stripping — the sidebar reads that as "no
filter". Raises ``re.error`` on an invalid regex (either mode).
"""
text_index = text_index or {}
stripped = q.strip()
if not stripped:
return {"names": None, "reason": "empty-query"}
all_runs = qubit_index.keys() | text_index.keys()
if use_regex:
pattern = _compile_search_pattern(
stripped,
case_sensitive=case_sensitive,
whole_word=whole_word,
use_regex=True,
)
def blob(run: str) -> str:
return " ".join((*qubit_index.get(run, ()), *text_index.get(run, ())))
matches = sorted(
(run for run in all_runs if pattern.search(blob(run))), reverse=True
)
return {"names": matches}
tokens = [t for t in re.split(r"[\s,]+", stripped) if t]
qubits = []
text_terms = []
for token in tokens:
canonical = _canonical_qubit(token)
(qubits if canonical is not None else text_terms).append(
canonical if canonical is not None else token
)
term_patterns = [
_compile_search_pattern(
t, case_sensitive=case_sensitive, whole_word=whole_word, use_regex=False
)
for t in text_terms
]
def matches_run(run: str) -> bool:
if qubits:
measured = qubit_index.get(run, set())
if not all(qb in measured for qb in qubits):
return False
if term_patterns:
terms = text_index.get(run, set())
if not all(
any(pattern.search(term) for term in terms) for pattern in term_patterns
):
return False
return True
matches = sorted(
(run for run in all_runs if matches_run(run)),
reverse=True, # run-folder names are timestamps → newest first
)
return {"names": matches, "qubits": qubits, "terms": text_terms}
# --------------------------------------------------------------------------- #
# Small host utilities #
# --------------------------------------------------------------------------- #
def _open_browser(url: str) -> None:
try:
webbrowser.open(url)
except Exception:
pass
def _find_free_port(host: str, preferred: int) -> int:
"""Try the preferred port first; fall back to an OS-assigned one."""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((host, preferred))
s.close()
return preferred
except OSError:
pass
s.close()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, 0))
port = s.getsockname()[1]
s.close()
return port
[docs]
class Archive:
"""Live state + FastAPI app for a directory of timestamped run folders."""
def __init__(self, target: Path, traffic_saver: bool = False) -> None:
self.target = target
# Serve each plot's half-resolution ``*_preview.png`` when it exists.
self.traffic_saver = traffic_saver
self._lock = threading.Lock()
# key → bundle (keys are ``<run_ts>__<session>``, globally unique)
self.session_by_key: dict[str, server.SessionBundle] = {}
# run_ts → its bundles (drives the per-run pipeline view)
self.run_bundles: dict[str, list[server.SessionBundle]] = {}
# run_ts → measured qubits (search index)
self.qubit_index: dict[str, set[str]] = {}
# run_ts → searchable text terms — run/session/step names (search index)
self.text_index: dict[str, set[str]] = {}
# run_ts → last-seen timeline mtimes, to skip runs that haven't changed
self._signatures: dict[str, list[tuple[str, int]]] = {}
# -- lookups used by the route dependencies -------------------------- #
[docs]
def bundle(self, key: str) -> server.SessionBundle | None:
return self.session_by_key.get(key)
[docs]
def run(self, run_ts: str) -> list[server.SessionBundle]:
return self.run_bundles.get(run_ts, [])
# -- filesystem scanning --------------------------------------------- #
[docs]
def scan_run_folders(self) -> list[Path]:
return sorted(
(d for d in self.target.iterdir() if d.is_dir() and _TS_RE.match(d.name)),
reverse=True,
)
def _session_lists(self, run_dir: Path) -> tuple[list[str], list[str]]:
"""(complete, incomplete) session names, ordered by execution start time."""
items: list[tuple[str, str, bool]] = []
for sd in (
d for d in run_dir.iterdir() if d.is_dir() and d.name.startswith("session_")
):
name = sd.name[len("session_") :]
timeline = sd / "session_timeline.json"
if timeline.exists():
ts = _read_session_start_ts(timeline)
items.append((ts, name, True))
else:
items.append(("", name, False))
items.sort(key=lambda x: x[0])
complete = [n for _, n, ok in items if ok]
incomplete = [n for _, n, ok in items if not ok]
return complete, incomplete
def _timeline_mtimes(self, folder: Path) -> list[tuple[str, int]]:
"""``(session_name, timeline_mtime_ns)`` for each session with a timeline.
The discover signature and the ``fresh`` token both derive from this: any
append or finalize rewrites ``session_timeline.json`` and bumps its mtime,
so a growing or completing session is detected without parsing the file.
"""
out: list[tuple[str, int]] = []
for sd in sorted(
d for d in folder.iterdir() if d.is_dir() and d.name.startswith("session_")
):
timeline = sd / "session_timeline.json"
try:
out.append((sd.name, timeline.stat().st_mtime_ns))
except OSError:
pass # no timeline yet (session dir created, not started)
return out
[docs]
def run_descriptor(self, folder: Path) -> dict:
"""One scan → a run folder's sidebar/JSON metadata (single source).
Shared by the initial page render and the ``/runs`` poll so a folder is
never described two ways. ``done`` (bragi_quantum.api wrote ``index.html``) drives the
spinner; ``fresh`` (newest timeline mtime) drives the live iframe reload;
``error`` flags any session whose timeline ended in error.
"""
complete, incomplete = self._session_lists(folder)
name = folder.name
mtimes = self._timeline_mtimes(folder)
done = (folder / "index.html").exists()
bundles = self.run_bundles.get(name, [])
errored_sessions = [
b.session_root.name[len("session_") :]
for b in bundles
if b.tl.start_config.get("status") == "error"
]
# A run is "crashed" when every bundle has a terminal status (complete or
# error) but bragi_quantum.api never wrote index.html — sessions finished but the
# final report generation was skipped or the process died before it.
all_terminal = bool(bundles) and all(
b.tl.start_config.get("status") in ("complete", "error") for b in bundles
)
total_sessions = len(complete) + len(incomplete)
n_qubits = len(self.qubit_index.get(name, set()))
return {
"name": name,
"date": f"{name[:4]}-{name[4:6]}-{name[6:8]}",
"time": f"{name[9:11]}:{name[11:13]}:{name[13:15]}",
# Used as the run's title in the sidebar (grouped date headers
# already carry the date, so the row itself just needs the name).
"sanitized_run_name": (name[16:] if len(name) > 15 else ""),
"src": f"/static/{name}/index.html",
"count": len(complete),
"total_sessions": total_sessions,
"partial": bool(incomplete),
"qubits": n_qubits,
# Sidebar display values: the counts above grow while the run is
# live, so the UI shows a placeholder until the run is done.
"sessions_display": str(total_sessions) if done else "—",
"qubits_display": str(n_qubits) if done else "—",
"done": done,
"crashed": all_terminal and not done,
"errored_sessions": errored_sessions,
"fresh": max((m for _, m in mtimes), default=0) // 1_000_000,
# Per-session freshness so the JS can name the session that changed.
"session_mtimes": {
sd_name[len("session_") :]: m // 1_000_000 for sd_name, m in mtimes
},
"error": bool(errored_sessions),
}
[docs]
def generate_run_page(self, run_dir: Path, run_ts: str) -> str:
"""Render a run's index page on demand, in memory.
Read-only: bragi_quantum.gui never writes ``index.html`` back to the run folder.
That file is bragi_quantum.api's alone — its presence is the run-complete signal
(written by ``generate_html_report`` when the run finishes), so bragi_quantum.gui
must not forge it by persisting its own render.
"""
complete, incomplete = self._session_lists(run_dir)
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
bundles = self.run_bundles.get(run_ts, [])
run_name = next((b.tl.run_name for b in bundles if b.tl.run_name), "")
return create_multi_session_html(
session_names=complete,
datetime_hour_path=run_dir,
incomplete_session_names=incomplete,
pipeline_url=f"/pipeline/{run_ts}",
generated_at=now,
generated_by="qc2-show",
run_name=run_name,
)
# -- discovery (the only writer) ------------------------------------- #
[docs]
def discover(self) -> None:
"""(Re)bundle any run whose timelines changed since last seen.
The signature is each session timeline's mtime, so this fires on a brand-
new run, a new session, *and* a new step or completion inside an existing
session — that last case is what un-freezes a live-growing timeline.
Runs under the lock so the background poller and any on-demand call can't
corrupt the maps.
"""
with self._lock:
for folder in self.scan_run_folders():
run_ts = folder.name
signature = self._timeline_mtimes(folder)
if self._signatures.get(run_ts) == signature:
continue
self._signatures[run_ts] = signature
session_dirs = sorted(
d
for d in folder.iterdir()
if d.is_dir() and d.name.startswith("session_")
)
bundles = [
dataclasses.replace(b, key=f"{run_ts}__{b.key}")
for b in server._make_bundles(session_dirs)
]
self.run_bundles[run_ts] = bundles
for b in bundles:
self.session_by_key[b.key] = b
self.qubit_index.setdefault(run_ts, set())
for name, qubits in build_qubit_index(bundles).items():
self.qubit_index.setdefault(name, set()).update(qubits)
self.text_index.setdefault(run_ts, set())
for name, terms in build_text_index(bundles).items():
self.text_index.setdefault(name, set()).update(terms)
# -- FastAPI app ----------------------------------------------------- #
[docs]
def build_app(self) -> FastAPI:
@asynccontextmanager
async def lifespan(_app: FastAPI):
stop = threading.Event()
def poll() -> None:
while not stop.wait(POLL_INTERVAL_SECONDS):
try:
self.discover()
except Exception:
logger.exception("archive discovery failed")
thread = threading.Thread(target=poll, daemon=True)
thread.start()
try:
yield
finally:
stop.set()
app = FastAPI(
title="bragi_quantum.gui archive", version="0.1.0", lifespan=lifespan
)
app.state.archive = self
server._register_common_middleware(app)
app.include_router(assets_router())
app.include_router(server.session_router())
app.include_router(server.pipeline_router())
app.add_exception_handler(replay.ReplayError, server._replay_error_handler)
app.add_exception_handler(
replay.PlotRenderError, server._plot_render_error_handler
)
app.add_exception_handler(Exception, server._fallback_handler)
@app.get("/", response_class=HTMLResponse)
def serve_archive() -> HTMLResponse:
runs = [
r
for r in (self.run_descriptor(f) for f in self.scan_run_folders())
if r["done"] or r["total_sessions"] > 0
]
return HTMLResponse(content=build_archive_html(runs))
@app.get("/runs")
def list_runs() -> JSONResponse:
# Pure read: discovery happens in the background, not here.
return JSONResponse(
[
r
for r in (self.run_descriptor(f) for f in self.scan_run_folders())
if r["done"] or r["total_sessions"] > 0
]
)
@app.get("/version")
def get_version() -> JSONResponse:
from bragi_quantum.gui import __version__
return JSONResponse({"version": __version__})
@app.get("/stats")
def get_stats() -> JSONResponse:
from collections import Counter
if not self.run_bundles:
self.discover()
node_class_counts: Counter[str] = Counter()
qubit_counts: Counter[str] = Counter()
coupler_calibrated: Counter[str] = Counter()
device_couplers: set[str] = set()
run_dates: list[str] = []
for run_ts, bundles in self.run_bundles.items():
run_dates.append(f"{run_ts[:4]}-{run_ts[4:6]}-{run_ts[6:8]}")
for b in bundles:
for q in b.tl.qubits:
qubit_counts[q] += 1
for c in b.tl.couplers:
device_couplers.add(c)
for step in b.tl.node_steps:
node_class_counts[step.get("node_class") or "unknown"] += 1
for c in step.get("parameters", {}).get("couplers") or []:
coupler_calibrated[c] += 1
# Merge device topology with calibration counts so uncalibrated
# couplers appear with count 0 rather than being silently absent.
coupler_counts = {
c: coupler_calibrated.get(c, 0) for c in sorted(device_couplers)
}
# Sort: calibrated (count > 0) first, then uncalibrated, within each
# group sorted by count descending then name.
coupler_counts = dict(
sorted(coupler_counts.items(), key=lambda kv: (-kv[1], kv[0]))
)
return JSONResponse(
{
"total_runs": len(self.run_bundles),
"total_sessions": sum(len(bl) for bl in self.run_bundles.values()),
"unique_qubits": len(qubit_counts),
"device_couplers": len(device_couplers),
"calibrated_couplers": len(coupler_calibrated),
"date_range": {
"first": min(run_dates) if run_dates else None,
"last": max(run_dates) if run_dates else None,
},
"node_class_counts": dict(node_class_counts.most_common(15)),
"qubit_counts": dict(qubit_counts.most_common()),
"coupler_counts": coupler_counts,
}
)
@app.get("/search")
def search(
q: str = "",
case: bool = False,
word: bool = False,
regex: bool = False,
) -> JSONResponse:
try:
result = archive_search(
q,
self.qubit_index,
self.text_index,
case_sensitive=case,
whole_word=word,
use_regex=regex,
)
except re.error as exc:
return JSONResponse({"names": [], "error": str(exc)})
return JSONResponse(result)
@app.get("/static/{run_ts}/index.html", response_class=HTMLResponse)
def serve_run_index(run_ts: str) -> HTMLResponse:
run_dir = self.target / run_ts
if not run_dir.is_dir():
raise HTTPException(status_code=404, detail="run not found")
return HTMLResponse(
content=self.generate_run_page(run_dir, run_ts),
headers={"Cache-Control": "no-store"},
)
@app.get(
"/static/{run_ts}/{session_dir}/html_rendering.html",
response_class=HTMLResponse,
)
def serve_session_html(run_ts: str, session_dir: str) -> HTMLResponse:
key = f"{run_ts}__{session_dir}"
bundle = self.bundle(key)
if bundle is None:
# A brand-new run may not be discovered yet; try once on demand.
self.discover()
bundle = self.bundle(key)
if bundle is None:
raise HTTPException(status_code=404, detail="session not found")
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,
pipeline_href=f"/pipeline/{run_ts}",
plotly_src=plotly_asset_url(),
)
return HTMLResponse(content=html, headers={"Cache-Control": "no-store"})
app.mount("/static", StaticFiles(directory=str(self.target)), name="static")
return app
# -- entry point ----------------------------------------------------- #
[docs]
def serve(self, host: str, port: int, log_level: str) -> int:
self.discover()
run_folders = self.scan_run_folders()
if not run_folders:
print(
f"⚠️ no timestamped run folders found in {self.target}.\n"
" Point qc2-show at a directory of YYYYMMDD_HHMMSS[_sanitized_name] run folders.",
file=sys.stderr,
)
return 1
port = _find_free_port(host, port)
endpoint = f"http://{host}:{port}"
app = self.build_app()
print("🔭 bragi_quantum.gui — qc2-show")
print(f" path : {self.target}")
print(
f" mode : archive ({len(run_folders)} run folders, "
f"{len(self.session_by_key)} sessions)"
)
print(f" endpoint : {endpoint}")
print(f" polling : background every {POLL_INTERVAL_SECONDS} s")
if self.traffic_saver:
print(" images : traffic saver on (serving *_preview.png)")
print(" search : in-memory index (from session timelines)")
print()
logging.getLogger("uvicorn.access").addFilter(
type(
"_SuppressRunsPoll",
(logging.Filter,),
{"filter": lambda self, r: "/runs" not in r.getMessage()},
)()
)
_open_browser(endpoint)
uvicorn.run(app, host=host, port=port, log_level=log_level)
return 0