Repository navigation
Adding a Framework
Written against d5aad1f44 on 19 Nov 2026.
- A framework (PyPSA, Calliope) reaches Conductor as three workspace packages: one that describes it, one that reads and writes its files, and one that solves its networks.
- The conductor, the runner, the HTTP transport and the durable runner never import those packages. They find them through entry points, and import-linter forbids the import.
- The
Frameworkcontract has only two required members, so a framework lands in stages: describe it first (networks can be built and edited), then files, then the solver. Each stage wires its own package, and is checked on the real serve path before the next. - Much of the work outside the three packages is wiring: hand-kept lists in
backend/pyproject.toml, the lock file, the deployment script, the release manifest and CI. A test names most of what you miss. - Calliope is the worked example. Skeleton code below follows the Calliope packages and uses
X(tz_ps_x,tz_ps_files_x,tz_ps_solver_x) for the new framework. The skeletons were checked name by name against the code, and were not executed.
| Package | Calliope example | What it holds | May import the framework's own library? |
|---|---|---|---|
| Description | backend/libs/tz_ps_calliope |
The Framework subclass, the component registry, component classes, whole-network rules, the mapping to and from the framework's own model |
No. A forbidden contract keeps calliope and xarray out, so the package installs anywhere. |
| Files | backend/libs/tz_ps_files_calliope |
One class for each file format, the reader, the writer, and the code that builds the framework's native model | Yes, pinned exactly, imported lazily |
| Solver | backend/libs/tz_ps_solver_calliope |
The Solver class and one solve from input handover to output handover |
Yes, the same pin |
The diagram shows the three packages, the entry-point group each announces (dotted), and what they depend on (solid).
flowchart TB
subgraph above["Packages that name no framework"]
C["tz_ps_conductor (composition root)"]
R["tz_ps_runner"]
SP["solve and export processes"]
end
subgraph x["Framework X"]
S["tz_ps_solver_x<br/>runs X's library"]
F["tz_ps_files_x<br/>reads and writes X's files"]
D["tz_ps_x<br/>describes X, imports no X library"]
end
subgraph shared["Shared support"]
SS["tz_ps_solver_support"]
RS["tz_ps_reader_support"]
P["tz_ps_ports"]
M["tz_ps_models"]
end
C -. "tz_ps_conductor.frameworks" .-> D
C -. "tz_ps_conductor.network_file_formats" .-> F
C -. "tz_ps_conductor.library_loggers" .-> F
R -. "tz_ps_runner.solvers" .-> S
SP -. "tz_ps_conductor.solve_runtimes" .-> S
S --> F
S --> D
S --> SS
F --> D
F --> RS
D --> M
S --> P
F --> P
Backend core owns the full description of each group; this table is what a framework author needs.
| Group | Declared by | Value | Read by | A bad entry |
|---|---|---|---|---|
tz_ps_conductor.frameworks |
description | the Framework class |
discover_frameworks in backend/src/tz_ps_conductor/dependencies.py
|
logged and skipped |
tz_ps_conductor.network_file_formats |
files | one class per format |
discover_network_file_formats in backend/src/tz_ps_conductor/network_file_formats.py
|
logged and skipped |
tz_ps_runner.solvers |
solver | the solver class |
SolverRegistry in backend/libs/tz_ps_runner/src/tz_ps_runner/registry.py
|
logged and skipped |
tz_ps_conductor.solve_runtimes |
solver | a module |
load_solve_runtime in backend/src/tz_ps_conductor/solve_process.py, for a solve and for an export |
an import error fails that solve; a missing or misnamed entry is skipped without a message |
tz_ps_conductor.library_loggers |
files, solver | a logger name |
logging_config.py; read as a name, never loaded |
— |
tz_ps_conductor.demo_data |
tz_ps_demo_data only |
a builder |
seed.py; the first by name is tried, no other |
PyPSA only today |
The diagram shows how a framework's name becomes typed components and then a solve, without any package above importing it.
sequenceDiagram
participant U as Caller
participant C as tz_ps_conductor
participant M as Framework registry
participant D as tz_ps_x
participant R as tz_ps_runner
participant P as Solve process
participant S as tz_ps_solver_x
U->>C: build a Network on framework x
C->>M: Framework.get
M->>C: run the discovery function
C->>D: load the tz_ps_conductor.frameworks entry point
C->>M: Framework.register
U->>C: add a component
C->>D: build_component
C->>D: list_network_problems on each save
U->>C: Network.solve with a method and params
C->>D: methods, validate_params, is_precondition_met
C->>R: Runner.solve records and enqueues the run
R->>R: LocalSolveWorker writes the input handover
R->>P: start a child with a SolveRequestRecord
P->>S: discover_framework then load_solve_runtime
P->>S: solve with a SolveRequest
S->>S: read input, run X, write output handover
S->>P: the output NetworkHandover
P->>R: solved or a solve error
R->>C: publish as a new version
tz_ps_models loads no entry points. Importing tz_ps_conductor.dependencies installs the
discovery function with Framework.set_discovery, and every registry read runs it first.
Architecture-Execution covers the runner and the solve process.
A convention or a technology choice is asked, not assumed (root CLAUDE.md, Decisions).
Settle these with the owner before any code:
| Decision | Why it needs an answer | What Calliope chose |
|---|---|---|
| The upstream version and the solver library | Each is a new runtime dependency, which backend/CLAUDE.md says to confirm first |
calliope==0.7.0, HiGHS only |
| How the framework's concepts become component types and attribute names | It fixes every URL token and stored attribute name | Four types; bracketed names such as cost_flow_cap[costs=monetary]
|
| Registry: generated from upstream, or hand-written | A generated one gets drift and narrowing checks | Generated from Calliope's maths YAML |
| Component classes: source files, or built at runtime | Source is reviewable; runtime needs no generator | Built at runtime with pydantic.create_model
|
| Shipped or not | Wheel and image: a member ships unless _NOT_RELEASED lists it. Desktop app: only if tz-ps-app also depends on it. |
Not shipped |
| Installed by default, or behind a switch |
uv sync is exact, so "optional" means a switch in backend/scripts/serve.sh
|
make serve CALLIOPE=1 |
| CI: every leg, or a shard of its own; and whether its scenarios run on PostgreSQL | A heavy runtime slows every job | One shard on one Python, plus the PostgreSQL scenarios on that Python |
| New members of closed vocabularies | Each is a contract change (see Shared places) | Added ParameterGroup, TypeGlyph and MethodPrecondition members |
| Which measures, in which units | The catalogue is shared code | 5 of 13, with units in words |
| Frontend work in or out | Some of the UI assumes PyPSA (see Frontend impact) | Out |
Then:
- Write the design to
docs/specs/YYYY-MM-DD-x-framework-design.md. Calliope's isdocs/specs/2026-10-01-calliope-framework-design.md; read "Packages and layers" and decision 20 (build order and what to cut). - A framework is an epic. Run
/tz-skills:epic, and create no sub-issues until the owner approves. - Pin the upstream version once, in a dependency group of
backend/pyproject.tomlthat is never installed at runtime, ascalliope-registry = ["calliope==0.7.0"]is. The files and solver packages repeat the exact pin. The registry drift check fails when the solver's pin differs, anduv lockrefuses a files-package pin that differs.
| After | A modeller can | Still missing |
|---|---|---|
| Stage 1, description | Create an X network from Python and over HTTP; add, edit and validate typed components; see X in GET /frameworks and every description route |
Import, export, solve. A run is accepted and then fails as no_solver_found. |
| Stage 2, files | Import X files (over HTTP when the format is self-contained) and export them; the network_files capability lists the formats |
Solve |
| Stage 3, solver | Run a network and read results, objective and solve time as a new version; use the workflow solve step |
Measures, custom constraints and extra methods, unless built |
| Stage 4, release and CI | Have X in or out of the wheel, and tested on the legs chosen | — |
| Stage 5, frontend and examples | Use the UI without PyPSA assumptions; follow a notebook | — |
A stored X network also loads on a host without X; its components are then generic
ComponentModels. Calliope's pull requests ran in the same order: registry (#821), types and
checks (#823), import (#824), solve (#781), then constraints (#932), measures (#1445),
attribute groups (#1586), run methods (#1726), format classes and the writer (#1867, #1869,
#1879, #1880), type display (#2300).
Every package has the same manifest frame. Only the name, the dependencies, the entry points
and the matching [tool.uv.sources] lines change:
[project]
name = "tz-ps-x"
version = "0.1.0"
requires-python = ">=3.13,<3.15"
dependencies = ["pydantic>=2.12", "tz-ps-models"]
# The conductor may not import this package, so the composition root discovers it here.
[project.entry-points."tz_ps_conductor.frameworks"]
tz-ps-x = "tz_ps_x:XFramework"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src/tz_ps_x"]
[tool.uv.sources]
tz-ps-models = { workspace = true }
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = ["--import-mode=importlib"]1. Create backend/libs/tz_ps_x/ with the manifest above, src/tz_ps_x/ and tests/.
2. Build the registry. All of it is your work; nothing in the contract requires an artefact. Calliope's layout is the model:
-
registry/x.gen.json: the committed artefact, withschema_version,sourceandcontent_hash. The two existing artefacts share no other schema. -
registry/vocabulary.py: the parser and typed schema of the artefact, andregistry/__init__.pywithload_registryandread_registry_version. -
registry/attribute_groups.pyandregistry/type_display.py: hand-kept, because upstream does not say whichParameterGroupan attribute belongs to or how a type is drawn. - If generated:
backend/ci_scripts/generate_x_registry.py(with--check),check_x_registry_narrowing.py, threex-registry*targets inbackend/Makefile, and tests besidebackend/tests/test_generate_calliope_registry.py.
3. Declare each component type and give it a typed class. One component, end to end:
from typing import ClassVar, Literal
from pydantic import ConfigDict
from tz_ps_models import (
ComponentModel,
ComponentType,
ComponentTypeDisplay,
FloatArray,
ParameterGroup,
TypeGlyph,
TypeVisibility,
)
from tz_ps_models.expressions import AttributeKind
from tz_ps_models.parameter import ParameterType, SeriesSupport, ValueType
FRAMEWORK_NAME = "X"
class Plant(ComponentModel):
# Forbid, so an attribute the type does not declare is refused on a write.
model_config = ConfigDict(extra="forbid", validate_assignment=True)
series_fields: ClassVar[frozenset[str]] = frozenset({"availability"})
name: str
component_type: Literal["Plant"] = "Plant"
capacity: float | None = None
availability: float | FloatArray | None = None
def _input(name: str, group: ParameterGroup, series: SeriesSupport, unit: str) -> ParameterType:
return ParameterType(
name=name,
framework_name=FRAMEWORK_NAME,
value_type=ValueType.FLOAT,
series_support=series,
display_name=name.capitalize(),
description="",
is_output_field=False,
kind=AttributeKind.INPUT,
unit=unit,
group=group,
)
PLANT = ComponentType(
name="Plant",
framework_name=FRAMEWORK_NAME,
url_token="plants",
description="A unit that generates.",
display=ComponentTypeDisplay(
glyph=TypeGlyph.GENERATOR, rank=10, visibility=TypeVisibility.ALWAYS
),
parameter_types=(
_input("capacity", ParameterGroup.CAPACITY, SeriesSupport.NONE, "MW"),
_input("availability", ParameterGroup.OPERATION, SeriesSupport.OPTIONAL, "p.u."),
),
)The class and the type must agree: the same canonical name, the same inputs, and
series_fields equal to ComponentType.series_fields. Only inputs are model fields; an
output is a ParameterType with is_output_field=True and no field. A class that falls back
to plain ComponentModel appears to work until a series write or a reload. PyPSA's generated
backend/libs/tz_ps_pypsa/src/tz_ps_pypsa/models/load.py is this shape; Calliope's
build_component_class in component_classes.py builds the same from the registry, and its
CalliopeComponent shows the extra validator a framework with dynamic attribute names needs.
4. Write the framework class in src/tz_ps_x/__init__.py:
import logging
from typing import Any
from tz_ps_models import ComponentModel, ComponentType, NetworkModel
from tz_ps_models.errors import Inconsistency
from tz_ps_models.framework import Framework
from tz_ps_x.components import FRAMEWORK_NAME, PLANT, Plant
from tz_ps_x.registry import read_registry_version
_CLASSES: dict[str, type[ComponentModel]] = {"Plant": Plant}
class XFramework(Framework):
@property
def name(self) -> str:
return FRAMEWORK_NAME
@property
def version(self) -> str:
return read_registry_version()
@property
def component_types(self) -> tuple[ComponentType, ...]:
return (PLANT,)
def build_component(self, data: dict[str, Any]) -> ComponentModel:
component_type = data.get("component_type")
if isinstance(component_type, ComponentType):
component_type = component_type.name
data = {**data, "component_type": component_type}
if not isinstance(component_type, str):
raise ValueError("`component_type` must be a string or ComponentType")
declared = self.find_component_type(component_type) or self.get_component_type(
component_type
)
return _CLASSES[declared.name].model_validate(data)
def list_network_problems(self, model: NetworkModel) -> list[Inconsistency]:
return []
# Tests run with discovery off, so importing this package must register it.
Framework.register(XFramework())
logging.getLogger(__name__).addHandler(logging.NullHandler())
__all__ = ["FRAMEWORK_NAME", "XFramework"]Only name and build_component are abstract. build_component may raise
pydantic.ValidationError; Network turns it into InvalidComponentAttributesError. Add
solve_options, methods, is_precondition_met, constraints, standard types and snapshot
weightings later, each by overriding one member
(the contract).
5. Wire the package
-
backend/pyproject.toml,[tool.uv.sources]:tz-ps-x = { workspace = true }. -
[project.optional-dependencies]:x = ["tz-ps-x"]. Only the packages that exist. The extra grows by one package at each stage. -
[dependency-groups]: thex-registrypin. -
mypy_path, import-linterroot_packages,[tool.coverage.run] source. - The
layerscontract:tz_ps_xon the description row. -
forbidden_modulesof the four framework-blind contracts ("the conductor does not know about frameworks", "the runner does not know about frameworks", "tz_ps_http must not import the framework or solver packages", thetz_ps_durable_runnercontract) and of "the support packages do not know about frameworks". -
source_modulesof "a framework package does not know the expression grammar". - A new contract that keeps X's library out of
tz_ps_x, and X's library inforbidden_modulesof "the constraint grammar does not know about frameworks". -
backend/libs/tz_ps_http/pyproject.toml:x = ["tz-ps-conductor-backend[x]"]. -
backend/scripts/serve.sh: auv syncline with a literal--extra x, by default or behind a switch, and the switch inbackend/tests/test_serve_script.py. A variable on themakecommand line reaches the script, somake dev X=1needs no Makefile change. -
backend/mutation.toml: a[[packages]]block (checked only by the weeklymutation_kittests, so a pull request will not catch a miss). - Run
uv lockinbackend/and commitbackend/uv.lock. CI installs with--locked.
6. Tests
-
backend/libs/tz_ps_x/tests/:test_framework.py,test_registry.py,test_component_types.py,test_attribute_groups.py, one file per rule module, and a test that writes a series on a component, saves and reloads it. - New modeller behaviour (build and validate an X network): a scenario under
backend/tests/acceptance/, which runs under both drivers and names no route or status. - Wire shape, status codes and problem slugs: plain pytest under
backend/tests/contract/. -
backend/tests/features/: only to extend a feature that is already there, such as a scenario for X inframework_description.featureorframeworks_methods.feature.
Check it works
make -C backend lint-imports # the contracts hold
uv run pytest tests/test_import_contracts.py libs/tz_ps_x # in backend/
make -C backend serve X=1 # or no switch, if on by default
curl <server>/api/frameworks # lists X with its version
curl <server>/api/frameworks/x/component-types # lists plantsThen create an X network over HTTP and add one component with a series.
1. Create backend/libs/tz_ps_files_x/ with the same manifest frame. Dependencies:
tz-ps-x, tz-ps-models, tz-ps-ports, the exact pin of X's library, and
tz-ps-reader-support for NetCDF. Entry points:
[project.entry-points."tz_ps_conductor.network_file_formats"]
x-netcdf = "tz_ps_files_x:XNetCDF"
# Each third-party library that logs in this package's process.
[project.entry-points."tz_ps_conductor.library_loggers"]
x = "x"2. Write one class for each format in src/tz_ps_files_x/formats.py, and re-export it
from src/tz_ps_files_x/__init__.py (from tz_ps_files_x.formats import XNetCDF), because
the entry point names the package root. Neither module may import X's library at its top:
both load in the API process.
from __future__ import annotations
from pathlib import Path
from tz_ps_models import NetworkModel
from tz_ps_ports import NetworkFileReader, NetworkFileWriter
from tz_ps_x import ReadModel
class XNetCDF(NetworkFileReader, NetworkFileWriter):
format = "x-netcdf"
framework = "X"
title = "X NetCDF"
file_extension = ".nc"
is_self_contained = True
def read(self, path: Path) -> ReadModel:
from tz_ps_files_x._reader import read_x_file # yours
return read_x_file(path)
def write(self, model: NetworkModel, path: Path) -> None:
# Imported here, not at the top, so the API process does not import X.
from tz_ps_files_x.writer import write_x_file # yours
write_x_file(model, path)-
ReadModelis yours: the read object. Define it intz_ps_xand add it to that package's__all__, as Calliope does, so the files package depends on the description package. - Abilities are read by
isinstance. A format that only reads subclassesNetworkFileReaderalone. -
formatis a slug clients match on and never changes.file_extensionhas its dot and only letters and digits, or the format is skipped. -
is_self_contained = Falsewhen a read can open other files the file names. Such a format is never offered over HTTP;CalliopeYamlis one. -
readraisesNetworkLoadError(LoadFailureReason, detail). Open a NetCDF file only throughtz_ps_reader_support.open_dataset, whose lock must cover every NetCDF read.
3. Connect the read to the framework. Network.load_network_file hands what read
answers to XFramework.import_network:
def import_network(self, network: Any, *, name: str | None = None) -> NetworkModel:
if not isinstance(network, ReadModel):
raise TypeError(f"an X network is imported from a ReadModel, not {network!r}")
return import_read_model(network, self.build_component, name=name) # yoursName the model with name before validating it, so a source with no name imports.
4. Report what could not be carried over by logging, on the calling thread, at WARNING or
above, with extra=NetworkFileWarning.build_log_extra(component_type, name, attribute, value_left_out=True). An import leaves out a value the framework's models refuse instead of
failing the file; a dangling reference imports as it stands. PyPSA's implementation is
backend/libs/tz_ps_pypsa/src/tz_ps_pypsa/invalid_values.py.
5. Put the code that builds X's native model here, so the writer and the solver share it
(build_calliope_model in tz_ps_files_calliope/calliope_model.py). The writer runs in a
child process under the memory limit and raises SolveError when X refuses the network.
That child preloads only the tz_ps_conductor.solve_runtimes entry point, which the
solver package declares. Until stage 3, or in an install with files and no solver, the writer
imports X under the limit.
6. Wire the package
-
[tool.uv.sources],mypy_path,root_packages, coverage source,mutation.toml. -
layers:tz_ps_files_xon the files row. - The four framework-blind contracts and the support-packages contract.
-
source_modulesof "only the warehouse library names a storage adapter" and "only the composition root names an object store adapter". - Extras:
x = ["tz-ps-x", "tz-ps-files-x"], andx-importwith the same two. -
uv lock, and commit the lock.
7. Tests. backend/libs/tz_ps_files_x/tests/: test_formats.py, test_loader.py,
test_round_trip.py, test_writer.py. An import scenario under backend/tests/acceptance/.
A fixture builder under backend/ci_scripts/, as build_calliope_fixtures.py is.
Check it works
curl <server>/api/capabilities # network_files lists x-netcdf with can_import and can_exportImport a file over HTTP and from Python (Network.load_network_file("x", path)), then export
it. Run the export once in each install shape you support, and watch the child's memory.
1. Create backend/libs/tz_ps_solver_x/. Dependencies: tz-ps-models, tz-ps-ports,
tz-ps-x, tz-ps-files-x, tz-ps-solver-support, the exact pin. Entry points:
# Both names are the framework's name.
[project.entry-points."tz_ps_runner.solvers"]
x = "tz_ps_solver_x:XSolver"
# Imported before a solve process applies its memory limit.
[project.entry-points."tz_ps_conductor.solve_runtimes"]
x = "tz_ps_solver_x.solve"
[project.entry-points."tz_ps_conductor.library_loggers"]
x = "x"
[dependency-groups]
dev = ["tz-ps-testing"]2. Write the solver class in src/tz_ps_solver_x/solver.py, and re-export it from
src/tz_ps_solver_x/__init__.py (from tz_ps_solver_x.solver import XSolver):
from __future__ import annotations
import importlib.util
from tz_ps_ports import NetworkHandover, Solver, SolverDependencies, SolveRequest
from tz_ps_x import FRAMEWORK_NAME
class XSolver(Solver):
framework = FRAMEWORK_NAME
def __init__(self, dependencies: SolverDependencies) -> None:
self._limits = dependencies.limits
def is_provisioned(self) -> bool:
return importlib.util.find_spec("x") is not None
def solve(self, request: SolveRequest) -> NetworkHandover:
# Imported here so that discovering the entry point and asking whether the solver
# is provisioned import neither X nor DuckDB.
from tz_ps_solver_x.solve import solve_handover
solve_handover(request, self._limits)
return request.output_handover3. Write one solve in src/tz_ps_solver_x/solve.py. This module is X's solve runtime:
import X and every heavy library the solve needs at its top, as
tz_ps_solver_calliope/solve.py imports calliope.model and pandas. load_solve_runtime
only imports the module, and a library first loaded under the limit can end the process.
from __future__ import annotations
import time
import pandas as pd # noqa: F401
import x
from tz_ps_files_x.x_model import build_x_model # yours
from tz_ps_models import OBJECTIVE, SOLVE_TIME, FailureReason
from tz_ps_ports import (
SolveCancelledError,
SolveError,
SolveLimits,
SolveRequest,
TransientSolveError,
)
from tz_ps_solver_support import (
SolvedNetwork,
build_output_document,
open_connection,
read_input_document,
read_wide_frames,
write_output_handover,
)
def solve_handover(request: SolveRequest, limits: SolveLimits | None) -> None:
parameters = validate_run_parameters(request.params, request.method) # yours
document = read_input_document(request.input_handover)
with open_connection(request.input_handover, limits) as connection:
series = {
(wide.component_type, wide.attribute): wide.frame
for wide in read_wide_frames(connection, document.timesteps)
}
started = time.monotonic()
try:
native = build_x_model(document.model, series)
x.solve(native, **parameters) # X's own call
except (MemoryError, SolveError, TransientSolveError, SolveCancelledError):
raise
except Exception as error:
raise SolveError(
FailureReason.SOLVER_ERROR, detail=f"x refused the model: {error}"
) from error
seconds = time.monotonic() - started
# Before any output is read: a solve that is not optimal has none to place.
reason = map_termination_condition(native) # yours: None for optimal
if reason is not None:
raise SolveError(reason, detail="x solve did not end optimal")
placed = place_outputs(native, document.model) # yours
output = build_output_document(
framework_name=document.model.framework_name,
metadata={OBJECTIVE: placed.objective, SOLVE_TIME: seconds},
timesteps=document.timesteps,
parameters=placed.parameters,
)
write_output_handover(
request.output_handover, SolvedNetwork(output, tuple(placed.frames)), limits
)- Whole-horizon values are
SolvedParameters in the document. Each per-timestep series is aSolvedFrame: timesteps down, one column per component. - Map X's end state onto
FailureReason:INFEASIBLE,TIMED_OUT,INVALIDfor a network that cannot be solved as it stands, elseSOLVER_ERROR. Calliope's map ismap_termination_conditionintz_ps_solver_calliope/termination.py. - Pass on no param the framework does not declare. Read only declared names (PyPSA's
_optimize_call.py), or fail the run naming the unknown key (Calliope'svalidate_run_parameters). -
SolvedNetworkdefaults to no run values and no measures.write_output_handoverstill writes an empty run values object when the handover asks for one.
4. Optional, each a later rung
| Add | How |
|---|---|
| Run methods | Declare RunMethods on the framework; branch on request.method in XSolver.solve. |
| Measures | Three parts. Name X on each Measure it provides in tz_ps_expressions/measures.py. In the solve, pass the rows as SolvedNetwork.run_values and the names as measures. Subclass MeasuresWriter (write_measures(self, request: MeasuresRequest) -> None) so the backfill can work them out for a version solved before. Framework.measure_keys only names the keys measures are grouped and filtered by. Bump APPLICATION_VERSION. |
| Machine-narrowed options | Subclass SolveOptionsBuilder; read the machine once, in __init__. |
| Custom constraints |
supports_constraints, a constraint_vocabulary, find_constraint_lookup, and the compile into X's model. The files or solver package then depends on tz-ps-expressions, which only the description package may not import. |
| Live solver log | Write LogLines to request.log, as PyPSA's _solve_log.py does. |
5. Wire the package
-
[tool.uv.sources],mypy_path,root_packages, coverage source,mutation.toml. -
layers:tz_ps_solver_xon the solver row. - The four framework-blind contracts, the support-packages contract, both adapter contracts.
-
source_modulesof "a solver must not import the warehouse". - Extras:
x = ["tz-ps-x", "tz-ps-files-x", "tz-ps-solver-x"]; X's library indev. -
uv lock, and commit the lock.
6. Tests. backend/libs/tz_ps_solver_x/tests/: test_solver.py, test_termination.py,
test_parameters.py, each building its request with
tz_ps_testing.input_handover.write_input_handover. A solve scenario under
backend/tests/acceptance/. A notebook under docs/examples/x/.
Check it works. On the serve path, POST <server>/api/projects/<project>/networks/<name>/runs,
then read the run until it ends succeeded with an objective. Run an infeasible network too,
and check it fails with the reason infeasible and not solver_error.
-
backend/ci_scripts/generate_release_manifest.py: add the three distributions to_NOT_RELEASED, or leave them out of it to ship them. Runmake release-manifest;backend/tests/test_release_manifest.pypins the set. - To ship X in the desktop app, also add
tz-ps-conductor-backend[x]tobackend/libs/tz_ps_app/pyproject.toml.desktop/scripts/payload.tsinstalls third-party packages only fromtz-ps-app's locked export, so without it X's code arrives without X's library. -
.github/workflows/backend.yml: a registry drift job besidecalliope-registry-drift. - If X gets a shard of its own: a pytest marker in
backend/pyproject.toml, the path rule inbackend/conftest.py, a tag on each feature, and a job in.github/workflows/backend-tests.yml. Every other job passes--no-install-package <X's distribution>and-m "not x". - Decide the
bdd-postgresqlleg. On the Calliope Python it installs Calliope and runs its scenarios, becausebackend/tests/postgresql_expected_failures.txtnames some. Either install X there too, or deselect X's scenarios there and keep their ids out of that file. -
backend/tests/test_shards.py: the checks that each test runs once and that each framework-named file and feature carries its mark. -
APPLICATION_VERSIONintz_ps_durable_runner/runtime.py, when X's measures are added or change. -
backend/CLAUDE.md(commands, the gate),backend/README.md,README.md, and abackend/libs/tz_ps_x/CLAUDE.mdonly for a rule nothing else states.
Check it works. make release-manifest-check; then make release VERSION=0.0.0 and
make release-smoke if X ships. Open the pull request and confirm X's tests ran in the job
you meant, and nowhere else.
Architecture-Build-CI-and-Release describes the manifest, the image and the workflows.
- For backend-only work, check X over HTTP and from Python, and record the UI gaps. When taking on the UI, start with the places in Frontend impact.
- Add notebooks under
docs/examples/x/, and a walkthrough if wanted (Walkthroughs). - Run the whole gate before each pull request (
backend/CLAUDE.md, The gate):make lint,make test,make test-bdd, the four existing registry checks, X's own two, andmake maintainability. Thenmake checkat the root.
Testing rules that bite a new framework (Testing-Philosophy):
- A test that uses X imports
tz_ps_x; discovery is off in the test process (registry_without_discoveryintz_ps_testing). - A test that needs X's library carries X's marker, or it fails on every job that does not
install X. Do not guard it with a
skipifonfind_spec. - A test that needs a framework name no package owns uses
register_stub_frameworkinbackend/tests/conftest.py. - Stage a new file before
make lint: it checks tracked files only.
The docstrings are the contract. This section lists only what they do not gather in one place.
Framework in
backend/libs/tz_ps_models/src/tz_ps_models/framework.py:
| Member | Default | What reads it |
|---|---|---|
name (required) |
— | The registry key, normalised |
build_component(data) (required) |
— | Every component write and every load |
component_types |
() |
Description routes, ComponentTypeSpellings, series capability, references |
version |
None |
GET /frameworks/{framework} |
solve_options, methods
|
empty; one method named solve
|
The options and methods routes; validate_params at Network.solve
|
is_precondition_met(precondition, model) |
False |
The run pre-flight. HAS_RESULTS is answered by version metadata. |
list_standard_types(component_type) |
() |
The standard-types route; reference checks |
list_network_problems(model) |
[] |
Every save. It must not raise. |
snapshot_weighting_names, energy_weighting_name
|
(), None
|
Snapshot weightings; derived values |
supports_constraints, constraint_vocabulary
|
False, empty |
Saves; the vocabulary route |
measure_keys |
the vocabulary's filter keys but name
|
Grouping and filtering a run's measures |
find_value_lookup, find_constraint_lookup
|
None |
Derived values; the constraint check, which reads no series |
import_network(network, *, name=None) |
raises | Network.import_network |
revision (do not override) |
a digest | The ETag of every framework read |
Framework.get raises UnknownFrameworkError. get_framework_or_fallback answers a bare
ComponentModelFramework, whose components are generic. The routes that serve all of this are
generic, so a new framework needs no new route
(Architecture-HTTP-API-and-Contracts).
Solver, SolveRequest, SolverDependencies and SolveLimits are in
backend/libs/tz_ps_ports/src/tz_ps_ports/solver.py;
the docstring of Solver.solve states what a solve writes. Neither existing solver reads
SolveRequest.cancellation: each solve runs in a child process, and LocalProcessSolver
kills it on a cancel. backend/libs/tz_ps_solver_support is what both solvers share:
| Helper | What it does |
|---|---|
read_input_document(handover) |
.model, a NetworkModel without its series, and .timesteps
|
open_connection(handover, limits) |
A DuckDB connection bound to the handover, with the memory cap and spill directory set |
read_wide_frames(connection, timesteps) |
One WideFrame for each component type and attribute |
build_output_document(*, framework_name, metadata, timesteps, parameters) |
The output document, with the status succeeded
|
write_output_handover(handover, solved, limits) |
Writes every object, discards them all if the write fails, and reports DuckDB's out-of-memory as OUT_OF_MEMORY
|
write_run_values(handover, run_values, measures, limits) |
The run values alone, for write_measures
|
These are in shared packages, so X cannot stay inside its own three.
| Place | What is hard-coded | What X needs |
|---|---|---|
backend/libs/tz_ps_expressions/src/tz_ps_expressions/measures.py |
PYPSA and CALLIOPE constants; each Measure lists the frameworks that provide it and framework_units
|
A constant, and an entry on each measure X provides |
LogSource in tz_ps_models/run_log.py
|
Members PYPSA and LINOPY, none for Calliope |
A member, if X's log lines should be labelled |
ParameterGroup in tz_ps_models/parameter.py
|
A closed set that already holds Calliope-only members | A member for a group that is not there |
TypeGlyph in tz_ps_models/component.py
|
A closed set; TECHNOLOGY came with Calliope |
A member, and a drawing in the frontend |
MethodPrecondition in tz_ps_models/run_method.py
|
Two members came with Calliope's operate | A member for a new kind of precondition |
tz_ps_demo_data, tz_ps_app
|
Depend on tz-ps-pypsa by name |
Nothing, unless X ships or gets demo data |
A new member of any of these enums reaches contracts/openapi/core-api.yaml and the generated
SDK.
The API describes each framework, component URLs use the declared url_token, and the
expression grammar in frontend-sdk is generic, so a backend-only framework works in the UI
without a frontend change. These places assume PyPSA; each was opened and confirmed.
Architecture-Frontends-and-Desktop describes the frontend.
A row under frontend-next/ is in the redesign, which is merged into frontend/ at feature
parity.
| File | What it does |
|---|---|
frontend-next/src/features/runs/solve-form.tsx |
Requests run methods for the literal "PyPSA", whatever the network's framework. Fix this first. |
frontend-next/src/features/networks/installed-capacity.tsx |
Shows the card only when the framework is pypsa
|
frontend-next/src/features/networks/network-card.tsx, networks-table.tsx, import-network-dialog.tsx
|
Read counts by the tokens buses, lines, links, transformers, generators
|
frontend-next/src/features/networks/constraints-card.tsx |
Reads global_constraints
|
frontend-next/src/features/networks/utils.ts |
typeLabel has translated labels for PyPSA and Calliope tokens; another token gets a readable fallback, untranslated |
frontend-next/src/features/networks/component-glyph.tsx |
A map over TypeGlyph, falling back to generic
|
frontend-next/src/features/networks/use-network-destination.ts, frontend/src/features/networks/network-import.ts
|
Preselect pypsa
|
frontend/src/features/networks/constraint-editor.tsx |
Example placeholders keyed pypsa and calliope
|
frontend/src/features/components/grid/statistic-columns.ts, add/sense-warning.ts, frontend/src/features/costs/cost-calculator-helper.tsx
|
PyPSA type and attribute names |
docs/specs/2026-11-18-framework-type-display-design.md moved glyph, order and visibility to
each framework's type_display.py, and leaves the node and branch roles and Home's count
columns for later.
-
uv syncis exact. A sync without X's extra uninstalls X, and its entry points go with it. - Name the solver and solve-runtime entry points for the framework. A misnamed solver entry point still works, but each solve process then loads every installed solver. A misnamed solve-runtime entry point is skipped without a message, so X loads under the memory limit.
-
An extra that passes the deployment guard can still omit a package.
test_every_framework_package_is_installed_by_the_deploymentchecks description packages only. -
Discard the output handover if you raise after writing. A write commits when its
stream closes.
write_output_handoverdoes this; a writer of your own must. -
No Python object for each number on the write path: no
PIVOT, nomodel_dump(mode="json")on a series. -
Keep the argument shapes of
SolveErrorandTransientSolveError. They are rebuilt fromargsacross a process boundary. - Code in a solver package that never touches X's library belongs in
tz_ps_solver_support. -
Do not flatten
url_tokens across frameworks, and do not memoiseComponentTypeSpellingson a framework name. - A registry bump can strand stored networks. The narrowing check is the guard, and no check compares descriptions.
-
A review asking for a fix in a layer the rung does not reach is a note, not a change
(root
CLAUDE.md, Conventions).
This is the evidence for which parts are optional or can come later.
| Capability | PyPSA | Calliope |
|---|---|---|
| Standard types, snapshot weightings, piecewise curves | Yes | No |
| Component classes | Generated source (make models) |
Built at runtime |
| Solve options narrowed to the machine | Yes | No; fixed to HiGHS |
| Solver log lines, size estimate before a solve | Yes | No |
| Run methods |
optimize, pf, two fix methods |
plan, fix_optimal_capacities, operate
|
| Measures | All 13; 3 built-ins and 2 run-level built-ins | 5; 1 built-in and 2 run-level built-ins |
| Import over HTTP | NetCDF | NetCDF; model.yaml is Python-only |
| Wheel, image, desktop app; installed by default; demo project | Yes | No |
| CI | Every leg | One shard on one Python |
| Example notebooks | 40 folders and COVERAGE.md
|
1 |
The Calliope design also defers spores mode, time clustering, scenarios at import and
generated typed models.
Epic #984 (open) adds Sienna on branches issue-989-sienna-spike to
issue-998-sienna-examples, none merged and not read for this page. Two things matter to
anyone adding a framework:
- It is the first framework whose solver runtime is not a Python package. The epic says it settles how a solver runtime runs outside the process, for GenX and any later Julia framework to reuse. A framework with a non-Python runtime should wait for it or build on it.
-
It touches the same hand-kept lists, so two framework stacks open at once will conflict
in
backend/pyproject.tomlandbackend/uv.lock.
.github/workflows/sienna-runtime.yml on main is a stub: GitHub dispatches only a workflow
whose file is on main, so it holds the manual trigger alone, and the image build comes with
#996.
-
The run dialog asks for PyPSA's methods on every network
(
frontend-next/src/features/runs/solve-form.tsx), which is already wrong for Calliope. -
The measures catalogue is keyed by framework name in shared code
(
tz_ps_expressions/measures.py). Nothing on theFrameworkcontract declares measures. -
LogSourcenames PyPSA's libraries and not Calliope's (tz_ps_models/run_log.py), and the Calliope solver writes nothing toSolveRequest.log. -
An export preloads the solver package's runtime, not the files package's
(
backend/src/tz_ps_conductor/export_process.py), so a files-only install writes under the memory limit with nothing preloaded. -
A new workspace member ships in the wheel by default.
_NOT_RELEASEDinbackend/ci_scripts/generate_release_manifest.pyis an exclusion list. -
CI's opt-in shard is written for exactly one framework.
backend/conftest.pyand.github/workflows/backend-tests.ymlnamecalliopethroughout. - There is no behavioural conformance suite that runs over every installed framework, so a contract a new framework breaks is caught only by tests its author writes.
-
backend/CLAUDE.mdstill namesbackend/tests/features/as where a scenario goes, whiledocs/specs/2026-10-29-four-layer-acceptance-tests-design.mdputs new and changed features inbackend/tests/acceptance/. -
Only
tz_ps_pypsahas a packageCLAUDE.md. Calliope's package rules sit inbackend/CLAUDE.md. -
The Calliope design still names
tz_ps_reader_calliopeand thefile_loadersgroup. The code hastz_ps_files_calliopeandtz_ps_conductor.network_file_formats.
Using the app
Architecture
- Overview
- Python API
- Domain model
- Backend core
- Composition root and config
- Expression language internals
- Storage
- Execution
- Imports and exports
- Workflow engine
- HTTP API and contracts
- Frontend and desktop
- Build, CI and release
Contributing