# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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
# ══════════════════════════════════════════════════════════════════════════
"""
Session management for the Calibration Toolkit.
This module provides a validated context for calibration runs, ensuring that
all nodes and analysis objects share the same persistence settings and
device models without manual parameter passing.
"""
import logging
import threading
import uuid
from pathlib import Path
from typing import Any
from pydantic import BaseModel, ConfigDict, Field, field_validator
from bragi_quantum.datalayer.managing.redis import (
CALIBRATION_KEYS,
read_calibration_metadata,
read_calibration_values,
)
from bragi_quantum.datalayer.managing.session_timeline import SessionTimeline
from bragi_quantum.datalayer.managing.time_tracing import TimingTraceCollector
from bragi_quantum.datalayer.utils.logging.script_save_helper import (
get_toolkit_version,
to_jsonable,
)
from bragi_quantum.experiments.utils.deprecation import deprecated
[docs]
class SessionOptions(BaseModel):
"""
Global configuration options for the current calibration run.
This includes both data handling/reporting options and cluster
execution parameters that may vary between runs within a session.
"""
model_config = ConfigDict(extra="forbid")
session_name: str = Field(
default="default_session",
description="Human-readable name for the calibration session. "
"Used in result directory structure as run_{session_name}.",
)
qubits: str = Field(
default="all",
description="Comma-separated list of qubits to include in the run.",
)
couplers: str = Field(
default="all",
description="Comma-separated list of couplers to include in the run.",
)
last_cooldown: str | None = Field(
default=None,
description="The date or ID of the physical cooldown. Overrides the device config's.",
)
is_internal: bool = Field(
default=True, description="Flag for internal vs external report formatting."
)
runner_logo: str = Field(
default="resources/runner_logo.png", description="Path to the logo for PDFs."
)
pdf_report_filepath: Path | None = Field(
default="calibration_report.pdf",
description="Path where the final PDF report will be saved. If relative, it will be saved in the session root directory.",
)
produce_support_figures: bool = Field(
default=True,
description="Whether to generate support figures. These are usually helpful when "
"one needs to have a more fine-grained look at the data. We recommend setting this to False when running "
"large-scale runs or a lightweight report is desired.",
)
execution_mode: str = Field(
default="measurement",
description="Execution mode ('measurement' or 'dummy').",
)
cluster_ips: str | None = Field(
default=None,
description="Comma-separated list of cluster IP addresses. None means auto-detect.",
)
save_cluster_metadata_to_disk: bool = Field(
default=False,
description="Whether to save cluster snapshots, q1asm programs, and waveform plots "
"to disk during execution. When False, timing and status are still printed to terminal.",
)
save_log_level: int = Field(
default=logging.INFO,
description="Logging level for local logs(e.g., logging.INFO, logging.DEBUG).",
)
spi_serial_port: str | None = Field(
default=None,
description=(
"Serial port for SPI DAC rack connection (e.g. '/dev/ttyACM0'). "
"None (the default) skips SPI hardware initialization entirely for "
"this session — nodes that require the SPI DAC handler (e.g. "
"resonator/qubit spectroscopy vs current) will raise a RuntimeError "
"if they run without one, so sessions that sweep DC currents must "
"set the port explicitly."
),
)
[docs]
@field_validator("pdf_report_filepath", mode="before")
@classmethod
def convert_pdf_path_to_pathlib(cls, v):
"""Convert string paths to Path objects."""
if v is None:
return None
if isinstance(v, str):
return Path(v)
return v
@deprecated("SessionOptions")
class RunOptions(SessionOptions):
"""
This class is retained for backward compatibility. Use SessionOptions
instead.
"""
[docs]
class SessionContext(BaseModel):
"""
Pydantic model representing the active calibration session.
This context acts as the source of truth for all environment settings
during an orchestrated execution run. It centralizes device, cluster,
and hardware configuration to avoid passing parameters through the call stack.
Attributes:
session_id (str): Unique identifier for the calibration session.
run_name (str): Optional human-readable label for the run this session
belongs to, passed through from CalibrationOrchestrator.name and
recorded as "run_name" in the session timeline.
root_path (Path): Base directory for all data and reports.
device_config (Any): Validated bragi_quantum.datalayer DeviceConfiguration instance. It is a quite sophisticated
object, built around the Qblox QuantumDevice.
device (Any): Fully configured QuantumDevice instance, hydrated from device_config.
Available for immediate use by utilities and nodes.
hardware_agent (Any): Reference to the qblox-scheduler HardwareAgent that owns the
cluster connections; schedules are run via its `run()` method.
redis_connection (Optional[Any]): Optional Redis connection object for nodes that require direct access.
It can be None if using local snapshots instead of Redis.
spi_dac_handler (Optional[Any]): Initialized SpiDAC instance for flux/coupler control.
Contains all configured DACs based on the device template SPI configuration.
cluster_config (Optional[Any]): Cluster configuration built from the device template, after
bragi_quantum.api's `autocomplete_hardware_options()` has filled in the physical-analog-path
hardware_options (attenuation, gain, LO frequencies, mixer corrections) for related
clocks sharing a physical port. This — not the raw template — is what the schedules
compile against, and therefore what the session timeline records as the start config.
spi_config (Optional[Any]): Raw SPI configuration dictionary from the device template.
session_options (SessionOptions): Configuration options for the current calibration run, including
cluster execution parameters, reporting options, and qubit/coupler selection.
"""
model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid")
session_id: str
experiment_template_name: str | None = None
device_templates_dir: Path | None = None
run_name: str = ""
root_path: Path
device_config: Any
device: Any
hardware_agent: Any
redis_connection: Any | None
spi_dac_handler: Any | None = None
cluster_config: Any | None = None
spi_config: Any | None = None
session_options: SessionOptions = Field(default_factory=SessionOptions)
wiring_config: Any | None = None
# Convenience pass-through so call sites can do
# `ActiveSession.get().get_session_timeline()`. The tracker itself lives
# on ActiveSession (the class) since it is tied to the active session
# lifecycle, not to the SessionContext data model.
[docs]
def get_session_timeline(self) -> Any:
return ActiveSession.get_session_timeline()
[docs]
def get_timing_trace_collector(self) -> Any:
return ActiveSession.get_timing_trace_collector()
[docs]
class ActiveSession:
"""
Global registry for the current calibration session context.
Uses a thread-safe singleton pattern to provide access to the session
configuration across bragi_quantum.experiments and bragi_quantum.api nodes without explicit injection.
"""
_current: SessionContext | None = None
_session_timeline: Any | None = None # SessionTimeline instance
_timing_trace_collector: TimingTraceCollector | None = None
_lock = threading.Lock()
[docs]
@classmethod
def start(cls, context: SessionContext) -> None:
"""
Register a new session context.
Args:
context: The validated SessionContext object.
"""
with cls._lock:
cls._current = context
cls._session_timeline = SessionTimeline(context.root_path)
cls._timing_trace_collector = TimingTraceCollector(
process_name=context.session_id
)
# Record step 0 (start config) immediately. Outside the lock because
# the timeline does its own file I/O and we don't want to hold the
# session lock during disk writes.
try:
device_cfg = context.device_config
qubits = list(getattr(device_cfg, "qubits", []) or [])
couplers = list(getattr(device_cfg, "couplers", []) or [])
session_opts_dict = (
context.session_options.model_dump(mode="json")
if hasattr(context.session_options, "model_dump")
else dict(context.session_options or {})
)
cls._session_timeline.record_start_config(
session_id=context.session_id,
template_name=context.experiment_template_name,
device_templates_dir=(
str(context.device_templates_dir)
if context.device_templates_dir is not None
else None
),
run_name=context.run_name,
toolkit_version=get_toolkit_version(),
session_options=session_opts_dict,
qubits=qubits,
couplers=couplers,
initial_configurations={
"cluster": to_jsonable(context.cluster_config),
"device": to_jsonable(context.device_config),
"spi": to_jsonable(context.spi_config),
"wiring": to_jsonable(context.wiring_config),
},
redis_configurations=(
{
"meta": to_jsonable(
read_calibration_metadata(context.redis_connection)
),
"couplers": to_jsonable(
read_calibration_values(
context.redis_connection,
CALIBRATION_KEYS["couplers"],
couplers,
)
),
"transmons": to_jsonable(
read_calibration_values(
context.redis_connection,
CALIBRATION_KEYS["transmons"],
qubits,
)
),
"cs": to_jsonable(
read_calibration_values(
context.redis_connection,
CALIBRATION_KEYS["cs"],
qubits,
)
),
}
if context.redis_connection is not None
else {}
),
)
except Exception as e: # never let timeline bookkeeping break a session
logging.getLogger(__name__).warning(
f"Could not record session start_config in timeline: {e}"
)
[docs]
@classmethod
def get(cls) -> SessionContext:
"""
Retrieve the current active session.
Returns:
SessionContext: The active session context.
Raises:
RuntimeError: If no session has been initialized.
"""
if cls._current is None:
raise RuntimeError(
"No active session found. Ensure you are using the "
"CalibrationOrchestrator to run your nodes."
)
return cls._current
[docs]
@classmethod
def stop(cls) -> None:
"""
Clear the current session registry.
"""
with cls._lock:
cls._current = None
cls._session_timeline = None
cls._timing_trace_collector = None
[docs]
@classmethod
def next_node_dir_name(cls, name: str) -> str:
"""Return a fresh, unique `{name}_{uuid8}` output-folder name."""
return f"{name}_{uuid.uuid4().hex[:8]}"
[docs]
@classmethod
def get_session_timeline(cls) -> Any:
"""
Retrieve the session timeline (ordered step log) for the current session.
Returns:
SessionTimeline: The timeline tracker.
Raises:
RuntimeError: If no session has been initialized.
"""
if cls._session_timeline is None:
raise RuntimeError(
"No session timeline available. Ensure a session is active."
)
return cls._session_timeline
[docs]
@classmethod
def write_timing_trace_events(cls, root_path: Path) -> None:
"""Write the active session's Chrome/Perfetto timing trace to `root_path/timing_trace_events.json`, logging (not raising) on failure."""
try:
collector = cls.get_timing_trace_collector()
if collector is not None:
timing_trace_path = root_path / "timing_trace_events.json"
collector.write(timing_trace_path)
logging.getLogger(__name__).info(
f"⏱️ Timing trace events saved to {timing_trace_path}"
)
except Exception as e:
logging.getLogger(__name__).warning(
f"⚠️ Could not write timing trace events: {e}"
)
[docs]
@classmethod
def get_timing_trace_collector(cls) -> TimingTraceCollector | None:
"""
Retrieve the timing trace collector for the current session.
Every active session has one (tracing is always on — see
:meth:`start`). Unlike :meth:`get_session_timeline`, this does not
raise when there's no active session at all, since timing trace collection
is a best-effort side channel — callers should treat ``None`` as
"skip recording this span".
Returns:
TimingTraceCollector | None: The active collector, or None if no
session is active.
"""
return cls._timing_trace_collector
[docs]
@classmethod
def record_node_boundary(cls, node: Any) -> None:
"""Mark this node's start in the session trace (a labeled instant,
not tied to any category swimlane), so bragi_quantum.gui can draw a divider
between consecutive nodes' spans. Best-effort: tracing is a side
channel and must never break a measurement run.
"""
try:
collector = cls.get_timing_trace_collector()
if collector is not None:
node_name = getattr(getattr(node, "parameters", None), "name", None)
collector.record_instant(
node_name or node.__class__.__name__,
args={"node_class": node.__class__.__name__},
)
except Exception as e:
logging.getLogger(__name__).warning(
f"Could not record node boundary marker: {e}"
)