Skip to content

feat(safety,devices): Phase 4 – PR 4-G Akku-Steuerung über das Gate mit den Invarianten aus ADR-0013 - #33

Open
PXLJAKE wants to merge 16 commits into
phase-4/f-plannerfrom
phase-4/g-battery
Open

PXLJAKE wants to merge 16 commits into
phase-4/f-plannerfrom
phase-4/g-battery

Conversation

@PXLJAKE

@PXLJAKE PXLJAKE commented Oct 28, 2026

Copy link
Copy Markdown
Owner

Gestapelt auf #31 (PR 4-F). Die Basis wird nach dem Merge der Vorgänger umgestellt.

Was

WP10 aus docs/plans/phase-4.md, nach ADR-0013 (vom Maintainer am 2026-10-19 angenommen; die Statuszeile ist auf dem 4-A-Branch eingetragen).

  • Verträge:
    • BatteryAction beschreibt Grenzen, keine Sollwerte. None bedeutet „Wert vor der Übernahme“ (Baseline).
    • battery_identity mit Identitäts-Token.
    • Akku-Modus in operation.battery_mode. Schatten ist Standard; ein Import, eine Neuzuordnung oder eine Änderung von fallback_measured setzt zurück auf Schatten.
  • Adapter (suncore/devices/battery/, Aufruf nur über das Gate):
    • generic: über HA-Entitäten (Number, Select, Switch).
    • kostal_plenticore (REST): Min-SoC als Reserve bzw. Entladesperre. Es gibt keinen Lade-Sollwert, Netzladen wird nur angezeigt. Wartezeit 35 s für den Read-back. Stille Schreibfehler werden über den Read-back erkannt.
    • kostal_modbus: Grenzen aus §3.5 über modbus.write_register (nur in diesem Adapter, nie read-only).
      • Voraussetzungen: Register 1080 = 0x02, Register 5 passt zur konfigurierten Wortreihenfolge.
      • Die Fallback-Register 1284/1286 werden zuerst geschrieben und zurückgelesen, 1288 = 60 s, Heartbeat ≤ 20 s.
      • Höchstens „assistiert“, bis fallback_measured gesetzt ist (Hardware UNVERIFIED).
  • Regler: setzt das Akku-Band des Plans in Intents um, nur bei Änderung, mit Hysterese, höchstens ein Intent pro 60 s. Ein gehaltenes Netzladen zählt nie als Überschuss für Geräte.
  • Safety: Die pauschale Ablehnung safety.battery_not_supported gilt nur noch ohne Adapter. Akku-Intents laufen durch die Invarianten B1–B9.
    • Freigabe: gilt erst als abgeschlossen, wenn der Read-back die ursprüngliche Baseline zeigt. Sonst Wiederholung mit Back-off (30 s bis 10 min), auch unter Not-Aus. Ein von SunCore geschriebener Wert wird nie zur neuen Baseline. Eine echte Änderung durch den Nutzer bleibt stehen, danach Halten bis 04:00.
    • Rückfall auf den Wechselrichter: bei Watchdog-Auslösung (Akkuleistung oder SoC eingefroren bei bewegtem Netz, hängender Wechselrichter), Not-Aus, Herunterfahren, Crash-Recovery, Modus → Schatten, veraltetem Plan und Verbindungsverlust (dann kein Heartbeat, der Hardware-Fallback greift).
  • Simulator:
    • Akku mit BMS-Drift, Wechselrichter-Eigenregelung, Kostal-ähnlicher Fallback-Timer, REST-Abfrage alle 30 s, Modbus-Scan-Verzug.
    • Szenarien: inverter_hang_battery, battery_reserve_drift, grid_charge_price_level, kostal_rest_reserve, modbus_heartbeat_lost.
  • API: PUT /api/v1/operation/battery mit {mode, identity}; Akku im Regelstatus. Keine UI (kommt in 4-H).

Warum

