Skip to content

Backend Core

James Dunkerley edited this page Dec 3, 2026 · 4 revisions

Home · Architecture

In short

  • The backend is one uv workspace:
    • the application package tz_ps_conductor under backend/src/ and 21 member packages under backend/libs/.
    • They are published as a single wheel, tz-ps-conductor.
  • The packages form twelve layers.
    • import-linter enforces the order, and eleven further contracts forbid specific imports the order would allow.
  • Anything a package may not import by name it reaches through a Protocol in tz_ps_ports or an entry point.
    • Frameworks, solvers, file formats, the workflow engine and the demo data are all plug-ins.
  • backend/src/tz_ps_conductor/dependencies.py is the composition root.
    • It reads one JSON config document and builds everything shared, once per process.
  • Four parts have their own page.

Overview

Callers reach the backend through the Python API. The composition root reads the config, builds what a process shares, and discovers the plug-ins. Everything rests on the domain model and the contracts.

flowchart TD
    callers["Callers<br/>tz_ps_http routes, a notebook"]
    config[/"One JSON config document"/]
    subgraph conductor["tz_ps_conductor"]
        direction LR
        api["The Python API<br/>Project, Network, ComponentHandle"]
        root["The composition root<br/>dependencies.py"]
        api -- "asks for what it needs" --> root
    end
    subgraph built["Built once per process"]
        direction LR
        persistence["Persistence<br/>warehouse and stores"] ~~~ objects["Object store"] ~~~ runner["Runner and the<br/>durable runtime"]
    end
    subgraph plugins["Found by entry point"]
        direction LR
        frameworks["Frameworks"] ~~~ formats["File formats"] ~~~ solvers["Solvers"]
    end
    models["tz_ps_models · tz_ps_ports<br/>the domain model and the contracts everything shares"]
    callers --> conductor
    config --> conductor
    conductor -- "builds" --> built
    conductor -- "discovers" --> plugins
    built --> models
    plugins --> models
Loading

The package map

  • Every member is a hatchling src-layout package for Python 3.13 or 3.14.
  • A member's own pyproject.toml matters inside the workspace and to import-linter.
  • The wheel is built from the generated backend/release/pyproject.toml, which folds the members into one distribution.

Foundations

Every other package may import these.

Package What it is for Third-party libraries of note
tz_ps_models The domain model: networks, components, frameworks, runs, versions, the Config base. Imports no sibling. numpy, pydantic
tz_ps_expressions The expression language: parser, check, evaluator, the measure catalogue. antlr4-python3-runtime
tz_ps_ports The plug-in and execution contracts, and the exceptions they raise. none
tz_ps_duckdb_filesystem The fsspec filesystem through which DuckDB reads and writes an object store. fsspec

Storage

See Storage.

Package What it is for Third-party libraries of note
tz_ps_datawarehouse Storage contracts and their adapters: git, non-versioned JSON, SQLite, PostgreSQL. See Storage. duckdb, filelock; sqlalchemy, alembic and asyncpg as extras
tz_ps_local_objectstore The local-filesystem ObjectStore adapter. none

Frameworks

Each framework is a description, its file formats and its solver, with two shared support packages. See Adding a framework.

Package What it is for Third-party libraries of note
tz_ps_pypsa The PyPSA framework description: generated component models, lookups, solve options. Does not import pypsa. pandas
tz_ps_calliope The Calliope framework description. May import neither calliope nor xarray. pandas, pyyaml
tz_ps_files_pypsa, tz_ps_files_calliope Each framework's file formats, and the projection of a NetworkModel into the framework's own object. pypsa 1.4.0, calliope 0.7.0, xarray
tz_ps_solver_pypsa, tz_ps_solver_calliope Each framework's solver behind the Solver contract. The Calliope solver is not in the published wheel. pypsa, highspy, calliope
tz_ps_reader_support What every file reader shares: refuse a URL, open a NetCDF file under one lock. xarray, netcdf4
tz_ps_solver_support What every solver shares: read the input handover, write the output handover. duckdb, pandas

Execution

See Execution.

Package What it is for Third-party libraries of note
tz_ps_runner The solve seam: record a run, dispatch its job, solve in a child process, publish, record the outcome. none
tz_ps_durable_runner The DBOS adapters for the runner's outbound seams. dbos lives only here. dbos, sqlalchemy

The API and what sits on it

See The HTTP API and the contracts for the transport.

Package What it is for Third-party libraries of note
tz_ps_conductor The Python API and the composition root. opentelemetry (one minor series), pandas
tz_ps_workflow The fluent workflow builder, its code generator and parser, and the engine that runs a stored workflow. pydantic
tz_ps_demo_data The Demo project a server writes at its first start. none
tz_ps_http The FastAPI transport. See The HTTP API and the contracts. fastapi, uvicorn
tz_ps_app The tz-ps-conductor command and the app that serves the built frontend beside the API. fastapi, uvicorn

Development only

Never shipped.

Package What it is for Third-party libraries of note
tz_ps_testing Shared pytest fixtures and the object store conformance suite. Development only. embedded-postgres, pytest

