Skip to content

Data update coordinator

The coordinator runs optimizations when inputs change and distributes the results to sensors.

Purpose

HAEO's coordinator implements Home Assistant's DataUpdateCoordinator pattern. The implementation is in coordinator/coordinator.py. coordinator/network.py checks network connectivity and keeps its repair issues current.

The coordinator:

  • Reads resolved values from the input stores in runtime_data.input_stores
  • Applies the inputs that changed to the network built by build_network
  • Runs the LP solver in an executor thread
  • Builds the outputs that sensors read
  • Reports failed optimizations through the status sensor and repair issues

Each hub config entry has one coordinator. It is created during setup from the same snapshot of element subentries that built the input stores, so the elements it optimizes always match the stores it reads. Adding, changing, or removing an element reloads the config entry, which builds a new coordinator. An input entity writing a new value does not reload; it signals the coordinator instead.

The coordinator has no update interval. Optimizations run when an input store reports a new value, when the HorizonManager advances, or when one is requested.

Initialization

async_initialize() runs once every input store has settled:

  1. Assembles each element's config from the stores' values
  2. Calls build_network in core/adapters/network_builder.py to build the network, and build_element_updaters to build an updater per element for it
  3. Serializes the topology for the frontend card and checks network connectivity
  4. Subscribes to each input store, the auto-optimize switch, and the HorizonManager

Setup then runs the first optimization before adding the output sensors.

Update cycle

sequenceDiagram
    participant Trigger as Trigger
    participant C as Coordinator
    participant S as Input stores
    participant N as Network
    participant LP as Executor

    Trigger->>C: _optimize()
    C->>C: Wait for the optimization lock
    alt Inputs not aligned to the horizon
        C-->>Trigger: Skip (stores request again once loaded)
    else Inputs aligned
        C->>S: Check availability and read values
        C->>N: update_periods() and updaters of changed elements
        C->>LP: network.optimize()
        LP-->>C: Cost, or InfeasibleError or SolverError
        C->>C: Build outputs
    end

Warm start

Each store listener marks its element stale. Before a solve, the coordinator copies the horizon's period durations onto the network and calls the updater of every stale element. When the horizon has a different number of periods from the network, as an entity horizon can, it rebuilds the network from the loaded inputs instead, because the network's variables are sized for the count it was built with. An updater calls the adapter's model_elements() with the new values and writes them to the TrackedParam descriptors on the live model elements, so only the constraints that read them are rebuilt.

All network changes happen on the event loop before the solve is handed to the executor, so the network is never mutated while it is being solved.

Outputs

_build_outputs() stores the results in coordinator.data.outputs, keyed by element name, then device name, then output name. Each adapter's outputs() maps the model outputs to its devices. The network's own outputs, the optimization cost and duration, are keyed by the network subentry's title, which its sensors look them up by. An OutputData marked diagnostic becomes a sensor in the diagnostic entity category.

Scheduling

Single-flight refresh

Every optimization goes through _optimize(), which holds a lock while it runs, so optimizations never overlap. A request sets a single "rerun wanted" flag before waiting for the lock. Each optimization reads every input as it is when it starts and clears the flag, so requests made while one runs share a single follow-up, and a request already met by an optimization that started after it does nothing. When an optimization ends with the flag set, it requests the follow-up through the debounce window, unless another optimization is already waiting for the lock and will read the inputs itself. An optimization is skipped while any available forecast input is still loading for a new horizon, since its horizon_start does not yet match the horizon's. Those stores request another optimization once they load.

async_refresh() optimizes as soon as the lock allows, which setup uses for the first optimization. The haeo.optimize action calls async_run_optimization(), which returns once the next optimization to start has finished, whatever the auto-optimize switch says. An optimization already scheduled is that next one; otherwise it requests one. With the action's immediate field on, the default, the request skips the debounce window, and an optimization waiting out the window starts on the next loop iteration instead. With it off, the request waits out the window like an automatic one. The action registers a future in _result_waiters before requesting, and the optimization that next starts reading inputs takes every registered future and resolves it when it ends, with the optimization's own HomeAssistantError when it fails. While an action waits, input changes request optimizations even with auto-optimize off, and turning auto-optimize off does not cancel the scheduled one, so an optimization skipped while inputs load for a new horizon is retried once they have loaded.

Debouncing

Automatic requests wait out the debounce window:

sequenceDiagram
    participant E as Store or entity update
    participant C as Coordinator
    participant Timer

    E->>C: signal_optimization_stale() or async_request_refresh()
    C->>C: Set rerun wanted
    alt Optimization running or timer pending
        Note over C: The running optimization or the timer picks it up
    else Within debounce window
        C->>Timer: Start timer for the remaining window
    else Otherwise
        C->>C: Optimize
    end

    Timer->>C: Window expires
    alt Rerun still wanted
        C->>C: Optimize
    end