Exit-Kriterium von Phase 4: „Akku-Steuerung im Schattenmodus, dann assistiert“ (Roadmap). Grundlage ist die Strategie „Akku möglichst voll“ des Maintainers. Netzladen soll nur geplant, bewusst und begrenzt passieren.

Wie getestet

  • ./scripts/check.sh grün: 4651 Python-Tests, 219 Frontend-Tests, Abdeckung 96 %. markdownlint ohne Fehler.
  • Property-Tests (hypothesis) für B1–B9, darunter beliebige Baselines bei B4/B5 und „ein eigener oder Baseline-Wert ist nie ein Nutzerwert“.
  • 31 Gate-Tests für den Akku, darunter alle Freigabepfade, Latch über 240 Ticks, Not-Aus ohne Verzögerung und Override.
  • Regressionstests aus den Probes des Reviewers:
    • fehlgeschlagene Freigabe
    • nicht verfügbare REST-Number
    • geerbte Sperre
    • verspätet ankommender eigener Write
    • teilweise geschriebener Write
  • Die fünf Szenarien prüfen am simulierten Wechselrichter, was dort tatsächlich passiert:
    • Fallback ≤ 60 s nach einem Absturz.
    • Untergrenze ≥ 15 % trotz Drift.
    • Hang wird erkannt, die Pause hält.
    • Netzbezug ≤ 8000 W.
    • Ein Preissprung beendet das Netzladen.

Risiken

  • Kostal Modbus: Das externe Batteriemanagement ist beim Maintainer nicht aktiviert, der Fallback-Timer ist nicht gemessen. Der Adapter läuft deshalb nur im Simulator und ist auf „assistiert“ begrenzt (UNVERIFIED).
  • Kostal REST: Vorzeichen, Read-back-Zeiten und Klemmverhalten sind UNVERIFIED. Die Number-Entitäten sind in HA standardmäßig deaktiviert.
  • Restfälle aus dem letzten Re-Check (minor):
    • Wählt der Nutzer zufällig einen Wert, den SunCore in derselben Kontrollphase schon versucht hat, wird er auf die Baseline zurückgesetzt. Das ist die sichere Richtung und wird in der Nutzer-Doku (4-H) erklärt.
    • Ein älterer eigener Write, der außerhalb der Reihenfolge ankommt, wird während einer Lease nur geloggt. Ein Fix folgt in diesem PR.

Safety-Review

control-safety (Implementierung) und reviewer (unabhängig, zwei Re-Checks): freigegeben, mit einem offenen Minor-Punkt, der in diesem PR nachgezogen wird.

# Invariante Ergebnis
B1 Geschriebener Min-SoC nie unter effective_reserve_pct bzw. der Untergrenze des Nutzers; keine von SunCore verursachte Entladung unter die Reserve bestanden
B2 Netzladen ≤ min(Akku, Adapter, Band, Import-Spielraum); unbekannte Grenze → 0 bestanden
B3 Netzladen nur aus einem frischen Planintervall, mit Live-Preis innerhalb der Richtlinie, SoC < Max bestanden
B4 Entladesperre am geschriebenen Zustand (inkl. geerbter Werte), nur wenn geplant bestanden
B5 Importgrenze für jede Aktion, die Import verursachen kann bestanden
B6 Live-Bereiche und Akkugrenzen; keine Grenze über der Baseline bestanden
B7 Schreibrate, nur bei Änderung, Pflicht-Read-back; Heartbeat nur mit gültiger Lease bestanden
B8 Eingefrorene Werte oder hängender Wechselrichter → Freigabe, Schreibstopp, Latch bestanden
B9 Kein Feld ohne Adapter-Fähigkeit bestanden
Freigabe Abschluss erst bei Read-back der Original-Baseline; Back-off auch unter Not-Aus; nie eine eigene Baseline; Nutzerwert bleibt mit Halten bis 04:00 bestanden
Phase 3 Alle Geräte-Invarianten, einziger Schreiber, Not-Aus bestanden