Layers and import contracts

  • All packages install into one virtualenv, so nothing in Python stops one importing another.
  • The [tool.importlinter] section of backend/pyproject.toml is the only enforcement.
  • make lint runs it.

The layers

  • A package may import any layer below its own.
  • Packages in one layer are siblings and may not import each other.

These are the twelve layers of the packages are layered contract, top to bottom. Architecture draws the idea behind them.

# Layer Packages
1 Development only tz_ps_testing
2 Deployment tz_ps_app
3 Transport tz_ps_http
4 Above the root tz_ps_workflow · tz_ps_demo_data
5 Composition root and Python API tz_ps_conductor
6 Execution tz_ps_solver_pypsa · tz_ps_solver_calliope · tz_ps_runner · tz_ps_durable_runner
7 File formats tz_ps_files_pypsa · tz_ps_files_calliope
8 Frameworks, support and storage tz_ps_pypsa · tz_ps_calliope · tz_ps_reader_support · tz_ps_solver_support · tz_ps_datawarehouse · tz_ps_local_objectstore
9 DuckDB bridge tz_ps_duckdb_filesystem
10 Contracts tz_ps_ports
11 Expression language tz_ps_expressions
12 Domain model tz_ps_models

Three things the order does not show:

  • tz_ps_conductor sits above the framework, file and solver packages but declares none of them as a dependency. It reaches them by entry point.
  • tz_ps_runner and tz_ps_durable_runner are siblings. The conductor gives the runner its DbosExecutor.
  • tz_ps_workflow and tz_ps_demo_data sit above the conductor, use its Python API, and are loaded by entry point.

The forbidden contracts

Each of these bans an import that the layer order would allow.

Contract Who is bound What is banned Why
Only the warehouse library names a storage adapter Every package above the warehouse, except the test fixtures tz_ps_datawarehouse.adapters Naming an adapter binds a deployment to one backend.
Only the composition root names an object store adapter Every package above the object store, except tz_ps_conductor tz_ps_local_objectstore The same rule for the object store.
A framework package does not know the expression grammar tz_ps_pypsa, tz_ps_calliope tz_ps_expressions A framework answers questions about one reference and never parses.
A solver must not import the warehouse The solver packages and tz_ps_solver_support tz_ps_datawarehouse Both sides share an object store, and the warehouse's series codec must not leak.
The conductor, the runner and tz_ps_http do not know about frameworks (three contracts) tz_ps_conductor, tz_ps_runner, tz_ps_http The six framework, file and solver packages Each works with whichever frameworks are installed.
The durable runner depends only on models, ports and the warehouse tz_ps_durable_runner Runner, conductor, HTTP and the six Keeps dbos out of the core.
tz_ps_calliope imports neither calliope nor xarray tz_ps_calliope Those two libraries The description stays importable without the runtime.
The support packages do not know about frameworks tz_ps_reader_support, tz_ps_solver_support The six A framework import there would make every framework install it.
The constraint grammar does not know about frameworks tz_ps_expressions pypsa, calliope, linopy The grammar is shared, and each framework supplies its own names.

What the contract tests add

backend/tests/test_import_contracts.py holds the rules import-linter cannot express:

  • Every workspace member appears in each hand-kept list: the import-linter root packages, the mypy path, the coverage sources and the two adapter contracts. import-linter ignores a package no layer names, so a test catches that too.
  • tz_ps_testing stays the top layer, so no shipped module can import the fixtures.
  • Every package that announces a framework is installed by backend/scripts/serve.sh. The test reads the script's uv sync lines and follows the extras.
  • Every package that announces a framework, a file format or a solver is banned in each framework-blind contract.
  • No package below the conductor imports the OpenTelemetry SDK, and no package imports another package's underscore-prefixed name. Both are syntax-tree scans.
  • tz_ps_models declares exactly numpy and pydantic, and imports no pandas.
  • Every module of tz_ps_solver_pypsa imports pypsa, with five named exceptions; code that does not belongs in tz_ps_solver_support.

Ports and plug-ins

The contracts in tz_ps_ports

Contract What it promises Implemented by Used by
ObjectStore Keyed objects: a seekable read, an atomic write, exists, discard, a listing by prefix. LocalObjectStore Warehouse, runner, solvers, workflow engine
Solver is_provisioned and solve(SolveRequest), which answers a NetworkHandover. PyPSASolver, CalliopeSolver, wrapped by LocalProcessSolver SolverRegistry, the solve process
SolveOptionsBuilder, MeasuresWriter Optional abilities of a solver, found with isinstance. MeasuresWriter: both solvers. SolveOptionsBuilder: PyPSASolver only. LocalProcessSolver passes each through. Runner, the measures backfill
Executor submit_solve and cancel_solve, off the caller's thread. DbosExecutor Runner
ImportExecutor, ExportExecutor, WorkflowRunExecutor The same for an import, an export and a workflow run. The payload is an id, never the data. The Dbos...Executor classes NetworkImports, NetworkExports, the routes, Workflow.run
SolveSteps The checkpointed steps of a solve: solve, publish, record_outcome. LocalSolveWorker in tz_ps_runner The durable workflow
ImportSteps, ExportSteps, MeasuresSteps The checkpointed steps of an import, an export and the measures backfill. NetworkImports, NetworkExports, MeasuresBackfill in tz_ps_conductor The durable workflows and start-up sweeps
WorkflowRuns, StepRecorder Run a stored workflow to its end; run one step, or replay its record. WorkflowEngine; DbosStepRecorder The durable runtime; the engine
ScheduledJobs The jobs a storage backend needs run on a schedule. A warehouse backend, through Persistence.scheduled_jobs The durable runtime
NetworkFileReader, NetworkFileWriter One file format: its slug, framework, title, extension, and read or write. Abstract base classes, not Protocols. PyPSANetCDF, CalliopeNetCDF, CalliopeYaml Imports and exports

