From 594282cf7cf54743071b819cee074b8bc17f601a Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:57:14 +0100 Subject: [PATCH 01/22] fix(learning): reset every learned state through one registry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The "Gelerntes löschen" action called a fixed list of resets and missed the HA sync cache, the PV raster, PV model and weather, the forecast check, the cycle tracker and the engine's last run. Components now register a Resetter with the hub next to their saver, and the hub resets all of them in registration order, collecting errors per name. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/learn_engine.go | 12 ++ dashboard/cmd/dashboard/learn_reset_test.go | 27 ++++ dashboard/cmd/dashboard/main.go | 15 +- dashboard/internal/autolearn/engine.go | 11 ++ dashboard/internal/autolearn/forecast.go | 11 ++ dashboard/internal/autolearn/pvmodelstore.go | 11 ++ dashboard/internal/autolearn/pvraster.go | 5 + .../internal/autolearn/pvreserve_runner.go | 13 ++ dashboard/internal/autolearn/pvtracker.go | 22 +++ dashboard/internal/autolearn/reset_test.go | 133 ++++++++++++++++++ dashboard/internal/learnrec/hasync.go | 14 ++ dashboard/internal/learnrec/hub.go | 70 +++++++-- dashboard/internal/learnrec/hub_test.go | 37 +++++ 13 files changed, 369 insertions(+), 12 deletions(-) create mode 100644 dashboard/cmd/dashboard/learn_reset_test.go create mode 100644 dashboard/internal/autolearn/reset_test.go diff --git a/dashboard/cmd/dashboard/learn_engine.go b/dashboard/cmd/dashboard/learn_engine.go index 57a81824..9cd425cd 100644 --- a/dashboard/cmd/dashboard/learn_engine.go +++ b/dashboard/cmd/dashboard/learn_engine.go @@ -522,3 +522,15 @@ func loadPVRaster(path string, limits learnrec.Limits, logf func(string, ...any) } return autolearn.LoadRaster(data, limits.PVCellAzDeg, limits.PVCellElDeg) } + +// Reset setzt den Zustand der Zyklen auf leer und loescht cycles.json. Ein +// erneutes Save schreibt den leeren Stand. +func (c *cycleRunner) Reset() error { + c.mu.Lock() + c.tracker = autolearn.NewCycleTracker(nil) + c.mu.Unlock() + if err := os.Remove(c.path); err != nil && !os.IsNotExist(err) { + return fmt.Errorf("cycle state reset: %w", err) + } + return nil +} diff --git a/dashboard/cmd/dashboard/learn_reset_test.go b/dashboard/cmd/dashboard/learn_reset_test.go new file mode 100644 index 00000000..3a2ffd01 --- /dev/null +++ b/dashboard/cmd/dashboard/learn_reset_test.go @@ -0,0 +1,27 @@ +package main + +import ( + "os" + "path/filepath" + "testing" +) + +func TestCycleRunnerResetClearsStateAndFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "cycles.json") + c := newCycleRunner(path, nil, nil, func(string, ...any) {}) + if err := c.Save(); err != nil { + t.Fatal(err) + } + if err := c.Reset(); err != nil { + t.Fatalf("Reset = %v", err) + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("cycles.json still exists after Reset (err %v)", err) + } + if err := c.Save(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(path); err != nil { + t.Fatalf("Save after Reset writes no file: %v", err) + } +} diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index df4262c2..d0381dc8 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -468,6 +468,7 @@ func main() { // Abgleich mit dem Companion: holt fehlende Minuten- und 5-Minuten-Werte // fuer die Lernfunktionen, nur im RAM. learnHA := learnrec.NewHASync(time.Now, learnLimits, time.Local) + learnHub.AddResetter("hasync", learnHA) learnHub.SetOutdoor(func() string { if value, err := settingsStore.LoadSettings(); err == nil { return value.AutomationOutdoorEntity @@ -481,7 +482,9 @@ func main() { automationChecker.ObserveTick(at, automationState(), balanceRuleValues(snap.Balance), automationEntityValue) })) learnHub.AddSaver("chainwatch", chainMonitor) + learnHub.AddResetter("chainwatch", learnrec.ResetterFunc(chainMonitor.ResetLearned)) learnHub.AddSaver("chainsuggest", chainSuggest) + learnHub.AddResetter("chainsuggest", learnrec.ResetterFunc(chainSuggest.ResetLearned)) learnHub.AddSaver("autolearn", automationObserver) // Herkunft der Schaltvorgaenge: Regel, Hand oder Aussen. Die Reaktionszeiten // liegen in autolearn/reaction.json und werden vom Hub mitgesichert. @@ -491,6 +494,7 @@ func main() { originTracker := autolearn.NewTracker(reactions) learnHub.AddMinute("origin", originTracker) learnHub.AddSaver("reactions", reactions) + learnHub.AddResetter("reactions", reactions) // Demo: mit ENERGY_NODE_AUTOLEARN_FAST=1 bekommt ein leeres Tagesverzeichnis // die Demo-Profile, dazu Himmelsraster und Dachmodell. Der Block steht vor // den Trackern, die die Dateien beim Start laden. Vorhandene Dateien bleiben unberührt. @@ -538,10 +542,12 @@ func main() { pvSite.refresh() return pvTracker.Save() })) + learnHub.AddResetter("pvtracker", pvTracker) // Geometriemodell der Dachflaechen: nachts aus dem Himmelsraster neu gefittet, // nur bei Aenderung gespeichert. pvModelStore := autolearn.NewPVModelStore(filepath.Join(autolearnDir, "pvmodel.json")) learnHub.AddSaver("pvmodel", pvModelStore) + learnHub.AddResetter("pvmodel", pvModelStore) // Wetterfaktor und PV-Reserve: laeuft nach dem Tracker, damit dieselbe Minute // schon im Raster steht. Die Reserve geht ueber den Minutenrahmen in den // Tagesspeicher (Schluessel k). @@ -550,6 +556,7 @@ func main() { autolearn.LoadPVWeather(pvWeatherPath, log.Printf), pvWeatherPath) learnHub.AddMinute("pvreserve", pvReserve) learnHub.AddSaver("pvweather", pvReserve) + learnHub.AddResetter("pvweather", pvReserve) // Tagesdateien: je Minute der Rahmen, je Minute die Ereignisse des Trackers. // Die Aufbewahrung kommt aus den Einstellungen, 0 heisst 56 Tage. dayStore := autolearn.OpenDayStore(filepath.Join(autolearnDir, "days"), time.Local, func() int { @@ -560,10 +567,12 @@ func main() { }, log.Printf) learnHub.AddMinute("daystore", dayStore) learnHub.AddSaver("daystore", dayStore) + learnHub.AddResetter("daystore", dayStore) // Zyklen der Geraete: ohne Herkunftsabfrage enden alle Zyklen als self. cycles := newCycleRunner(filepath.Join(autolearnDir, "cycles.json"), dayStore, nil, log.Printf) learnHub.AddMinute("cycles", cycles) learnHub.AddSaver("cycles", cycles) + learnHub.AddResetter("cycles", cycles) // Automationen-Engine: die Erkenner laufen in eigener Goroutine, nie im // MQTT-Pfad. Die Gruppen folgen dem Schalter Muster lernen und den beiden // Gruppenschaltern darunter. Ohne lesbare Einstellungen bleibt alles an. @@ -588,6 +597,7 @@ func main() { // Prognose-Selbstpruefung des Rest-Ueberschusses, gespeichert mit dem Hub. forecastCheck := autolearn.LoadForecastCheck(filepath.Join(autolearnDir, "forecast.json"), log.Printf) learnHub.AddSaver("forecast", forecastCheck) + learnHub.AddResetter("forecast", forecastCheck) registerEnergyDetectors(automationEngine, pvReserve.Current, forecastCheck) automationEngine.Register(autolearn.BaseLoadDetector) automationEngine.Register(autolearn.BatteryDetector) @@ -647,6 +657,8 @@ func main() { } engineLoop := newEngineRunner(automationEngine, engineGroups, engineDowngrade) learnHub.AddMinute("autolearn-engine", engineLoop) + // Die Engine hat keinen Speicher, ihr Reset verwirft nur die letzte Runde. + learnHub.AddResetter("autolearn-engine", automationEngine) // Tagesanteil der Lernlast, stuendlich in den Lernstand. learnHub.AddSaver("daily-share", dailyShareSaver(automationEngine, engineGroups, &learnStateMu, &learnState, learnStatePath, time.Now)) // Vorschlaege der Gewohnheiten: nach jeder Runde durch die Gates, gespeichert @@ -794,6 +806,7 @@ func main() { mount: storageMountPoint, }) learnHub.AddMinute("minutes", minutes.store) + learnHub.AddResetter("minutes", minutes) var minuteReader learnrec.Reader = minutes.store // Der schwere Lauf liest eigene Minuten zuerst, dann Home Assistant. Vor dem Lauf // holt der Vorlauf fehlende Tage beim Companion und verwirft sie danach. @@ -1390,7 +1403,7 @@ func main() { HAMinuteDays: learnHA.Days, Reset: func() error { resetLearned(learnedStore, client) - return errors.Join(dayStore.Reset(), reactions.Reset(), chainSuggest.ResetLearned(), chainMonitor.ResetLearned(), suggestions.Reset(), minutes.Reset()) + return errors.Join(learnHub.Reset(), suggestions.Reset()) }, } handler := perfTiming.Middleware(basepath.Middleware(httpapi.NewAuthenticatedRouter(reg, configManager, settingsStore, tinytuya.NewClient( diff --git a/dashboard/internal/autolearn/engine.go b/dashboard/internal/autolearn/engine.go index 68af7f1d..14b9e752 100644 --- a/dashboard/internal/autolearn/engine.go +++ b/dashboard/internal/autolearn/engine.go @@ -605,3 +605,14 @@ func sortedDeviceIDs(devices map[string]DeviceInfo) []string { sort.Strings(ids) return ids } + +// Reset verwirft die letzte Runde, die Warteschlange und die Serien. Die Stufe +// bleibt, wie der Nutzer sie gewaehlt hat. +func (e *Engine) Reset() error { + e.mu.Lock() + defer e.mu.Unlock() + e.last = map[string][]Candidate{} + e.queue = nil + e.streak = map[string]int{} + return nil +} diff --git a/dashboard/internal/autolearn/forecast.go b/dashboard/internal/autolearn/forecast.go index 24abd9fc..1ecf759b 100644 --- a/dashboard/internal/autolearn/forecast.go +++ b/dashboard/internal/autolearn/forecast.go @@ -187,3 +187,14 @@ func (c *ForecastCheck) Save() error { c.dirty = false return nil } + +// Reset verwirft alle offenen und abgeschlossenen Prognosen und loescht die Datei. +// Die Datei wird beim naechsten Save als leerer Stand neu geschrieben. +func (c *ForecastCheck) Reset() error { + c.mu.Lock() + defer c.mu.Unlock() + c.pending = map[string]float64{} + c.days = nil + c.dirty = true + return removeIfExists(c.path) +} diff --git a/dashboard/internal/autolearn/pvmodelstore.go b/dashboard/internal/autolearn/pvmodelstore.go index d10e152c..190c357f 100644 --- a/dashboard/internal/autolearn/pvmodelstore.go +++ b/dashboard/internal/autolearn/pvmodelstore.go @@ -127,3 +127,14 @@ func (t *PVTracker) Snapshot() *Raster { defer t.mu.Unlock() return LoadRaster(t.raster.State(), t.raster.azDeg, t.raster.elDeg) } + +// Reset verwirft das Modell und loescht die Datei. Ohne Modell schreibt Save +// nichts, eine fehlende Datei ist der leere Stand. +func (s *PVModelStore) Reset() error { + s.mu.Lock() + defer s.mu.Unlock() + s.model = PVModel{} + s.ok = false + s.dirty = false + return removeIfExists(s.path) +} diff --git a/dashboard/internal/autolearn/pvraster.go b/dashboard/internal/autolearn/pvraster.go index e49cb88b..4a6c1400 100644 --- a/dashboard/internal/autolearn/pvraster.go +++ b/dashboard/internal/autolearn/pvraster.go @@ -148,6 +148,11 @@ type pvRasterState struct { Cells []pvCell `json:"cells"` } +// clear leert alle Zellen, die Zellgroesse bleibt. +func (r *Raster) clear() { + r.cells = map[[2]int]*pvCell{} +} + // State returns the raster as JSON for storage. func (r *Raster) State() []byte { st := pvRasterState{AzDeg: r.azDeg, ElDeg: r.elDeg, Cells: make([]pvCell, 0, len(r.cells))} diff --git a/dashboard/internal/autolearn/pvreserve_runner.go b/dashboard/internal/autolearn/pvreserve_runner.go index f9ee6e01..d8063ed3 100644 --- a/dashboard/internal/autolearn/pvreserve_runner.go +++ b/dashboard/internal/autolearn/pvreserve_runner.go @@ -170,3 +170,16 @@ func PVReserveDetector(current func() (float64, bool, bool)) Detector { // pvReserveStepW is the rounding step of the published PV reserve in W. const pvReserveStepW = 50.0 + +// Reset setzt den Wetterfaktor und die Reserve zurueck und loescht pvweather.json. +// Ein erneutes Save schreibt den leeren Stand. +func (r *PVReserveRunner) Reset() error { + r.mu.Lock() + defer r.mu.Unlock() + r.weather = LoadWeather(WeatherState{}) + r.saved = nil + r.have = false + r.w = 0 + r.est = false + return removeIfExists(r.path) +} diff --git a/dashboard/internal/autolearn/pvtracker.go b/dashboard/internal/autolearn/pvtracker.go index 8f55980c..d9de25b4 100644 --- a/dashboard/internal/autolearn/pvtracker.go +++ b/dashboard/internal/autolearn/pvtracker.go @@ -126,3 +126,25 @@ func (t *PVTracker) Save() error { } return nil } + +// Reset leert das Himmelsraster und loescht die Datei. Ein erneutes Save schreibt +// den leeren Raster. +func (t *PVTracker) Reset() error { + t.mu.Lock() + defer t.mu.Unlock() + t.raster.clear() + t.lastUnthrottled = false + return removeIfExists(t.path) +} + +// removeIfExists loescht path. Eine fehlende Datei ist kein Fehler, ein leerer +// Pfad heisst: keine Datei. +func removeIfExists(path string) error { + if path == "" { + return nil + } + if err := os.Remove(path); err != nil && !os.IsNotExist(err) { + return fmt.Errorf("autolearn: reset %s: %w", path, err) + } + return nil +} diff --git a/dashboard/internal/autolearn/reset_test.go b/dashboard/internal/autolearn/reset_test.go new file mode 100644 index 00000000..82d53c00 --- /dev/null +++ b/dashboard/internal/autolearn/reset_test.go @@ -0,0 +1,133 @@ +package autolearn + +import ( + "context" + "os" + "path/filepath" + "reflect" + "testing" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" +) + +func assertGone(t *testing.T, path string) { + t.Helper() + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("%s still exists after Reset (err %v)", path, err) + } +} + +func TestPVTrackerResetClearsRasterAndFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "pvraster.json") + tr := NewPVTracker(NewRaster(5, 3), nil, nil, func() string { return "2026-11-20" }, path) + tr.Raster().Add(180, 40, 1200, "2026-11-20") + if err := tr.Save(); err != nil { + t.Fatal(err) + } + if err := tr.Reset(); err != nil { + t.Fatalf("Reset = %v", err) + } + assertGone(t, path) + if n := len(tr.Raster().cells); n != 0 { + t.Fatalf("raster keeps %d cells after Reset", n) + } + if err := tr.Save(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(path); err != nil { + t.Fatalf("Save after Reset writes no file: %v", err) + } + if n := len(LoadRaster(tr.Raster().State(), 5, 3).cells); n != 0 { + t.Fatalf("saved raster after Reset has %d cells", n) + } +} + +func TestPVModelStoreResetClearsModelAndFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "pvmodel.json") + s := NewPVModelStore(path) + s.Set(PVModel{}) + if err := s.Save(); err != nil { + t.Fatal(err) + } + if err := s.Reset(); err != nil { + t.Fatalf("Reset = %v", err) + } + assertGone(t, path) + if _, ok := s.Model(); ok { + t.Fatal("model still present after Reset") + } + // Ohne Modell schreibt Save nichts: eine fehlende Datei ist der leere Stand. + if err := s.Save(); err != nil { + t.Fatal(err) + } + assertGone(t, path) +} + +func TestPVReserveRunnerResetClearsWeatherAndFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "pvweather.json") + r := NewPVReserveRunner(nil, nil, nil, LoadWeather(WeatherState{}), path) + r.weather.Observe(time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC), 1000, 1200, true) + if err := r.Save(); err != nil { + t.Fatal(err) + } + if err := r.Reset(); err != nil { + t.Fatalf("Reset = %v", err) + } + assertGone(t, path) + if !reflect.DeepEqual(r.weather.State(), LoadWeather(WeatherState{}).State()) { + t.Fatal("weather state not empty after Reset") + } + if err := r.Save(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(path); err != nil { + t.Fatalf("Save after Reset writes no file: %v", err) + } +} + +func TestForecastCheckResetClearsEntriesAndFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "forecast.json") + c := LoadForecastCheck(path, func(string, ...any) {}) + c.Record("2026-11-20", 5000) + if err := c.Save(); err != nil { + t.Fatal(err) + } + if err := c.Reset(); err != nil { + t.Fatalf("Reset = %v", err) + } + assertGone(t, path) + if c.Recorded("2026-11-20") || len(c.Pending()) != 0 { + t.Fatal("forecast entries survive Reset") + } + if err := c.Save(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(path); err != nil { + t.Fatalf("Save after Reset writes no file: %v", err) + } + if again := LoadForecastCheck(path, func(string, ...any) {}); len(again.Pending()) != 0 { + t.Fatal("reloaded check has pending days after Reset") + } +} + +func TestEngineResetClearsCandidatesKeepsLevel(t *testing.T) { + e := newTestEngine(t, learnrec.LimitsFor(learnrec.LevelBalanced, 4)) + e.Register(Detector{Name: "rule", Group: "habit", Light: true, Run: func(ctx context.Context, in *Input, device string) []Candidate { + return []Candidate{{Finding: Finding{Kind: "rule"}}} + }}) + e.Tick(at(t, "2026-11-20", "10:00"), habitOnly) + if len(e.Candidates()) != 1 { + t.Fatal("precondition: no candidates after a run") + } + if err := e.Reset(); err != nil { + t.Fatalf("Reset = %v", err) + } + if got := e.Candidates(); len(got) != 0 { + t.Fatalf("candidates after Reset = %+v", got) + } + e.Tick(at(t, "2026-11-20", "10:20"), habitOnly) + if len(e.Candidates()) != 1 { + t.Fatal("engine does not run again after Reset") + } +} diff --git a/dashboard/internal/learnrec/hasync.go b/dashboard/internal/learnrec/hasync.go index c3d4ba65..32cbf3de 100644 --- a/dashboard/internal/learnrec/hasync.go +++ b/dashboard/internal/learnrec/hasync.go @@ -314,6 +314,20 @@ func (s *HASync) Drop() { s.fiveMin = map[string]map[string]bool{} } +// Reset verwirft wie Drop den Zwischenspeicher, offene Nachfragen und Warteschlange, +// dazu die angebotenen Serien. Der Abgleich bleibt angemeldet und fragt neu an. +func (s *HASync) Reset() error { + s.mu.Lock() + defer s.mu.Unlock() + s.offered = map[string]map[string]historyexchange.Census{} + s.queue = nil + s.pending = nil + s.deadline = time.Time{} + s.days = map[string]map[string]*[minutesPerDay]float32{} + s.fiveMin = map[string]map[string]bool{} + return nil +} + // haSeriesFor uebersetzt einen Lern-Schluessel in den Serienamen des // Companion. Nur e:, b:pv und b:battery_soc sind belegt; Netz, Last und // Speicher bleiben offen, bis Vorzeichen und Einheit geprueft sind. diff --git a/dashboard/internal/learnrec/hub.go b/dashboard/internal/learnrec/hub.go index aa998874..0334d62c 100644 --- a/dashboard/internal/learnrec/hub.go +++ b/dashboard/internal/learnrec/hub.go @@ -1,6 +1,8 @@ package learnrec import ( + "errors" + "fmt" "math" "sort" "strings" @@ -34,6 +36,18 @@ type Saver interface { Save() error } +// Resetter setzt den gelernten Zustand eines Verbrauchers zurueck und loescht +// seine Dateien. Der Hub ruft Reset nur auf Wunsch des Nutzers auf. +type Resetter interface { + Reset() error +} + +// ResetterFunc macht eine Funktion zum Resetter des Hubs. +type ResetterFunc func() error + +// Reset ruft die Funktion auf. +func (f ResetterFunc) Reset() error { return f() } + // TickFunc macht eine Funktion zum TickConsumer. type TickFunc func(time.Time, energy.Snapshot) @@ -62,6 +76,11 @@ type namedTick struct { c TickConsumer } +type namedResetter struct { + name string + r Resetter +} + type namedSaver struct { name string s Saver @@ -84,17 +103,18 @@ type devAcc struct { // Hub verteilt Beobachtungen an Verbraucher und sichert die Saver stuendlich. // Consumer duerfen den Hub nicht selbst aufrufen, sonst blockiert der Mutex. type Hub struct { - mu sync.Mutex - loc *time.Location - limits func() Limits - logf func(string, ...any) - minutes []namedMinute - replays []namedReplay - ticks []namedTick - savers []*namedSaver - minute time.Time - acc map[string]*devAcc - balance map[string]float64 + mu sync.Mutex + loc *time.Location + limits func() Limits + logf func(string, ...any) + minutes []namedMinute + replays []namedReplay + ticks []namedTick + savers []*namedSaver + resetters []namedResetter + minute time.Time + acc map[string]*devAcc + balance map[string]float64 // outdoorID liefert die unique_id der Aussentemperatur-Entitaet. outdoor // sammelt deren Beobachtungen in der laufenden Minute. outdoorID func() string @@ -448,3 +468,31 @@ func (h *Hub) Stats() map[string]time.Duration { } return out } + +// AddResetter meldet einen Zuruecksetzer an. Resets laufen in Anmeldereihenfolge. +func (h *Hub) AddResetter(name string, r Resetter) { + h.mu.Lock() + defer h.mu.Unlock() + h.resetters = append(h.resetters, namedResetter{name: name, r: r}) +} + +// Reset setzt alle angemeldeten Verbraucher zurueck, in Anmeldereihenfolge. Ein +// Fehler bricht nicht ab: jeder Verbraucher laeuft. Die Fehler kommen gesammelt +// zurueck, je mit dem Namen des Verbrauchers. +func (h *Hub) Reset() error { + h.mu.Lock() + list := append([]namedResetter(nil), h.resetters...) + h.mu.Unlock() + + var errs []error + for _, nr := range list { + if err := nr.r.Reset(); err != nil { + err = fmt.Errorf("%s: %w", nr.name, err) + if h.logf != nil { + h.logf("learnrec: Zuruecksetzen fehlgeschlagen: %v", err) + } + errs = append(errs, err) + } + } + return errors.Join(errs...) +} diff --git a/dashboard/internal/learnrec/hub_test.go b/dashboard/internal/learnrec/hub_test.go index b5ed55c2..7f6aecee 100644 --- a/dashboard/internal/learnrec/hub_test.go +++ b/dashboard/internal/learnrec/hub_test.go @@ -2,6 +2,7 @@ package learnrec import ( "math" + "strings" "testing" "time" @@ -382,3 +383,39 @@ func TestHubReplayWithoutRecordingDoesNothing(t *testing.T) { t.Fatalf("zero ReplayFrom: frames = %d, want 0", len(rec.frames)) } } + +func TestHubResetRunsEveryResetterAndJoinsErrors(t *testing.T) { + h := newTestHub(t, Limits{}) + var ran []string + h.AddResetter("a", ResetterFunc(func() error { ran = append(ran, "a"); return nil })) + h.AddResetter("b", ResetterFunc(func() error { ran = append(ran, "b"); return errTest("kaputt") })) + h.AddResetter("c", ResetterFunc(func() error { ran = append(ran, "c"); return nil })) + + err := h.Reset() + if strings.Join(ran, ",") != "a,b,c" { + t.Fatalf("ran %v, want all three in registration order", ran) + } + if err == nil || !strings.Contains(err.Error(), "b") || !strings.Contains(err.Error(), "kaputt") { + t.Fatalf("Reset error = %v, want it to name b and carry kaputt", err) + } +} + +func TestHubResetWithoutResettersIsNil(t *testing.T) { + if err := newTestHub(t, Limits{}).Reset(); err != nil { + t.Fatalf("Reset without resetters = %v", err) + } +} + +func TestHASyncResetClearsCacheAndQueue(t *testing.T) { + s := NewHASync(time.Now, func() Limits { return Limits{} }, time.UTC) + s.days["2026-11-20"] = map[string]*[minutesPerDay]float32{"e:1": {}} + s.fiveMin["2026-11-20"] = map[string]bool{"e:1": true} + s.queue = []haJob{{}} + s.pending = &haPending{} + if err := s.Reset(); err != nil { + t.Fatalf("Reset = %v", err) + } + if len(s.days) != 0 || len(s.fiveMin) != 0 || len(s.queue) != 0 || s.pending != nil { + t.Fatalf("Reset left days=%d fiveMin=%d queue=%d pending=%v", len(s.days), len(s.fiveMin), len(s.queue), s.pending) + } +} From 102cad01bca76f0a151edf28707b57ae73904b9b Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:59:54 +0100 Subject: [PATCH 02/22] fix(autolearn): survive a detector panic and keep results of finished devices A panicking detector now counts as finished without candidates and is logged, instead of taking the process down. The engine keeps the results per detector and device: a carried device that did not finish keeps its last result, the finished devices of a late round are adopted, and a device that no longer exists is dropped. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/engine.go | 73 +++++++++++++++++---- dashboard/internal/autolearn/engine_test.go | 40 ++++++++++- dashboard/internal/autolearn/pool.go | 14 +++- dashboard/internal/autolearn/pool_test.go | 23 +++++++ 4 files changed, 132 insertions(+), 18 deletions(-) diff --git a/dashboard/internal/autolearn/engine.go b/dashboard/internal/autolearn/engine.go index 14b9e752..d5b3c920 100644 --- a/dashboard/internal/autolearn/engine.go +++ b/dashboard/internal/autolearn/engine.go @@ -88,7 +88,9 @@ type Engine struct { lastLight time.Time lastDaily time.Time dailyDay string - last map[string][]Candidate + // last[detector][device] is the result of the last finished run of that + // device, "" for a detector without devices. + last map[string]map[string][]Candidate streak map[string]int overruns []time.Time spend []spend @@ -110,7 +112,7 @@ func NewEngine(days *DayStore, reactions *Reactions, readDoc func() ([]byte, err limits: limits, loc: loc, catchUp: engineCatchUpAfter, - last: map[string][]Candidate{}, + last: map[string]map[string][]Candidate{}, streak: map[string]int{}, } } @@ -232,24 +234,41 @@ func (e *Engine) Tick(now time.Time, groups map[string]bool) { } in := e.input(now, limits, devices) + // outs[i] is written by the task i only. It is read after the pool returns + // for the finished tasks, a late task writes its own slot and is ignored. + outs := make([][]Candidate, len(work)) tasks := make([]Task, len(work)) for i, p := range work { - p := p + i, p := i, p tasks[i] = Task{Detector: p.det.Name, Device: p.device, Run: func(ctx context.Context) []Candidate { out := p.det.Run(ctx, in, p.device) for j := range out { out[j].Detector = p.det.Name } + outs[i] = out return out }} } - done, unfinished, took := RunPool(context.Background(), limits.Workers, limits.Budget, tasks) - e.record(now, limits, work, done, unfinished, took) + _, unfinished, took := RunPool(context.Background(), limits.Workers, limits.Budget, tasks) + lost := map[string]bool{} + for _, t := range unfinished { + lost[t.Detector+"\x00"+t.Device] = true + } + results := map[string][]Candidate{} + for i, p := range work { + if key := p.det.Name + "\x00" + p.device; !lost[key] { + results[key] = outs[i] + } + } + e.record(now, limits, devices, work, unfinished, results, took) } // record stores the results of a round, the unfinished work, the overruns and -// the compute time, and sets the downgrade signal when a limit is hit. -func (e *Engine) record(now time.Time, limits learnrec.Limits, work []pending, done []Candidate, unfinished []Task, took map[string]time.Duration) { +// the compute time, and sets the downgrade signal when a limit is hit. results +// holds the candidates of every finished run by detector and device key. A +// device that did not finish keeps its last result, and a device that no longer +// exists is dropped. +func (e *Engine) record(now time.Time, limits learnrec.Limits, devices map[string]DeviceInfo, work []pending, unfinished []Task, results map[string][]Candidate, took map[string]time.Duration) { byKey := map[string]pending{} ran := map[string]bool{} for _, p := range work { @@ -262,10 +281,6 @@ func (e *Engine) record(now time.Time, limits learnrec.Limits, work []pending, d late[t.Detector] = true carry = append(carry, byKey[t.Detector+"\x00"+t.Device]) } - byDet := map[string][]Candidate{} - for _, c := range done { - byDet[c.Detector] = append(byDet[c.Detector], c) - } e.mu.Lock() defer e.mu.Unlock() @@ -277,7 +292,30 @@ func (e *Engine) record(now time.Time, limits learnrec.Limits, work []pending, d continue } e.streak[name] = 0 - e.last[name] = byDet[name] + } + // The finished devices of a late round are kept as well. + for _, p := range work { + cands, finished := results[p.det.Name+"\x00"+p.device] + if !finished { + continue + } + devs := e.last[p.det.Name] + if devs == nil { + devs = map[string][]Candidate{} + e.last[p.det.Name] = devs + } + if len(cands) == 0 { + delete(devs, p.device) + } else { + devs[p.device] = cands + } + } + for _, devs := range e.last { + for dev := range devs { + if _, ok := devices[dev]; !ok && dev != "" { + delete(devs, dev) + } + } } e.spend = append(e.spend, spend{at: now, took: took}) e.pruneLocked(now) @@ -335,7 +373,14 @@ func (e *Engine) lastInOrder() []Candidate { sort.Strings(names) var out []Candidate for _, name := range names { - out = append(out, e.last[name]...) + devs := make([]string, 0, len(e.last[name])) + for dev := range e.last[name] { + devs = append(devs, dev) + } + sort.Strings(devs) + for _, dev := range devs { + out = append(out, e.last[name][dev]...) + } } return out } @@ -611,7 +656,7 @@ func sortedDeviceIDs(devices map[string]DeviceInfo) []string { func (e *Engine) Reset() error { e.mu.Lock() defer e.mu.Unlock() - e.last = map[string][]Candidate{} + e.last = map[string]map[string][]Candidate{} e.queue = nil e.streak = map[string]int{} return nil diff --git a/dashboard/internal/autolearn/engine_test.go b/dashboard/internal/autolearn/engine_test.go index 460d8e61..7aa91271 100644 --- a/dashboard/internal/autolearn/engine_test.go +++ b/dashboard/internal/autolearn/engine_test.go @@ -327,19 +327,19 @@ func TestEngineShareLimitPerLevel(t *testing.T) { // 6 % of one core over 24 hours: over the eco limit, under the others. six := map[string]time.Duration{"x": 5184 * time.Second} e := newTestEngine(t, eco) - e.record(now, eco, nil, nil, nil, six) + e.record(now, eco, nil, nil, nil, nil, six) if !e.Downgrade() { t.Fatal("eco: 6 % share did not ask for a downgrade") } e = newTestEngine(t, balanced) - e.record(now, balanced, nil, nil, nil, six) + e.record(now, balanced, nil, nil, nil, nil, six) if e.Downgrade() { t.Fatal("balanced: 6 % share asked for a downgrade, want none") } // 12 % is over the limit of the other levels. twelve := map[string]time.Duration{"x": 10368 * time.Second} e = newTestEngine(t, balanced) - e.record(now, balanced, nil, nil, nil, twelve) + e.record(now, balanced, nil, nil, nil, nil, twelve) if !e.Downgrade() { t.Fatal("balanced: 12 % share did not ask for a downgrade") } @@ -400,3 +400,37 @@ func TestEnginePreparerWrapsOnlyTheDailyRun(t *testing.T) { t.Fatalf("der Erkenner muss im Lauf laufen, runs = %d", runs.Load()) } } + +func TestEngineCarryKeepsOtherDevices(t *testing.T) { + limits := learnrec.LimitsFor(learnrec.LevelBalanced, 4) + limits.Workers = 1 + limits.Budget = 20 * time.Millisecond + limits.LightEvery = 15 * time.Minute + e := newTestEngine(t, limits) + e.devices = func() map[string]DeviceInfo { + return map[string]DeviceInfo{"A": {}, "B": {}} + } + // B overruns in the daily round only. A finishes there. + var slowB atomic.Bool + slowB.Store(true) + e.Register(Detector{Name: "per", Group: "habit", Light: false, PerDevice: true, Run: func(ctx context.Context, in *Input, device string) []Candidate { + if device == "B" && slowB.Load() { + <-ctx.Done() + return nil + } + return []Candidate{{Finding: Finding{Kind: device}}} + }}) + e.Register(Detector{Name: "tick", Group: "habit", Light: true, Run: func(ctx context.Context, in *Input, device string) []Candidate { + return nil + }}) + + e.Tick(at(t, "2026-11-20", "03:00"), habitOnly) // start, only the light detector is due + e.Tick(at(t, "2026-11-20", "03:30"), habitOnly) // daily round: A done, B carried + slowB.Store(false) + e.Tick(at(t, "2026-11-20", "03:45"), habitOnly) // light round runs the carried B + + got := e.Candidates() + if len(got) != 2 || got[0].Finding.Kind != "A" || got[1].Finding.Kind != "B" { + t.Fatalf("candidates = %+v, want the results of A (daily round) and B (carried)", got) + } +} diff --git a/dashboard/internal/autolearn/pool.go b/dashboard/internal/autolearn/pool.go index 61e38e11..a4a25286 100644 --- a/dashboard/internal/autolearn/pool.go +++ b/dashboard/internal/autolearn/pool.go @@ -2,6 +2,7 @@ package autolearn import ( "context" + "log" "sort" "sync" "time" @@ -65,7 +66,18 @@ func RunPool(ctx context.Context, workers int, budget time.Duration, tasks []Tas // The result channel is buffered, so a task that outlives the // budget does not block on the send after the pool has moved on. ch := make(chan []Candidate, 1) - go func() { ch <- t.Run(ctx) }() + go func() { + // A panicking task counts as finished without candidates, so + // one detector bug does not stop the daemon. + var out []Candidate + defer func() { + if r := recover(); r != nil { + log.Printf("autolearn: detector %s/%s panicked: %v", t.Detector, t.Device, r) + } + ch <- out + }() + out = t.Run(ctx) + }() var out []Candidate finished := false select { diff --git a/dashboard/internal/autolearn/pool_test.go b/dashboard/internal/autolearn/pool_test.go index e43ef3b1..7f0a21a0 100644 --- a/dashboard/internal/autolearn/pool_test.go +++ b/dashboard/internal/autolearn/pool_test.go @@ -136,3 +136,26 @@ func TestPoolUnfinishedKeepsInputOrderWithWorkers(t *testing.T) { } } } + +func TestRunPoolRecoversPanic(t *testing.T) { + ok := func(name string) Task { + return Task{Detector: name, Run: func(ctx context.Context) []Candidate { + return []Candidate{{Detector: name}} + }} + } + boom := Task{Detector: "boom", Device: "dev", Run: func(ctx context.Context) []Candidate { + panic("detector bug") + }} + + done, unfinished, took := RunPool(context.Background(), 2, 5*time.Second, []Task{ok("a"), boom, ok("c")}) + + if len(done) != 2 || done[0].Detector != "a" || done[1].Detector != "c" { + t.Fatalf("done = %+v, want the candidates of a and c", done) + } + if len(unfinished) != 0 { + t.Fatalf("unfinished = %d, want 0: a panicking task counts as finished", len(unfinished)) + } + if _, ok := took["boom"]; !ok { + t.Fatalf("took has no entry for the panicking task: %v", took) + } +} From bde4c6a3fbfab242feef0c71de835bb81bd2c6e4 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:03:57 +0100 Subject: [PATCH 03/22] fix(autolearn): keep harm first, cap open suggestions and give every value a spread Harmful findings sort before all others, and the detector variety is chosen inside each severity. Hidden findings leave the list before the cap but keep their shown entry. Every candidate value now has a spread: flapping the MAD of the gaps, threshold the MAD of the daily peaks, no-effect and overridden one case, surplus window the MAD of the day starts, with the window start added as a value. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/learn_suggestions.go | 2 +- .../internal/autolearn/detect_flapping.go | 1 + .../internal/autolearn/detect_noeffect.go | 1 + .../internal/autolearn/detect_overridden.go | 1 + .../internal/autolearn/detect_surplus.go | 24 ++- .../internal/autolearn/detect_threshold.go | 25 ++- dashboard/internal/autolearn/gates.go | 111 +++++++++---- dashboard/internal/autolearn/gates_test.go | 154 ++++++++++++++++-- .../internal/autolearn/replaycheck_test.go | 8 +- 9 files changed, 270 insertions(+), 57 deletions(-) diff --git a/dashboard/cmd/dashboard/learn_suggestions.go b/dashboard/cmd/dashboard/learn_suggestions.go index 6ea214c0..e28e0fd6 100644 --- a/dashboard/cmd/dashboard/learn_suggestions.go +++ b/dashboard/cmd/dashboard/learn_suggestions.go @@ -133,7 +133,7 @@ func gateSuggestions(book *suggestionBook, source suggestionCandidates, readDoc } } before := shownIDs(book.state.Shown()) - out, shown := autolearn.Gate(cands, doc, book.state.Shown()) + out, shown := autolearn.Gate(cands, doc, book.state.Shown(), autolearn.GateOptions{Hidden: book.state.Hidden}) for i := range out { f := &out[i] // The temperature limit is the cure for warm weather, so it is never rested. diff --git a/dashboard/internal/autolearn/detect_flapping.go b/dashboard/internal/autolearn/detect_flapping.go index 2d3a6e31..5e9b68b4 100644 --- a/dashboard/internal/autolearn/detect_flapping.go +++ b/dashboard/internal/autolearn/detect_flapping.go @@ -165,6 +165,7 @@ func flappingCandidate(device string, info DeviceInfo, rules map[string]Rule, id Lower: 1, Limit: 1, Values: map[string]float64{"period_s": period}, + Spread: map[string]float64{"period_s": MADScale(gaps)}, } } diff --git a/dashboard/internal/autolearn/detect_noeffect.go b/dashboard/internal/autolearn/detect_noeffect.go index 97348cce..2aa1e1ea 100644 --- a/dashboard/internal/autolearn/detect_noeffect.go +++ b/dashboard/internal/autolearn/detect_noeffect.go @@ -166,6 +166,7 @@ func noEffectCandidate(device string, info DeviceInfo, rule Rule, t *noEffectTal Lower: lower, Limit: noEffectLimit, Values: map[string]float64{"share": share}, + Spread: map[string]float64{"share": 1 / float64(t.considered)}, } } diff --git a/dashboard/internal/autolearn/detect_overridden.go b/dashboard/internal/autolearn/detect_overridden.go index 2af9fadc..9cbc1016 100644 --- a/dashboard/internal/autolearn/detect_overridden.go +++ b/dashboard/internal/autolearn/detect_overridden.go @@ -369,6 +369,7 @@ func overriddenCandidate(device string, in *Input, rule Rule, sw []overrideSwitc Lower: lower, Limit: overriddenLimit, Values: map[string]float64{"share": share}, + Spread: map[string]float64{"share": 1 / float64(n)}, }, true } diff --git a/dashboard/internal/autolearn/detect_surplus.go b/dashboard/internal/autolearn/detect_surplus.go index 639565a0..49842517 100644 --- a/dashboard/internal/autolearn/detect_surplus.go +++ b/dashboard/internal/autolearn/detect_surplus.go @@ -188,7 +188,12 @@ func surWinCandidate(ctx context.Context, in *Input, device string, p, cycle flo Limit: surWinWindowLimit, HalvesAgree: true, Benefit: benefit, - Values: map[string]float64{"window_quarters": float64(n), "on_w": onW}, + Values: map[string]float64{"window_quarters": float64(n), "on_w": onW, "start": float64(start * 15)}, + Spread: map[string]float64{ + "window_quarters": 1, + "on_w": surWinRoundW, + "start": MADScale(surWinDayStarts(days, start, n, p+surWinReserveMarginW, pick)), + }, } if verdict, b, err := surWinReplay(ctx, in, device, id, onW, source, p, peak, cycle, runS); err == nil && verdict != nil { cand.Replay = verdict @@ -446,3 +451,20 @@ func surWinClock(q int) string { m := q * 15 return fmt.Sprintf("%02d:%02d", m/60%24, m%60) } + +// surWinDayStarts is the minute of the day on which each day first reached the +// threshold inside the window [start, start+n). Days that never reached it in +// the window are left out. +func surWinDayStarts(days []surWinDay, start, n int, threshold float64, pick func(*surWinDay) *[dayQuarters]float64) []float64 { + var out []float64 + for i := range days { + xs := pick(&days[i]) + for q := start; q < start+n && q < dayQuarters; q++ { + if days[i].seen[q] && xs[q] >= threshold { + out = append(out, float64(q*15)) + break + } + } + } + return out +} diff --git a/dashboard/internal/autolearn/detect_threshold.go b/dashboard/internal/autolearn/detect_threshold.go index ae90f2fd..4999e4c1 100644 --- a/dashboard/internal/autolearn/detect_threshold.go +++ b/dashboard/internal/autolearn/detect_threshold.go @@ -176,7 +176,9 @@ func thresholdRule(ctx context.Context, in *Input, r Rule, minutes []ReplayMinut kwh = (chosenEval.ePV - todayPt.ePV) * 7 / nDays } joint := in.Limits.ReplayJointHold - return thresholdCandidate(in, r, device, p, code, kwh, gainWeek, today, soll, chosen, joint, estimate, nDays, chosenEval), true + cand := thresholdCandidate(in, r, device, p, code, kwh, gainWeek, today, soll, chosen, joint, estimate, nDays, chosenEval) + cand.Spread = thresholdSpread(minutes, loc, r.Conditions[idx].Field) + return cand, true } // thresholdTarget holds what does not change over the grid of one rule. @@ -446,3 +448,24 @@ func thresholdSplit(minutes []ReplayMinute, loc *time.Location, days []string) i } return len(minutes) } + +// thresholdSpread is the spread of the values of a threshold proposal. The +// threshold and its proposal move with the daily peak of the signal the rule +// reads, so their spread is 1,4826 · MAD of those daily peaks. The gain is +// judged against the smallest gain that counts. +func thresholdSpread(minutes []ReplayMinute, loc *time.Location, field string) map[string]float64 { + peaks := map[string]float64{} + for _, m := range minutes { + d := m.At.In(loc).Format(dayLayout) + v := m.Balance[field] + if p, ok := peaks[d]; !ok || v > p { + peaks[d] = v + } + } + xs := make([]float64, 0, len(peaks)) + for _, v := range peaks { + xs = append(xs, v) + } + dailySpread := MADScale(xs) + return map[string]float64{"today": dailySpread, "soll": dailySpread, "gain_week": thresholdMinGainKWhWeek} +} diff --git a/dashboard/internal/autolearn/gates.go b/dashboard/internal/autolearn/gates.go index 25ee988c..42f6ba40 100644 --- a/dashboard/internal/autolearn/gates.go +++ b/dashboard/internal/autolearn/gates.go @@ -32,16 +32,29 @@ const ( // unchecked for compatibility. var prefillRules = map[string]func(prefill map[string]any) (Rule, bool){} +// GateOptions are the inputs of Gate that the caller knows and the candidates +// do not. The zero value hides nothing and has no targets. +type GateOptions struct { + // Hidden reports a finding that was dismissed or postponed. Nil hides nothing. + Hidden func(id string) bool + // Targets returns the targets of a rule ID. Nil means no targets. + Targets func(ruleID string) []Target +} + +// scored is a candidate that passed the gates, with its finding as shown and +// its sort score. +type scored struct { + finding Finding + cand Candidate + score float64 +} + // Gate runs the candidates through the gates of spec 15.8: minimum data, // benefit, confidence, compatibility with the rule document and calm. The // result is ordered and capped. prev holds what was shown last time, keyed by -// finding ID, and shown is what is shown now. -func Gate(cands []Candidate, doc Doc, prev map[string]Shown) (out []Finding, shown map[string]Shown) { - type scored struct { - finding Finding - cand Candidate - score float64 - } +// finding ID, and shown is what is shown now. Hidden findings do not count +// against the cap. +func Gate(cands []Candidate, doc Doc, prev map[string]Shown, opt GateOptions) (out []Finding, shown map[string]Shown) { var kept []scored for _, c := range cands { f := c.Finding @@ -95,38 +108,26 @@ func Gate(cands []Candidate, doc Doc, prev map[string]Shown) (out []Finding, sho return kept[i].finding.ID < kept[j].finding.ID }) - // The first slots take at most gatePerDetector of each detector. The rest - // keep their order behind them. - used := make([]bool, len(kept)) - perDetector := map[string]int{} - picked := 0 - for i, s := range kept { - if picked == gateTopSlots { - break - } - if perDetector[s.cand.Detector] >= gatePerDetector { + // A hidden finding leaves the open list before the cap, but keeps its + // entry in shown, so the calm rule and Since do not jump. + shown = make(map[string]Shown, len(kept)) + var open []scored + for _, s := range kept { + id := s.finding.ID + if opt.Hidden != nil && opt.Hidden(id) { + if last, ok := prev[id]; ok { + shown[id] = last + } continue } - perDetector[s.cand.Detector]++ - used[i] = true - picked++ - } - var ordered []scored - for i, s := range kept { - if used[i] { - ordered = append(ordered, s) - } - } - for i, s := range kept { - if !used[i] { - ordered = append(ordered, s) - } + open = append(open, s) } + + ordered := gateOrder(open) if len(ordered) > gateMaxFindings { ordered = ordered[:gateMaxFindings] } - shown = make(map[string]Shown, len(ordered)) for _, s := range ordered { last, seen := prev[s.finding.ID] entry := Shown{Lower: s.cand.Lower, Values: copyValues(s.cand.Values)} @@ -142,6 +143,52 @@ func Gate(cands []Candidate, doc Doc, prev map[string]Shown) (out []Finding, sho return out, shown } +// gateOrder puts the harmful findings ("bad") before all others. The detector +// variety is chosen inside each severity, so a benefit never pushes out a harm +// from the top slots. Both lists keep the order of kept, which is by score. +func gateOrder(kept []scored) []scored { + var harm, rest []scored + for _, s := range kept { + if s.finding.Severity == "bad" { + harm = append(harm, s) + } else { + rest = append(rest, s) + } + } + return append(gateVariety(harm), gateVariety(rest)...) +} + +// gateVariety lets at most gatePerDetector of each detector into the first +// gateTopSlots places. The rest keep their order behind them. +func gateVariety(list []scored) []scored { + used := make([]bool, len(list)) + perDetector := map[string]int{} + picked := 0 + for i, s := range list { + if picked == gateTopSlots { + break + } + if perDetector[s.cand.Detector] >= gatePerDetector { + continue + } + perDetector[s.cand.Detector]++ + used[i] = true + picked++ + } + ordered := make([]scored, 0, len(list)) + for i, s := range list { + if used[i] { + ordered = append(ordered, s) + } + } + for i, s := range list { + if !used[i] { + ordered = append(ordered, s) + } + } + return ordered +} + // displayFinding returns f with the stabilised values in its summary params // and in the prefills of its fixes. Only keys that exist in those maps change, // the keys "time" and "latest" are shown as HH:MM. f and its maps are not modified. diff --git a/dashboard/internal/autolearn/gates_test.go b/dashboard/internal/autolearn/gates_test.go index 6b822ee7..e85a4e4b 100644 --- a/dashboard/internal/autolearn/gates_test.go +++ b/dashboard/internal/autolearn/gates_test.go @@ -1,10 +1,12 @@ package autolearn import ( + "context" "encoding/json" "fmt" "math" "testing" + "time" ) // gateCand is a habit candidate with a benefit in kWh per week that passes @@ -32,7 +34,7 @@ func gateIDs(out []Finding) []string { } func TestGateKeepsBorderlineCandidateAsHigh(t *testing.T) { - out, shown := Gate([]Candidate{gateCand("a", "x", 1, 2, 2, true)}, Doc{}, nil) + out, shown := Gate([]Candidate{gateCand("a", "x", 1, 2, 2, true)}, Doc{}, nil, GateOptions{}) if len(out) != 1 { t.Fatalf("got %d findings, want 1", len(out)) } @@ -45,7 +47,7 @@ func TestGateKeepsBorderlineCandidateAsHigh(t *testing.T) { } func TestGateDropsCandidateBelowLimitWithoutPrevious(t *testing.T) { - out, _ := Gate([]Candidate{gateCand("a", "x", 1, 1.9, 2, true)}, Doc{}, nil) + out, _ := Gate([]Candidate{gateCand("a", "x", 1, 1.9, 2, true)}, Doc{}, nil, GateOptions{}) if len(out) != 0 { t.Errorf("got %v, want none", gateIDs(out)) } @@ -54,7 +56,7 @@ func TestGateDropsCandidateBelowLimitWithoutPrevious(t *testing.T) { func TestGateKeepsShownCandidateAboveSeventyFivePercent(t *testing.T) { prev := map[string]Shown{"a": {Lower: 2}} - out, _ := Gate([]Candidate{gateCand("a", "x", 1, 1.6, 2, false)}, Doc{}, prev) + out, _ := Gate([]Candidate{gateCand("a", "x", 1, 1.6, 2, false)}, Doc{}, prev, GateOptions{}) if len(out) != 1 { t.Fatalf("80 %%: got %v, want the candidate to stay", gateIDs(out)) } @@ -62,7 +64,7 @@ func TestGateKeepsShownCandidateAboveSeventyFivePercent(t *testing.T) { t.Errorf("80 %%: Confidence = %q, want estimate", out[0].Confidence) } - out, _ = Gate([]Candidate{gateCand("a", "x", 1, 1.4, 2, false)}, Doc{}, prev) + out, _ = Gate([]Candidate{gateCand("a", "x", 1, 1.4, 2, false)}, Doc{}, prev, GateOptions{}) if len(out) != 0 { t.Errorf("70 %%: got %v, want none", gateIDs(out)) } @@ -76,7 +78,7 @@ func TestGateQuietValuesChangeOnlyBeyondSpread(t *testing.T) { prev := map[string]Shown{"a": {Lower: 2, Values: map[string]float64{"time": 1350}, Since: 5}} cand.Values = map[string]float64{"time": 1355} - _, shown := Gate([]Candidate{cand}, Doc{}, prev) + _, shown := Gate([]Candidate{cand}, Doc{}, prev, GateOptions{}) if got := shown["a"].Values["time"]; got != 1350 { t.Errorf("22:35 within spread: shown time = %v, want 1350 (22:30)", got) } @@ -85,7 +87,7 @@ func TestGateQuietValuesChangeOnlyBeyondSpread(t *testing.T) { } cand.Values = map[string]float64{"time": 1370} - _, shown = Gate([]Candidate{cand}, Doc{}, prev) + _, shown = Gate([]Candidate{cand}, Doc{}, prev, GateOptions{}) if got := shown["a"].Values["time"]; got != 1370 { t.Errorf("22:50 beyond spread: shown time = %v, want 1370", got) } @@ -104,13 +106,13 @@ func TestGateDropsDuplicateOfExistingRule(t *testing.T) { cand := gateCand("a", "x", 1, 2, 2, true) cand.Finding.Apply = []Fix{{Code: "fix", Template: "test_tpl"}} - if out, _ := Gate([]Candidate{cand}, doc, nil); len(out) != 0 { + if out, _ := Gate([]Candidate{cand}, doc, nil, GateOptions{}); len(out) != 0 { t.Errorf("duplicate kept: %v", gateIDs(out)) } // Without a rule to build from, the candidate is kept. cand.Finding.Apply = []Fix{{Code: "fix", Template: "unknown_tpl"}} - if out, _ := Gate([]Candidate{cand}, doc, nil); len(out) != 1 { + if out, _ := Gate([]Candidate{cand}, doc, nil, GateOptions{}); len(out) != 1 { t.Errorf("unbuildable template dropped: %v", gateIDs(out)) } } @@ -122,7 +124,7 @@ func TestGateOrderLimitsTwoPerDetectorInTopThree(t *testing.T) { gateCand("a3", "a", 7, 2, 2, true), gateCand("b1", "b", 1, 2, 2, true), } - out, _ := Gate(cands, Doc{}, nil) + out, _ := Gate(cands, Doc{}, nil, GateOptions{}) if len(out) != 4 { t.Fatalf("got %v, want 4", gateIDs(out)) } @@ -147,7 +149,7 @@ func TestGateCapsAtTwentyAndPutsBadFirst(t *testing.T) { Confidence: "high", RuleIDs: []string{"r"}}, Detector: "check", NEff: 30, MinNEff: 10} cands = append(cands, bad) - out, _ := Gate(cands, Doc{}, nil) + out, _ := Gate(cands, Doc{}, nil, GateOptions{}) if len(out) != 20 { t.Fatalf("got %d findings, want 20", len(out)) } @@ -163,7 +165,7 @@ func TestGateCheckGroupOnlyNeedsMinimumData(t *testing.T) { Confidence: "high", RuleIDs: []string{"r"}}, Detector: "check", NEff: 30, MinNEff: 10, HalvesAgree: false} - out, _ := Gate([]Candidate{low, ok}, Doc{}, nil) + out, _ := Gate([]Candidate{low, ok}, Doc{}, nil, GateOptions{}) if got := gateIDs(out); len(got) != 1 || got[0] != "check:ok" { t.Fatalf("got %v, want [check:ok]", got) } @@ -175,7 +177,7 @@ func TestGateCheckGroupOnlyNeedsMinimumData(t *testing.T) { func TestGateRuntimePresetHighWithoutLimitStaysHigh(t *testing.T) { cand := gateCand("runtime:heater", "runtime", 1, 0, 0, false) cand.Finding.Confidence = "high" - out, _ := Gate([]Candidate{cand}, Doc{}, nil) + out, _ := Gate([]Candidate{cand}, Doc{}, nil, GateOptions{}) if len(out) != 1 || out[0].Confidence != "high" { t.Fatalf("got %+v, want one high finding", out) } @@ -183,14 +185,14 @@ func TestGateRuntimePresetHighWithoutLimitStaysHigh(t *testing.T) { func TestGateEstimateRules(t *testing.T) { onlyLower := gateCand("a", "x", 1, 2, 2, false) - out, _ := Gate([]Candidate{onlyLower}, Doc{}, nil) + out, _ := Gate([]Candidate{onlyLower}, Doc{}, nil, GateOptions{}) if len(out) != 1 || out[0].Confidence != "estimate" { t.Errorf("Lower >= Limit without halves: got %+v, want estimate", out) } preset := gateCand("b", "x", 1, 1, 2, false) preset.Finding.Confidence = "estimate" - out, _ = Gate([]Candidate{preset}, Doc{}, nil) + out, _ = Gate([]Candidate{preset}, Doc{}, nil, GateOptions{}) if len(out) != 1 || out[0].Confidence != "estimate" { t.Errorf("preset estimate: got %+v, want estimate", out) } @@ -198,7 +200,7 @@ func TestGateEstimateRules(t *testing.T) { func TestGateDropsBelowBenefitMinimum(t *testing.T) { small := gateCand("a", "x", 0.4, 2, 2, true) - out, _ := Gate([]Candidate{small}, Doc{}, nil) + out, _ := Gate([]Candidate{small}, Doc{}, nil, GateOptions{}) if len(out) != 0 { t.Errorf("0.4 kWh/week kept: %v", gateIDs(out)) } @@ -224,7 +226,7 @@ func gateClockCand(minute float64) Candidate { func TestGateShowsStabilisedTime(t *testing.T) { prev := map[string]Shown{"switch_time:lamp:off:0:2230": {Lower: 2, Values: map[string]float64{"time": 1350}}} - out, _ := Gate([]Candidate{gateClockCand(1355)}, Doc{}, prev) + out, _ := Gate([]Candidate{gateClockCand(1355)}, Doc{}, prev, GateOptions{}) if len(out) != 1 { t.Fatalf("got %v, want one finding", gateIDs(out)) } @@ -238,7 +240,7 @@ func TestGateShowsStabilisedTime(t *testing.T) { t.Errorf("ID = %q, want unchanged", out[0].ID) } - out, _ = Gate([]Candidate{gateClockCand(1370)}, Doc{}, prev) + out, _ = Gate([]Candidate{gateClockCand(1370)}, Doc{}, prev, GateOptions{}) if len(out) != 1 { t.Fatalf("got %v, want one finding", gateIDs(out)) } @@ -274,7 +276,7 @@ func TestGateShowsStabilisedLatestAsClock(t *testing.T) { cand.Spread = map[string]float64{"latest": 8} prev := map[string]Shown{"shift:spuelmaschine": {Lower: 2, Values: map[string]float64{"latest": 1245}}} - out, _ := Gate([]Candidate{cand}, Doc{}, prev) + out, _ := Gate([]Candidate{cand}, Doc{}, prev, GateOptions{}) if len(out) != 1 { t.Fatalf("got %v, want one finding", gateIDs(out)) } @@ -285,3 +287,119 @@ func TestGateShowsStabilisedLatestAsClock(t *testing.T) { t.Errorf("prefill latest = %v, want 20:45", got) } } + +func TestGateHarmFirstAfterVariety(t *testing.T) { + bad := func(id string, kwh float64) Candidate { + c := gateCand(id, "x", kwh, 2, 2, true) + c.Finding.Severity = "bad" + return c + } + cands := []Candidate{ + bad("x1", 9), + bad("x2", 8), + bad("x3", 7), + gateCand("y1", "y", 1, 2, 2, true), + } + out, _ := Gate(cands, Doc{}, nil, GateOptions{}) + want := []string{"x1", "x2", "x3", "y1"} + if got := gateIDs(out); fmt.Sprint(got) != fmt.Sprint(want) { + t.Errorf("order = %v, want %v", got, want) + } +} + +func TestGateCapCountsOpen(t *testing.T) { + var cands []Candidate + for i := 0; i < 21; i++ { + cands = append(cands, gateCand(fmt.Sprintf("c%02d", i), fmt.Sprintf("d%02d", i), float64(30-i), 2, 2, true)) + } + prev := map[string]Shown{"c00": {Lower: 2, Since: 42}} + opt := GateOptions{Hidden: func(id string) bool { return id == "c00" }} + out, shown := Gate(cands, Doc{}, prev, opt) + if len(out) != 20 { + t.Fatalf("got %d findings, want 20", len(out)) + } + for _, f := range out { + if f.ID == "c00" { + t.Errorf("hidden finding c00 is in the result %v", gateIDs(out)) + } + } + if got := shown["c00"].Since; got != 42 { + t.Errorf("hidden finding Since = %d, want 42 kept in shown", got) + } +} + +// spreadCovers reports whether every key of the values has a spread. +func spreadCovers(t *testing.T, c Candidate) { + t.Helper() + for k := range c.Values { + s, ok := c.Spread[k] + if !ok { + t.Errorf("%s: value %q has no spread", c.Detector, k) + continue + } + if !(s > 0) { + t.Errorf("%s: spread of %q = %v, want > 0", c.Detector, k, s) + } + } +} + +func TestFlappingCandidateSpreadOfGaps(t *testing.T) { + gaps := []float64{300, 330, 270, 310, 290} + rules := map[string]Rule{} + events := []ruleEvent{{at: 1}, {at: 2}} + c := flappingCandidate("dev", DeviceInfo{}, rules, []string{"r1", "r2"}, "r1", 60, Median(gaps), gaps, events, false) + spreadCovers(t, c) + if want := MADScale(gaps); c.Spread["period_s"] != want { + t.Errorf("period spread = %v, want %v", c.Spread["period_s"], want) + } +} + +func TestNoEffectCandidateSpreadIsOneCase(t *testing.T) { + tally := &noEffectTally{considered: 20, failures: 5, offline: 5, failAt: []int64{1, 2, 3, 4, 5}} + c := noEffectCandidate("dev", DeviceInfo{}, Rule{ID: "r1"}, tally, 0.3) + spreadCovers(t, c) + if want := 1.0 / 20; c.Spread["share"] != want { + t.Errorf("share spread = %v, want %v", c.Spread["share"], want) + } +} + +func TestSurplusCandidateSpreadOfWindowStart(t *testing.T) { + const p = 1000.0 + var days []surWinDay + for i := 0; i < 4; i++ { + d := surWinDay{weight: 1} + for q := 0; q < dayQuarters; q++ { + d.seen[q] = true + } + for q := 40 + i; q < 48; q++ { + d.without[q] = p + surWinReserveMarginW + 500 + } + days = append(days, d) + } + pick := func(d *surWinDay) *[dayQuarters]float64 { return &d.without } + c := surWinCandidate(context.Background(), &Input{}, "dev", p, 1500, "export", 40, 8, 2, 1, days, 30, pick) + spreadCovers(t, c) + if got := c.Spread["start"]; !(got > 0) { + t.Errorf("start spread = %v, want > 0", got) + } +} + +func TestThresholdSpreadOfDailyPeaks(t *testing.T) { + loc := time.UTC + var minutes []ReplayMinute + for day := 0; day < 4; day++ { + start := time.Date(2026, 11, 10+day, 0, 0, 0, 0, loc) + for m := 0; m < 1440; m += 60 { + v := 100.0 + if m == 720 { + v = float64(1000 + 200*day) + } + minutes = append(minutes, ReplayMinute{At: start.Add(time.Duration(m) * time.Minute), Balance: map[string]float64{"grid_export": v}}) + } + } + spread := thresholdSpread(minutes, loc, "grid_export") + spreadCovers(t, Candidate{Detector: "threshold_rating", Values: map[string]float64{"today": 0, "soll": 0, "gain_week": 0}, Spread: spread}) + if want := thresholdMinGainKWhWeek; spread["gain_week"] != want { + t.Errorf("gain_week spread = %v, want %v", spread["gain_week"], want) + } +} diff --git a/dashboard/internal/autolearn/replaycheck_test.go b/dashboard/internal/autolearn/replaycheck_test.go index c5105e71..c784d8ce 100644 --- a/dashboard/internal/autolearn/replaycheck_test.go +++ b/dashboard/internal/autolearn/replaycheck_test.go @@ -103,21 +103,21 @@ func replayCand(kwh float64, base, alt ReplayResult) Candidate { func TestGateDropsReplayWithMoreGridThanExport(t *testing.T) { c := replayCand(1, ReplayResult{GridWh: 0, ExportWh: 1000}, ReplayResult{GridWh: 1500, ExportWh: 0}) - if out, _ := Gate([]Candidate{c}, Doc{}, nil); len(out) != 0 { + if out, _ := Gate([]Candidate{c}, Doc{}, nil, GateOptions{}); len(out) != 0 { t.Fatalf("kept %v, want dropped, the suggestion draws more from the grid than it uses", gateIDs(out)) } } func TestGateKeepsReplayWhenExportCoversGrid(t *testing.T) { c := replayCand(1, ReplayResult{GridWh: 0, ExportWh: 1000}, ReplayResult{GridWh: 500, ExportWh: 0}) - if out, _ := Gate([]Candidate{c}, Doc{}, nil); len(out) != 1 { + if out, _ := Gate([]Candidate{c}, Doc{}, nil, GateOptions{}); len(out) != 1 { t.Fatalf("kept %v, want one suggestion", gateIDs(out)) } } func TestGateDropsReplayBelowBenefitMinimum(t *testing.T) { c := replayCand(0.3, ReplayResult{}, ReplayResult{}) - if out, _ := Gate([]Candidate{c}, Doc{}, nil); len(out) != 0 { + if out, _ := Gate([]Candidate{c}, Doc{}, nil, GateOptions{}); len(out) != 0 { t.Fatalf("kept %v, want dropped at 0,3 kWh per week", gateIDs(out)) } } @@ -125,7 +125,7 @@ func TestGateDropsReplayBelowBenefitMinimum(t *testing.T) { func TestGateCapsReplayEstimateAtEstimate(t *testing.T) { c := replayCand(1, ReplayResult{}, ReplayResult{}) c.Replay.Estimate = true - out, _ := Gate([]Candidate{c}, Doc{}, nil) + out, _ := Gate([]Candidate{c}, Doc{}, nil, GateOptions{}) if len(out) != 1 || out[0].Confidence != "estimate" { t.Fatalf("out = %+v, want one finding with confidence estimate", out) } From 420f0922214e79f0be4b378fc1b011c345f9cc2d Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:08:25 +0100 Subject: [PATCH 04/22] fix(autolearn): drop suggestions an existing rule covers and energy suggestions without replay Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/learn_suggestions.go | 7 +- dashboard/internal/autolearn/gates.go | 99 +++++++---- dashboard/internal/autolearn/gates_test.go | 100 +++++++++-- dashboard/internal/autolearn/intent.go | 176 +++++++++++++++++++ dashboard/internal/autolearn/intent_test.go | 102 +++++++++++ 5 files changed, 431 insertions(+), 53 deletions(-) create mode 100644 dashboard/internal/autolearn/intent.go create mode 100644 dashboard/internal/autolearn/intent_test.go diff --git a/dashboard/cmd/dashboard/learn_suggestions.go b/dashboard/cmd/dashboard/learn_suggestions.go index e28e0fd6..1f615fcc 100644 --- a/dashboard/cmd/dashboard/learn_suggestions.go +++ b/dashboard/cmd/dashboard/learn_suggestions.go @@ -133,7 +133,12 @@ func gateSuggestions(book *suggestionBook, source suggestionCandidates, readDoc } } before := shownIDs(book.state.Shown()) - out, shown := autolearn.Gate(cands, doc, book.state.Shown(), autolearn.GateOptions{Hidden: book.state.Hidden}) + // The switch entities of a rule come from its entity_id actions. The command + // topic table is not needed for that, so no payload check runs here. + out, shown := autolearn.Gate(cands, doc, book.state.Shown(), autolearn.GateOptions{ + Hidden: book.state.Hidden, + Targets: autolearn.RuleTargets(doc, nil), + }) for i := range out { f := &out[i] // The temperature limit is the cure for warm weather, so it is never rested. diff --git a/dashboard/internal/autolearn/gates.go b/dashboard/internal/autolearn/gates.go index 42f6ba40..e777ce67 100644 --- a/dashboard/internal/autolearn/gates.go +++ b/dashboard/internal/autolearn/gates.go @@ -23,21 +23,15 @@ const ( gateTopSlots = 3 // gatePerDetector is the most suggestions of one detector in the top slots. gatePerDetector = 2 - // probeRuleID names the prepared rule in the compatibility check. - probeRuleID = "candidate-probe" ) -// prefillRules builds the rule of a template from its prefill. A template -// without a builder, or a prefill the builder rejects, leaves the candidate -// unchecked for compatibility. -var prefillRules = map[string]func(prefill map[string]any) (Rule, bool){} - // GateOptions are the inputs of Gate that the caller knows and the candidates // do not. The zero value hides nothing and has no targets. type GateOptions struct { // Hidden reports a finding that was dismissed or postponed. Nil hides nothing. Hidden func(id string) bool - // Targets returns the targets of a rule ID. Nil means no targets. + // Targets returns the targets of a rule or scenario ID. Nil means no targets, + // so the rules cover no suggestion. Targets func(ruleID string) []Target } @@ -55,6 +49,7 @@ type scored struct { // finding ID, and shown is what is shown now. Hidden findings do not count // against the cap. func Gate(cands []Candidate, doc Doc, prev map[string]Shown, opt GateOptions) (out []Finding, shown map[string]Shown) { + active := activeIntents(doc, opt.Targets) var kept []scored for _, c := range cands { f := c.Finding @@ -72,6 +67,9 @@ func Gate(cands []Candidate, doc Doc, prev map[string]Shown, opt GateOptions) (o if c.Replay != nil && replayAddsGrid(*c.Replay) { continue } + if replayRequired(c) && c.Replay == nil { + continue + } conf := f.Confidence var score float64 @@ -85,7 +83,7 @@ func Gate(cands []Candidate, doc Doc, prev map[string]Shown, opt GateOptions) (o if !pass && seen { conf, pass = "estimate", true } - if !pass || !compatible(f, doc) { + if !pass || coveredBy(f, active) { continue } if c.Replay != nil && c.Replay.Estimate && conf == "high" { @@ -292,47 +290,76 @@ func benefitKWh(b Benefit) (float64, bool) { return b.Value, true } -// compatible runs the prepared rule of the first template fix through the -// static rule check together with the document. A new duplicate or -// contradiction makes the candidate incompatible. -func compatible(f Finding, doc Doc) bool { - for _, fix := range f.Apply { - if fix.Template == "" { - continue - } - build := prefillRules[fix.Template] - if build == nil { - return true +// replayRequired reports the energy suggestions that are shown only with a +// replay verdict (spec 15.6): surplus windows, load shifts, threshold ratings +// and the after_battery_full suggestion of the battery detector. +func replayRequired(c Candidate) bool { + switch c.Detector { + case "surplus_window", "load_shift", "threshold_rating": + return true + case "battery": + for _, fix := range c.Finding.Apply { + if fix.Template == "after_battery_full" { + return true + } } - rule, ok := build(fix.Prefill) - if !ok { - return true + } + return false +} + +// activeIntents returns the intents of the enabled rules of doc and of its +// enabled scenarios. A scenario switches its regulated entity as a surplus +// trigger. Without targets there are no intents. +func activeIntents(doc Doc, targets func(ruleID string) []Target) []Intent { + if targets == nil { + return nil + } + var out []Intent + for _, r := range doc.Rules { + if r.Enabled { + out = append(out, RuleIntents(r, targets(r.ID))...) } - rule.ID = probeRuleID - rule.Enabled = true - probe := Doc{ - Rules: append(append([]Rule(nil), doc.Rules...), rule), - Scenarios: doc.Scenarios, + } + for _, s := range doc.Scenarios { + if !s.Enabled { + continue } - for _, pf := range StaticFindings(probe, nil) { - if (pf.Kind == "duplicate" || pf.Kind == "contradiction") && containsID(pf.RuleIDs, probeRuleID) { - return false + for _, t := range targets(s.ID) { + if t.Entity != "" { + out = append(out, Intent{Entity: t.Entity, On: t.On != nil && *t.On, Trigger: "surplus"}) } } - return true } - return true + return out } -func containsID(ids []string, id string) bool { - for _, x := range ids { - if x == id { +// coveredBy reports whether an active rule switches the entity of the first +// fix of f with the same trigger. The same direction is a duplicate, the +// other direction a contradiction, and both are dropped. A finding without a +// known intent is never covered. +func coveredBy(f Finding, active []Intent) bool { + in, ok := findingIntent(f) + if !ok || in.Entity == "" { + return false + } + for _, a := range active { + if a.Entity == in.Entity && a.Trigger == in.Trigger { return true } } return false } +// findingIntent returns the intent of the first fix with a known template. +func findingIntent(f Finding) (Intent, bool) { + for _, fix := range f.Apply { + if in, ok := TemplateIntent(fix); ok { + return in, true + } + } + return Intent{}, false +} + // valuesMoved reports whether a value wandered further than its spread from // the value on screen, or whether the sets of keys differ. func valuesMoved(now, shown, spread map[string]float64) bool { diff --git a/dashboard/internal/autolearn/gates_test.go b/dashboard/internal/autolearn/gates_test.go index e85a4e4b..9c8ce1e2 100644 --- a/dashboard/internal/autolearn/gates_test.go +++ b/dashboard/internal/autolearn/gates_test.go @@ -93,27 +93,95 @@ func TestGateQuietValuesChangeOnlyBeyondSpread(t *testing.T) { } } -func TestGateDropsDuplicateOfExistingRule(t *testing.T) { - prefillRules["test_tpl"] = func(map[string]any) (Rule, bool) { - return Rule{Name: "neu", Conditions: []Condition{gateThreshold()}, - Actions: []Action{{Type: "publish", Topic: "t/x", Payload: "1"}}}, true +// gateCoverDoc is a rule that switches lamp off at 22:30 by a time window. +func gateCoverDoc(entity string, on bool) (Doc, func(string) []Target) { + off := !on + rule := Rule{ID: "lamp-night", Name: "Lampe", Enabled: true, + Conditions: []Condition{{Type: "time_window", Raw: json.RawMessage(`{"type":"time_window","start":"22:30","end":"22:31"}`)}}, + Actions: []Action{{Type: "publish", EntityID: entity, Payload: "x"}}} + doc := Doc{Rules: []Rule{rule}} + targets := func(id string) []Target { + if id != rule.ID { + return nil + } + return []Target{{Entity: entity, On: &off}} } - t.Cleanup(func() { delete(prefillRules, "test_tpl") }) + return doc, targets +} - doc := Doc{Rules: []Rule{{ID: "old", Name: "alt", Enabled: true, - Conditions: []Condition{gateThreshold()}, - Actions: []Action{{Type: "publish", Topic: "t/x", Payload: "1"}}}}} +// gateTimeCand is a time_point suggestion for entity at 22:30. +func gateTimeCand(id, entity string, on bool) Candidate { + cand := gateCand(id, "switch_time", 1, 2, 2, true) + cand.Finding.Apply = []Fix{{Code: "time_point", Template: "time_point", + Prefill: map[string]any{"entity": entity, "on": on, "time": "22:30"}}} + return cand +} - cand := gateCand("a", "x", 1, 2, 2, true) - cand.Finding.Apply = []Fix{{Code: "fix", Template: "test_tpl"}} - if out, _ := Gate([]Candidate{cand}, doc, nil, GateOptions{}); len(out) != 0 { - t.Errorf("duplicate kept: %v", gateIDs(out)) +func TestGateDropsCoveredSuggestion(t *testing.T) { + doc, targets := gateCoverDoc("switch.lamp", false) + cand := gateTimeCand("a", "switch.lamp", false) + if out, _ := Gate([]Candidate{cand}, doc, nil, GateOptions{Targets: targets}); len(out) != 0 { + t.Fatalf("kept %v, want the covered suggestion dropped", gateIDs(out)) + } +} + +func TestGateDropsContradiction(t *testing.T) { + doc, targets := gateCoverDoc("switch.lamp", true) + cand := gateTimeCand("a", "switch.lamp", false) + if out, _ := Gate([]Candidate{cand}, doc, nil, GateOptions{Targets: targets}); len(out) != 0 { + t.Fatalf("kept %v, want the contradicting suggestion dropped", gateIDs(out)) + } +} + +func TestGateKeepsOtherEntity(t *testing.T) { + doc, targets := gateCoverDoc("switch.lamp", false) + cand := gateTimeCand("a", "switch.other", false) + if out, _ := Gate([]Candidate{cand}, doc, nil, GateOptions{Targets: targets}); len(out) != 1 { + t.Fatalf("kept %v, want one suggestion for another entity", gateIDs(out)) + } +} + +func TestGateKeepsOtherTrigger(t *testing.T) { + doc, targets := gateCoverDoc("switch.lamp", false) + cand := gateCand("a", "runtime", 1, 2, 2, true) + cand.Finding.Apply = []Fix{{Code: "runtime_off", Template: "runtime_off", + Prefill: map[string]any{"entity": "switch.lamp"}}} + if out, _ := Gate([]Candidate{cand}, doc, nil, GateOptions{Targets: targets}); len(out) != 1 { + t.Fatalf("kept %v, want one suggestion with another trigger", gateIDs(out)) + } +} + +func TestGateDisabledRuleCoversNothing(t *testing.T) { + doc, targets := gateCoverDoc("switch.lamp", false) + doc.Rules[0].Enabled = false + cand := gateTimeCand("a", "switch.lamp", false) + if out, _ := Gate([]Candidate{cand}, doc, nil, GateOptions{Targets: targets}); len(out) != 1 { + t.Fatalf("kept %v, want one suggestion, the rule is off", gateIDs(out)) + } +} + +func TestGateDropsUnreplayedEnergy(t *testing.T) { + verdict := &ReplayVerdict{} + for _, det := range []string{"surplus_window", "load_shift", "threshold_rating"} { + if out, _ := Gate([]Candidate{gateCand("e", det, 1, 2, 2, true)}, Doc{}, nil, GateOptions{}); len(out) != 0 { + t.Errorf("%s without replay kept", det) + } + c := gateCand("e", det, 1, 2, 2, true) + c.Replay = verdict + if out, _ := Gate([]Candidate{c}, Doc{}, nil, GateOptions{}); len(out) != 1 { + t.Errorf("%s with replay verdict dropped", det) + } } - // Without a rule to build from, the candidate is kept. - cand.Finding.Apply = []Fix{{Code: "fix", Template: "unknown_tpl"}} - if out, _ := Gate([]Candidate{cand}, doc, nil, GateOptions{}); len(out) != 1 { - t.Errorf("unbuildable template dropped: %v", gateIDs(out)) + battery := gateCand("b", "battery", 1, 2, 2, true) + battery.Finding.Apply = []Fix{{Code: "after_battery_full", Template: "after_battery_full", + Prefill: map[string]any{"entity": "switch.boiler"}}} + if out, _ := Gate([]Candidate{battery}, Doc{}, nil, GateOptions{}); len(out) != 0 { + t.Errorf("after_battery_full without replay kept") + } + battery.Replay = verdict + if out, _ := Gate([]Candidate{battery}, Doc{}, nil, GateOptions{}); len(out) != 1 { + t.Errorf("after_battery_full with replay verdict dropped") } } diff --git a/dashboard/internal/autolearn/intent.go b/dashboard/internal/autolearn/intent.go new file mode 100644 index 00000000..907deb70 --- /dev/null +++ b/dashboard/internal/autolearn/intent.go @@ -0,0 +1,176 @@ +package autolearn + +import ( + "encoding/json" + "time" +) + +// Intent is what a rule or a suggestion switches: the entity, the direction and +// the kind of condition that triggers the switch. An active rule with the same +// entity and trigger as a suggestion already covers it, or contradicts it. +type Intent struct { + Entity string + On bool + Trigger string +} + +// nightEnd is the clock time before which the end of a midnight window counts +// as night, 08:00 in minutes of the day. +const nightEnd = 8 * 60 + +// TemplateIntent returns the intent of a suggestion fix built from a known +// template. An unknown template gives false. +func TemplateIntent(fix Fix) (Intent, bool) { + p := fix.Prefill + switch fix.Template { + case "time_point": + return Intent{Entity: prefillString(p, "entity"), On: prefillBool(p, "on"), Trigger: "time"}, true + case "runtime_off": + return Intent{Entity: prefillString(p, "entity"), Trigger: "runtime"}, true + case "quiet_off": + return Intent{Entity: prefillString(p, "entity"), Trigger: "quiet"}, true + case "night_off": + return Intent{Entity: prefillString(p, "entity"), Trigger: "night"}, true + case "after_battery_full": + return Intent{Entity: prefillString(p, "entity"), On: true, Trigger: "battery_full"}, true + case "follow_switch": + return Intent{Entity: prefillString(p, "target_entity"), On: prefillBool(p, "target_on"), Trigger: "follow"}, true + case "shift_start": + return Intent{Entity: prefillString(p, "entity"), On: true, Trigger: "surplus"}, true + } + return Intent{}, false +} + +// RuleIntents returns the intents of a rule, one per target entity and trigger. +// Triggers come from the conditions: a time window is "time", or "night" when it +// crosses midnight and ends before 08:00, a sun window is "time", a learned +// quiet state is "quiet", a balance threshold on battery_soc is "battery_full" +// and on grid_export "surplus". An entity_value holding the target itself is +// "runtime" when it has a hold, and an entity_value on another entity is "follow". +// A target without a known payload counts as off, since the direction does not +// decide the gate. Without targets the rule has no intents. +func RuleIntents(rule Rule, targets []Target) []Intent { + if len(targets) == 0 { + return nil + } + own := make(map[string]bool, len(targets)) + for _, t := range targets { + own[t.Entity] = true + } + var triggers []string + seen := map[string]bool{} + for _, c := range rule.Conditions { + trigger := conditionTrigger(c, own) + if trigger == "" || seen[trigger] { + continue + } + seen[trigger] = true + triggers = append(triggers, trigger) + } + var out []Intent + for _, t := range targets { + if t.Entity == "" { + continue + } + for _, trigger := range triggers { + out = append(out, Intent{Entity: t.Entity, On: t.On != nil && *t.On, Trigger: trigger}) + } + } + return out +} + +// conditionTrigger names the trigger a condition gives its rule, or "" for a +// condition that triggers nothing. own holds the entities the rule switches. +func conditionTrigger(c Condition, own map[string]bool) string { + switch c.Type { + case "time_window": + if isNightWindow(c) { + return "night" + } + return "time" + case "sun_window": + return "time" + case "learned_state": + if rawString(c.Raw, "equals") == "quiet" { + return "quiet" + } + case "balance_threshold": + switch c.Field { + case "battery_soc": + return "battery_full" + case "grid_export": + return "surplus" + } + case "entity_value": + if c.EntityID == "" { + return "" + } + if !own[c.EntityID] { + return "follow" + } + _, learnedHold := c.Learned["hold_seconds"] + if c.HoldSeconds != nil || learnedHold { + return "runtime" + } + } + return "" +} + +// isNightWindow reports a window that crosses midnight and ends before 08:00. +// A bound that is a learned reference counts with its fallback, and a window +// whose bounds cannot be read is no night window. +func isNightWindow(c Condition) bool { + start, okStart := windowClock(c, "start") + end, okEnd := windowClock(c, "end") + return okStart && okEnd && start > end && end < nightEnd +} + +// windowClock reads a bound of a time window in minutes of the day. +func windowClock(c Condition, name string) (int, bool) { + if ref, ok := c.Learned[name]; ok { + text, _ := ref.Fallback.(string) + return clockOfText(text) + } + var text string + if err := json.Unmarshal(rawField(c.Raw, name), &text); err != nil { + return 0, false + } + return clockOfText(text) +} + +// clockOfText reads "HH:MM" in minutes of the day. +func clockOfText(text string) (int, bool) { + t, err := time.Parse("15:04", text) + if err != nil { + return 0, false + } + return t.Hour()*60 + t.Minute(), true +} + +// rawField returns the field name of a raw JSON object, nil when it is absent. +func rawField(raw json.RawMessage, name string) json.RawMessage { + var fields map[string]json.RawMessage + if err := json.Unmarshal(raw, &fields); err != nil { + return nil + } + return fields[name] +} + +// rawString returns the text of a field of a raw JSON object, "" when it is not text. +func rawString(raw json.RawMessage, name string) string { + var text string + if err := json.Unmarshal(rawField(raw, name), &text); err != nil { + return "" + } + return text +} + +func prefillString(prefill map[string]any, key string) string { + text, _ := prefill[key].(string) + return text +} + +func prefillBool(prefill map[string]any, key string) bool { + on, _ := prefill[key].(bool) + return on +} diff --git a/dashboard/internal/autolearn/intent_test.go b/dashboard/internal/autolearn/intent_test.go new file mode 100644 index 00000000..71fff09e --- /dev/null +++ b/dashboard/internal/autolearn/intent_test.go @@ -0,0 +1,102 @@ +package autolearn + +import ( + "reflect" + "strings" + "testing" +) + +func TestTemplateIntent(t *testing.T) { + cases := []struct { + name string + fix Fix + want Intent + ok bool + }{ + {"time_point off", Fix{Template: "time_point", Prefill: map[string]any{"entity": "switch.lamp", "on": false}}, + Intent{Entity: "switch.lamp", On: false, Trigger: "time"}, true}, + {"time_point on", Fix{Template: "time_point", Prefill: map[string]any{"entity": "switch.lamp", "on": true}}, + Intent{Entity: "switch.lamp", On: true, Trigger: "time"}, true}, + {"runtime_off", Fix{Template: "runtime_off", Prefill: map[string]any{"entity": "switch.a"}}, + Intent{Entity: "switch.a", On: false, Trigger: "runtime"}, true}, + {"quiet_off", Fix{Template: "quiet_off", Prefill: map[string]any{"entity": "switch.b"}}, + Intent{Entity: "switch.b", On: false, Trigger: "quiet"}, true}, + {"night_off", Fix{Template: "night_off", Prefill: map[string]any{"entity": "switch.c"}}, + Intent{Entity: "switch.c", On: false, Trigger: "night"}, true}, + {"after_battery_full", Fix{Template: "after_battery_full", Prefill: map[string]any{"entity": "switch.d"}}, + Intent{Entity: "switch.d", On: true, Trigger: "battery_full"}, true}, + {"follow_switch", Fix{Template: "follow_switch", Prefill: map[string]any{ + "source_entity": "switch.s", "target_entity": "switch.t", "target_on": true}}, + Intent{Entity: "switch.t", On: true, Trigger: "follow"}, true}, + {"shift_start", Fix{Template: "shift_start", Prefill: map[string]any{"device": "dev"}}, + Intent{On: true, Trigger: "surplus"}, true}, + {"unknown template", Fix{Template: "surplus_switch", Prefill: map[string]any{"entity": "switch.e"}}, Intent{}, false}, + {"empty template", Fix{Code: "fix"}, Intent{}, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, ok := TemplateIntent(tc.fix) + if ok != tc.ok || got != tc.want { + t.Fatalf("TemplateIntent = %+v, %v; want %+v, %v", got, ok, tc.want, tc.ok) + } + }) + } +} + +// ruleWith builds a rule with the given raw conditions and one publish action +// to entity, which is on or off. +func ruleWith(t *testing.T, entity string, conditions ...string) (Rule, []Target) { + t.Helper() + doc, err := ParseDoc([]byte(`{"rules":[{"id":"r","name":"R","enabled":true,"conditions":[` + + strings.Join(conditions, ",") + `],"actions":[{"type":"publish","topic":"x/set","entity_id":"` + entity + + `","payload_source":"constant","payload":"off"}]}]}`)) + if err != nil { + t.Fatalf("ParseDoc: %v", err) + } + off := false + return doc.Rules[0], []Target{{Entity: entity, On: &off}} +} + +func TestRuleIntentsTriggers(t *testing.T) { + cases := []struct { + name string + conditions []string + want []string + }{ + {"time window", []string{`{"type":"time_window","start":"08:00","end":"22:00"}`}, []string{"time"}}, + {"sun window", []string{`{"type":"sun_window","from":"sunset","to":"sunrise"}`}, []string{"time"}}, + {"night window", []string{`{"type":"time_window","start":"22:00","end":"06:00"}`}, []string{"night"}}, + {"night window learned", []string{`{"type":"time_window","start":{"learned":"site/night_rest","fallback":"23:00"},"end":{"learned":"site/day_start","fallback":"06:00"}}`}, []string{"night"}}, + {"quiet", []string{`{"type":"learned_state","learned":"site/house_state","equals":"quiet","fallback":"active"}`}, []string{"quiet"}}, + {"battery full", []string{`{"type":"balance_threshold","field":"battery_soc","comparison":"above","threshold":96}`}, []string{"battery_full"}}, + {"surplus", []string{`{"type":"balance_threshold","field":"grid_export","comparison":"above","threshold":500}`}, []string{"surplus"}}, + {"runtime", []string{`{"type":"entity_value","entity_id":"switch.lamp","comparison":"equals","text":"ON","hold_seconds":3600}`}, []string{"runtime"}}, + {"runtime learned", []string{`{"type":"entity_value","entity_id":"switch.lamp","comparison":"equals","text":"ON","hold_seconds":{"learned":"device/lamp/usual_runtime_s","fallback":3600}}`}, []string{"runtime"}}, + {"follow", []string{`{"type":"entity_value","entity_id":"switch.other","comparison":"equals","text":"ON"}`}, []string{"follow"}}, + {"own state without hold", []string{`{"type":"entity_value","entity_id":"switch.lamp","comparison":"equals","text":"ON"}`}, nil}, + {"other balance field", []string{`{"type":"balance_threshold","field":"grid_import","comparison":"above","threshold":100}`}, nil}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rule, targets := ruleWith(t, "switch.lamp", tc.conditions...) + got := RuleIntents(rule, targets) + var triggers []string + for _, in := range got { + if in.Entity != "switch.lamp" || in.On { + t.Fatalf("intent %+v, want entity switch.lamp off", in) + } + triggers = append(triggers, in.Trigger) + } + if !reflect.DeepEqual(triggers, tc.want) { + t.Fatalf("triggers = %v, want %v", triggers, tc.want) + } + }) + } +} + +func TestRuleIntentsWithoutTargetsIsEmpty(t *testing.T) { + rule, _ := ruleWith(t, "switch.lamp", `{"type":"time_window","start":"08:00","end":"22:00"}`) + if got := RuleIntents(rule, nil); len(got) != 0 { + t.Fatalf("intents = %+v, want none without a target", got) + } +} From 2f2cd59b15d4a17cc4eeec0c3a4246b858a6a713 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:10:07 +0100 Subject: [PATCH 05/22] fix(autolearn): match rule actions by direction and use one minimum run table A rule action with a set direction now only claims a state change in that direction, so a hand switch after a rule that switched off is no longer attributed to the rule. RuleState walks rule IDs in sorted order, so two rules on the same entity claim deterministically. The separate reliabilityMinRuntime table is removed. Every caller uses minRunForRole, so other switchable devices now get 300 s instead of 120 s. Co-Authored-By: Claude Sonnet 5.5 --- .../internal/autolearn/detect_flapping.go | 2 +- .../autolearn/detect_flapping_test.go | 6 ++-- .../internal/autolearn/detect_reliability.go | 18 ---------- .../internal/autolearn/detect_threshold.go | 2 +- dashboard/internal/autolearn/minrun_test.go | 6 ++++ dashboard/internal/autolearn/observed.go | 2 +- dashboard/internal/autolearn/origin.go | 11 ++++++- dashboard/internal/autolearn/origin_test.go | 33 +++++++++++++++++++ 8 files changed, 55 insertions(+), 25 deletions(-) diff --git a/dashboard/internal/autolearn/detect_flapping.go b/dashboard/internal/autolearn/detect_flapping.go index 5e9b68b4..d02c0615 100644 --- a/dashboard/internal/autolearn/detect_flapping.go +++ b/dashboard/internal/autolearn/detect_flapping.go @@ -36,7 +36,7 @@ func flappingRun(ctx context.Context, in *Input, device string) []Candidate { if !ok { return nil } - minRun := reliabilityMinRuntime(info) + minRun := minRunForRole(info) if minRun <= 0 { return nil } diff --git a/dashboard/internal/autolearn/detect_flapping_test.go b/dashboard/internal/autolearn/detect_flapping_test.go index f31b26e6..ff777b11 100644 --- a/dashboard/internal/autolearn/detect_flapping_test.go +++ b/dashboard/internal/autolearn/detect_flapping_test.go @@ -60,9 +60,9 @@ func TestFlappingFlagsAlternatingRulesBelowMinimumRuntime(t *testing.T) { if len(op.Path) != 3 || op.Path[0] != "conditions" || op.Path[1] != 0 || op.Path[2] != "hold_seconds" { t.Errorf("op path = %v", op.Path) } - // Period 60 s, three periods are 180 s, above the 120 s minimum of other devices. - if op.Value != 180 { - t.Errorf("hold_seconds = %v, want 180", op.Value) + // The hold is the minimum run of other devices, 300 s. + if op.Value != 300 { + t.Errorf("hold_seconds = %v, want 300", op.Value) } } diff --git a/dashboard/internal/autolearn/detect_reliability.go b/dashboard/internal/autolearn/detect_reliability.go index 55002e9b..23c96f09 100644 --- a/dashboard/internal/autolearn/detect_reliability.go +++ b/dashboard/internal/autolearn/detect_reliability.go @@ -3,8 +3,6 @@ package autolearn import ( "sort" "time" - - "github.com/Developer-Simon/energy-node-dashboard/internal/energy" ) // Shared parts of the reliability detectors (spec 15.4 "Takten" and "Aktion @@ -22,22 +20,6 @@ const ( reliabilityPeakShare = 0.5 ) -// reliabilityMinRuntime is the shortest runtime in seconds a device tolerates -// by role: heat pump 10 minutes, wallbox 3 minutes, lights none (0), all other -// switchable devices 2 minutes. -func reliabilityMinRuntime(info DeviceInfo) float64 { - switch { - case info.Light: - return 0 - case info.Role == energy.RoleHeatPump: - return 600 - case info.Role == energy.RoleWallbox: - return 180 - default: - return 120 - } -} - // ruleEvent is a switching event of a device that a rule caused. type ruleEvent struct { at int64 diff --git a/dashboard/internal/autolearn/detect_threshold.go b/dashboard/internal/autolearn/detect_threshold.go index 4999e4c1..72c44b63 100644 --- a/dashboard/internal/autolearn/detect_threshold.go +++ b/dashboard/internal/autolearn/detect_threshold.go @@ -110,7 +110,7 @@ func thresholdRule(ctx context.Context, in *Input, r Rule, minutes []ReplayMinut return Candidate{}, false } hyst0 := r.Conditions[idx].Hysteresis - run0 := reliabilityMinRuntime(info) + run0 := minRunForRole(info) base := thresholdTarget{rule: r.ID, device: device, opW: p, peakW: feedbackInrush(in.Days, device, p), cycleWh: cycle} real := RealState(in, device, minutes) diff --git a/dashboard/internal/autolearn/minrun_test.go b/dashboard/internal/autolearn/minrun_test.go index 58eb08e4..2a22795e 100644 --- a/dashboard/internal/autolearn/minrun_test.go +++ b/dashboard/internal/autolearn/minrun_test.go @@ -24,3 +24,9 @@ func TestMinRunForRole(t *testing.T) { } } } + +func TestMinRunDefault(t *testing.T) { + if got := minRunForRole(DeviceInfo{ID: "dev", Switchable: true, Role: energy.RoleLoad}); got != 300 { + t.Fatalf("minRunForRole(other device) = %v, want 300", got) + } +} diff --git a/dashboard/internal/autolearn/observed.go b/dashboard/internal/autolearn/observed.go index 8527883a..d1878b99 100644 --- a/dashboard/internal/autolearn/observed.go +++ b/dashboard/internal/autolearn/observed.go @@ -242,7 +242,7 @@ func frequentSoll(in *Input, rule Rule, idx, h int, from, to int64) (soll []int6 site = *in.Doc.Location } target := ReplayTarget{RuleID: rule.ID, Device: device, OpW: p, - PeakW: feedbackInrush(in.Days, device, p), CycleWh: cycle, MinRunS: reliabilityMinRuntime(info)} + PeakW: feedbackInrush(in.Days, device, p), CycleWh: cycle, MinRunS: minRunForRole(info)} res, err := Replay(context.Background(), raw, target, minutes, RealState(in, device, minutes), replayLoc(in), site) if err != nil { return nil, false, false diff --git a/dashboard/internal/autolearn/origin.go b/dashboard/internal/autolearn/origin.go index 687ce77f..a8fbd495 100644 --- a/dashboard/internal/autolearn/origin.go +++ b/dashboard/internal/autolearn/origin.go @@ -156,7 +156,13 @@ func (t *Tracker) RuleState(at time.Time, payload string, targets func(ruleID st defer t.mu.Unlock() first := !t.seeded t.seeded = true - for id, r := range doc.Rules { + ids := make([]string, 0, len(doc.Rules)) + for id := range doc.Rules { + ids = append(ids, id) + } + sort.Strings(ids) + for _, id := range ids { + r := doc.Rules[id] prev := t.counts[id] t.counts[id] = r.FireCount if first || r.FireCount <= prev || targets == nil { @@ -233,6 +239,9 @@ func (t *Tracker) claimRuleActLocked(c *change, start time.Time) *ruleAct { if ra.act.At.Before(start) || ra.act.At.After(c.at) { continue } + if ra.act.WantOn != nil && *ra.act.WantOn != c.on { + continue + } ra.attributed = true return ra } diff --git a/dashboard/internal/autolearn/origin_test.go b/dashboard/internal/autolearn/origin_test.go index cb317599..30a62d22 100644 --- a/dashboard/internal/autolearn/origin_test.go +++ b/dashboard/internal/autolearn/origin_test.go @@ -223,3 +223,36 @@ func TestRuleActionEffectiveClaimReaction(t *testing.T) { t.Fatalf("actions = %+v, want effective with reaction 2s", actions) } } + +func TestOriginRuleActMatchesDirection(t *testing.T) { + tr := NewTracker(NewReactions()) + // The rule switches off, the device is already off, so nothing changes. + tg := targetsFor("r1", Target{Device: "dev", Entity: "light.a", On: boolPtr(false)}) + tr.RuleState(originT0, ruleDocState("r1", 0, originT0), tg) + tr.RuleState(originT0, ruleDocState("r1", 1, originT0), tg) + // Three seconds later the hand switches the device on. + tr.Command(originT0.Add(3*time.Second), "dev", "light.a", true) + tr.StateChange(originT0.Add(3*time.Second), "dev", "light.a", true) + + events, _ := tr.Drain(originT0.Add(time.Minute)) + if len(events) != 1 || events[0].Origin != OriginHand { + t.Fatalf("events = %+v, want one hand event", events) + } +} + +func TestOriginRuleStateOrderStable(t *testing.T) { + both := func(string) []Target { + return []Target{{Device: "dev", Entity: "light.a", On: boolPtr(true)}} + } + for i := 0; i < 50; i++ { + tr := NewTracker(NewReactions()) + tr.RuleState(originT0, `{"rules":{"r1":{"fire_count":0},"r2":{"fire_count":0}}}`, both) + tr.RuleState(originT0, `{"rules":{"r1":{"fire_count":1,"fired_at":`+fmt.Sprint(originT0.Unix())+`},"r2":{"fire_count":1,"fired_at":`+fmt.Sprint(originT0.Unix())+`}}}`, both) + tr.StateChange(originT0.Add(time.Second), "dev", "light.a", true) + + events, _ := tr.Drain(originT0.Add(time.Minute)) + if len(events) != 1 || events[0].RuleID != "r1" { + t.Fatalf("run %d: events = %+v, want rule r1 every time", i, events) + } + } +} From 2764157b9d941d273f6f1022145640cbfa182495 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:13:57 +0100 Subject: [PATCH 06/22] fix(autolearn): skip unreachable and away days and keep switch time IDs stable Switch times and couplings count unreachable and away days neither as hits nor as misses. A shown switch time ID is kept while its centre stays within 30 minutes of it, so a centre that drifts across a grid line keeps its ID. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/main.go | 2 + .../internal/autolearn/detect_coupling.go | 29 +++++++ .../autolearn/detect_coupling_test.go | 37 +++++++++ .../internal/autolearn/detect_switchtime.go | 52 +++++++++++-- .../autolearn/detect_switchtime_test.go | 78 +++++++++++++++++++ dashboard/internal/autolearn/engine.go | 13 ++++ dashboard/internal/autolearn/input.go | 3 + 7 files changed, 207 insertions(+), 7 deletions(-) diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index d0381dc8..727269c9 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -821,6 +821,8 @@ func main() { }) // Die Reglerschritte fuer die Regelguete der Nulleinspeisung. automationEngine.SetSteps(minutes.steps.Steps) + // Die gezeigten Vorschläge, damit eine Schaltzeit ihre ID behält. + automationEngine.SetShown(func() map[string]bool { return shownIDs(suggestionState.Shown()) }) go runStorageResume(ctx, storageService) // Die Belegung der Systemplatte: in der Demo feste Werte, sonst eine Messung // im Hintergrund, die alle zehn Minuten erneuert wird. diff --git a/dashboard/internal/autolearn/detect_coupling.go b/dashboard/internal/autolearn/detect_coupling.go index 071be259..d7039ba8 100644 --- a/dashboard/internal/autolearn/detect_coupling.go +++ b/dashboard/internal/autolearn/detect_coupling.go @@ -172,6 +172,10 @@ func ruleReadsEntity(r Rule, entities map[string]bool) bool { // couplingCandidate checks one pair of streams and builds its candidate, or // reports false when a gate fails. func couplingCandidate(in *Input, loc *time.Location, a, b string, onA, onB bool, sa, sb *couplingStream) (Candidate, bool) { + sa = couplingCases(in, loc, a, b, sa) + if len(sa.times) < couplingMinCases { + return Candidate{}, false + } // The longest window sets the reference, the shortest window that keeps // enough of its hits is chosen. longest := couplingWindows[len(couplingWindows)-1] @@ -229,6 +233,31 @@ func couplingCandidate(in *Input, loc *time.Location, a, b string, onA, onB bool return couplingBuild(in, loc, a, b, onA, onB, sa, sb, window, hits, cases, lower, share, lag, matchedB, deltas, halves), true } +// couplingCases keeps the switchings of a that count as cases for the pair a +// and b. A switching on an absent day does not count, and neither does one at +// a quarter in which a or b was not reachable, since b could not follow then +// (spec 15.3 Zähltage). The quarter of the switching of a is used for both. +func couplingCases(in *Input, loc *time.Location, a, b string, sa *couplingStream) *couplingStream { + days := make(map[string]*DayFile, len(in.Days)) + for i := range in.Days { + days[in.Days[i].Day] = &in.Days[i] + } + out := &couplingStream{entity: sa.entity} + for _, t := range sa.times { + at := time.Unix(t, 0).In(loc) + day := at.Format(dayLayout) + if in.Base.Away[day] { + continue + } + q := quarterOf(at) + if f := days[day]; f != nil && (unreachable(f.Devices[a], q) || unreachable(f.Devices[b], q)) { + continue + } + out.times = append(out.times, t) + } + return out +} + // couplingBuild assembles the candidate of a pair that passed the gates. func couplingBuild(in *Input, loc *time.Location, a, b string, onA, onB bool, sa, sb *couplingStream, window int64, hits, cases int, lower, share, lag float64, matchedB []int64, deltas []float64, halves bool) Candidate { diff --git a/dashboard/internal/autolearn/detect_coupling_test.go b/dashboard/internal/autolearn/detect_coupling_test.go index 9699c69a..9a4e30f2 100644 --- a/dashboard/internal/autolearn/detect_coupling_test.go +++ b/dashboard/internal/autolearn/detect_coupling_test.go @@ -172,3 +172,40 @@ func couplingFact(c Candidate, code string) any { } return -1 } + +func TestCouplingSkipsUnreachableAndAway(t *testing.T) { + loc := berlinLoc(t) + start := time.Date(2026, 1, 5, 0, 0, 0, 0, loc) + // Days 0 to 4: B is out of reach, so it cannot follow A. Days 5 to 9: the + // days are away. Days 10 to 19: B follows A within two minutes every day. + days := couplingDays(start, 20, func(i int, day time.Time) []EventRec { + aAt := time.Date(day.Year(), day.Month(), day.Day(), 19, 0, 0, 0, loc) + evs := []EventRec{couplingHand("a", true, aAt)} + if i >= 10 { + evs = append(evs, couplingHand("b", true, aAt.Add(40*time.Second))) + } + return evs + }) + for i := range days { + for _, id := range []string{"a", "b"} { + dd := &DeviceDay{} + dd.Seen[76], dd.Reach[76] = 4, 4 + if id == "b" && i < 5 { + dd.Reach[76] = 0 + } + days[i].Devices[id] = dd + } + } + in := couplingInput(t, days, Doc{}, NewReactions()) + for i := 5; i < 10; i++ { + in.Base.Away[days[i].Day] = true + } + cands := CouplingDetector.Run(context.Background(), in, "") + got := couplingFor(cands, "coupling:a:on:b:on") + if len(got) != 1 { + t.Fatalf("coupling:a:on:b:on candidates = %d, want 1 (all: %d)", len(got), len(cands)) + } + if got[0].Finding.Summary.Params["hits"] != 10 || got[0].Finding.Summary.Params["cases"] != 10 { + t.Errorf("hits and cases = %v and %v, want 10 and 10", got[0].Finding.Summary.Params["hits"], got[0].Finding.Summary.Params["cases"]) + } +} diff --git a/dashboard/internal/autolearn/detect_switchtime.go b/dashboard/internal/autolearn/detect_switchtime.go index 636df626..50aec8c5 100644 --- a/dashboard/internal/autolearn/detect_switchtime.go +++ b/dashboard/internal/autolearn/detect_switchtime.go @@ -5,6 +5,8 @@ import ( "fmt" "math" "sort" + "strconv" + "strings" "time" "github.com/Developer-Simon/energy-node-dashboard/internal/sun" @@ -39,9 +41,12 @@ const ( // switchTimeEstLower and switchTimeEstSpread are the bounds for an estimate. switchTimeEstLower = 0.45 switchTimeEstSpread = 40.0 - // switchTimeRoundMin rounds the proposed time, switchTimeIDMin the time in the ID. + // switchTimeRoundMin rounds the proposed time. switchTimeRoundMin = 5.0 - switchTimeIDMin = 30.0 + // switchTimeIDMin is the grid width of the time in the ID, 30 minutes like + // the existing grid. A shown ID is kept while the centre stays within this + // distance of it, so a centre that drifts across a grid line keeps its ID. + switchTimeIDMin = 30.0 ) // swRef is one day of the device that the detector reads. @@ -192,14 +197,15 @@ func switchTimeCandidate(in *Input, device string, g int, on bool, refs []swRef, q := int(c / 15) prev := (q + dayQuarters - 1) % dayQuarters - // Counted days: the quarter of the centre was seen, and the device was not - // already in the target state in the quarter before. For a centre in - // quarter 0 the quarter before is quarter 95 of the previous day, and a day - // without a previous day is not counted. + // Counted days: the quarter of the centre was seen and the device was + // reachable in it, and the device was not already in the target state in + // the quarter before. For a centre in quarter 0 the quarter before is + // quarter 95 of the previous day, and a day without a previous day is not + // counted. Unreachable days count neither as hit nor as miss (spec 15.3). var counted, hit []int for _, i := range group { r := &refs[i] - if r.dd == nil || r.dd.Seen[q] == 0 { + if r.dd == nil || r.dd.Seen[q] == 0 || unreachable(r.dd, q) { continue } before, pq := r.dd, prev @@ -244,6 +250,9 @@ func switchTimeCandidate(in *Input, device string, g int, on bool, refs []swRef, propMin := math.Mod(math.Round(c/switchTimeRoundMin)*switchTimeRoundMin, minutesPerDay) idMin := math.Mod(math.Round(c/switchTimeIDMin)*switchTimeIDMin, minutesPerDay) + if m, ok := switchTimeShownMin(in.ShownIDs, device, dirName, g, c); ok { + idMin = m + } clock := switchTimeClock(propMin) id := fmt.Sprintf("switch_time:%s:%s:%d:%s", device, dirName, g, switchTimeCompact(idMin)) @@ -559,6 +568,35 @@ func switchTimeClock(m float64) string { return fmt.Sprintf("%02d:%02d", v/60, v%60) } +// switchTimeShownMin returns the time of the shown ID of the device, direction +// and group that lies closest to center, when it lies within switchTimeIDMin. +// Ties go to the smaller ID. +func switchTimeShownMin(shown map[string]bool, device, dirName string, g int, center float64) (float64, bool) { + prefix := fmt.Sprintf("switch_time:%s:%s:%d:", device, dirName, g) + var best float64 + bestDist := math.Inf(1) + bestID := "" + for id := range shown { + if !strings.HasPrefix(id, prefix) { + continue + } + digits := id[len(prefix):] + v, err := strconv.Atoi(digits) + if err != nil || len(digits) != 4 { + continue + } + m := float64((v/100)*60 + v%100) + d := math.Abs(circDelta(m, center)) + if d > switchTimeIDMin { + continue + } + if d < bestDist || (d == bestDist && id < bestID) { + best, bestDist, bestID = m, d, id + } + } + return best, bestDist < math.Inf(1) +} + // switchTimeCompact formats minutes of the day as HHMM, for IDs. func switchTimeCompact(m float64) string { v := int(m) diff --git a/dashboard/internal/autolearn/detect_switchtime_test.go b/dashboard/internal/autolearn/detect_switchtime_test.go index e6bebea0..43ec5708 100644 --- a/dashboard/internal/autolearn/detect_switchtime_test.go +++ b/dashboard/internal/autolearn/detect_switchtime_test.go @@ -591,3 +591,81 @@ func TestSwitchTimeSunOffsetOutOfRangeIsClock(t *testing.T) { t.Errorf("prefill = %+v, want no sun anchor", c.Apply[0].Prefill) } } + +func TestSwitchTimeSkipsUnreachableDays(t *testing.T) { + loc := berlinLoc(t) + start := time.Date(2026, 1, 5, 0, 0, 0, 0, loc) + // The lamp is out of reach on five days, so it does not switch on at 07:00. + // Those days count neither as hits nor as misses: 17 of 17 stays high. The + // days are 22 so that 17 counted days clear switchTimeMinNEff. + days := synthDays(start, 22, synthOpts{ + Seed: 29, + Devices: []string{"lamp"}, + Outages: []synthOutage{{Device: "lamp", synthSpan: synthSpan{From: 2, To: 7}}}, + Habits: []synthHabit{ + {Device: "lamp", On: true, Minute: 420, Spread: 0, Hit: 1}, + {Device: "lamp", On: false, Minute: 1350, Spread: 8, Hit: 1}, + }, + }) + got := switchTimeFor(SwitchTimeDetector.Run(context.Background(), switchTimeInput(t, days), "lamp"), "lamp", "on") + if len(got) != 1 { + t.Fatalf("on candidates = %d, want 1", len(got)) + } + if got[0].Finding.Confidence != "high" { + t.Errorf("confidence = %s, want high (lower %.2f)", got[0].Finding.Confidence, got[0].Lower) + } + if got[0].Finding.Summary.Params["days"] != 17 || got[0].Finding.Summary.Params["hits"] != 17 { + t.Errorf("days and hits = %v and %v, want 17 and 17", got[0].Finding.Summary.Params["days"], got[0].Finding.Summary.Params["hits"]) + } +} + +func TestSwitchTimeSkipsAwayDays(t *testing.T) { + loc := berlinLoc(t) + start := time.Date(2026, 1, 5, 0, 0, 0, 0, loc) + days := synthDays(start, 22, synthOpts{ + Seed: 31, + Devices: []string{"lamp"}, + Habits: []synthHabit{ + {Device: "lamp", On: true, Minute: 420, Spread: 0, Hit: 1}, + {Device: "lamp", On: false, Minute: 1350, Spread: 8, Hit: 1}, + }, + }) + in := switchTimeInput(t, days) + for i := 2; i < 7; i++ { + in.Base.Away[days[i].Day] = true + } + got := switchTimeFor(SwitchTimeDetector.Run(context.Background(), in, "lamp"), "lamp", "on") + if len(got) != 1 { + t.Fatalf("on candidates = %d, want 1", len(got)) + } + if got[0].Finding.Summary.Params["days"] != 17 { + t.Errorf("days = %v, want 17 without the five away days", got[0].Finding.Summary.Params["days"]) + } +} + +func TestSwitchTimeIDStable(t *testing.T) { + loc := berlinLoc(t) + start := time.Date(2026, 1, 5, 0, 0, 0, 0, loc) + habits := func(minute float64) []synthHabit { + return []synthHabit{ + {Device: "lamp", On: true, Minute: minute, Spread: 0, Hit: 1}, + {Device: "lamp", On: false, Minute: 1350, Spread: 8, Hit: 1}, + } + } + before := synthDays(start, 14, synthOpts{Seed: 37, Devices: []string{"lamp"}, Habits: habits(404)}) + later := synthDays(start, 14, synthOpts{Seed: 37, Devices: []string{"lamp"}, Habits: habits(406)}) + + first := switchTimeFor(SwitchTimeDetector.Run(context.Background(), switchTimeInput(t, before), "lamp"), "lamp", "on") + if len(first) != 1 { + t.Fatalf("first candidates = %d, want 1", len(first)) + } + in := switchTimeInput(t, later) + in.ShownIDs = map[string]bool{first[0].Finding.ID: true} + second := switchTimeFor(SwitchTimeDetector.Run(context.Background(), in, "lamp"), "lamp", "on") + if len(second) != 1 { + t.Fatalf("second candidates = %d, want 1", len(second)) + } + if second[0].Finding.ID != first[0].Finding.ID { + t.Errorf("ID = %s, want the shown ID %s", second[0].Finding.ID, first[0].Finding.ID) + } +} diff --git a/dashboard/internal/autolearn/engine.go b/dashboard/internal/autolearn/engine.go index d5b3c920..1b86d80f 100644 --- a/dashboard/internal/autolearn/engine.go +++ b/dashboard/internal/autolearn/engine.go @@ -73,6 +73,7 @@ type Engine struct { minutes func() learnrec.Reader prep Preparer steps func(scenario string, from, to time.Time) []Step + shown func() map[string]bool // recentC is the mean outdoor temperature of the last three days as the // last round read it, nil when unknown. recentC *float64 @@ -478,6 +479,7 @@ func (e *Engine) input(now time.Time, limits learnrec.Limits, devices map[string learned := e.learned minutes := e.minutes steps := e.steps + shown := e.shown e.mu.Unlock() if minutes != nil { in.Minutes = minutes() @@ -485,6 +487,9 @@ func (e *Engine) input(now time.Time, limits learnrec.Limits, devices map[string if steps != nil { in.Steps = steps } + if shown != nil { + in.ShownIDs = shown() + } if learned != nil { in.Learned = learned() } @@ -517,6 +522,14 @@ func (e *Engine) SetLearned(f func() map[string]LearnedEntry) { e.learned = f } +// SetShown gives the engine the IDs the band shows now. A round reads them into +// Input.ShownIDs, so a switch time keeps its ID. Without it no ID is kept. +func (e *Engine) SetShown(f func() map[string]bool) { + e.mu.Lock() + defer e.mu.Unlock() + e.shown = f +} + // SetMinutes gives the engine the minute record. A round reads it into // Input.Minutes. Without it the replay works from the quarter hours. func (e *Engine) SetMinutes(f func() learnrec.Reader) { diff --git a/dashboard/internal/autolearn/input.go b/dashboard/internal/autolearn/input.go index 4f475fbd..8c126375 100644 --- a/dashboard/internal/autolearn/input.go +++ b/dashboard/internal/autolearn/input.go @@ -40,6 +40,9 @@ type Input struct { // Learned holds the learned values by key, such as site/base_w. Nil when // no store is wired. Learned map[string]LearnedEntry + // ShownIDs holds the IDs the band shows now. A switch time keeps a shown + // ID while its centre stays within switchTimeIDMin of it. Nil means none. + ShownIDs map[string]bool // PriorEmptyShare returns the share of the days of an ISO week of the year // before that were empty before sunrise, and whether a record of that week // exists. Nil, or a week without a record, means the empty finding is not made. From c3a946e0ab701d042fbb76a6cf0d6981126b5102 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:17:33 +0100 Subject: [PATCH 07/22] fix(autolearn): detect downward shifts in the change point test CUSUM now runs S+ and S- on standardised values and reports the direction. The base load drift reuses it, so a sustained fall gives a baseload.drift.down notice without a device or fix. Co-Authored-By: Claude Sonnet 5.5 --- .../internal/autolearn/detect_baseload.go | 59 +++++++++-------- .../autolearn/detect_baseload_test.go | 49 +++++++++++---- dashboard/internal/autolearn/stats.go | 63 ++++++++++++------- dashboard/internal/autolearn/stats_test.go | 25 ++++++-- dashboard/internal/webui/catalogs/de.json | 3 + dashboard/internal/webui/catalogs/en.json | 3 + 6 files changed, 138 insertions(+), 64 deletions(-) diff --git a/dashboard/internal/autolearn/detect_baseload.go b/dashboard/internal/autolearn/detect_baseload.go index a30ffd40..3b0ddf18 100644 --- a/dashboard/internal/autolearn/detect_baseload.go +++ b/dashboard/internal/autolearn/detect_baseload.go @@ -189,7 +189,7 @@ func baseLoadDrift(in *Input, ns []baseloadNight) []Candidate { for i, n := range ns { z[i] = (n.night - exp[i]) / sigma } - at, ok := baseLoadCUSUM(z) + at, rising, ok := CUSUM(z, 0, 1) if !ok || at < 1 { return nil } @@ -202,9 +202,12 @@ func baseLoadDrift(in *Input, ns []baseloadNight) []Candidate { } } shift := Median(after) - Median(before) - if shift <= 0 { + if shift == 0 || rising != (shift > 0) { return nil } + if !rising { + return baseloadFall(ns, at, before, after, shift) + } device := baseloadDevice(in, ns, at, shift) date := ns[at].date w := baseloadRound(shift, baseloadRoundW) @@ -248,6 +251,34 @@ func baseLoadDrift(in *Input, ns []baseloadNight) []Candidate { }} } +// baseloadFall reports a sustained fall of the nights from before to after. It +// names no device and suggests no rule: a lower base load is a notice for the +// monitoring, with no saving to win back, so the benefit stays empty. +func baseloadFall(ns []baseloadNight, at int, before, after []float64, shift float64) []Candidate { + w := baseloadRound(-shift, baseloadRoundW) + after0, before0 := Median(after), Median(before) + finding := Finding{ + ID: FindingID("baseload", ns[at].date), + Kind: "baseload", + Group: "check", + Severity: "info", + Confidence: "high", + Summary: Text{Code: "baseload.drift.down", Params: map[string]any{ + "w": w, "kwh_month": round1(-shift * baseloadMonthH / 1000), + }}, + Evidence: Evidence{Shape: "scale", Unit: "W", IstValue: &after0, SollValue: &before0}, + } + return []Candidate{{ + Finding: finding, + Detector: "baseload", + NEff: float64(len(after)), + MinNEff: baseloadLearnMin, + Lower: 1, + Limit: 1, + HalvesAgree: true, + }} +} + // baseloadExpect returns the expected night load of each night. With the same // weeks of baseloadMinYears earlier years in the season store that is their // median, else the reference of the window. @@ -328,30 +359,6 @@ func baseloadDevice(in *Input, ns []baseloadNight, at int, shift float64) string return best } -// baseLoadCUSUM looks for an upward shift in the residuals z, with the slack -// and the threshold of CUSUM and a baseline of 0. It returns the index where -// the shift starts. A run that goes over the threshold counts only when the -// residuals from its start on stay above the slack, so a single night does -// not count as a drift. -func baseLoadCUSUM(z []float64) (int, bool) { - s, start := 0.0, 0 - for t, x := range z { - prev := s - s = math.Max(0, s+x-cusumK) - if prev == 0 && s > 0 { - start = t - } - if s > cusumH { - tail := z[start:] - if len(tail) >= 3 && Median(tail) > cusumK { - return start, true - } - s = 0 - } - } - return 0, false -} - // baseloadRound rounds v to a multiple of step. func baseloadRound(v, step float64) float64 { return math.Round(v/step) * step diff --git a/dashboard/internal/autolearn/detect_baseload_test.go b/dashboard/internal/autolearn/detect_baseload_test.go index cbf9a592..c528ace8 100644 --- a/dashboard/internal/autolearn/detect_baseload_test.go +++ b/dashboard/internal/autolearn/detect_baseload_test.go @@ -157,10 +157,11 @@ func TestBaseLoadSingleNightIsNoFinding(t *testing.T) { } } -// TestBaseLoadFridgeSwapIsNoFindingOnlyBaseFollows is review focus 4: the base -// load falls after a fridge is swapped. A fall is no finding, the learned -// site/base_w follows the new level. -func TestBaseLoadFridgeSwapIsNoFindingOnlyBaseFollows(t *testing.T) { +// TestBaseLoadFridgeSwapGivesDownNoticeAndBaseFollows is review focus 4: the base +// load falls after a fridge is swapped. The earlier "no finding on a fall" was +// replaced by Task 7 of PR 6a, so the fall is one downward notice without a fix, +// and the learned site/base_w follows the new level. +func TestBaseLoadFridgeSwapGivesDownNoticeAndBaseFollows(t *testing.T) { in := blInput(60, func(i int) float64 { if i < 40 { return 260 @@ -168,8 +169,11 @@ func TestBaseLoadFridgeSwapIsNoFindingOnlyBaseFollows(t *testing.T) { return 180 }, nil) findings, values := blSplit(in) - if len(findings) != 0 { - t.Fatalf("a falling base load gave %d findings, want none", len(findings)) + if len(findings) != 1 { + t.Fatalf("a falling base load gave %d findings, want exactly one", len(findings)) + } + if f := findings[0]; f.Summary.Code != "baseload.drift.down" || len(f.Apply) != 0 { + t.Errorf("finding %q with Apply %+v, want baseload.drift.down without a fix", f.Summary.Code, f.Apply) } if v, ok := values["site/base_w"]; !ok || v.Num != 180 { t.Errorf("site/base_w = %+v, want 180 after the swap", v) @@ -198,7 +202,7 @@ func TestBaseLoadDetectorIsEnergyDaily(t *testing.T) { } } -func TestBaseLoadCUSUMFindsSustainedRiseOnly(t *testing.T) { +func TestCUSUMFindsSustainedShiftInBothDirections(t *testing.T) { up := make([]float64, 40) down := make([]float64, 40) for i := range up { @@ -207,11 +211,34 @@ func TestBaseLoadCUSUMFindsSustainedRiseOnly(t *testing.T) { down[i] = -1.4 } } - if at, ok := baseLoadCUSUM(up); !ok || at != 20 { - t.Errorf("rise: got (%d, %v), want (20, true)", at, ok) + if at, rising, ok := CUSUM(up, 0, 1); !ok || !rising || at != 20 { + t.Errorf("rise: got (%d, %v, %v), want (20, true, true)", at, rising, ok) + } + if at, rising, ok := CUSUM(down, 0, 1); !ok || rising || at != 20 { + t.Errorf("fall: got (%d, %v, %v), want (20, false, true)", at, rising, ok) + } +} + +func TestBaseLoadDriftFallingNightsReportsDown(t *testing.T) { + in := blInput(60, func(i int) float64 { + if i < 20 { + return 260 + } + return 180 + }, func(i int) (float64, bool) { return 0, false }) + findings, _ := blSplit(in) + if len(findings) != 1 { + t.Fatalf("want one drift finding for falling nights, got %d", len(findings)) + } + f := findings[0] + if f.Summary.Code != "baseload.drift.down" { + t.Errorf("summary %q, want baseload.drift.down", f.Summary.Code) + } + if w := f.Summary.Params["w"]; w != 80.0 { + t.Errorf("w = %v, want 80 (the size of the fall)", w) } - if _, ok := baseLoadCUSUM(down); ok { - t.Errorf("fall gave a drift") + if len(f.Apply) != 0 { + t.Errorf("Apply = %+v, want none for a fall", f.Apply) } } diff --git a/dashboard/internal/autolearn/stats.go b/dashboard/internal/autolearn/stats.go index 696ece61..7a6a2648 100644 --- a/dashboard/internal/autolearn/stats.go +++ b/dashboard/internal/autolearn/stats.go @@ -193,33 +193,50 @@ func CircSpread(minutes []float64, center float64) float64 { return madToSigma * Median(dist) } -// CUSUM looks for an upward shift of the mean in the sequence r. The baseline -// is the median of r, the slack is 0.5 and the threshold 5. changeAt is the -// index where the shift starts. ok is false when there is no alarm, or when the -// values from changeAt on do not stay above the baseline plus the slack (so a -// single outlier does not count as a change). -func CUSUM(r []float64) (changeAt int, ok bool) { - if len(r) < 4 { - return 0, false - } - base := Median(r) - s := 0.0 - start := 0 - for t, x := range r { - prev := s - s = math.Max(0, s+x-base-cusumK) - if prev == 0 && s > 0 { - start = t +// CUSUM looks for a change of the mean in values, both ways (Spec 15.3). Each value +// is standardised as (v - expect) / spread, then S+ and S- run with the slack +// cusumK and the threshold cusumH. The first alarm is reported at index, the start +// of the run that crossed the threshold, and up tells the direction. A run only +// counts when its tail from index on stays beyond the slack in that direction, so a +// single outlier does not count as a change. ok is false when there is no change +// or spread is not positive. +func CUSUM(values []float64, expect, spread float64) (index int, up bool, ok bool) { + if len(values) < 4 || spread <= 0 { + return 0, false, false + } + z := make([]float64, len(values)) + for i, v := range values { + z[i] = (v - expect) / spread + } + sp, sm := 0.0, 0.0 + startP, startM := 0, 0 + for t, x := range z { + prevP := sp + sp = math.Max(0, sp+x-cusumK) + if prevP == 0 && sp > 0 { + startP = t + } + if sp > cusumH { + tail := z[startP:] + if len(tail) >= 3 && Median(tail) > cusumK { + return startP, true, true + } + sp = 0 + } + prevM := sm + sm = math.Max(0, sm-x-cusumK) + if prevM == 0 && sm > 0 { + startM = t } - if s > cusumH { - tail := append([]float64(nil), r[start:]...) - if len(tail) >= 3 && Median(tail) > base+cusumK { - return start, true + if sm > cusumH { + tail := z[startM:] + if len(tail) >= 3 && Median(tail) < -cusumK { + return startM, false, true } - return 0, false + sm = 0 } } - return 0, false + return 0, false, false } // TheilSen returns the Theil-Sen estimate of slope and intercept: the median of diff --git a/dashboard/internal/autolearn/stats_test.go b/dashboard/internal/autolearn/stats_test.go index 2017b08a..74ecddd9 100644 --- a/dashboard/internal/autolearn/stats_test.go +++ b/dashboard/internal/autolearn/stats_test.go @@ -147,9 +147,26 @@ func TestCUSUMDetectsStep(t *testing.T) { for i := 0; i < 10; i++ { r = append(r, 2.0) } - changeAt, ok := CUSUM(r) - if !ok { - t.Fatalf("CUSUM on step: ok = false, want true") + changeAt, up, ok := CUSUM(r, 0, 1) + if !ok || !up { + t.Fatalf("CUSUM on upward step: ok = %v, up = %v, want true, true", ok, up) + } + if changeAt < 20 || changeAt > 23 { + t.Fatalf("CUSUM changeAt = %d, want 20 to 23", changeAt) + } +} + +func TestCUSUMDetectsDownwardStep(t *testing.T) { + r := make([]float64, 0, 30) + for i := 0; i < 20; i++ { + r = append(r, 0) + } + for i := 0; i < 10; i++ { + r = append(r, -2.0) + } + changeAt, up, ok := CUSUM(r, 0, 1) + if !ok || up { + t.Fatalf("CUSUM on downward step: ok = %v, up = %v, want true, false", ok, up) } if changeAt < 20 || changeAt > 23 { t.Fatalf("CUSUM changeAt = %d, want 20 to 23", changeAt) @@ -159,7 +176,7 @@ func TestCUSUMDetectsStep(t *testing.T) { func TestCUSUMIgnoresSingleOutlier(t *testing.T) { r := make([]float64, 30) r[10] = 6.0 - if _, ok := CUSUM(r); ok { + if _, _, ok := CUSUM(r, 0, 1); ok { t.Fatalf("CUSUM on single outlier: ok = true, want false") } } diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index 7b0d47c9..d395c5e4 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -486,6 +486,9 @@ "automations.learn.band.more": "+{count}", "automations.learn.band.title": "Vorschläge aus dem Verhalten deiner Geräte", "automations.learn.baseload.candidate.none": "ein nicht gemessener Verbraucher", + "automations.learn.baseload.drift.down.line": "Nachts {w} W weniger, rund {kwh_month} kWh im Monat", + "automations.learn.baseload.drift.down.text": "Nachts braucht das Haus seit einigen Wochen {w} W weniger, rund {kwh_month} kWh im Monat.", + "automations.learn.baseload.drift.down.title": "Grundlast gesunken", "automations.learn.baseload.drift.line": "Nachts {w} W mehr, rund {kwh_month} kWh im Monat", "automations.learn.baseload.drift.text": "Nachts braucht das Haus seit einigen Wochen {w} W mehr, rund {kwh_month} kWh im Monat. Verursacher ist {candidate}.", "automations.learn.baseload.drift.title": "Grundlast steigt", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 0e6cd8e1..32793671 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -486,6 +486,9 @@ "automations.learn.band.more": "+{count}", "automations.learn.band.title": "Suggestions from how your devices are used", "automations.learn.baseload.candidate.none": "an unmeasured consumer", + "automations.learn.baseload.drift.down.line": "{w} W less at night, about {kwh_month} kWh a month", + "automations.learn.baseload.drift.down.text": "For several weeks the house has needed {w} W less at night, about {kwh_month} kWh a month.", + "automations.learn.baseload.drift.down.title": "Base load has dropped", "automations.learn.baseload.drift.line": "{w} W more at night, about {kwh_month} kWh a month", "automations.learn.baseload.drift.text": "For several weeks the house has needed {w} W more at night, about {kwh_month} kWh a month. The cause is {candidate}.", "automations.learn.baseload.drift.title": "Base load is rising", From 081de7b2c0681124d425fe681ad834531e95600a Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:20:02 +0100 Subject: [PATCH 08/22] fix(autolearn): replay learned values over their history and fix season edge cases Co-Authored-By: Claude Sonnet 5.5 --- .../internal/autolearn/detect_baseload.go | 7 +- dashboard/internal/autolearn/replaydata.go | 71 ++++++++++++++----- .../internal/autolearn/replaydata_test.go | 65 +++++++++++++++++ dashboard/internal/autolearn/season_store.go | 27 ++++--- .../internal/autolearn/season_store_test.go | 38 +++++++++- 5 files changed, 175 insertions(+), 33 deletions(-) diff --git a/dashboard/internal/autolearn/detect_baseload.go b/dashboard/internal/autolearn/detect_baseload.go index 3b0ddf18..03fc72a4 100644 --- a/dashboard/internal/autolearn/detect_baseload.go +++ b/dashboard/internal/autolearn/detect_baseload.go @@ -56,6 +56,7 @@ const ( type baseloadNight struct { date string week int + at time.Time group int night float64 // dev is the average power of each device with a record in the night, W. @@ -162,7 +163,7 @@ func baseloadNights(in *Input) []baseloadNight { dev[id] = sum / float64(n) } } - out = append(out, baseloadNight{date: f.Day, week: week, group: g, night: basePercentile10(load), dev: dev}) + out = append(out, baseloadNight{date: f.Day, week: week, at: t, group: g, night: basePercentile10(load), dev: dev}) } return out } @@ -295,7 +296,7 @@ func baseloadExpect(in *Input, ns []baseloadNight) []float64 { continue } var vals []float64 - for _, w := range in.Season.Same(n.week, baseloadMinYears) { + for _, w := range in.Season.Same(n.at, n.week, baseloadMinYears) { if w.BaseW > 0 { vals = append(vals, w.BaseW) } @@ -315,7 +316,7 @@ func baseloadSeasonKnown(in *Input, ns []baseloadNight) bool { } for _, n := range ns { count := 0 - for _, w := range in.Season.Same(n.week, baseloadMinYears) { + for _, w := range in.Season.Same(n.at, n.week, baseloadMinYears) { if w.BaseW > 0 { count++ } diff --git a/dashboard/internal/autolearn/replaydata.go b/dashboard/internal/autolearn/replaydata.go index cc142ee2..221ce50f 100644 --- a/dashboard/internal/autolearn/replaydata.go +++ b/dashboard/internal/autolearn/replaydata.go @@ -57,6 +57,15 @@ func ReplayDays(in *Input, days int) (minutes []ReplayMinute, estimate bool) { if in.Minutes != nil { pool = shapePool(in.Minutes, minuteStarts) } + if len(plan) > 0 { + // A value that changed after the first minute is replayed from its + // history, which is an estimate. + for _, e := range learned { + if e.hist && e.at.After(plan[0].start) { + estimate = true + } + } + } for _, p := range plan { if p.file == nil { minutes = append(minutes, minuteDay(in.Minutes, p.start, learned)...) @@ -165,11 +174,32 @@ func replayLoc(in *Input) *time.Location { return time.Local } -// learnedEntry is one numeric learned value with the time it was learned. +// learnedEntry is one numeric learned value. at is the time it became the +// value it has now, the change time when the entry has one, else its learning +// time. hist marks an entry with a change time: its value is known at every +// minute, before the change as prev (or the current value without prev). type learnedEntry struct { - key string - val float64 - at time.Time + key string + val float64 + prev float64 + hasPrev bool + at time.Time + hist bool +} + +// numericValue returns the number held in x, ok false for other values. +func numericValue(x any) (float64, bool) { + switch v := x.(type) { + case float64: + return v, true + case float32: + return float64(v), true + case int: + return float64(v), true + case int64: + return float64(v), true + } + return 0, false } // numericLearned keeps the learned values that hold a number, in key order. @@ -182,35 +212,40 @@ func numericLearned(in map[string]LearnedEntry) []learnedEntry { var out []learnedEntry for _, k := range keys { e := in[k] - var v float64 - switch x := e.Value.(type) { - case float64: - v = x - case float32: - v = float64(x) - case int: - v = float64(x) - case int64: - v = float64(x) - default: + v, ok := numericValue(e.Value) + if !ok { continue } - out = append(out, learnedEntry{key: k, val: v, at: time.Unix(e.At, 0)}) + le := learnedEntry{key: k, val: v, at: time.Unix(e.At, 0)} + if e.ChangedAt > 0 { + le.hist = true + le.at = time.Unix(e.ChangedAt, 0) + le.prev, le.hasPrev = numericValue(e.Prev) + } + out = append(out, le) } return out } // learnedAt returns the learned values that were known at t, nil when none. +// A value with a change time is known at every minute: its prev before the +// change, its current value from then on. Any other value is known from its +// learning time on. func learnedAt(entries []learnedEntry, t time.Time) map[string]float64 { var out map[string]float64 for _, e := range entries { - if e.at.After(t) { + v := e.val + if e.hist { + if t.Before(e.at) && e.hasPrev { + v = e.prev + } + } else if e.at.After(t) { continue } if out == nil { out = make(map[string]float64, len(entries)) } - out[e.key] = e.val + out[e.key] = v } return out } diff --git a/dashboard/internal/autolearn/replaydata_test.go b/dashboard/internal/autolearn/replaydata_test.go index de8c1cb1..9b877c74 100644 --- a/dashboard/internal/autolearn/replaydata_test.go +++ b/dashboard/internal/autolearn/replaydata_test.go @@ -295,3 +295,68 @@ func TestEngineInputCarriesTheSteps(t *testing.T) { t.Fatal("after SetSteps the input has no step reader") } } + +// minuteAt returns the replayed minute that starts at at. +func minuteAt(ms []ReplayMinute, at time.Time) (ReplayMinute, bool) { + for _, m := range ms { + if m.At.Equal(at) { + return m, true + } + } + return ReplayMinute{}, false +} + +func TestReplayLearnedBeforeChange(t *testing.T) { + loc := time.UTC + now := replayTestNow() + changed := now.AddDate(0, 0, -30) // 2026-10-23 10:00 + before := time.Date(2026, 10, 22, 0, 0, 0, 0, loc) + after := time.Date(2026, 10, 24, 0, 0, 0, 0, loc) + minutes := fakeMinutes{loc: loc, days: map[string]map[string][]float32{ + "2026-10-22": {"b:load_total": minuteValues(500)}, + "2026-10-24": {"b:load_total": minuteValues(500)}, + }} + entry := func(prev any, changedAt int64) map[string]LearnedEntry { + return map[string]LearnedEntry{"site/pv_reserve_w": {Key: "site/pv_reserve_w", Kind: ValueNumber, + Value: 1500.0, Prev: prev, At: now.Unix(), ChangedAt: changedAt}} + } + + t.Run("prev before the change", func(t *testing.T) { + in := &Input{Now: now, Loc: loc, Minutes: minutes, Learned: entry(900.0, changed.Unix())} + got, est := ReplayDays(in, 40) + if !est { + t.Fatal("estimate = false, want true when a value is replayed before its change") + } + m, ok := minuteAt(got, before) + if !ok || m.Learned["site/pv_reserve_w"] != 900 { + t.Fatalf("before the change = %v, want the prev value 900", m.Learned) + } + m, ok = minuteAt(got, after) + if !ok || m.Learned["site/pv_reserve_w"] != 1500 { + t.Fatalf("after the change = %v, want 1500", m.Learned) + } + }) + + t.Run("no prev uses the current value", func(t *testing.T) { + in := &Input{Now: now, Loc: loc, Minutes: minutes, Learned: entry(nil, changed.Unix())} + got, est := ReplayDays(in, 40) + if !est { + t.Fatal("estimate = false, want true") + } + m, ok := minuteAt(got, before) + if !ok || m.Learned["site/pv_reserve_w"] != 1500 { + t.Fatalf("before the change = %v, want the current value 1500", m.Learned) + } + }) + + t.Run("without change time the value is not known before At", func(t *testing.T) { + in := &Input{Now: now, Loc: loc, Minutes: minutes, Learned: entry(900.0, 0)} + got, est := ReplayDays(in, 40) + if est { + t.Fatal("estimate = true, want false without history") + } + if m, ok := minuteAt(got, before); !ok || len(m.Learned) != 0 { + t.Fatalf("before At = %v, want no learned value", m.Learned) + } + }) +} diff --git a/dashboard/internal/autolearn/season_store.go b/dashboard/internal/autolearn/season_store.go index 85f5b1bb..35bce68a 100644 --- a/dashboard/internal/autolearn/season_store.go +++ b/dashboard/internal/autolearn/season_store.go @@ -321,7 +321,7 @@ func (s *SeasonStore) PriorEmptyShare(week int) (float64, bool) { return 0, false } var vals []float64 - for _, w := range s.Same(week, seasonYears) { + for _, w := range s.Same(time.Now(), week, seasonYears) { if w.EmptyShare != nil { vals = append(vals, *w.EmptyShare) } @@ -333,18 +333,19 @@ func (s *SeasonStore) PriorEmptyShare(week int) (float64, bool) { } // Same lists the weeks of the calendar week and its neighbours (one week before -// and after) in the given number of years before the current year, oldest first. -func (s *SeasonStore) Same(week int, years int) []Week { +// and after) in the given number of years before the ISO year of ref, oldest +// first. The weeks are taken from the Monday of each week, so week 1 reaches +// into the year before and a week 53 that a year does not have is the week +// it is in the next year. +func (s *SeasonStore) Same(ref time.Time, week int, years int) []Week { s.mu.Lock() defer s.mu.Unlock() - year := time.Now().Year() + year, _ := ref.ISOWeek() var out []Week for k := 1; k <= years; k++ { - for w := week - 1; w <= week+1; w++ { - if w < 1 || w > 53 { - continue - } - if rec, ok := s.weeks[fmt.Sprintf("%d-W%02d", year-k, w)]; ok { + for d := -1; d <= 1; d++ { + key := isoWeekKey(isoWeekMondayOf(year-k, week+d)) + if rec, ok := s.weeks[key]; ok { out = append(out, rec) } } @@ -400,9 +401,15 @@ func isoWeekMonday(key string) (time.Time, bool) { if _, err := fmt.Sscanf(key, "%d-W%d", &y, &w); err != nil { return time.Time{}, false } + return isoWeekMondayOf(y, w), true +} + +// isoWeekMondayOf is the Monday (UTC) of week w of ISO year y. A week number +// past the end of the year, or below 1, falls into the neighbouring year. +func isoWeekMondayOf(y, w int) time.Time { jan4 := time.Date(y, time.January, 4, 0, 0, 0, 0, time.UTC) offset := (int(jan4.Weekday()) + 6) % 7 - return jan4.AddDate(0, 0, -offset+(w-1)*7), true + return jan4.AddDate(0, 0, -offset+(w-1)*7) } func sortWeeks(ws []Week) { diff --git a/dashboard/internal/autolearn/season_store_test.go b/dashboard/internal/autolearn/season_store_test.go index e9eccfbd..1e6fddbe 100644 --- a/dashboard/internal/autolearn/season_store_test.go +++ b/dashboard/internal/autolearn/season_store_test.go @@ -187,7 +187,7 @@ func TestSeasonSameWeekOfPriorYears(t *testing.T) { store.Put(Week{Key: fmt.Sprintf("%d-W47", y), Source: "days"}) var keys []string - for _, w := range store.Same(47, 2) { + for _, w := range store.Same(time.Now(), 47, 2) { keys = append(keys, w.Key) } want := []string{ @@ -195,7 +195,7 @@ func TestSeasonSameWeekOfPriorYears(t *testing.T) { fmt.Sprintf("%d-W46", y-1), fmt.Sprintf("%d-W47", y-1), fmt.Sprintf("%d-W48", y-1), } if !reflect.DeepEqual(keys, want) { - t.Errorf("Same(47, 2) = %v, want %v", keys, want) + t.Errorf("Same(now, 47, 2) = %v, want %v", keys, want) } } @@ -342,3 +342,37 @@ func TestSeasonEmptyShareSavedAndLoaded(t *testing.T) { t.Fatalf("reloaded week = %+v, want empty share 0.25", ws) } } + +func TestSeasonSameUsesISOYear(t *testing.T) { + store := LoadSeasonStore(filepath.Join(t.TempDir(), "season.json"), nil) + // 2027-01-02 is ISO week 2026-W53. 2025 has 52 weeks, so its week 53 is + // 2026-W01, and the running week 2026-W53 must never be an answer. + for _, k := range []string{"2024-W53", "2025-W52", "2026-W01", "2026-W02", "2026-W53", "2027-W01"} { + store.Put(Week{Key: k, Source: "days"}) + } + ref := time.Date(2027, 1, 2, 0, 0, 0, 0, time.UTC) + var keys []string + for _, w := range store.Same(ref, 53, 1) { + keys = append(keys, w.Key) + } + want := []string{"2025-W52", "2026-W01", "2026-W02"} + if !reflect.DeepEqual(keys, want) { + t.Errorf("Same(2027-01-02, 53, 1) = %v, want %v", keys, want) + } +} + +func TestSeasonSameWrapsWeekOne(t *testing.T) { + store := LoadSeasonStore(filepath.Join(t.TempDir(), "season.json"), nil) + for _, k := range []string{"2024-W52", "2025-W01", "2025-W02", "2025-W03"} { + store.Put(Week{Key: k, Source: "days"}) + } + ref := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) // ISO 2026-W01 + var keys []string + for _, w := range store.Same(ref, 1, 1) { + keys = append(keys, w.Key) + } + want := []string{"2024-W52", "2025-W01", "2025-W02"} + if !reflect.DeepEqual(keys, want) { + t.Errorf("Same(2026-01-01, 1, 1) = %v, want %v", keys, want) + } +} From 0a38900a3a946cf0a4211893cd7ab44b952d15da Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:23:20 +0100 Subject: [PATCH 09/22] fix(autolearn): fix threshold plateau, replay base once and count PV days Co-Authored-By: Claude Sonnet 5.5 --- .../internal/autolearn/detect_threshold.go | 75 ++++++++++++++----- .../autolearn/detect_threshold_test.go | 45 +++++++++++ dashboard/internal/autolearn/pvraster.go | 11 +++ dashboard/internal/autolearn/pvraster_test.go | 14 ++++ .../internal/autolearn/pvreserve_runner.go | 33 +++++++- .../autolearn/pvreserve_runner_test.go | 40 +++++++++- 6 files changed, 197 insertions(+), 21 deletions(-) diff --git a/dashboard/internal/autolearn/detect_threshold.go b/dashboard/internal/autolearn/detect_threshold.go index 72c44b63..bac2cb74 100644 --- a/dashboard/internal/autolearn/detect_threshold.go +++ b/dashboard/internal/autolearn/detect_threshold.go @@ -113,6 +113,7 @@ func thresholdRule(ctx context.Context, in *Input, r Rule, minutes []ReplayMinut run0 := minRunForRole(info) base := thresholdTarget{rule: r.ID, device: device, opW: p, peakW: feedbackInrush(in.Days, device, p), cycleWh: cycle} real := RealState(in, device, minutes) + bases := newThresholdBases(base, minutes, real, loc, site) hysts := []float64{hyst0} runs := []float64{run0} @@ -128,7 +129,7 @@ func thresholdRule(ctx context.Context, in *Input, r Rule, minutes []ReplayMinut bestRow, bestJ := -1, math.Inf(-1) for _, h := range hysts { for _, m := range runs { - row, err := thresholdRow(ctx, in, r, idx, base, m, h, grid, minutes, real, loc, site) + row, err := thresholdRow(ctx, in, r, idx, bases, m, h, grid) if err != nil { return Candidate{}, false } @@ -153,11 +154,11 @@ func thresholdRule(ctx context.Context, in *Input, r Rule, minutes []ReplayMinut // Gain against today's rule, per week, and the halves of the days. nDays := float64(len(days)) - todayPt := thresholdEval(ctx, in, r, idx, base, run0, hyst0, today, minutes, real, loc, site) + todayPt := thresholdEval(ctx, in, r, idx, bases, run0, hyst0, today) if todayPt.err != nil { return Candidate{}, false } - chosenEval := thresholdEval(ctx, in, r, idx, base, chosen.m, chosen.h, soll, minutes, real, loc, site) + chosenEval := thresholdEval(ctx, in, r, idx, bases, chosen.m, chosen.h, soll) if chosenEval.err != nil { return Candidate{}, false } @@ -199,19 +200,56 @@ type thresholdEvalResult struct { err error } -// thresholdEval replays one point of the grid on the given minutes: the rule -// with threshold x, hysteresis h and minimum run m. It returns J with its terms. -func thresholdEval(ctx context.Context, in *Input, r Rule, idx int, t thresholdTarget, m, h, x float64, minutes []ReplayMinute, real []bool, loc *time.Location, site sun.Location) thresholdEvalResult { - target := ReplayTarget{RuleID: t.rule, Device: t.device, OpW: t.opW, PeakW: t.peakW, CycleWh: t.cycleWh, MinRunS: m} +// thresholdBaseReplay runs the base replay of the rating. Tests replace it to +// count the base runs. +var thresholdBaseReplay = Replay + +// thresholdBases holds the base replays of one rule on one set of minutes. The +// base depends only on MinRunS, so each MinRunS is replayed once. +type thresholdBases struct { + t thresholdTarget + minutes []ReplayMinute + real []bool + loc *time.Location + site sun.Location + byM map[float64]ReplayResult +} + +// newThresholdBases creates an empty cache for the minutes. +func newThresholdBases(t thresholdTarget, minutes []ReplayMinute, real []bool, loc *time.Location, site sun.Location) *thresholdBases { + return &thresholdBases{t: t, minutes: minutes, real: real, loc: loc, site: site, byM: map[float64]ReplayResult{}} +} + +// target returns the replay target of the rule with minimum run m. +func (b *thresholdBases) target(m float64) ReplayTarget { + return ReplayTarget{RuleID: b.t.rule, Device: b.t.device, OpW: b.t.opW, PeakW: b.t.peakW, CycleWh: b.t.cycleWh, MinRunS: m} +} + +// base returns the base replay for minimum run m, replaying it on first use. +func (b *thresholdBases) base(ctx context.Context, m float64) (ReplayResult, error) { + if res, ok := b.byM[m]; ok { + return res, nil + } + res, err := thresholdBaseReplay(ctx, replayBaseRule, b.target(m), b.minutes, b.real, b.loc, b.site) + if err != nil { + return ReplayResult{}, err + } + b.byM[m] = res + return res, nil +} + +// thresholdEval replays one point of the grid: the rule with threshold x, +// hysteresis h and minimum run m, against the base. It returns J with its terms. +func thresholdEval(ctx context.Context, in *Input, r Rule, idx int, b *thresholdBases, m, h, x float64) thresholdEvalResult { raw, err := thresholdRuleJSON(r, idx, x, h) if err != nil { return thresholdEvalResult{err: err} } - base, err := Replay(ctx, replayBaseRule, target, minutes, real, loc, site) + base, err := b.base(ctx, m) if err != nil { return thresholdEvalResult{err: err} } - alt, err := Replay(ctx, raw, target, minutes, real, loc, site) + alt, err := Replay(ctx, raw, b.target(m), b.minutes, b.real, b.loc, b.site) if err != nil { return thresholdEvalResult{err: err} } @@ -220,13 +258,13 @@ func thresholdEval(ctx context.Context, in *Input, r Rule, idx int, t thresholdT } // thresholdRow rates the whole grid for one hysteresis and minimum run. -func thresholdRow(ctx context.Context, in *Input, r Rule, idx int, t thresholdTarget, m, h float64, grid []float64, minutes []ReplayMinute, real []bool, loc *time.Location, site sun.Location) ([]thresholdPoint, error) { +func thresholdRow(ctx context.Context, in *Input, r Rule, idx int, b *thresholdBases, m, h float64, grid []float64) ([]thresholdPoint, error) { row := make([]thresholdPoint, 0, len(grid)) for _, x := range grid { if err := ctx.Err(); err != nil { return nil, err } - ev := thresholdEval(ctx, in, r, idx, t, m, h, x, minutes, real, loc, site) + ev := thresholdEval(ctx, in, r, idx, b, m, h, x) if ev.err != nil { return nil, ev.err } @@ -236,20 +274,22 @@ func thresholdRow(ctx context.Context, in *Input, r Rule, idx int, t thresholdTa } // thresholdWidest returns the middle of the widest run of points whose J is -// at least thresholdPlateau of the maximum of the row. Ties keep the first run. +// at least the plateau floor maxJ - (1 - thresholdPlateau) * |maxJ| of the +// maximum of the row. Ties keep the first run. func thresholdWidest(row []thresholdPoint) thresholdPoint { maxJ := math.Inf(-1) for _, pt := range row { maxJ = math.Max(maxJ, pt.j) } + floor := maxJ - (1-thresholdPlateau)*math.Abs(maxJ) bestStart, bestEnd := -1, -1 for i := 0; i < len(row); { - if row[i].j < thresholdPlateau*maxJ { + if row[i].j < floor { i++ continue } s := i - for i < len(row) && row[i].j >= thresholdPlateau*maxJ { + for i < len(row) && row[i].j >= floor { i++ } e := i - 1 @@ -276,10 +316,9 @@ func thresholdHalvesAgree(ctx context.Context, in *Input, r Rule, idx int, t thr if hi <= lo { return false } - mins := minutes[lo:hi] - rl := real[lo:hi] - prop := thresholdEval(ctx, in, r, idx, t, m, h, soll, mins, rl, loc, site) - now := thresholdEval(ctx, in, r, idx, t, run0, hyst0, today, mins, rl, loc, site) + halfBases := newThresholdBases(t, minutes[lo:hi], real[lo:hi], loc, site) + prop := thresholdEval(ctx, in, r, idx, halfBases, m, h, soll) + now := thresholdEval(ctx, in, r, idx, halfBases, run0, hyst0, today) if prop.err != nil || now.err != nil { return false } diff --git a/dashboard/internal/autolearn/detect_threshold_test.go b/dashboard/internal/autolearn/detect_threshold_test.go index 6507b712..f691fb07 100644 --- a/dashboard/internal/autolearn/detect_threshold_test.go +++ b/dashboard/internal/autolearn/detect_threshold_test.go @@ -3,10 +3,12 @@ package autolearn import ( "context" "fmt" + "math" "testing" "time" "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" ) // thresholdDoc builds the rule document of one surplus rule switching the plug. @@ -177,3 +179,46 @@ func TestThresholdJointHoldAddsFactsOnly(t *testing.T) { t.Fatalf("joint hold must set only the threshold, fixes = %+v", f.Apply) } } + +func TestThresholdWidestNegative(t *testing.T) { + // All J are negative. The maximum -1 sits at 1200, the points within 5 % + // of it (1000 to 1400) form the plateau, its middle is 1200. + var row []thresholdPoint + for i := 0; i < 15; i++ { + x := 600 + 100*float64(i) + j := -3.0 + if math.Abs(x-1200) <= 200 { + j = -1.0 - 0.02*math.Abs(x-1200)/200 + } + row = append(row, thresholdPoint{x: x, j: j}) + } + if mid := thresholdWidest(row).x; mid != 1200 { + t.Fatalf("mid = %v, want 1200", mid) + } +} + +func TestThresholdBaseReplayOnce(t *testing.T) { + // Count the base replays by the minutes they run on and their MinRunS. + // Every pair must run once, however many grid points use it. + calls := map[string]int{} + orig := thresholdBaseReplay + thresholdBaseReplay = func(ctx context.Context, rule any, target ReplayTarget, mins []ReplayMinute, real []bool, loc *time.Location, site sun.Location) (ReplayResult, error) { + if r, ok := rule.(Rule); ok && r.ID == replayBaseRule.ID && len(mins) > 0 { + calls[fmt.Sprintf("%v/%d/%v", mins[0].At, len(mins), target.MinRunS)]++ + } + return orig(ctx, rule, target, mins, real, loc, site) + } + t.Cleanup(func() { thresholdBaseReplay = orig }) + + in := thresholdInput(t, thresholdDoc(t, 3000, ""), thresholdFixtureDays(t, surplus2500)) + in.Limits = learnrec.LimitsFor(learnrec.LevelFull, 4) + thresholdRunOn(t, in) + if len(calls) == 0 { + t.Fatal("no base replay counted") + } + for k, n := range calls { + if n != 1 { + t.Errorf("base replay %s ran %d times, want 1", k, n) + } + } +} diff --git a/dashboard/internal/autolearn/pvraster.go b/dashboard/internal/autolearn/pvraster.go index 4a6c1400..b76d9dd8 100644 --- a/dashboard/internal/autolearn/pvraster.go +++ b/dashboard/internal/autolearn/pvraster.go @@ -88,6 +88,17 @@ func (r *Raster) Cell(az, el float64) (w float64, ok bool) { return c.Vals[1].W, true } +// DayCount returns the number of distinct days that have a stored sample. +func (r *Raster) DayCount() int { + days := map[string]bool{} + for _, c := range r.cells { + for _, s := range c.Vals { + days[s.Day] = true + } + } + return len(days) +} + // Each calls fn with the centre az/el and the Cell value of every cell that // has a value. Cells with fewer than two values are skipped. func (r *Raster) Each(fn func(az, el, w float64)) { diff --git a/dashboard/internal/autolearn/pvraster_test.go b/dashboard/internal/autolearn/pvraster_test.go index ed275d80..b30779a9 100644 --- a/dashboard/internal/autolearn/pvraster_test.go +++ b/dashboard/internal/autolearn/pvraster_test.go @@ -174,3 +174,17 @@ func TestRasterPruneDaysKeepsTheGivenWindow(t *testing.T) { t.Fatal("recent cell dropped") } } + +func TestRasterDayCountCountsDaysWithData(t *testing.T) { + r := NewRaster(5, 3) + r.Add(100, 40, 3000, "2026-06-01") + r.Add(100, 40, 2000, "2026-06-01") + r.Add(200, 30, 1000, "2026-06-02") + r.Add(10, 20, 500, "2026-06-03") + if n := r.DayCount(); n != 3 { + t.Fatalf("DayCount = %d, want 3", n) + } + if n := NewRaster(5, 3).DayCount(); n != 0 { + t.Fatalf("empty DayCount = %d, want 0", n) + } +} diff --git a/dashboard/internal/autolearn/pvreserve_runner.go b/dashboard/internal/autolearn/pvreserve_runner.go index d8063ed3..ce70bd24 100644 --- a/dashboard/internal/autolearn/pvreserve_runner.go +++ b/dashboard/internal/autolearn/pvreserve_runner.go @@ -80,6 +80,9 @@ func (r *PVReserveRunner) ObserveMinute(f learnrec.Frame) { r.weather.Observe(f.Minute, pv, best, r.tracker.LastUnthrottled()) k, kLow, fresh := r.weather.K(f.Minute) r.w, r.est = Reserve(best, pv, kLow, fresh) + if !model.Safe { + r.est = true + } r.have = true if f.Balance != nil { f.Balance["k"] = k @@ -95,6 +98,12 @@ func (r *PVReserveRunner) Current() (w float64, est bool, ok bool) { return r.w, r.est, r.have } +// DayCount returns the number of days the PV raster has samples for. It works +// on a snapshot, so it is safe while the minute hub runs. +func (r *PVReserveRunner) DayCount() int { + return r.tracker.Snapshot().DayCount() +} + // Save writes the weather state atomically, but only when it changed since the // last save. func (r *PVReserveRunner) Save() error { @@ -144,6 +153,19 @@ func writePVWeatherFile(path string, data []byte) error { // site/pv_reserve_w in W, rounded to 50 W. current is the runner's Current. The // detector returns one learned value and no finding. func PVReserveDetector(current func() (float64, bool, bool)) Detector { + return pvReserveDetector(current, nil) +} + +// PVReserveDetectorWithDays is PVReserveDetector with the gate on the days of +// the PV raster: days returns how many days have samples, and the candidate +// needs pvReserveMinDays of them. +func PVReserveDetectorWithDays(current func() (float64, bool, bool), days func() int) Detector { + return pvReserveDetector(current, days) +} + +// pvReserveDetector builds the detector. A nil days function gives one day and +// no gate. +func pvReserveDetector(current func() (float64, bool, bool), days func() int) Detector { return Detector{ Name: "learn_pv_reserve", Group: "energy", @@ -157,10 +179,14 @@ func PVReserveDetector(current func() (float64, bool, bool)) Detector { if !ok { return nil } + neff, minNEff := 1.0, 1.0 + if days != nil { + neff, minNEff = float64(days()), pvReserveMinDays + } return []Candidate{{ Detector: "learn_pv_reserve", - NEff: 1, - MinNEff: 1, + NEff: neff, + MinNEff: minNEff, Value: &Value{Key: "site/pv_reserve_w", Kind: ValueNumber, Unit: "W", Group: "energy", Num: math.Round(w/pvReserveStepW) * pvReserveStepW, N: 1, Estimate: est}, }} @@ -171,6 +197,9 @@ func PVReserveDetector(current func() (float64, bool, bool)) Detector { // pvReserveStepW is the rounding step of the published PV reserve in W. const pvReserveStepW = 50.0 +// pvReserveMinDays is the number of days with PV samples the reserve needs. +const pvReserveMinDays = 14.0 + // Reset setzt den Wetterfaktor und die Reserve zurueck und loescht pvweather.json. // Ein erneutes Save schreibt den leeren Stand. func (r *PVReserveRunner) Reset() error { diff --git a/dashboard/internal/autolearn/pvreserve_runner_test.go b/dashboard/internal/autolearn/pvreserve_runner_test.go index 54b65fe9..63b9a347 100644 --- a/dashboard/internal/autolearn/pvreserve_runner_test.go +++ b/dashboard/internal/autolearn/pvreserve_runner_test.go @@ -10,12 +10,13 @@ import ( "time" "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" ) // reserveTestModel is a model whose surfaces give nothing, so Best is the raster // cell value, capped at 10000 W. func reserveTestModel() PVModel { - return PVModel{CapW: 10000} + return PVModel{CapW: 10000, Safe: true} } // reserveTestRunner builds a runner with a model in store, a location, a tracker @@ -197,3 +198,40 @@ func TestPVReserveDetectorPublishesRoundedNumber(t *testing.T) { }) } } + +func TestPVReserveNeedsDays(t *testing.T) { + r, tr := reserveTestRunner(t, true) + // One sample on each of 10 days, each day in its own sky cell so no cell + // keeps only the top values and drops a day. The sample of pvTestMinute's + // cell is the reserve base. + az, el := sun.Position(pvTestMinute, 52.5, 13.4) + start := time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC) + for i := 0; i < 10; i++ { + tr.Raster().Add(az+5*float64(i), el, 4000, start.AddDate(0, 0, i).Format(pvDayLayout)) + } + bal := map[string]float64{"pv": 1500} + r.ObserveMinute(learnrec.Frame{Minute: pvTestMinute, Balance: bal}) + if _, est, ok := r.Current(); !ok || est { + t.Fatalf("Current ok=%v est=%v, want ok true, est false", ok, est) + } + + det := PVReserveDetectorWithDays(r.Current, r.DayCount) + out := det.Run(context.Background(), &Input{}, "") + if len(out) != 1 { + t.Fatalf("got %d candidates, want 1", len(out)) + } + c := out[0] + if c.NEff != 10 || c.MinNEff != 14 { + t.Fatalf("NEff, MinNEff = %v, %v; want 10, 14", c.NEff, c.MinNEff) + } + if c.NEff >= c.MinNEff { + t.Fatal("candidate with 10 days must fall at the gate") + } + + // A model that does not cover enough sky makes the reserve an estimate. + r.models.Set(PVModel{CapW: 10000, Safe: false}) + r.ObserveMinute(learnrec.Frame{Minute: pvTestMinute, Balance: bal}) + if _, est, ok := r.Current(); !ok || !est { + t.Fatalf("Current ok=%v est=%v with unsafe model, want ok true, est true", ok, est) + } +} From 6edba7cfab220cedcf8fa0d34112e9fc5ec4dd0e Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:23:57 +0100 Subject: [PATCH 10/22] fix(autolearn): use the PV day count in production wiring Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/learn_engine.go | 6 +++--- dashboard/cmd/dashboard/main.go | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/dashboard/cmd/dashboard/learn_engine.go b/dashboard/cmd/dashboard/learn_engine.go index 9cd425cd..d66f1525 100644 --- a/dashboard/cmd/dashboard/learn_engine.go +++ b/dashboard/cmd/dashboard/learn_engine.go @@ -221,10 +221,10 @@ func anyGroupOn(groups map[string]bool) bool { // registerEnergyDetectors meldet die Erkenner der Gruppe Energie bei der Engine. // Sie laufen nur, wenn der Schalter Energie an ist. reserve liefert die PV-Reserve -// der letzten Minute, check ist die Selbstpruefung der Prognose des Rest-Ueberschusses. -func registerEnergyDetectors(e *autolearn.Engine, reserve func() (float64, bool, bool), check *autolearn.ForecastCheck) { +// der letzten Minute, days zaehlt die Tage der PV-Daten fuer das Tor, check ist die Selbstpruefung der Prognose des Rest-Ueberschusses. +func registerEnergyDetectors(e *autolearn.Engine, reserve func() (float64, bool, bool), days func() int, check *autolearn.ForecastCheck) { e.Register(autolearn.TemperatureDetector) - e.Register(autolearn.PVReserveDetector(reserve)) + e.Register(autolearn.PVReserveDetectorWithDays(reserve, days)) e.Register(autolearn.LearnCyclesDetector) e.Register(autolearn.NewLearnSurplusDetector(check)) e.Register(autolearn.SurplusDetector) diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index 727269c9..aae24bbf 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -598,7 +598,7 @@ func main() { forecastCheck := autolearn.LoadForecastCheck(filepath.Join(autolearnDir, "forecast.json"), log.Printf) learnHub.AddSaver("forecast", forecastCheck) learnHub.AddResetter("forecast", forecastCheck) - registerEnergyDetectors(automationEngine, pvReserve.Current, forecastCheck) + registerEnergyDetectors(automationEngine, pvReserve.Current, pvReserve.DayCount, forecastCheck) automationEngine.Register(autolearn.BaseLoadDetector) automationEngine.Register(autolearn.BatteryDetector) automationEngine.Register(autolearn.NewPVModelDetector(pvTracker.Snapshot, pvModelStore)) From edc5b1d79982b3af821a2f4b2cd4ff7e888d559d Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:26:31 +0100 Subject: [PATCH 11/22] fix(learnrec): keep recording what Home Assistant cannot deliver and clean every location While paused, the minute store now only skips the keys Home Assistant can deliver (e:*, b:pv, b:battery_soc). Other keys keep being recorded. Reset and retention cover every location the store has used, not only the current and the previous one. Days dropped with unwritten minutes are logged. The prefetch is skipped when the companion has not offered any series. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/learn_ha_prepare.go | 3 +- .../cmd/dashboard/learn_ha_prepare_test.go | 14 ++ dashboard/internal/learnrec/hasync.go | 15 +++ dashboard/internal/learnrec/hasync_test.go | 17 +++ dashboard/internal/learnrec/minutestore.go | 108 +++++++++++----- .../internal/learnrec/minutestore_test.go | 121 +++++++++++++++++- 6 files changed, 242 insertions(+), 36 deletions(-) diff --git a/dashboard/cmd/dashboard/learn_ha_prepare.go b/dashboard/cmd/dashboard/learn_ha_prepare.go index e52e33b2..41d8028f 100644 --- a/dashboard/cmd/dashboard/learn_ha_prepare.go +++ b/dashboard/cmd/dashboard/learn_ha_prepare.go @@ -14,6 +14,7 @@ const haPrefetchTimeout = 90 * time.Second // haFetcher ist der Teil des Abgleichs, den der Vorlauf braucht. type haFetcher interface { + Offered() bool Prefetch(keys []string, days []string, deadline time.Time) WaitIdle(ctx context.Context) bool Drop() @@ -61,7 +62,7 @@ func (p *haPreparer) Prepare(now time.Time) { days = append(days, start.Format("2006-01-02")) } } - if len(days) == 0 { + if len(days) == 0 || !p.ha.Offered() { return } keys := make([]string, 0, len(keySet)) diff --git a/dashboard/cmd/dashboard/learn_ha_prepare_test.go b/dashboard/cmd/dashboard/learn_ha_prepare_test.go index 585ac283..dfd4d232 100644 --- a/dashboard/cmd/dashboard/learn_ha_prepare_test.go +++ b/dashboard/cmd/dashboard/learn_ha_prepare_test.go @@ -26,8 +26,11 @@ type fakeHA struct { days []string deadline time.Time drops int + noOffer bool } +func (f *fakeHA) Offered() bool { return !f.noOffer } + func (f *fakeHA) Prefetch(keys []string, days []string, deadline time.Time) { f.prefetches++ f.keys, f.days, f.deadline = keys, days, deadline @@ -37,6 +40,17 @@ func (f *fakeHA) WaitIdle(ctx context.Context) bool { return true } func (f *fakeHA) Drop() { f.drops++ } +func TestHAPreparerSkipsPrefetchWithoutOffer(t *testing.T) { + now := time.Date(2026, 11, 20, 3, 30, 0, 0, time.UTC) + ha := &fakeHA{noOffer: true} + own := &fakeOwn{keys: []string{"e:uid1"}} + p := &haPreparer{own: own, ha: ha, active: func() bool { return true }, loc: time.UTC} + p.Prepare(now) + if ha.prefetches != 0 { + t.Fatalf("Prefetch ohne Angebot des Companion aufgerufen: %d", ha.prefetches) + } +} + func TestHAPreparerDoesNothingWhenReconcileIsOff(t *testing.T) { ha := &fakeHA{} p := &haPreparer{own: &fakeOwn{}, ha: ha, active: func() bool { return false }, loc: time.UTC} diff --git a/dashboard/internal/learnrec/hasync.go b/dashboard/internal/learnrec/hasync.go index 32cbf3de..4692aac5 100644 --- a/dashboard/internal/learnrec/hasync.go +++ b/dashboard/internal/learnrec/hasync.go @@ -328,6 +328,21 @@ func (s *HASync) Reset() error { return nil } +// HASeriesKey meldet, ob der Companion einen Lern-Schluessel liefern kann +// (e:, b:pv, b:battery_soc). +func HASeriesKey(key string) bool { + _, ok := haSeriesFor(key) + return ok +} + +// Offered meldet, ob der Companion Serien angeboten hat, die der Abgleich +// nutzen kann. +func (s *HASync) Offered() bool { + s.mu.Lock() + defer s.mu.Unlock() + return len(s.offered) > 0 +} + // haSeriesFor uebersetzt einen Lern-Schluessel in den Serienamen des // Companion. Nur e:, b:pv und b:battery_soc sind belegt; Netz, Last und // Speicher bleiben offen, bis Vorzeichen und Einheit geprueft sind. diff --git a/dashboard/internal/learnrec/hasync_test.go b/dashboard/internal/learnrec/hasync_test.go index 1d9a52e1..c9bc5a15 100644 --- a/dashboard/internal/learnrec/hasync_test.go +++ b/dashboard/internal/learnrec/hasync_test.go @@ -319,3 +319,20 @@ func TestHASyncWaitIdleTrueWithoutWork(t *testing.T) { t.Fatal("ohne Nachfragen muss WaitIdle sofort Leerlauf melden") } } + +func TestPrefetchWithoutOfferReturnsAtOnce(t *testing.T) { + s := NewHASync(hsClock, hsLimits(16<<20), hsLoc) + s.Prefetch([]string{"e:x", "b:pv"}, []string{"2026-11-19"}, hsNow.Add(time.Minute)) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + start := time.Now() + if !s.WaitIdle(ctx) { + t.Fatal("WaitIdle without offer: want idle, got timeout") + } + if d := time.Since(start); d > 200*time.Millisecond { + t.Fatalf("WaitIdle without offer took %v, want at once", d) + } + if s.Offered() { + t.Fatal("Offered() without offer: want false") + } +} diff --git a/dashboard/internal/learnrec/minutestore.go b/dashboard/internal/learnrec/minutestore.go index e95060b9..edeb9564 100644 --- a/dashboard/internal/learnrec/minutestore.go +++ b/dashboard/internal/learnrec/minutestore.go @@ -72,15 +72,14 @@ type MinuteStore struct { logf func(string, ...any) files map[string]*minuteFileState - mu sync.Mutex // schuetzt die Felder darunter - days map[string]*minuteDay - keys map[string]bool - since time.Time - written int64 - lastNow time.Time - curKey string - curDir string - prevDir string + mu sync.Mutex // schuetzt die Felder darunter + days map[string]*minuteDay + keys map[string]bool + since time.Time + written int64 + lastNow time.Time + curKey string + dirsUsed map[string]bool // alle Orte, an denen Dateien liegen koennen } var _ MinuteConsumer = (*MinuteStore)(nil) @@ -92,22 +91,24 @@ func NewMinuteStore(loc *time.Location, plan func() MinutePlan, dirs func() Minu logf = func(string, ...any) {} } return &MinuteStore{ - loc: loc, - plan: plan, - dirs: dirs, - driveUp: driveUp, - limits: limits, - logf: logf, - files: map[string]*minuteFileState{}, - days: map[string]*minuteDay{}, - keys: map[string]bool{}, + loc: loc, + plan: plan, + dirs: dirs, + driveUp: driveUp, + limits: limits, + logf: logf, + files: map[string]*minuteFileState{}, + days: map[string]*minuteDay{}, + keys: map[string]bool{}, + dirsUsed: map[string]bool{}, } } // ObserveMinute legt die Werte des Rahmens im RAM ab. Schluessel sind e: // fuer Leistung, b: fuer die Bilanz und t:outdoor fuer die Aussentemperatur. func (s *MinuteStore) ObserveMinute(f Frame) { - if pl := s.plan(); !pl.On || pl.Paused { + pl := s.plan() + if !pl.On { return } vals := map[string]float64{} @@ -122,6 +123,13 @@ func (s *MinuteStore) ObserveMinute(f Frame) { if f.OutdoorC != nil { vals["t:outdoor"] = *f.OutdoorC } + // Pausiert liefert der Companion die Schluessel, die er kennt. Die + // uebrigen bleiben aufgezeichnet. + for key := range vals { + if pl.Paused && HASeriesKey(key) { + delete(vals, key) + } + } if len(vals) == 0 { return } @@ -174,7 +182,8 @@ func (s *MinuteStore) place(pl MinutePlan, dirs MinuteDirs, up bool) (key, dir s // Flush schreibt die ausstehenden Minuten an den Ort. Ist das Laufwerk nicht // da, bleibt alles im RAM. Danach kommen Tage aus dem RAM, die aelter als die -// Aufbewahrung sind oder ueber die RAM-Tage hinausgehen. +// Aufbewahrung sind oder ueber die RAM-Tage hinausgehen. Die Aufbewahrung gilt +// an allen bekannten Orten, die jetzt erreichbar sind. func (s *MinuteStore) Flush(now time.Time) error { s.flushMu.Lock() defer s.flushMu.Unlock() @@ -186,19 +195,26 @@ func (s *MinuteStore) Flush(now time.Time) error { key, dir, writable := s.place(pl, dirs, up) cutoff := now.In(s.loc).AddDate(0, 0, -pl.Days).Format(minuteDayLayout) + type dropped struct { + day string + n int + } + var drops []dropped + s.mu.Lock() s.lastNow = now if key != s.curKey { s.curKey = key - if s.curDir != "" && s.curDir != dir { - s.prevDir = s.curDir - } - s.curDir = dir s.files = map[string]*minuteFileState{} } if !writable { s.files = map[string]*minuteFileState{} } + for _, d := range []string{dir, dirs.Drive, dirs.System} { + if d != "" { + s.dirsUsed[d] = true + } + } // RAM-Tage: aelter als die Aufbewahrung oder hinter den neuesten RAM-Tagen. keep := RAMDays(lim, int64(len(s.keys))*minutesPerDay*4) @@ -209,6 +225,9 @@ func (s *MinuteStore) Flush(now time.Time) error { sort.Sort(sort.Reverse(sort.StringSlice(names))) for i, k := range names { if i >= keep || k <= cutoff { + if n := pendingCount(s.days[k]); n > 0 { + drops = append(drops, dropped{day: k, n: n}) + } delete(s.days, k) } } @@ -234,10 +253,18 @@ func (s *MinuteStore) Flush(now time.Time) error { jobs = append(jobs, minuteJob{day: k, path: path, d: d}) } } + // Ein Ort ohne Laufwerk wird nicht angefasst, sonst landet die Aufbewahrung + // auf dem Systemdatentraeger. + var prune []string + for d := range s.dirsUsed { + if d != dirs.Drive || up { + prune = append(prune, d) + } + } s.mu.Unlock() - if !writable { - return nil + for _, dr := range drops { + s.logf("learnrec: Tag %s mit %d ungeschriebenen Minuten verworfen", dr.day, dr.n) } var errs []error for _, j := range jobs { @@ -245,8 +272,10 @@ func (s *MinuteStore) Flush(now time.Time) error { errs = append(errs, err) } } - if err := s.pruneFiles(dir, cutoff); err != nil { - errs = append(errs, err) + for _, d := range prune { + if err := s.pruneFiles(d, cutoff); err != nil { + errs = append(errs, err) + } } for _, err := range errs { s.logf("learnrec: Minuten schreiben fehlgeschlagen: %v", err) @@ -254,6 +283,17 @@ func (s *MinuteStore) Flush(now time.Time) error { return errors.Join(errs...) } +// pendingCount zaehlt die Minuten eines Tages, die noch nicht in der Datei stehen. +func pendingCount(d *minuteDay) int { + n := 0 + for _, p := range d.pending { + if p { + n++ + } + } + return n +} + // writeDay haengt die ausstehenden Minuten eines Tages an seine Datei an. Die // Minuten, die die Datei schon hat, werden uebersprungen. func (s *MinuteStore) writeDay(j minuteJob) error { @@ -428,16 +468,20 @@ func (s *MinuteStore) Usage() MinuteUsage { return u } -// Reset leert das RAM und loescht die Tagesdateien des aktuellen und des vorigen Orts. +// Reset leert das RAM und loescht die Tagesdateien an allen Orten, die der +// Speicher je benutzt hat, und an den eingerichteten Laufwerken. func (s *MinuteStore) Reset() error { s.flushMu.Lock() defer s.flushMu.Unlock() - _, placeDir, _ := s.place(s.plan(), s.dirs(), true) + dirs := s.dirs() s.mu.Lock() dirSet := map[string]bool{} - for _, d := range []string{s.curDir, s.prevDir, placeDir} { + for d := range s.dirsUsed { + dirSet[d] = true + } + for _, d := range []string{dirs.Drive, dirs.System} { if d != "" { dirSet[d] = true } @@ -447,7 +491,7 @@ func (s *MinuteStore) Reset() error { s.written = 0 s.since = time.Time{} s.lastNow = time.Time{} - s.prevDir = "" + s.dirsUsed = map[string]bool{} s.files = map[string]*minuteFileState{} s.mu.Unlock() diff --git a/dashboard/internal/learnrec/minutestore_test.go b/dashboard/internal/learnrec/minutestore_test.go index 85b1d3ce..6166a1ba 100644 --- a/dashboard/internal/learnrec/minutestore_test.go +++ b/dashboard/internal/learnrec/minutestore_test.go @@ -2,9 +2,11 @@ package learnrec import ( "encoding/binary" + "fmt" "io/fs" "os" "path/filepath" + "strings" "testing" "time" ) @@ -296,9 +298,122 @@ func TestMinuteStorePausedRecordsNothingUntilResumed(t *testing.T) { t.Fatalf("Flush: %v", err) } path := msPath(env.dirs.System, testMinuteDay) - if got := msBlockMinutes(t, path); got != 1 { - t.Fatalf("minutes in blocks = %d, want 1 (only the minute after the pause)", got) - } _, values := readMinuteFile(t, path) + requireMinuteValue(t, values, "e:uid1", 600, testGap) + requireMinuteValue(t, values, "e:uid1", 601, testGap) requireMinuteValue(t, values, "e:uid1", 600+2, 3) } + +func TestPausedKeepsKeysHACannotDeliver(t *testing.T) { + env := newMsEnv(t, LocSystem) + s := newMsStore(env) + env.plan.Paused = true + outdoor := 4.5 + s.ObserveMinute(Frame{ + Minute: msTime(10, 0), + Devices: []DeviceMinute{{ID: "dev", Power: map[string]float64{"x": 1}}}, + Balance: map[string]float64{"pv": 2, "load_total": 3, "grid_import": 4}, + OutdoorC: &outdoor, + }) + if err := s.Flush(msTime(10, 1)); err != nil { + t.Fatalf("Flush: %v", err) + } + keys, values := readMinuteFile(t, msPath(env.dirs.System, testMinuteDay)) + for _, key := range []string{"e:x", "b:pv"} { + for _, k := range keys { + if k == key { + t.Fatalf("key %q recorded while paused, Home Assistant delivers it", key) + } + } + } + requireMinuteValue(t, values, "b:load_total", 600, 3) + requireMinuteValue(t, values, "b:grid_import", 600, 4) + requireMinuteValue(t, values, "t:outdoor", 600, 4.5) +} + +func TestResetRemovesAllLocations(t *testing.T) { + env := newMsEnv(t, LocDrive) + env.plan.Days = 2 + s := newMsStore(env) + drive := filepath.Join(env.dirs.Drive, "learnrec", "minutes") + system := filepath.Join(env.dirs.System, "learnrec", "minutes") + + // Alter Tag auf dem Laufwerk, der beim naechsten Lauf verfallen muss. + old := time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC) + s.ObserveMinute(msFrame(old, 1)) + if err := s.Flush(old); err != nil { + t.Fatalf("Flush drive: %v", err) + } + if n := msCountFiles(t, drive); n != 1 { + t.Fatalf("files on drive after first flush = %d, want 1", n) + } + + env.plan.Location = LocSystem + for i := 0; i < 3; i++ { + s.ObserveMinute(msFrame(msTime(10, i), 1)) + } + if err := s.Flush(msTime(10, 3)); err != nil { + t.Fatalf("Flush system: %v", err) + } + // Der Lauf auf System prueft die Aufbewahrung an allen bekannten Orten. + if n := msCountFiles(t, drive); n != 0 { + t.Fatalf("old file on drive not pruned by later flush: %d files", n) + } + if n := msCountFiles(t, system); n != 1 { + t.Fatalf("files on system = %d, want 1", n) + } + + env.plan.Location = LocRAM + s.ObserveMinute(msFrame(msTime(10, 4), 1)) + if err := s.Flush(msTime(10, 5)); err != nil { + t.Fatalf("Flush ram: %v", err) + } + + // Ein Laufwerk dazu, das nicht mehr gewaehlt ist, muss der Reset auch leeren. + stray := filepath.Join(env.dirs.Drive, "learnrec", "minutes", "2026-11-21.enm") + if err := os.MkdirAll(filepath.Dir(stray), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(stray, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + + if err := s.Reset(); err != nil { + t.Fatalf("Reset: %v", err) + } + if n := msCountFiles(t, drive) + msCountFiles(t, system); n != 0 { + t.Fatalf("files left after Reset on drive and system: %d", n) + } +} + +func TestFlushLogsDroppedUnwrittenDay(t *testing.T) { + env := newMsEnv(t, LocDrive) + env.up = false + env.limits = Limits{RAMMinuteDays: 2, RAMMinuteBytes: 16 << 20} + var logs []string + s := NewMinuteStore(time.UTC, + func() MinutePlan { return env.plan }, + func() MinuteDirs { return env.dirs }, + func() bool { return env.up }, + func() Limits { return env.limits }, + func(format string, a ...any) { logs = append(logs, fmt.Sprintf(format, a...)) }, + ) + for d := 0; d < 3; d++ { + for m := 0; m < 2; m++ { + at := time.Date(2026, 11, 19+d, 10, m, 0, 0, time.UTC) + s.ObserveMinute(msFrame(at, 1)) + } + } + if err := s.Flush(time.Date(2026, 11, 21, 10, 2, 0, 0, time.UTC)); err != nil { + t.Fatalf("Flush: %v", err) + } + found := false + for _, line := range logs { + if strings.Contains(line, "2026-11-19") && strings.Contains(line, "2 ungeschriebenen") { + found = true + } + } + if !found { + t.Fatalf("no log for the dropped unwritten day 2026-11-19 with 2 minutes, got %q", logs) + } +} From c70503a1f7dfcdc581b96b92df4c5c45a305fa7f Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:27:23 +0100 Subject: [PATCH 12/22] fix(learnrec): reset zeroed minute file headers on append A power loss can leave the header of a minute file zeroed. OpenAppend now truncates such a file to empty and logs the path. Files with another non-zero header still return an error and stay untouched. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/learnrec/minutefile.go | 19 ++++++++++++ .../internal/learnrec/minutefile_test.go | 30 +++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/dashboard/internal/learnrec/minutefile.go b/dashboard/internal/learnrec/minutefile.go index 6f852157..e0495c4b 100644 --- a/dashboard/internal/learnrec/minutefile.go +++ b/dashboard/internal/learnrec/minutefile.go @@ -6,6 +6,7 @@ import ( "fmt" "hash/crc32" "io" + "log" "math" "os" ) @@ -180,6 +181,15 @@ func OpenAppend(path string) (known map[string]int, size int64, err error) { if err != nil { return nil, 0, err } + // Ein Stromausfall kann den Kopf auf Nullen stehen lassen. Solche Dateien + // sind leer. Fremde Dateien mit anderem Kopf bleiben unangetastet. + if head := data[:min(len(data), 6)]; len(head) > 0 && allZero(head) { + log.Printf("learnrec: %s: header zeroed, resetting the file", path) + if err := os.Truncate(path, 0); err != nil { + return nil, 0, err + } + return map[string]int{}, 0, nil + } p, err := parseMinuteDay(data) switch { case errors.Is(err, errShortHeader): @@ -346,3 +356,12 @@ func appendFrame(dst, body []byte) []byte { dst = append(dst, body...) return binary.LittleEndian.AppendUint32(dst, crc32.ChecksumIEEE(body)) } + +func allZero(b []byte) bool { + for _, c := range b { + if c != 0 { + return false + } + } + return true +} diff --git a/dashboard/internal/learnrec/minutefile_test.go b/dashboard/internal/learnrec/minutefile_test.go index ec1fef88..9c23d3a1 100644 --- a/dashboard/internal/learnrec/minutefile_test.go +++ b/dashboard/internal/learnrec/minutefile_test.go @@ -3,9 +3,11 @@ package learnrec import ( "bytes" "fmt" + "log" "math" "os" "path/filepath" + "strings" "testing" ) @@ -246,3 +248,31 @@ func TestOpenAppendRecoversFromPartialHeader(t *testing.T) { _, values := readMinuteFile(t, path) requireMinuteValue(t, values, "e:a", 4, 1) } + +func TestOpenAppendBadHeaderTruncates(t *testing.T) { + path := filepath.Join(t.TempDir(), testMinuteDay+".enm") + if err := os.WriteFile(path, make([]byte, 4096), 0o644); err != nil { + t.Fatal(err) + } + var logBuf bytes.Buffer + prev := log.Writer() + log.SetOutput(&logBuf) + defer log.SetOutput(prev) + + known, size, err := OpenAppend(path) + if err != nil { + t.Fatalf("OpenAppend on zeroed file: %v", err) + } + if size != 0 || len(known) != 0 { + t.Fatalf("got size %d, known %v, want empty", size, known) + } + if fi, _ := os.Stat(path); fi.Size() != 0 { + t.Fatalf("file size %d, want 0", fi.Size()) + } + if !strings.Contains(logBuf.String(), path) { + t.Fatalf("no log line naming %s: %q", path, logBuf.String()) + } + appendMinuteBlock(t, path, MinuteBlock{First: 7, Keys: []string{"e:a"}, Values: [][]float32{{3}}}, known) + _, values := readMinuteFile(t, path) + requireMinuteValue(t, values, "e:a", 7, 3) +} From 15cd9c75aaa22761433b906c277f6057e14acb53 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:30:21 +0100 Subject: [PATCH 13/22] fix(automations): reject learned bounds on save that the service would reject The service refuses a learned reference whose min is above max or whose fallback lies outside min and max, but the dashboard saved such rules and the service only rejected them later. The save now runs the same check through a save hook in the config manager, which keeps config free of an import on autolearn. Both sides read the bounds section of learned_vectors.json. A learned value of NaN or Inf is no longer stored or published, since its payload would not encode and an empty payload deletes the retained topic. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/main.go | 1 + .../internal/autolearn/learned_bounds.go | 118 ++++++++++++++++++ .../internal/autolearn/learned_bounds_test.go | 116 +++++++++++++++++ dashboard/internal/autolearn/learned_store.go | 6 + dashboard/internal/autolearn/rules.go | 3 +- dashboard/internal/config/config.go | 19 +++ .../automation/tests/learned_vectors.json | 39 +++++- services/automation/tests/test_learned.py | 12 +- 8 files changed, 311 insertions(+), 3 deletions(-) create mode 100644 dashboard/internal/autolearn/learned_bounds.go create mode 100644 dashboard/internal/autolearn/learned_bounds_test.go diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index aae24bbf..6ee99d98 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -1238,6 +1238,7 @@ func main() { } else if len(bridgeCfg.Connections) > 0 { client.SetBridgeWatch(bridgeCfg.Connections[0].RemoteClientID) } + configManager.SetSaveCheck(autolearn.CheckLearnedBoundsOnSave) configManager.SetReloadFunc(func(name string, _ []byte) error { if serviceID, ok := config.ServiceIDForConfig(name); ok { return client.ReloadService(serviceID) diff --git a/dashboard/internal/autolearn/learned_bounds.go b/dashboard/internal/autolearn/learned_bounds.go new file mode 100644 index 00000000..000408dd --- /dev/null +++ b/dashboard/internal/autolearn/learned_bounds.go @@ -0,0 +1,118 @@ +package autolearn + +import ( + "encoding/json" + "fmt" + "regexp" + "sort" + "strconv" + "strings" +) + +// learnedBoundsDocument is the name of the rule document in the configuration. +const learnedBoundsDocument = "automation_rules" + +// boundsDayMinutes is the length of a day in minutes, the circle of a clock. +const boundsDayMinutes = 1440 + +var boundsClockRE = regexp.MustCompile(`^([01][0-9]|2[0-3]):([0-5][0-9])$`) + +// CheckLearnedBoundsOnSave refuses a rule document whose learned bounds the +// automation service would reject. Other documents pass unchecked. +func CheckLearnedBoundsOnSave(name string, data []byte) error { + if name != learnedBoundsDocument { + return nil + } + if errs := ValidateLearnedBounds(data); len(errs) > 0 { + return fmt.Errorf("learned bounds: %s", strings.Join(errs, ", ")) + } + return nil +} + +// ValidateLearnedBounds finds every learned reference in the rule document raw +// and reports where min is above max or where fallback lies outside min and +// max, with the same texts as the service. Time bounds run over midnight, so +// min to max is an arc of the clock. A reference is any object with a learned +// key. A reference whose bounds have the wrong type is left to the service. +func ValidateLearnedBounds(raw []byte) []string { + var doc any + if err := json.Unmarshal(raw, &doc); err != nil { + return nil + } + var errs []string + walkLearnedBounds(doc, "", &errs) + return errs +} + +func walkLearnedBounds(node any, path string, errs *[]string) { + switch typed := node.(type) { + case map[string]any: + if _, ok := typed["learned"]; ok { + checkLearnedBounds(typed, path, errs) + return + } + keys := make([]string, 0, len(typed)) + for key := range typed { + keys = append(keys, key) + } + sort.Strings(keys) + for _, key := range keys { + child := key + if path != "" { + child = path + "." + key + } + walkLearnedBounds(typed[key], child, errs) + } + case []any: + for i, item := range typed { + walkLearnedBounds(item, fmt.Sprintf("%s[%d]", path, i), errs) + } + } +} + +// checkLearnedBounds checks one reference. Text bounds are clock times, number +// bounds are numbers, and mixed types are not checked here. +func checkLearnedBounds(ref map[string]any, path string, errs *[]string) { + add := func(msg string) { *errs = append(*errs, path+": "+msg) } + if _, isText := ref["min"].(string); isText { + low, okLow := clockMinutes(ref["min"]) + high, okHigh := clockMinutes(ref["max"]) + fallback, okFallback := clockMinutes(ref["fallback"]) + if okLow && okHigh && okFallback && dayMod(fallback-low) > dayMod(high-low) { + add("fallback must lie between min and max") + } + return + } + low, okLow := ref["min"].(float64) + high, okHigh := ref["max"].(float64) + fallback, okFallback := ref["fallback"].(float64) + if !okLow || !okHigh || !okFallback { + return + } + switch { + case low > high: + add("min must not be above max") + case fallback < low || fallback > high: + add("fallback must lie between min and max") + } +} + +// clockMinutes reads an HH:MM text as minutes after midnight. +func clockMinutes(value any) (int, bool) { + text, ok := value.(string) + if !ok { + return 0, false + } + match := boundsClockRE.FindStringSubmatch(text) + if match == nil { + return 0, false + } + hours, _ := strconv.Atoi(match[1]) + minutes, _ := strconv.Atoi(match[2]) + return hours*60 + minutes, true +} + +// dayMod maps minutes onto the clock circle, 0 to 1439. +func dayMod(minutes int) int { + return ((minutes % boundsDayMinutes) + boundsDayMinutes) % boundsDayMinutes +} diff --git a/dashboard/internal/autolearn/learned_bounds_test.go b/dashboard/internal/autolearn/learned_bounds_test.go new file mode 100644 index 00000000..ff5a98ae --- /dev/null +++ b/dashboard/internal/autolearn/learned_bounds_test.go @@ -0,0 +1,116 @@ +package autolearn + +import ( + "encoding/json" + "math" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// learnedVectorsPath is the shared vector file of the service and the dashboard. +const learnedVectorsPath = "../../../services/automation/tests/learned_vectors.json" + +type boundsVector struct { + Name string `json:"name"` + Kind string `json:"kind"` + Ref map[string]any `json:"ref"` + Errors []string `json:"errors"` +} + +// TestLearnedBoundsVectors runs the bounds section that the service also runs. +// Each error is compared without its path, the path is the rule location. +func TestLearnedBoundsVectors(t *testing.T) { + data, err := os.ReadFile(filepath.FromSlash(learnedVectorsPath)) + if err != nil { + t.Fatal(err) + } + var file struct { + Bounds []boundsVector `json:"bounds"` + } + if err := json.Unmarshal(data, &file); err != nil { + t.Fatal(err) + } + if len(file.Bounds) == 0 { + t.Fatal("no bounds vectors") + } + for _, v := range file.Bounds { + t.Run(v.Name, func(t *testing.T) { + doc := map[string]any{"rules": []any{map[string]any{ + "id": "r", "conditions": []any{map[string]any{"type": "time_window", "start": v.Ref}}, + }}} + raw, err := json.Marshal(doc) + if err != nil { + t.Fatal(err) + } + got := ValidateLearnedBounds(raw) + if len(got) != len(v.Errors) { + t.Fatalf("errors = %q, want %q", got, v.Errors) + } + for i, msg := range got { + _, text, found := strings.Cut(msg, ": ") + if !found || text != v.Errors[i] { + t.Fatalf("error %d = %q, want text %q", i, msg, v.Errors[i]) + } + } + }) + } +} + +// TestLearnedBoundsWalksScenariosAndPath checks that scenario references are +// found too and that the error names the location in the document. +func TestLearnedBoundsWalksScenariosAndPath(t *testing.T) { + raw := []byte(`{"rules":[],"scenarios":[{"id":"s","while":{"regulator":{"threshold":{ + "learned":"site/pv_reserve_w","min":100,"max":0,"fallback":50}}}}]}`) + got := ValidateLearnedBounds(raw) + if len(got) != 1 { + t.Fatalf("errors = %q, want one", got) + } + if !strings.HasPrefix(got[0], "scenarios[0].while.regulator.threshold: ") || + !strings.HasSuffix(got[0], "min must not be above max") { + t.Fatalf("error = %q", got[0]) + } +} + +func TestLearnedBoundsAcceptsValidDocument(t *testing.T) { + raw := []byte(`{"rules":[{"conditions":[{"start":{"learned":"site/day_start","min":"23:00","max":"01:00","fallback":"00:00"}}]}]}`) + if got := ValidateLearnedBounds(raw); len(got) != 0 { + t.Fatalf("errors = %q, want none", got) + } +} + +func TestCheckLearnedBoundsOnSaveOnlyForAutomationRules(t *testing.T) { + bad := []byte(`{"rules":[{"conditions":[{"start":{"learned":"site/day_start","min":"23:00","max":"01:00","fallback":"12:00"}}]}]}`) + if err := CheckLearnedBoundsOnSave("shelly_presets", bad); err != nil { + t.Fatalf("other document rejected: %v", err) + } + if err := CheckLearnedBoundsOnSave("automation_rules", bad); err == nil { + t.Fatal("automation_rules with fallback outside the arc was accepted") + } +} + +// TestLearnedStoreSkipsNonFinite checks that NaN and Inf are not stored or +// published, and that the file stays writable afterwards. +func TestLearnedStoreSkipsNonFinite(t *testing.T) { + path := filepath.Join(t.TempDir(), "learned.json") + s := LoadLearnedStore(path, func(string, ...any) {}) + now := time.Unix(1794000000, 0) + for _, num := range []float64{math.NaN(), math.Inf(1), math.Inf(-1)} { + vals := []Value{{Key: "device/pump_1/usual_runtime_s", Kind: ValueNumber, Num: num, N: 4}} + if out := s.Update(vals, now, nil); len(out) != 0 { + t.Fatalf("Update(%v) messages = %v, want none", num, out) + } + } + if entries := s.Entries(); len(entries) != 0 { + t.Fatalf("entries = %v, want none", entries) + } + if err := s.Save(); err != nil { + t.Fatalf("Save: %v", err) + } + ok := []Value{{Key: "device/pump_1/usual_runtime_s", Kind: ValueNumber, Num: 42.5, N: 4}} + if out := s.Update(ok, now, nil); len(out) != 1 || out[0].Payload == "" { + t.Fatalf("finite value messages = %v, want one with payload", out) + } +} diff --git a/dashboard/internal/autolearn/learned_store.go b/dashboard/internal/autolearn/learned_store.go index 7c30eb5e..467109de 100644 --- a/dashboard/internal/autolearn/learned_store.go +++ b/dashboard/internal/autolearn/learned_store.go @@ -5,6 +5,7 @@ import ( "errors" "io/fs" "log" + "math" "os" "path/filepath" "sort" @@ -133,6 +134,11 @@ func (s *LearnedStore) Update(vals []Value, now time.Time, deviceExists func(str sort.SliceStable(sorted, func(i, j int) bool { return sorted[i].Key < sorted[j].Key }) for _, v := range sorted { cur := learnedCurrent(v) + // A NaN or Inf does not encode as JSON. Its payload would be empty, which + // deletes the retained topic, so it is neither stored nor published. + if f, isNumber := cur.(float64); isNumber && (math.IsNaN(f) || math.IsInf(f, 0)) { + continue + } e, ok := s.entries[v.Key] switch { case !ok: diff --git a/dashboard/internal/autolearn/rules.go b/dashboard/internal/autolearn/rules.go index 1e68a39b..a8de9204 100644 --- a/dashboard/internal/autolearn/rules.go +++ b/dashboard/internal/autolearn/rules.go @@ -350,7 +350,8 @@ func learnedValueRef(rawCond json.RawMessage, learned map[string]LearnedRef) err // whether it was one. // An object is a reference only with a non empty text under learned, as the // service's is_ref reads it. Any other object is not stored, so the numeric -// fields reject it and start and end ignore it. +// fields reject it and start and end ignore it. The bounds of a reference are +// checked on save by ValidateLearnedBounds. func learnedRef(raw json.RawMessage, name string, learned map[string]LearnedRef) (bool, error) { trimmed := bytes.TrimSpace(raw) if len(trimmed) == 0 || trimmed[0] != '{' { diff --git a/dashboard/internal/config/config.go b/dashboard/internal/config/config.go index b1878ff0..b697840d 100644 --- a/dashboard/internal/config/config.go +++ b/dashboard/internal/config/config.go @@ -103,10 +103,17 @@ type reloadStatus struct { err string } +// SaveCheck is run on a saved document after the schema check and before the +// file is written. An error rejects the save. It lets a package that the config +// package cannot import check the document, such as the learned bounds of the +// automation rules. +type SaveCheck func(name string, data []byte) error + type Manager struct { mu sync.Mutex dir string reload ReloadFunc + saveCheck SaveCheck excluded map[string]bool reloadState map[string]reloadStatus } @@ -159,6 +166,13 @@ func (m *Manager) SetReloadFunc(reload ReloadFunc) { m.reload = reload } +// SetSaveCheck sets the check that runs on every save, see SaveCheck. +func (m *Manager) SetSaveCheck(check SaveCheck) { + m.mu.Lock() + defer m.mu.Unlock() + m.saveCheck = check +} + func (m *Manager) Scan() ([]Document, error) { m.mu.Lock() defer m.mu.Unlock() @@ -330,6 +344,11 @@ func (m *Manager) Save(name string, data []byte) (Document, error) { if err := Validate(data, doc.SchemaPath); err != nil { return Document{}, err } + if m.saveCheck != nil { + if err := m.saveCheck(name, data); err != nil { + return Document{}, err + } + } old, err := os.ReadFile(doc.Path) if err != nil { return Document{}, err diff --git a/services/automation/tests/learned_vectors.json b/services/automation/tests/learned_vectors.json index 40213d32..c5f430f0 100644 --- a/services/automation/tests/learned_vectors.json +++ b/services/automation/tests/learned_vectors.json @@ -1,4 +1,5 @@ -[ +{ +"resolve": [ {"name": "time_clamp_over_midnight_late", "kind": "time", "ref": {"learned": "site/day_start", "min": "23:00", "max": "01:00", "fallback": "00:00"}, @@ -173,4 +174,40 @@ "payload": null, "now": 1794000060, "expect": {"value": "active", "source": "fallback"}} +], +"bounds": [ + {"name": "time_arc_over_midnight_valid", "kind": "time", + "ref": {"learned": "site/day_start", "min": "23:00", "max": "01:00", "fallback": "00:00"}, + "errors": []}, + {"name": "time_arc_fallback_on_min_valid", "kind": "time", + "ref": {"learned": "site/day_start", "min": "23:00", "max": "01:00", "fallback": "23:00"}, + "errors": []}, + {"name": "time_arc_fallback_on_max_valid", "kind": "time", + "ref": {"learned": "site/day_start", "min": "23:00", "max": "01:00", "fallback": "01:00"}, + "errors": []}, + {"name": "time_arc_fallback_outside", "kind": "time", + "ref": {"learned": "site/day_start", "min": "23:00", "max": "01:00", "fallback": "12:00"}, + "errors": ["fallback must lie between min and max"]}, + {"name": "time_plain_arc_valid", "kind": "time", + "ref": {"learned": "site/day_start", "min": "06:00", "max": "22:00", "fallback": "12:00"}, + "errors": []}, + {"name": "time_plain_arc_fallback_outside", "kind": "time", + "ref": {"learned": "site/day_start", "min": "06:00", "max": "22:00", "fallback": "23:00"}, + "errors": ["fallback must lie between min and max"]}, + {"name": "number_valid", "kind": "number", + "ref": {"learned": "device/pump_1/usual_runtime_s", "min": 0, "max": 100, "fallback": 50}, + "errors": []}, + {"name": "number_equal_bounds_valid", "kind": "number", + "ref": {"learned": "device/pump_1/usual_runtime_s", "min": 5, "max": 5, "fallback": 5}, + "errors": []}, + {"name": "number_min_above_max", "kind": "number", + "ref": {"learned": "device/pump_1/usual_runtime_s", "min": 100, "max": 0, "fallback": 50}, + "errors": ["min must not be above max"]}, + {"name": "number_fallback_above_max", "kind": "number", + "ref": {"learned": "device/pump_1/usual_runtime_s", "min": 0, "max": 100, "fallback": 150}, + "errors": ["fallback must lie between min and max"]}, + {"name": "number_fallback_below_min", "kind": "number", + "ref": {"learned": "device/pump_1/usual_runtime_s", "min": 0, "max": 100, "fallback": -1}, + "errors": ["fallback must lie between min and max"]} ] +} diff --git a/services/automation/tests/test_learned.py b/services/automation/tests/test_learned.py index 2a9b41ce..46484f4c 100644 --- a/services/automation/tests/test_learned.py +++ b/services/automation/tests/test_learned.py @@ -15,7 +15,9 @@ import learned -VECTORS = json.loads((Path(__file__).parent / "learned_vectors.json").read_text(encoding="utf-8")) +_VECTOR_FILE = json.loads((Path(__file__).parent / "learned_vectors.json").read_text(encoding="utf-8")) +VECTORS = _VECTOR_FILE["resolve"] +BOUNDS = _VECTOR_FILE["bounds"] @pytest.mark.parametrize("vector", VECTORS, ids=[v["name"] for v in VECTORS]) @@ -39,6 +41,14 @@ def _errors(ref, kind="time"): return errors +@pytest.mark.parametrize("vector", BOUNDS, ids=[v["name"] for v in BOUNDS]) +def test_bounds_vector(vector): + errors = [] + learned.validate_ref(vector["ref"], vector["kind"], "rules[0].start", errors) + # Jede Meldung beginnt mit dem Pfad, die Go-Seite prueft denselben Text. + assert [e.split(": ", 1)[1] for e in errors] == vector["errors"] + + def test_validate_accepts_midnight_arc(): assert _errors({"learned": "site/day_start", "min": "23:00", "max": "01:00", "fallback": "00:00"}) == [] From ba98fb829559807d5e6d0615206bd7d458919220 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:32:19 +0100 Subject: [PATCH 14/22] fix(dashboard): check field roles on settings restore and CSRF on monitoring ack Settings restore now compares the revision with the current settings and requires the role of every changed field, the same check as the PUT path. Monitoring acknowledgement checks the CSRF token like its neighbours. Day files are written through energystats.WriteFileAtomic, which syncs before the rename. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/daystore.go | 16 +---- dashboard/internal/autolearn/daystore_test.go | 28 ++++++++ dashboard/internal/httpapi/httpapi.go | 20 ++++++ dashboard/internal/httpapi/monitoring.go | 3 + dashboard/internal/httpapi/monitoring_test.go | 25 +++++++ .../internal/httpapi/settings_access_test.go | 72 +++++++++++++++++++ dashboard/internal/settings/settings.go | 19 ++++- 7 files changed, 168 insertions(+), 15 deletions(-) diff --git a/dashboard/internal/autolearn/daystore.go b/dashboard/internal/autolearn/daystore.go index fb870838..77bfc9e4 100644 --- a/dashboard/internal/autolearn/daystore.go +++ b/dashboard/internal/autolearn/daystore.go @@ -15,6 +15,7 @@ import ( "sync" "time" + "github.com/Developer-Simon/energy-node-dashboard/internal/energystats" "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" ) @@ -857,20 +858,7 @@ func (s *DayStore) writeFile(day string, f DayFile) error { if err := zw.Close(); err != nil { return fmt.Errorf("autolearn: compress %s: %w", day, err) } - tmp, err := os.CreateTemp(s.dir, ".day-*.tmp") - if err != nil { - return fmt.Errorf("autolearn: save %s: %w", day, err) - } - tmpName := tmp.Name() - _, err = tmp.Write(buf.Bytes()) - if cerr := tmp.Close(); err == nil { - err = cerr - } - if err == nil { - err = os.Rename(tmpName, s.path(day)) - } - if err != nil { - _ = os.Remove(tmpName) + if err := energystats.WriteFileAtomic(s.dir, s.path(day), buf.Bytes()); err != nil { return fmt.Errorf("autolearn: save %s: %w", day, err) } if s.written == nil { diff --git a/dashboard/internal/autolearn/daystore_test.go b/dashboard/internal/autolearn/daystore_test.go index 6c2b84fd..5fa1aa30 100644 --- a/dashboard/internal/autolearn/daystore_test.go +++ b/dashboard/internal/autolearn/daystore_test.go @@ -717,3 +717,31 @@ func TestDayStoreAddCyclesRespectsExcludedAndEnabled(t *testing.T) { t.Errorf("cycle = %+v", c) } } + +func TestDayStoreWriteFileLeavesOnlyTheDayFile(t *testing.T) { + loc := berlinLoc(t) + dir := t.TempDir() + s := OpenDayStore(dir, loc, keepAll, noLog) + f := DayFile{V: dayFileVersion, Day: "2026-11-19", Devices: map[string]*DeviceDay{}, + Events: []EventRec{}, Actions: []ActionRec{}} + for i := 0; i < 2; i++ { + if err := s.writeFile("2026-11-19", f); err != nil { + t.Fatal(err) + } + } + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || entries[0].Name() != "2026-11-19.json.gz" { + names := []string{} + for _, e := range entries { + names = append(names, e.Name()) + } + t.Fatalf("dir after two writes = %v, want only the day file", names) + } + days := mustDays(t, s, time.Date(2026, 11, 19, 0, 0, 0, 0, loc), time.Date(2026, 11, 19, 0, 0, 0, 0, loc)) + if len(days) != 1 || days[0].Day != "2026-11-19" { + t.Fatalf("day file not readable after write: %+v", days) + } +} diff --git a/dashboard/internal/httpapi/httpapi.go b/dashboard/internal/httpapi/httpapi.go index 0fbea2e8..f22259d6 100644 --- a/dashboard/internal/httpapi/httpapi.go +++ b/dashboard/internal/httpapi/httpapi.go @@ -2693,6 +2693,26 @@ func handleSettingsRevision(store *settings.Store) http.HandlerFunc { writeErrorDetail(w, http.StatusBadRequest, "invalid_body", err) return } + target, err := store.SettingsRevisionValue(request.Revision) + if err != nil { + writeErrorDetail(w, http.StatusBadRequest, "settings_restore_rejected", err) + return + } + current, err := store.LoadSettings() + if err != nil { + writeErrorDetail(w, http.StatusInternalServerError, "settings_invalid", err) + return + } + roles, err := settingsChangeRoles(current, target) + if err != nil { + writeErrorDetail(w, http.StatusInternalServerError, "settings_invalid", err) + return + } + for _, role := range roles { + if !requireSettingsRole(w, r, role) { + return + } + } value, err := store.RestoreSettings(request.Revision) if err != nil { writeErrorDetail(w, http.StatusBadRequest, "settings_restore_rejected", err) diff --git a/dashboard/internal/httpapi/monitoring.go b/dashboard/internal/httpapi/monitoring.go index 3b10cc2f..ab0c04d7 100644 --- a/dashboard/internal/httpapi/monitoring.go +++ b/dashboard/internal/httpapi/monitoring.go @@ -83,6 +83,9 @@ func handleMonitoringAck(manager *auth.Manager, deps *MonitoringDeps) http.Handl if !requireRole(w, r, manager, auth.RoleEditSetup, "monitoring_ack_forbidden", "error.monitoring_ack_forbidden", "Quittieren braucht das Recht Einrichten") { return } + if !requireCSRF(w, r, manager) { + return + } var body monitoringAckBody if err := decodeBody(r, &body); err != nil || body.ID == "" { writeErrorKey(w, http.StatusBadRequest, "monitoring_ack_invalid", "error.monitoring_ack_invalid", nil, "Die Kennung der Meldung ist ungültig.") diff --git a/dashboard/internal/httpapi/monitoring_test.go b/dashboard/internal/httpapi/monitoring_test.go index bb90b6e4..135859ff 100644 --- a/dashboard/internal/httpapi/monitoring_test.go +++ b/dashboard/internal/httpapi/monitoring_test.go @@ -168,3 +168,28 @@ func TestMonitoringNilDepsIs501(t *testing.T) { t.Fatalf("POST without deps: %d %s", recorder.Code, recorder.Body.String()) } } + +func TestMonitoringAckNeedsCSRF(t *testing.T) { + var acked []string + deps := &MonitoringDeps{ + Notices: func(time.Time) []monitoring.Notice { return nil }, + Ack: func(id string, ack bool, user string, now time.Time) error { + acked = append(acked, id) + return nil + }, + } + router, manager := monitoringRouter(t, deps) + cookie, csrf := guestCookie(t, router, manager, []string{auth.RoleViewMonitoring, auth.RoleEditSetup}) + + recorder := monitoringAckRequest(router, cookie, "", `{"id":"energy:a","ack":true}`) + if recorder.Code != http.StatusForbidden || !strings.Contains(recorder.Body.String(), `"csrf_failed"`) { + t.Fatalf("POST without CSRF: %d %s", recorder.Code, recorder.Body.String()) + } + if len(acked) != 0 { + t.Fatalf("acknowledged without CSRF: %v", acked) + } + + if recorder := monitoringAckRequest(router, cookie, csrf, `{"id":"energy:a","ack":true}`); recorder.Code != http.StatusOK { + t.Fatalf("POST with CSRF: %d %s", recorder.Code, recorder.Body.String()) + } +} diff --git a/dashboard/internal/httpapi/settings_access_test.go b/dashboard/internal/httpapi/settings_access_test.go index 98510c07..87b8d7fb 100644 --- a/dashboard/internal/httpapi/settings_access_test.go +++ b/dashboard/internal/httpapi/settings_access_test.go @@ -47,3 +47,75 @@ func TestSettingsAccessAutomationGroupSwitchesNeedEditSetup(t *testing.T) { t.Fatalf("automation_habits_disabled saved despite 403: %+v (err=%v)", value.AutomationHabitsDisabled, err) } } + +// TestSettingsRestoreChecksFieldRoles covers the restore path: the roles come +// from the fields that differ between the revision and the current settings, +// the same way the PUT path decides them. +func TestSettingsRestoreChecksFieldRoles(t *testing.T) { + restore := func(t *testing.T, store *settings.Store, roles []string) *httptest.ResponseRecorder { + t.Helper() + revisions, err := store.SettingsRevisions() + if err != nil || len(revisions) != 1 { + t.Fatalf("revisions = %+v (err=%v), want exactly one", revisions, err) + } + body := `{"revision":"` + revisions[0].Name + `"}` + request := httptest.NewRequest(http.MethodPost, "/api/v1/settings/restore", strings.NewReader(body)) + request = request.WithContext(auth.WithUser(context.Background(), auth.User{Roles: roles})) + recorder := httptest.NewRecorder() + handleSettingsRevision(store).ServeHTTP(recorder, request) + return recorder + } + + t.Run("setup field needs edit_setup", func(t *testing.T) { + store := settings.NewStore(t.TempDir()) + base, err := store.LoadSettings() + if err != nil { + t.Fatal(err) + } + if err := store.SaveSettings(base); err != nil { + t.Fatal(err) + } + changed := base + changed.AutomationPatternsDisabled = true + if err := store.SaveSettings(changed); err != nil { + t.Fatal(err) + } + + if recorder := restore(t, store, []string{auth.RoleEditSettings}); recorder.Code != http.StatusForbidden { + t.Fatalf("restore of automation_patterns_disabled with edit_settings only: %d %s", recorder.Code, recorder.Body.String()) + } + if value, err := store.LoadSettings(); err != nil || !value.AutomationPatternsDisabled { + t.Fatalf("setting restored despite 403: %+v (err=%v)", value.AutomationPatternsDisabled, err) + } + + if recorder := restore(t, store, []string{auth.RoleEditSettings, auth.RoleEditSetup}); recorder.Code != http.StatusOK { + t.Fatalf("restore with edit_setup: %d %s", recorder.Code, recorder.Body.String()) + } + if value, err := store.LoadSettings(); err != nil || value.AutomationPatternsDisabled { + t.Fatalf("setting not restored with edit_setup: %+v (err=%v)", value.AutomationPatternsDisabled, err) + } + }) + + t.Run("design field needs only edit_settings", func(t *testing.T) { + store := settings.NewStore(t.TempDir()) + base, err := store.LoadSettings() + if err != nil { + t.Fatal(err) + } + if err := store.SaveSettings(base); err != nil { + t.Fatal(err) + } + changed := base + changed.ShowRuntimeStatus = !base.ShowRuntimeStatus + if err := store.SaveSettings(changed); err != nil { + t.Fatal(err) + } + + if recorder := restore(t, store, []string{auth.RoleEditSettings}); recorder.Code != http.StatusOK { + t.Fatalf("restore of a design field with edit_settings: %d %s", recorder.Code, recorder.Body.String()) + } + if value, err := store.LoadSettings(); err != nil || value.ShowRuntimeStatus != base.ShowRuntimeStatus { + t.Fatalf("design field not restored: %+v (err=%v)", value.ShowRuntimeStatus, err) + } + }) +} diff --git a/dashboard/internal/settings/settings.go b/dashboard/internal/settings/settings.go index 2e9e6233..489e18f0 100644 --- a/dashboard/internal/settings/settings.go +++ b/dashboard/internal/settings/settings.go @@ -840,9 +840,16 @@ func (s *Store) ReadSettingsRevision(revision string) (json.RawMessage, error) { return s.readRevisionLocked("settings", revision) } -func (s *Store) RestoreSettings(revision string) (Settings, error) { +// SettingsRevisionValue returns a revision normalized and validated, without +// changing the stored settings. The restore path compares it with the current +// settings before it writes. +func (s *Store) SettingsRevisionValue(revision string) (Settings, error) { s.mu.Lock() defer s.mu.Unlock() + return s.settingsRevisionLocked(revision) +} + +func (s *Store) settingsRevisionLocked(revision string) (Settings, error) { data, err := s.readRevisionLocked("settings", revision) if err != nil { return Settings{}, err @@ -855,6 +862,16 @@ func (s *Store) RestoreSettings(revision string) (Settings, error) { if err := validateSettings(value); err != nil { return Settings{}, err } + return value, nil +} + +func (s *Store) RestoreSettings(revision string) (Settings, error) { + s.mu.Lock() + defer s.mu.Unlock() + value, err := s.settingsRevisionLocked(revision) + if err != nil { + return Settings{}, err + } if err := s.saveJSONLocked("settings.json", value); err != nil { return Settings{}, err } From cf08e7fe59874ed16be16fcb519a917dc8f0f403 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:36:20 +0100 Subject: [PATCH 15/22] fix(webui): gate finding actions, close the popover on scroll and keep every undo Finding popovers hide Ignorieren and the fixes without the automations right. The popover closes on page scroll and window resize. The learning settings treat an unreadable session as no edit right, so the new-feature hint stays hidden. The suggestion band keeps every dismiss within the hint time and undoes them newest first, and a failed dismiss shows a toast and keeps the tile. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/catalogs/de.json | 1 + dashboard/internal/webui/catalogs/en.json | 1 + .../webui/static/js/automation-suggestions.js | 40 +++++++++------ .../webui/static/js/automations.page.js | 7 +++ .../webui/static/js/learning-settings.js | 3 +- .../webui/templates/automations-finding.html | 2 +- .../internal/webui/templates/automations.html | 4 +- .../test/automation-suggestions.test.mjs | 50 +++++++++++++++++-- dashboard/test/automations.page.test.mjs | 18 +++++++ dashboard/test/learning-settings.test.mjs | 9 ++++ 10 files changed, 112 insertions(+), 23 deletions(-) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index d395c5e4..92d9dccf 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -546,6 +546,7 @@ "automations.learn.coupling.follow.line": "{hits} von {cases} Mal innerhalb von {lag_s} s", "automations.learn.coupling.follow.text": "{b} wurde {hits} von {cases} Mal innerhalb von {lag_s} Sekunden geschaltet, nachdem {a} geschaltet wurde. Eine Regel kann das übernehmen, dann musst du nur noch {a} schalten.", "automations.learn.coupling.follow.title": "{b} folgt {a}", + "automations.learn.drop_failed": "Das Verwerfen hat nicht geklappt. Bitte versuche es erneut.", "automations.learn.fact.cause": "Ursache", "automations.learn.fact.cause.clustered": "Die Befehle kamen gebündelt", "automations.learn.fact.cause.feedback": "Die Last selbst kippt die Bedingung", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 32793671..cb60857c 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -546,6 +546,7 @@ "automations.learn.coupling.follow.line": "{hits} of {cases} times within {lag_s} s", "automations.learn.coupling.follow.text": "{b} was switched {hits} of {cases} times within {lag_s} seconds after {a} was switched. A rule can take that over, so you only have to switch {a}.", "automations.learn.coupling.follow.title": "{b} follows {a}", + "automations.learn.drop_failed": "Dismissing did not work. Please try again.", "automations.learn.fact.cause": "Cause", "automations.learn.fact.cause.clustered": "The commands came in bunches", "automations.learn.fact.cause.feedback": "The load itself flips the condition", diff --git a/dashboard/internal/webui/static/js/automation-suggestions.js b/dashboard/internal/webui/static/js/automation-suggestions.js index c16206fa..2369329d 100644 --- a/dashboard/internal/webui/static/js/automation-suggestions.js +++ b/dashboard/internal/webui/static/js/automation-suggestions.js @@ -146,7 +146,8 @@ tipOpen: false, canEdit: false, csrf: '', - dropped: null, + // Alle Verwerfen seit dem letzten Ablauf des Hinweises, in der Reihenfolge des Verwerfens. + dropped: [], hintTimer: 0, // Spitze der Karte: Mitte der gewaehlten Kachel in px ab der linken Kante der Kacheln. caret: '', @@ -278,29 +279,38 @@ const index = this.items.findIndex((x) => x.id === s.id); let ok = false; try { ok = await this.send(s, action); } catch (error) { ok = false; } - if (!ok || index < 0) return; + if (index < 0) return; + if (!ok) { + const text = window.I18n && window.I18n.t ? window.I18n.t(CAT + 'drop_failed') : CAT + 'drop_failed'; + this.$store.toasts.push(text, 'critical'); + return; + } this.items = this.items.filter((x) => x.id !== s.id); if (this.open === s.id) { this.open = ''; this.tipOpen = false; } - this.dropped = { item: s, index }; + this.dropped = [...this.dropped, { item: s, index }]; this.armHint(); window.dispatchEvent(new window.CustomEvent(CHANGED)); }, armHint() { clearTimeout(this.hintTimer); - this.hintTimer = window.setTimeout(() => { this.dropped = null; }, HINT_MS); + this.hintTimer = window.setTimeout(() => { this.dropped = []; }, HINT_MS); }, + // Holt alle Verwerfen zurueck, das juengste zuerst: so kehrt jede Einfuegung an ihren Platz. + // Schlaegt eines fehl, bleiben es und die aelteren im Hinweis. async undo() { - const drop = this.dropped; - if (!drop) return; - let ok = false; - try { ok = await this.send(drop.item, 'undo'); } catch (error) { ok = false; } - if (!ok) return; - clearTimeout(this.hintTimer); - this.dropped = null; - const items = this.items.slice(); - items.splice(Math.min(drop.index, items.length), 0, drop.item); - this.items = items; - window.dispatchEvent(new window.CustomEvent(CHANGED)); + const drops = this.dropped.slice(); + for (let n = drops.length - 1; n >= 0; n -= 1) { + const drop = drops[n]; + let ok = false; + try { ok = await this.send(drop.item, 'undo'); } catch (error) { ok = false; } + if (!ok) break; + this.dropped = this.dropped.filter((entry) => entry !== drop); + const items = this.items.slice(); + items.splice(Math.min(drop.index, items.length), 0, drop.item); + this.items = items; + window.dispatchEvent(new window.CustomEvent(CHANGED)); + } + if (this.dropped.length === 0) clearTimeout(this.hintTimer); }, }; } diff --git a/dashboard/internal/webui/static/js/automations.page.js b/dashboard/internal/webui/static/js/automations.page.js index 3554e082..55763a09 100644 --- a/dashboard/internal/webui/static/js/automations.page.js +++ b/dashboard/internal/webui/static/js/automations.page.js @@ -410,6 +410,13 @@ get canEditAutomations() { return this.sessionRoles === null || this.sessionRoles.includes('automations'); }, + // Befunde haengen an ihrer Marke. Scrollen oder eine neue Fenstergroesse verschieben + // die Marke, der Popover schliesst dann statt an der falschen Stelle stehen zu bleiben. + init() { + const closeOpenFinding = () => { if (this.findingOpen) this.closeFinding(); }; + window.addEventListener('scroll', closeOpenFinding, { passive: true }); + window.addEventListener('resize', closeOpenFinding); + }, get canOperateAutomations() { return this.sessionRoles === null || this.sessionRoles.includes('operate_automations'); }, diff --git a/dashboard/internal/webui/static/js/learning-settings.js b/dashboard/internal/webui/static/js/learning-settings.js index 270c1e5a..391879c4 100644 --- a/dashboard/internal/webui/static/js/learning-settings.js +++ b/dashboard/internal/webui/static/js/learning-settings.js @@ -234,7 +234,8 @@ this.status = status; this.storageStatus = storageStatus; this.csrfToken = (session && session.csrf_token) || ''; - this.learnCanEdit = session ? session.edit_setup === true : true; + // Ohne lesbare Sitzung weiss die Seite nicht, ob das Recht da ist: dann gilt es als fehlend. + this.learnCanEdit = session ? session.edit_setup === true : false; this.automation_outdoor_entity = settings && typeof settings.automation_outdoor_entity === 'string' ? settings.automation_outdoor_entity : ''; // Fehlt das Feld (aelterer Server), bleibt der Hinweis verborgen. this.location_set = !(status && status.location_set === false); diff --git a/dashboard/internal/webui/templates/automations-finding.html b/dashboard/internal/webui/templates/automations-finding.html index 9d09b1cc..9e40fa1e 100644 --- a/dashboard/internal/webui/templates/automations-finding.html +++ b/dashboard/internal/webui/templates/automations-finding.html @@ -23,7 +23,7 @@

-
+