Checkliste

  • Tests für neues Verhalten, Lint/Typen/Tests grün
  • Keine hardcodierten UI-Strings; neue Keys in en und de
  • Doku aktualisiert (ADR-0011-Addendum, ADR-0013-Implementierungsnachtrag, Plan-Abweichungen, architecture.md; Nutzer-Doku in 4-H)
  • docs/STATUS.md aktualisiert
  • Nichts erfunden: Register, Services und Entitäten mit Quelle, Offenes als UNVERIFIED

Offene Fragen an den Maintainer

Für alle Fragen gilt ohne Antwort der jeweils genannte Standard.

  1. Netzladen am Kostal: über eine generische Zwangslade-Entität oder ein eigenes ADR für §3.4? Standard: eigenes ADR, später. Bis dahin wird Netzladen nur angezeigt.
  2. Messung des Rückfall-Timers, bevor fallback_measured gesetzt wird: Standard: Eine Schritt-für-Schritt-Anleitung kommt mit der Doku in 4-H.
  3. Reserve: SunCore setzt die effektive Reserve nur in Plan und Gate durch, nicht dauerhaft im Wechselrichter. Standard: so lassen (bestätigt).

Generated by Claude Code

claude added 16 commits October 24, 2026 17:57
…line, battery identity and mode (WP10)

- BatteryAction is the full desired state; None = the adapter's baseline value of that field
  (resolve_battery_action), capabilities per field, live field ranges, round-up quantisation
- core.identity.battery_identity / battery_identity_token (asset id, adapter template, role
  entities, site SoC and battery power, modbus hub and unit id)
- operation.battery_mode (additive): a battery or site put that changes the identity drops it
  to shadow, an import always resets it, a restore keeps it only for the recorded identity;
  a full operation put cannot raise it
- BatterySettings.modbus (hub, unit id, byte order, heartbeat, fallback timer) and
  fallback_measured (additive); mode providers report the battery mode

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…s pure functions (WP10)

- safety/battery.py: BatteryActuator protocol (capabilities, live ranges, settle, heartbeat,
  hardware-fallback prepare), BatteryContext from the resolved target, live flows, the band
  of a fresh plan interval, the live price and the import limit
- B1 floor never below the reserve nor the user's own floor (rounded up to the step), B2 grid
  charging bounded by battery, adapter, band and import headroom (0 when any bound is
  unknown), B3 only from a fresh planned interval inside the policy at the live price and
  below max SoC, B4 discharge lock only when planned, B5 import limit, B6 live ranges and no
  cap above the baseline, B9 capabilities; BatteryWatch for a frozen battery power / SoC (B8)
- property tests (hypothesis) for every claim; catalogue keys en/de
- the gate still rejects battery intents (wired in the next step)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…and kostal_modbus (WP10)

- suncore/devices/battery behind the gate's BatteryActuator protocol: capabilities from the
  mapped roles, live ranges from the entity attributes, write only on change, read-back,
  release to the baseline; generic numbers / mode select / force-charge switch
- kostal_plenticore: Battery:MinSoc only (no set-point over REST), settle 35 s for the silent
  REST write and the 30 s poll, the usage-mode select read only
- kostal_modbus: §3.5 via modbus.write_register (a write of this adapter only, through the
  rate-limited ServiceCaller, never a read-only action): float32/U32 words in the configured
  word order, refuses unless register 1080 reads 2, arms 1284/1286/1288 before any limit,
  heartbeat re-write, release writes the battery's own limits explicitly
- core.battery_adapter (adapter spec, mode meanings, modbus roles) so devices import only
  core; templates generic.battery, kostal.plenticore, kostal.plenticore_g3_modbus (driver,
  register map, sources, unverified lists) with conformance scenarios; boundary rules cover
  the battery adapters and their arm_fallback / keep_alive writes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…riants (WP10)

- the blanket safety.battery_not_supported rejection now applies only without a battery
  adapter (observe-only, no model) or to another asset id; intents for the configured
  battery pass the battery invariants B1-B6/B9 against the takeover baseline (None =
  baseline), the live flows, the band of a fresh plan interval, the live import price and
  the import limit, the adapter's precondition and capabilities, write only on change
