# ══════════════════════════════════════════════════════════════════════════
# ___ ___ ___ _ _ ___
# / _ \ / __|_ ) | | /_\ | _ )
# | (_) | (__ / / | |__ / _ \| _ \
# \__\_\\___/___| |____/_/ \_\___/
#
# 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
# ══════════════════════════════════════════════════════════════════════════
"""
Track an ordered timeline of session-level steps for a calibration session.
Where ExecutionHistory is keyed by element (q16, q17, ...), SessionTimeline is
ordered by step. Step 0 is always the session start configuration; every
subsequent step is a node execution with the parameters used and the per-element
results produced.
This is what the HTML "Pipeline" view consumes to render a clickable DAG.
"""
import json
import logging
from datetime import datetime
from pathlib import Path
from typing import Any
logger = logging.getLogger(__name__)
[docs]
class SessionTimeline:
"""Ordered, append-only log of session-level steps."""
TIMELINE_FILENAME = "session_timeline.json"
def __init__(self, session_root_path: Path):
self.session_root_path = Path(session_root_path)
self.timeline_file = self.session_root_path / self.TIMELINE_FILENAME
self.steps: list[dict[str, Any]] = self._load()
def _load(self) -> list[dict[str, Any]]:
if self.timeline_file.exists():
try:
with open(self.timeline_file, encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, list):
return data
except Exception as e:
logger.warning(f"Could not load session timeline: {e}")
return []
def _save(self) -> None:
try:
self.session_root_path.mkdir(parents=True, exist_ok=True)
with open(self.timeline_file, "w", encoding="utf-8") as f:
import math
def _safe_json(obj):
if isinstance(obj, float) and (math.isnan(obj) or math.isinf(obj)):
return
raise TypeError(type(obj).__name__)
json.dump(self.steps, f, indent=2, default=_safe_json)
except Exception as e:
logger.error(f"Could not save session timeline: {e}")
[docs]
def record_start_config(
self,
session_id: str,
template_name: str | None = None,
device_templates_dir: str | None = None,
run_name: str | None = None,
toolkit_version: str | None = None,
session_options: dict[str, Any] | None = None,
qubits: list[str] | None = None,
couplers: list[str] | None = None,
initial_configurations: dict[str, Any] | None = None,
redis_configurations: dict[str, Any] | None = None,
) -> None:
"""Record step 0: the configuration snapshot at session start."""
# Only record once per session; if step 0 already exists, skip.
if self.steps and self.steps[0].get("kind") == "start_config":
return
step = {
"step_index": 0,
"kind": "start_config",
"timestamp": datetime.now().isoformat(),
"status": "running",
"session_id": session_id,
"template_name": template_name,
"device_templates_dir": device_templates_dir,
"run_name": run_name,
"toolkit_version": toolkit_version,
"session_options": session_options or {},
"qubits": qubits or [],
"couplers": couplers or [],
"initial_configurations": initial_configurations or {},
"redis_configurations": redis_configurations or {},
}
self.steps.insert(0, step)
self._save()
[docs]
def finalize(self, status: str = "complete") -> None:
"""Stamp the session's completion status on the start-config step.
``status`` is ``"complete"`` when the session scope closed cleanly or
``"error"`` when it aborted. Called once when the session ends, so
readers can tell a finished session from one still measuring (which
stays ``"running"``). No-op if there is no start-config step yet.
"""
if not self.steps or self.steps[0].get("kind") != "start_config":
return
self.steps[0]["status"] = status
self._save()
[docs]
def record_node_execution(
self,
node_name: str,
node_class: str,
parameters: dict[str, Any],
target_qubits: list[str],
results: dict[str, dict[str, Any]],
replot_meta: dict[str, Any] | None = None,
) -> None:
"""
Record a node execution as the next step in the timeline.
Args:
node_name: User-facing name of the node (parameters.name).
node_class: Python class name (e.g., 'ResonatorSpectroscopy').
parameters: Parameter values used for this run.
target_qubits: Element ids touched by this node.
results: Mapping element_id -> qoi dict (the analysis output).
replot_meta: Optional metadata for replaying this node's analysis:
- analysis_module, analysis_class
- parameters_module, parameters_class
- qoi_module, qoi_class (optional)
- dataset_dir, dataset_basename
- element_kind ("qubit" or "coupler")
"""
step_index = len(self.steps)
step = {
"step_index": step_index,
"kind": "node",
"timestamp": datetime.now().isoformat(),
"node_name": node_name,
"node_class": node_class,
"parameters": parameters or {},
"target_qubits": target_qubits or [],
"results": results or {},
}
if replot_meta:
step["replot_meta"] = replot_meta
self.steps.append(step)
self._save()
[docs]
def get_steps(self) -> list[dict[str, Any]]:
return list(self.steps)