signal_optimization_stale() does nothing while the auto-optimize switch is off; async_request_refresh(), which an entity update calls, requests one either way. The debounce window, the hub's debounce seconds, starts when an optimization starts and again when it succeeds, which batches rapid input changes into one optimization. It is measured on the monotonic clock, so a wall clock set back does not stretch it. An input that changes while an optimization runs requests a follow-up through the same window.

A horizon roll does not wait out the window, since until it optimizes every output plans from a period that has already ended. Like the haeo.optimize action, it makes an immediate request: it cancels the debounce timer the reloaded inputs started and optimizes on the next loop iteration, after every input notified in the same pass has marked its element stale. Requests keep skipping the window until an optimization starts reading the inputs, so one skipped while forecasts load for the new horizon runs as soon as they have loaded.

Turning the auto-optimize switch off cancels an optimization waiting out the debounce window, unless an optimize action waits for it, and pauses the HorizonManager. Turning it back on resumes the HorizonManager, whose notification requests an optimization that catches up on changes made while it was off.

Error handling

Failures raise UpdateFailed, which sets last_update_success to false and makes the output sensors unavailable.

Optimization status

The optimization status sensor is added at setup and stays available. It reads coordinator.optimization_status:

  • failed when the latest optimization failed
  • degraded when it succeeded but used a reading held past the hold, recorded in CoordinatorData.degraded_inputs
  • success when it succeeded on live readings
  • pending before any optimization has produced data

Its error attribute shows coordinator.optimization_error. Home Assistant notifies listeners only when an update switches between failing and succeeding, so _async_refresh_finished also notifies them after each repeated failure to keep that attribute current.

Once updates have kept failing for FAILURE_SECONDS_BEFORE_REPAIR_ISSUE, _async_refresh_finished raises the general optimization_failure repair issue with the error message, once per failing stretch, and the next success dismisses it. A failure that raises a repair issue of its own fails the update with ReportedUpdateFailed instead, and the general issue is not raised for it.

Inputs

Setup waits for every input store to settle. If one rejects its source's value, or the stores do not settle in time, setup raises ConfigEntryNotReady naming the input.

Before each solve, _check_inputs() keeps the input repair issues current through sync_input_issues(): an unavailable_input error per input without a reading, naming its sources, and a degraded_input warning per input holding a reading past its hold, naming the held sources and when they lost their reading. It dismisses the issues of inputs that have recovered. New degraded_input issues wait until one input_hold_seconds has passed since the coordinator was created at entry setup, because after a restart HAEO usually sets up before the integrations whose sensors it reads, and their seeded readings are already past the hold. The status still reads degraded at once, and issues already raised stay current. The first sync that holds an issue back schedules _end_repair_grace() for the end of the grace, which syncs the issues again, so an input still degraded then gets its issue even if nothing else changes. With the hold at 0 there is no grace. An input holding a reading is available, so it never stops the solve; the solve goes ahead and its status reads degraded once the hold has passed. An unavailable input fails the update with the input_unavailable translation, and a store that rejected its source's value fails it with that error. It also keeps the mixed price currencies issue current.

Solver

A solve that stops for a reason other than infeasibility, such as an unbounded model, raises SolverError carrying the HiGHS status. The coordinator fails the update with the optimization_solver_failed translation.

Infeasible and relaxed plans

An infeasible model raises InfeasibleError carrying the conflicting constraint rows. The coordinator raises the optimization_infeasible repair issue naming the configured elements those rows belong to and the minutes from the start of the plan to the first of them, and fails the update with the same message. The wording lives in the translations; the coordinator passes only element names, numbers, and the plan's start time as placeholders.

When the hub's relax_infeasible option is on, the network relaxes the model instead and records Network.relaxations. The coordinator raises the optimization_relaxed warning issue after the update succeeds, naming the conflicting elements, the elements where constraints were relaxed, and how many periods.

An impossible or relaxed plan's cause can come and go between optimizations, so the coordinator never dismisses either issue. Both are persistent and fixable, and the user resolves them through the confirm flow repairs.async_create_fix_flow returns. While either is open, later failures leave it as it is.

When either issue is raised, the coordinator saves diagnostics built from the failing optimization's context with diagnostics_from_context, plus a failure section listing the conflicting and relaxed rows, to haeo/diagnostics/infeasible_*.json or relaxed_*.json. The path goes in the issue's data, and the file is deleted when the issue is resolved or the config entry is removed, so there is at most one file per open issue. Issues that change only when the configuration does, such as a disconnected network, clear themselves once fixed and are not fixable.

Testing

Coordinator tests are in coordinator/tests/, split by concern: scheduling, outputs, failures, connectivity, and the optimization context. They use Home Assistant's test fixtures.