- takeover arms and reads back the hardware fallback first; the mode is capped at assisted
  while the fallback is not measured; mandatory read-back, three failures trip and release
- the accepted state is a lease re-judged by poll() every tick: shadow, a watchdog pause,
  stale inputs or any failed invariant release it; heartbeat only while it holds; a change
  outside SunCore is an override; a release of an adapter without fallback is read back
- check_battery(): frozen battery power / SoC (B8) pause the battery scope and release
- every Phase 3 release path covers the battery (emergency stop, shutdown, mode to shadow,
  site/device trip, reconnect, crash recovery, re-mapped battery via its identity)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…nts (WP10)

- controller.battery.BatteryIntents: grid_charge_max_w -> grid_charge_w (rounded down, within
  the battery and adapter limits; an all-or-nothing switch only at full power), discharge_lock
  -> max_discharge_w 0 or a min-SoC floor at the live SoC rounded up (never below the reserve),
  nothing planned -> ReleaseAction only while the gate holds something (None = baseline)
- only a fresh plan interval counts (core.control.battery_band_now, shared with the gate);
  reasons controller.battery.* incl. grid_charge_unsupported (Kostal REST) for the plan view
- against oscillation: intents only on change, power hysteresis, a min-SoC lock moves only a
  full step after the SoC, one intent per interval, repeats after shadow/proposed every 15 min,
  property test with flapping bands
- a held forced grid charge is never surplus for the consumers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…pi/v1/operation/battery (WP10)

- ControlStack builds the battery adapter through safety.wiring (observe-only when it cannot be
  built or a device uses the id "battery"), hands the gate its BatteryGateConfig (identity,
  model, effective reserve, effective grid-charge policy, fallback_measured, the tick's plan,
  the live price), runs the battery watch every tick and gives the controller the adapter's
  capabilities, ranges and what the gate holds
- runtime: battery section loaded and applied (rebuild, resubscribe, identity rule), devices'
  reserve guard = effective_reserve_pct with a model, set_battery_mode with the identity token
- control state: battery (identity, capabilities, modes incl. the assisted cap, limits, held,
  baseline, wanted, reasons, pause, last decision); PUT /api/v1/operation/battery {mode,
  identity} (404 observe-only, 409 stale identity); OpenAPI and frontend types regenerated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
- sim/inverter.py: the inverter's own self-consumption control as the fallback, min-SoC floor
  judged on the BMS reading, BMS drift at night, REST refresh lag and silent REST failures,
  Kostal §3.5 registers through modbus.write_register with the fallback timer (1288), 1080
  external control, hang (frozen power, writes ignored); fake HA publishes its numbers and
  modbus sensors and routes number.set_value / modbus.write_register to it
- runner: battery wiring from the scenario (generic, kostal.plenticore, kostal_modbus templates)
- scenarios modbus_heartbeat_lost, battery_reserve_drift, kostal_rest_reserve,
  inverter_hang_battery (cloud flicker, write counts), grid_charge_price_level (real planner,
  controller and gate in automatic mode)
- gate fixes found by the scenarios: the heartbeat is timed from the write (not the read-back),
  a new takeover supersedes the check of the previous release

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…013 invariants (WP10)

- ADR-0011 addendum: control-safety sign-off - the battery_not_supported rejection is lifted
  only for intents to the configured battery adapter that pass B1-B9; it stays for
  observe-only batteries and every other asset id
- architecture §4: the battery path (controller band -> BatteryAction, gate invariants,
  hardware fallback, lease and heartbeat, release paths)
- plan phase-4 deviations for PR 4-G; templates README (battery templates, driver, register
  map, hardware_fallback)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…ostal Modbus and REST

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…line reads back (review B1, M3)

- the battery release keeps the runtime under control with the ORIGINAL baseline until a
  read-back shows it (or the user set a third value, which is kept without a write); a failed
  release write or a read-back that still shows SunCore's state is retried with back-off
  (30 s doubling to 10 min) - also during an emergency stop - and never adopted as a baseline;
  while it is pending no takeover, write or heartbeat happens (latched in the runtime, so a
  healthy watchdog tick cannot clear it)