The same package also holds three things that are not contracts:

  • NetworkHandover: the set of objects through which a network passes to and from a solver.
  • StoredObject: one object in an object store, held without its key.
  • set_log_context: lets any layer name the request, run and job a log record is for.

Two families of contract live elsewhere, with the concept they belong to:

  • The Framework contract is in tz_ps_models.
  • The storage contracts (NetworkWarehouse, ProjectWarehouse, RunStore and the other stores) are in tz_ps_datawarehouse beside their adapters. See Storage.

Entry-point groups

Group Announced by Loaded by
tz_ps_conductor.frameworks tz_ps_pypsa, tz_ps_calliope discover_frameworks in dependencies.py
tz_ps_conductor.network_file_formats tz_ps_files_pypsa, tz_ps_files_calliope tz_ps_conductor/network_file_formats.py
tz_ps_conductor.library_loggers The file and solver packages tz_ps_conductor/logging_config.py, which reads the names and imports nothing
tz_ps_conductor.solve_runtimes The solver packages load_solve_runtime in tz_ps_conductor/solve_process.py, inside the solve process
tz_ps_conductor.demo_data tz_ps_demo_data tz_ps_conductor/seed.py
tz_ps_conductor.workflow_runs tz_ps_workflow discover_workflow_runs in dependencies.py
tz_ps_runner.solvers The solver packages SolverRegistry in tz_ps_runner/registry.py
tz_ps_datawarehouse.warehouses tz_ps_datawarehouse itself: GIT, NON_VERSIONED, POSTGRESQL discover_backends in tz_ps_datawarehouse/backends.py
tz_ps_workflow.steps tz_ps_workflow, and tz_ps_testing for the tests tz_ps_workflow/_registry.py

The loaders do not all fail the same way:

  • Frameworks, file formats, solvers and warehouse backends: each candidate that fails to load is logged and left out, and the rest still load.
  • Demo data and the workflow engine: only the first candidate by name is tried, with a warning when there are several. If it fails, it is logged and the process has none.
  • Library loggers: the names are read from the metadata, and nothing is imported.
  • Solve runtimes: load_solve_runtime does not catch an import error, so a broken runtime module fails that solve. A missing or misnamed entry is skipped without a message, and the framework's libraries then load under the memory limit.

Adding a framework walks through what a new framework has to announce.

Cross-cutting concerns

Errors

  • Each package raises its own typed errors, never a bare ValueError, so a transport can map them.
  • ConductorError and ModelsError are the roots for the two packages a caller meets first.
  • An error a plug-in raises across a seam is defined with the seam, in tz_ps_ports: SolveError, TransientSolveError, NetworkLoadError, ObjectNotFoundError.
  • The HTTP layer maps error types to problem documents in one table. Anything unmapped is a 500.

Logging

configure_logging in tz_ps_conductor/logging_config.py attaches one console handler and one nightly-rotating file handler (14 days kept). It attaches them to:

  • the backend's own loggers;
  • every plug-in package it finds in the entry-point metadata;
  • a fixed list of third-party loggers.

Other rules:

  • A library named under tz_ps_conductor.library_loggers is held to WARNING.
  • Each record carries the request, run and job ids from set_log_context.
  • A solve process forwards its records to the parent.
  • Shipped code does not print, except tz_ps_app's command line.

Telemetry

  • tz_ps_conductor/telemetry.py is the only module that configures the OpenTelemetry SDK.
  • start_telemetry refuses to start over a provider another library installed.
  • It builds an OTLP-over-HTTP pipeline for traces, metrics and logs, and bridges standard logging into it.
  • The SDK's own OTEL_* variables stay live, so OTEL_SDK_DISABLED=true switches it off.

Capabilities

Update check

  • release.py reads the installed version and its channel.
  • find_newer_release in update_check.py lists the GitHub releases, with a short timeout and a cache, and answers a newer one on the same channel.

Demo data

  • tz_ps_demo_data builds a Demo project of two PyPSA networks with the Python API.
  • A server writes it only into a root that holds no projects and no demo-data-seeded marker.
  • tz-ps-conductor seed writes it whenever the project is absent.

Clone this wiki locally