- a failed battery write is pending, so a release never mistakes SunCore's partial state for
  the user's
- generic/kostal_plenticore release raises on an unavailable entity instead of reporting
  success, and restores the user's own select option / switch state (review minor 4)
- regression tests from the reviewer's probes (many check_battery ticks, stuck lock, new
  takeover, unavailable REST number); inverter_hang_battery asserts the latch until hang_to

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…seline and fallback values (review M1, M2, minors 1, 2, 3, 8)

- B4/B5 judge ctx.target, the resolved state that is written and heartbeated: an inherited
  max_discharge_w = 0 or floor is a discharge lock (forced grid charging is none); property
  test with arbitrary baselines; regression test from the reviewer's probe
- takeover_baseline(): kostal_modbus takes None fields from the battery's own limits
  (1076/1078), never from possibly stale 1280/1282
- kostal_modbus arms 1284/1286 with the larger of the model's and the own limits and
  prepared() compares with the values it wrote (UNVERIFIED: 1076/1078 dynamics); register 5
  is a role and must match the configured byte order before any write (minor 1)
- the lease ends when the adapter refuses (no heartbeat into a refusing inverter, minor 2) and
  when no fresh plan interval covers the held state any more, also without import (minor 8)
- the settle wait after arming runs outside the gate lock (an emergency stop is not delayed)
  and the invariants are judged again under the lock right before apply() (minor 3)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…oC sets a floor, realistic battery sim (review minors 5, 6, 7)

- battery identity includes fallback_measured: marking the fallback measured lifts the
  assisted cap, so the battery drops to shadow until re-confirmed with the new token (minor 5)
- the controller reads the SoC only with Quality.OK (minor 7)
- sim: REST refresh 30 s against the 35 s settle, modbus sensor scan lag (10 s), stale 1280/
  1282 left by an earlier controller; a §3.5 takeover is never skipped because the registers
  merely show the value (not in force); price jump inside the grid-charge window ends the
  lease (scenario test); the hang latch holds until hang_to (minor 6)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…ation addendum for the PR 4-G review fixes

- ADR-0013 addendum (no decision changed): invariants in safety/battery.py, B4/B5 on the
  written state, release completes on read-back, kostal_modbus baseline/fallback, identity
  includes fallback_measured, reserve behaviour (maintainer default) answered
- plan deviations: review fixes 2026-10-26; architecture §4: release latch and lease ends

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
… write for a user value

The release's third-value shortcut compared the read-back only with
last_written or pending_action. A pending write landing after an earlier
confirmed one, or a partly applied multi-field write, was finalised as
the user's choice and SunCore's own limit stayed on the battery.

- DeviceRuntime.attempted keeps the resolved target of every write
  SunCore sent or attempted while under control (saved before apply,
  cleared when control ends).
- safety.battery.user_changed_fields: a field is the user's only if it
  differs from the baseline and from every own value; restore_target
  keeps those fields and restores the rest. The release writes that
  state and waits for the read-back; the lease's override check uses the
  same rule.
- A user change found during the release sets the override hold (next
  04:00) like the lease's override path.
- Generic adapter: the user's select option and switch state are
  remembered only before the first write attempt, never after a failed
  or partial apply.

Regression tests: reviewer probe 3, mixed multi-field case, partial write
without user change, late write on the lease, hold, driver retry;
hypothesis properties for user_changed_fields/restore_target.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…-check fixes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…te lands

When the lease's read-back shows an older SunCore state instead of the
held one, the gate now re-writes the held state through the evaluated
write path (B1-B9 on the current inputs, read-back) and releases the
battery if that write is not accepted. Adapters without a heartbeat
would otherwise run the older, unjudged state until the lease ended.
STATUS notes the accepted edge case (a user value equal to an own value
is reset at release) for the 4-H user docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants