From 7485919bed2399155918224f3bae0dfd6f3a904b Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Sun, 25 Oct 2026 17:05:51 +0100 Subject: [PATCH 1/3] fix(app): history tiles draw measured power for grid, PV and battery Fredrik's box, 25 October 2026: the app's Solar history jumped between 0 and 1.2 kW while the sun gave about 0.4 kW. The tiles were built from the energy ledger, and a Sungrow's counters move in 0.1 kWh steps, so each step landed whole in the five minutes it ticked in (100 Wh over five minutes is 1.2 kW). The box's own charts draw the power rows and were right. appHistory.Window now takes grid, PV and battery from those rows (state.LoadPowerBuckets: the same tiers /api/history unions, averaged in fixed buckets from the tile's start, half-open). A flow some row did not measure is a hole in that bucket. Load stays the ledger's consumer use, which the source accounting balances from power. FTW Cloud's tiles use the same window, so they change with it. Co-Authored-By: Claude Opus 5.5 --- .changeset/app-history-measured-power.md | 5 ++ go/cmd/ftw/app_history_power_test.go | 72 +++++++++++++++++++ go/cmd/ftw/app_link.go | 46 +++++++++--- go/internal/state/history_power_buckets.go | 66 +++++++++++++++++ .../state/history_power_buckets_test.go | 55 ++++++++++++++ go/internal/state/store.go | 46 ++++++------ 6 files changed, 259 insertions(+), 31 deletions(-) create mode 100644 .changeset/app-history-measured-power.md create mode 100644 go/cmd/ftw/app_history_power_test.go create mode 100644 go/internal/state/history_power_buckets.go create mode 100644 go/internal/state/history_power_buckets_test.go diff --git a/.changeset/app-history-measured-power.md b/.changeset/app-history-measured-power.md new file mode 100644 index 000000000..b6eb73897 --- /dev/null +++ b/.changeset/app-history-measured-power.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +The app's history for solar, grid and battery now shows the measured power, the same as the box's own charts. Before, it came from the energy counters, which on a Sungrow move in 0.1 kWh steps, so each five minutes read 0 or 1.2 kW while the sun gave 0.4 kW. Home use is unchanged. A flow that was not measured for part of five minutes is now a gap there, not a lower value. diff --git a/go/cmd/ftw/app_history_power_test.go b/go/cmd/ftw/app_history_power_test.go new file mode 100644 index 000000000..837d6ef12 --- /dev/null +++ b/go/cmd/ftw/app_history_power_test.go @@ -0,0 +1,72 @@ +package main + +import ( + "context" + "math" + "path/filepath" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/state" + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// The app's tiles draw what was measured. A Sungrow's energy counters move in +// 0.1 kWh steps, so a ledger bucket read 0 or 1.2 kW while the sun shone at +// 0.4 kW (Fredrik's box, 25 October 2026). Grid, PV and battery now come from +// the power rows /api/history draws; a flow that fell silent is a hole there, +// never a mean of the rows that were left. +func TestAppHistoryDrawsMeasuredPower(t *testing.T) { + st, err := state.Open(filepath.Join(t.TempDir(), "state.db")) + if err != nil { + t.Fatal(err) + } + defer st.Close() + if err := st.EnableHistoryAggregation(); err != nil { + t.Fatal(err) + } + tel := telemetry.NewStore() + tel.Update("grid", telemetry.DerMeter, 300, nil, nil) + tel.RecordDriverSuccess("grid") + tel.Update("sungrow", telemetry.DerPV, -400, nil, nil) + tel.RecordDriverSuccess("sungrow") + const step = int64(300_000) + base := time.Now().Add(-20 * time.Minute).Truncate(5 * time.Minute).UnixMilli() + for i := int64(0); i < 60; i++ { + // The inverter falls silent six minutes in. + if i == 36 { + tel.Get("sungrow", telemetry.DerPV).UpdatedAt = time.Now().Add(-10 * time.Minute) + } + p, _ := buildHistoryPoint(tel, tickPersistControl{SiteMeterDriver: "grid"}, base+i*10_000, 90*time.Second) + p.Sources.AtMS = base + i*10_000 + if err := st.RecordTickWithEnergy(p, nil, nil); err != nil { + t.Fatal(err) + } + } + if err := st.FlushHistory(context.Background()); err != nil { + t.Fatal(err) + } + got, err := (&appHistory{st: st}).Window(context.Background(), []string{"pv_w", "grid_w"}, step, base, base+2*step) + if err != nil { + t.Fatal(err) + } + pv := map[int64]float64{} + for _, s := range got["pv_w"] { + pv[s.StartMs] = s.W + } + grid := map[int64]float64{} + for _, s := range got["grid_w"] { + grid[s.StartMs] = s.W + } + if w, ok := pv[base]; !ok || math.Abs(w+400) > 0.5 { + t.Fatalf("first five minutes: pv %v (present %v), want -400 W measured", w, ok) + } + if w, ok := pv[base+step]; ok { + t.Fatalf("a silent inverter's five minutes read %v W, want a hole", w) + } + for _, at := range []int64{base, base + step} { + if w, ok := grid[at]; !ok || math.Abs(w-300) > 0.5 { + t.Fatalf("grid at %d: %v (present %v), want 300 W", at, w, ok) + } + } +} diff --git a/go/cmd/ftw/app_link.go b/go/cmd/ftw/app_link.go index 89aeba800..210811bba 100644 --- a/go/cmd/ftw/app_link.go +++ b/go/cmd/ftw/app_link.go @@ -285,12 +285,14 @@ func (a *appModes) ObservedMode() (control.Mode, bool) { return a.ctrl.Mode, true } -// appHistory serves the app's history tiles from the energy ledger. +// appHistory serves the app's history tiles: mean power per bucket, signed +// as the site convention says (positive watts flow into the site). // -// The ledger stores energy per flow per bucket; the wire wants mean power per -// signed series. The mapping below is the site convention and nothing else: -// positive watts flow into the site, so import minus export is the grid, and -// PV is generation negated. W = Wh × 3 600 000 / bucket, no other arithmetic. +// Grid, PV and battery are the measured power rows /api/history draws, +// averaged over each bucket. Their energy counters may move in 0.1 kWh steps +// (Sungrow), so a ledger bucket held 0 or 1.2 kW while the sun shone at +// 0.4 kW. Load is the ledger's consumer use, which the source accounting +// already balances from power: W = Wh × 3 600 000 / bucket. type appHistory struct { st *state.Store } @@ -303,10 +305,16 @@ func (a *appHistory) Window( sign float64 } termsByName := map[string][]term{ - "grid_w": {{state.FlowGridImport, 1}, {state.FlowGridExport, -1}}, - "pv_w": {{state.FlowPVGeneration, -1}}, - "battery_w": {{state.FlowBatteryCharge, 1}, {state.FlowBatteryDischarge, -1}}, - "load_w": {{state.FlowConsumerUse, 1}}, + "load_w": {{state.FlowConsumerUse, 1}}, + } + type measured struct { + missing state.HistoryMissing + w func(state.PowerBucket) float64 + } + powerByName := map[string]measured{ + "grid_w": {state.MissingGrid, func(b state.PowerBucket) float64 { return b.GridW }}, + "pv_w": {state.MissingPV, func(b state.PowerBucket) float64 { return b.PVW }}, + "battery_w": {state.MissingBattery, func(b state.PowerBucket) float64 { return b.BatW }}, } points, _, err := a.st.LoadEnergyHistoryContext(ctx, state.EnergyHistoryQuery{ @@ -324,10 +332,30 @@ func (a *appHistory) Window( // where nothing was metered stays absent and becomes MISSING, which is // the honest answer — zero would claim the house used no power at all. byName := make(map[string]map[int64]float64, len(names)) + wantPower := false for _, name := range names { if termsByName[name] != nil { byName[name] = map[int64]float64{} } + if _, ok := powerByName[name]; ok { + byName[name] = map[int64]float64{} + wantPower = true + } + } + if wantPower { + buckets, err := a.st.LoadPowerBuckets(ctx, fromMs, toMs, stepMs) + if err != nil { + return nil, err + } + for _, b := range buckets { + for _, name := range names { + // A flow some row did not measure has no mean here: the + // rows that did would read as the whole bucket. + if m, ok := powerByName[name]; ok && b.Missing&m.missing == 0 { + byName[name][b.StartMS] = m.w(b) + } + } + } } for _, p := range points { for _, name := range names { diff --git a/go/internal/state/history_power_buckets.go b/go/internal/state/history_power_buckets.go new file mode 100644 index 000000000..4f8e6e99a --- /dev/null +++ b/go/internal/state/history_power_buckets.go @@ -0,0 +1,66 @@ +package state + +import ( + "context" + "errors" + "strings" + "time" +) + +// PowerBucket is the measured mean power over one fixed bucket, site-signed, +// from the same stored rows /api/history draws. Missing marks the flows that +// some row in the bucket did not measure; their mean is not a value then. +type PowerBucket struct { + StartMS int64 + GridW float64 + PVW float64 + BatW float64 + Missing HistoryMissing +} + +// LoadPowerBuckets returns the mean measured power in each bucketMs bucket of +// [fromMs, toMs), the buckets laid from fromMs. A bucket with no stored row is +// absent. Unlike an energy counter, which may move in 0.1 kWh steps, the +// power rows give each bucket its own shape. Load is not here: it comes from +// the source accounting, which the energy ledger keeps. +func (s *Store) LoadPowerBuckets(ctx context.Context, fromMs, toMs, bucketMs int64) ([]PowerBucket, error) { + if bucketMs <= 0 || toMs <= fromMs { + return nil, errors.New("power buckets need a positive width and range") + } + if (toMs-fromMs+bucketMs-1)/bucketMs > maxSeriesBuckets { + return nil, ErrHistoryQueryLimit + } + if s.history == nil { + return nil, nil + } + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + rows, err := s.history.QueryContext(ctx, halfOpenHistoryRange(historyTierUnion)+` + SELECT (ts_ms - ?) / ? AS bucket, + SUM(COALESCE(grid_w, 0)*n)/SUM(n), SUM(COALESCE(pv_w, 0)*n)/SUM(n), SUM(COALESCE(bat_w, 0)*n)/SUM(n), + `+historyMissingAggregate+` + FROM deduped GROUP BY bucket ORDER BY bucket`, + fromMs, toMs, fromMs, toMs, fromMs, toMs, fromMs, toMs, fromMs, toMs, fromMs, bucketMs) + if err != nil { + return nil, err + } + defer rows.Close() + var out []PowerBucket + for rows.Next() { + var b PowerBucket + var index int64 + if err := rows.Scan(&index, &b.GridW, &b.PVW, &b.BatW, &b.Missing); err != nil { + return nil, err + } + b.StartMS = fromMs + index*bucketMs + out = append(out, b) + } + return out, rows.Err() +} + +// halfOpenHistoryRange turns historyTierUnion's closed ranges into [from, to), +// so a row on a bucket boundary belongs to one bucket only. +func halfOpenHistoryRange(union string) string { + union = strings.ReplaceAll(union, "ts_ms BETWEEN ? AND ?", "ts_ms >= ? AND ts_ms < ?") + return strings.ReplaceAll(union, "last_ms BETWEEN ? AND ?", "last_ms >= ? AND last_ms < ?") +} diff --git a/go/internal/state/history_power_buckets_test.go b/go/internal/state/history_power_buckets_test.go new file mode 100644 index 000000000..ef025a7e8 --- /dev/null +++ b/go/internal/state/history_power_buckets_test.go @@ -0,0 +1,55 @@ +package state + +import ( + "context" + "path/filepath" + "testing" + "time" +) + +// The app's tiles ask for fixed five-minute buckets laid from the tile's +// start. A row on a boundary belongs to the bucket it starts, and a bucket +// with no row is absent rather than zero. +func TestLoadPowerBucketsLaysFixedBuckets(t *testing.T) { + s, err := Open(filepath.Join(t.TempDir(), "state.db")) + if err != nil { + t.Fatal(err) + } + defer s.Close() + base := time.Now().Add(-time.Hour).Truncate(5 * time.Minute).UnixMilli() + const step = int64(300_000) + for _, r := range []struct { + at int64 + pv, grid float64 + }{ + {base + 10_000, -400, 300}, + {base + 200_000, -600, 100}, + {base + step, -2000, -500}, // on the boundary: the second bucket's + // nothing in the third bucket + {base + 3*step + 1_000, -100, 700}, + } { + if err := s.RecordHistory(HistoryPoint{TsMs: r.at, PVW: r.pv, GridW: r.grid}); err != nil { + t.Fatal(err) + } + } + got, err := s.LoadPowerBuckets(context.Background(), base, base+4*step, step) + if err != nil { + t.Fatal(err) + } + want := []PowerBucket{ + {StartMS: base, PVW: -500, GridW: 200}, + {StartMS: base + step, PVW: -2000, GridW: -500}, + {StartMS: base + 3*step, PVW: -100, GridW: 700}, + } + if len(got) != len(want) { + t.Fatalf("got %d buckets, want %d: %+v", len(got), len(want), got) + } + for i := range want { + if got[i].StartMS != want[i].StartMS || got[i].PVW != want[i].PVW || got[i].GridW != want[i].GridW || got[i].Missing != 0 { + t.Fatalf("bucket %d: got %+v, want %+v", i, got[i], want[i]) + } + } + if _, err := s.LoadPowerBuckets(context.Background(), base, base, step); err == nil { + t.Fatal("an empty range must be refused") + } +} diff --git a/go/internal/state/store.go b/go/internal/state/store.go index 8a42ba7e9..9ab025a89 100644 --- a/go/internal/state/store.go +++ b/go/internal/state/store.go @@ -1498,6 +1498,28 @@ func (s *Store) LoadHistoryContext(ctx context.Context, sinceMs, untilMs int64, return s.loadArchiveHistory(ctx, sinceMs, untilMs, maxPoints) } +// historyTierUnion is every stored power row in a range, one per ts_ms: +// the hot tier over warm over cold, then the dashboard aggregates. COALESCE +// to 0 so NULL columns (from partial aggregations) scan cleanly; a row's +// missing flags say which of them were not measured. +const historyTierUnion = ` + WITH all_rows AS ( + SELECT ts_ms, grid_w, pv_w, bat_w, load_w, bat_soc, 0 AS tier,1 AS n,1 AS resolution_ms,ts_ms AS first_ms,0 AS missing FROM history_hot + WHERE ts_ms BETWEEN ? AND ? + UNION ALL + SELECT ts_ms, grid_w, pv_w, bat_w, load_w, bat_soc, 1,1,900000,ts_ms,0 FROM history_warm + WHERE ts_ms BETWEEN ? AND ? + UNION ALL + SELECT ts_ms, grid_w, pv_w, bat_w, load_w, bat_soc, 2,1,86400000,ts_ms,0 FROM history_cold + WHERE ts_ms BETWEEN ? AND ? + UNION ALL SELECT last_ms,grid_w,pv_w,bat_w,load_w,bat_soc,-1,n,d.resolution_ms,first_ms,COALESCE(q.missing,0) FROM history_dashboard d LEFT JOIN history_quality q ON q.kind='dashboard' AND q.start_ms=d.start_ms AND q.resolution_ms=d.resolution_ms WHERE last_ms BETWEEN ? AND ? + UNION ALL SELECT last_ms,grid_w,pv_w,bat_w,load_w,bat_soc,-2,n,d.resolution_ms,first_ms,COALESCE(q.missing,0) FROM history_dashboard_partial d LEFT JOIN history_quality q ON q.kind='partial_dashboard' AND q.start_ms=d.start_ms AND q.resolution_ms=d.resolution_ms WHERE last_ms BETWEEN ? AND ? + ), + deduped AS ( + SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ts_ms ORDER BY tier) AS rn FROM all_rows) WHERE rn=1 + ) + ` + func (s *Store) loadArchiveHistory(ctx context.Context, sinceMs, untilMs int64, maxPoints int) ([]HistoryPoint, error) { if maxPoints > maxSeriesBuckets { return nil, ErrHistoryQueryLimit @@ -1530,29 +1552,9 @@ func (s *Store) loadArchiveHistory(ctx context.Context, sinceMs, untilMs int64, bucketMs = max(sourceWidth, ((bucketMs+sourceWidth-1)/sourceWidth)*sourceWidth) queryFrom = bucketStart(sinceMs, ArchiveResolutionMS) } - // Union across all three tiers. Dedupe on ts_ms preferring hot over warm over cold. - // COALESCE to 0 so NULL columns (from partial aggregations) scan cleanly. - const tierUnion = ` - WITH all_rows AS ( - SELECT ts_ms, grid_w, pv_w, bat_w, load_w, bat_soc, 0 AS tier,1 AS n,1 AS resolution_ms,ts_ms AS first_ms,0 AS missing FROM history_hot - WHERE ts_ms BETWEEN ? AND ? - UNION ALL - SELECT ts_ms, grid_w, pv_w, bat_w, load_w, bat_soc, 1,1,900000,ts_ms,0 FROM history_warm - WHERE ts_ms BETWEEN ? AND ? - UNION ALL - SELECT ts_ms, grid_w, pv_w, bat_w, load_w, bat_soc, 2,1,86400000,ts_ms,0 FROM history_cold - WHERE ts_ms BETWEEN ? AND ? - UNION ALL SELECT last_ms,grid_w,pv_w,bat_w,load_w,bat_soc,-1,n,d.resolution_ms,first_ms,COALESCE(q.missing,0) FROM history_dashboard d LEFT JOIN history_quality q ON q.kind='dashboard' AND q.start_ms=d.start_ms AND q.resolution_ms=d.resolution_ms WHERE last_ms BETWEEN ? AND ? - UNION ALL SELECT last_ms,grid_w,pv_w,bat_w,load_w,bat_soc,-2,n,d.resolution_ms,first_ms,COALESCE(q.missing,0) FROM history_dashboard_partial d LEFT JOIN history_quality q ON q.kind='partial_dashboard' AND q.start_ms=d.start_ms AND q.resolution_ms=d.resolution_ms WHERE last_ms BETWEEN ? AND ? - ), - deduped AS ( - SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ts_ms ORDER BY tier) AS rn FROM all_rows) WHERE rn=1 - ) - ` - rangeUnion := tierUnion + rangeUnion := historyTierUnion if sourceMode { - rangeUnion = strings.ReplaceAll(tierUnion, "ts_ms BETWEEN ? AND ?", "ts_ms >= ? AND ts_ms < ?") - rangeUnion = strings.ReplaceAll(rangeUnion, "last_ms BETWEEN ? AND ?", "last_ms >= ? AND last_ms < ?") + rangeUnion = halfOpenHistoryRange(historyTierUnion) } var ( rows *sql.Rows From f6927afd4a7a672f59523666ae49e4a363c465b8 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Sun, 25 Oct 2026 17:20:34 +0100 Subject: [PATCH 2/3] fix(app): review fixes; each flow's mean over the rows that measured it - LoadPowerBuckets means each flow over the rows that measured it and marks it missing only past maxSourceDayUnknownShare (10 %) of the bucket's rows, as a source-era day's total is. One stale reading no longer removes five minutes, and a PV inverter waking at dawn keeps its buckets. - Window skips the ledger query when no ledger series is asked for. - Comments in appproto and cloud_link no longer say the series come from the ledger. - Tests: a row at `to` stays outside, battery charging is positive, and one stale reading keeps its bucket (it fails under an all-or-nothing rule). Co-Authored-By: Claude Opus 5.5 --- .changeset/app-history-measured-power.md | 2 +- go/cmd/ftw/app_history_power_test.go | 53 ++++++++++++++++++- go/cmd/ftw/app_link.go | 26 +++++---- go/cmd/ftw/cloud_link.go | 6 +-- go/internal/appproto/history.go | 9 ++-- go/internal/state/history_power_buckets.go | 38 ++++++++++--- .../state/history_power_buckets_test.go | 1 + 7 files changed, 110 insertions(+), 25 deletions(-) diff --git a/.changeset/app-history-measured-power.md b/.changeset/app-history-measured-power.md index b6eb73897..720bd217c 100644 --- a/.changeset/app-history-measured-power.md +++ b/.changeset/app-history-measured-power.md @@ -2,4 +2,4 @@ "ftw": patch --- -The app's history for solar, grid and battery now shows the measured power, the same as the box's own charts. Before, it came from the energy counters, which on a Sungrow move in 0.1 kWh steps, so each five minutes read 0 or 1.2 kW while the sun gave 0.4 kW. Home use is unchanged. A flow that was not measured for part of five minutes is now a gap there, not a lower value. +The app's history for solar, grid and battery now shows the measured power, the same as the box's own charts. Before, it came from the energy counters, which on a Sungrow move in 0.1 kWh steps, so each five minutes read 0 or 1.2 kW while the sun gave 0.4 kW. Home use is unchanged. Five minutes in which a flow went unmeasured for more than a tenth of the time is now a gap for that flow, not a lower value. diff --git a/go/cmd/ftw/app_history_power_test.go b/go/cmd/ftw/app_history_power_test.go index 837d6ef12..875cc3bcb 100644 --- a/go/cmd/ftw/app_history_power_test.go +++ b/go/cmd/ftw/app_history_power_test.go @@ -29,6 +29,7 @@ func TestAppHistoryDrawsMeasuredPower(t *testing.T) { tel.Update("grid", telemetry.DerMeter, 300, nil, nil) tel.RecordDriverSuccess("grid") tel.Update("sungrow", telemetry.DerPV, -400, nil, nil) + tel.Update("sungrow", telemetry.DerBattery, 500, nil, nil) tel.RecordDriverSuccess("sungrow") const step = int64(300_000) base := time.Now().Add(-20 * time.Minute).Truncate(5 * time.Minute).UnixMilli() @@ -46,7 +47,7 @@ func TestAppHistoryDrawsMeasuredPower(t *testing.T) { if err := st.FlushHistory(context.Background()); err != nil { t.Fatal(err) } - got, err := (&appHistory{st: st}).Window(context.Background(), []string{"pv_w", "grid_w"}, step, base, base+2*step) + got, err := (&appHistory{st: st}).Window(context.Background(), []string{"pv_w", "grid_w", "battery_w"}, step, base, base+2*step) if err != nil { t.Fatal(err) } @@ -69,4 +70,54 @@ func TestAppHistoryDrawsMeasuredPower(t *testing.T) { t.Fatalf("grid at %d: %v (present %v), want 300 W", at, w, ok) } } + // Charging is power into the site: positive, as the ledger had it. + battery := map[int64]float64{} + for _, s := range got["battery_w"] { + battery[s.StartMs] = s.W + } + if w, ok := battery[base]; !ok || math.Abs(w-500) > 0.5 { + t.Fatalf("battery: %v (present %v), want +500 W charging in the first five minutes", w, ok) + } +} + +// One stale reading in five minutes is not a hole: the mean is over the +// readings that measured the sun, as long as they cover 90 % of them. +func TestAppHistoryKeepsAFiveMinutesWithOneMissedReading(t *testing.T) { + st, err := state.Open(filepath.Join(t.TempDir(), "state.db")) + if err != nil { + t.Fatal(err) + } + defer st.Close() + if err := st.EnableHistoryAggregation(); err != nil { + t.Fatal(err) + } + tel := telemetry.NewStore() + tel.Update("grid", telemetry.DerMeter, 300, nil, nil) + tel.RecordDriverSuccess("grid") + tel.Update("sungrow", telemetry.DerPV, -400, nil, nil) + tel.RecordDriverSuccess("sungrow") + const step = int64(300_000) + base := time.Now().Add(-20 * time.Minute).Truncate(5 * time.Minute).UnixMilli() + for i := int64(0); i < 30; i++ { + pv := tel.Get("sungrow", telemetry.DerPV) + pv.UpdatedAt = time.Now() + if i == 12 { + pv.UpdatedAt = time.Now().Add(-10 * time.Minute) + } + p, _ := buildHistoryPoint(tel, tickPersistControl{SiteMeterDriver: "grid"}, base+i*10_000, 90*time.Second) + p.Sources.AtMS = base + i*10_000 + if err := st.RecordTickWithEnergy(p, nil, nil); err != nil { + t.Fatal(err) + } + } + if err := st.FlushHistory(context.Background()); err != nil { + t.Fatal(err) + } + got, err := (&appHistory{st: st}).Window(context.Background(), []string{"pv_w"}, step, base, base+step) + if err != nil { + t.Fatal(err) + } + if pv := got["pv_w"]; len(pv) != 1 || math.Abs(pv[0].W+400) > 0.5 { + t.Fatalf("pv: %+v, want -400 W over the readings that measured it", pv) + } } diff --git a/go/cmd/ftw/app_link.go b/go/cmd/ftw/app_link.go index 210811bba..2b9e58206 100644 --- a/go/cmd/ftw/app_link.go +++ b/go/cmd/ftw/app_link.go @@ -317,15 +317,23 @@ func (a *appHistory) Window( "battery_w": {state.MissingBattery, func(b state.PowerBucket) float64 { return b.BatW }}, } - points, _, err := a.st.LoadEnergyHistoryContext(ctx, state.EnergyHistoryQuery{ - SinceMS: fromMs, - UntilMS: toMs, - BucketMS: stepMs, - // One tile is at most 168 buckets; the ledger's own cap is 2000. - Limit: 2000, - }) - if err != nil { - return nil, err + wantLedger := false + for _, name := range names { + wantLedger = wantLedger || termsByName[name] != nil + } + var points []state.EnergyLedgerPoint + var err error + if wantLedger { + points, _, err = a.st.LoadEnergyHistoryContext(ctx, state.EnergyHistoryQuery{ + SinceMS: fromMs, + UntilMS: toMs, + BucketMS: stepMs, + // One tile is at most 168 buckets; the ledger's own cap is 2000. + Limit: 2000, + }) + if err != nil { + return nil, err + } } // A bucket exists on the wire only if some term reported it. A bucket diff --git a/go/cmd/ftw/cloud_link.go b/go/cmd/ftw/cloud_link.go index 128d74ffd..7040ce015 100644 --- a/go/cmd/ftw/cloud_link.go +++ b/go/cmd/ftw/cloud_link.go @@ -50,8 +50,8 @@ type cloudSite struct { // With it, the link sends the car class, and a charger's level and // goal fields are views of its session's car. cars *cars.Runtime - // history is the energy ledger, read as the app's history over Noise - // reads it, so a closed tile is the same bytes either way. + // history is the app's history, read as the app over Noise reads it, + // so a closed tile is the same bytes either way. history *appHistory sessMu sync.Mutex @@ -71,7 +71,7 @@ var _ cloudlink.HistorySite = (*cloudSite)(nil) // HistoryWindow serves the tiles class. func (c *cloudSite) HistoryWindow(ctx context.Context, names []string, stepMs, fromMs, toMs int64) (map[string][]protocol.HistorySample, error) { if c.history == nil { - return nil, errors.New("no energy ledger") + return nil, errors.New("no history") } return c.history.Window(ctx, names, stepMs, fromMs, toMs) } diff --git a/go/internal/appproto/history.go b/go/internal/appproto/history.go index a49755fab..8361391c5 100644 --- a/go/internal/appproto/history.go +++ b/go/internal/appproto/history.go @@ -14,10 +14,11 @@ import ( // in package protocol, because FTW Cloud must compute the same tiles. This // file plans which tiles answer a query and reads them from the store. // -// Power series are derived from the energy ledger: a bucket's mean power is -// its energy divided by its width. That is an average, and it is presented as -// one — the chunk carries its step, and the app labels it. Sub-bucket wiggles -// are gone, which is the correct price for history that survives a restart. +// A series holds a bucket's mean power: measured power for grid, PV and +// battery, the energy ledger's consumer use for load (see appHistory in +// cmd/ftw). That is an average, and it is presented as one — the chunk +// carries its step, and the app labels it. Sub-bucket wiggles are gone, +// which is the correct price for history that survives a restart. // HistoryProvider answers windows of stored series. // diff --git a/go/internal/state/history_power_buckets.go b/go/internal/state/history_power_buckets.go index 4f8e6e99a..7702a1fe5 100644 --- a/go/internal/state/history_power_buckets.go +++ b/go/internal/state/history_power_buckets.go @@ -2,14 +2,18 @@ package state import ( "context" + "database/sql" "errors" + "strconv" "strings" "time" ) // PowerBucket is the measured mean power over one fixed bucket, site-signed, -// from the same stored rows /api/history draws. Missing marks the flows that -// some row in the bucket did not measure; their mean is not a value then. +// from the same stored rows /api/history draws. Each flow's mean is over the +// rows that measured it. Missing marks a flow left unmeasured for more than +// maxSourceDayUnknownShare of the bucket's rows, or for all of them: its mean +// is not a value then, as a source-era day's total is not. type PowerBucket struct { StartMS int64 GridW float64 @@ -35,10 +39,18 @@ func (s *Store) LoadPowerBuckets(ctx context.Context, fromMs, toMs, bucketMs int } ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() + // Per flow: the mean over the rows that measured it, and how many rows + // did not. + flow := func(column string, bit HistoryMissing) string { + b := strconv.Itoa(int(bit)) + return `SUM(CASE WHEN missing&` + b + `=0 THEN COALESCE(` + column + `,0)*n END)/SUM(CASE WHEN missing&` + b + `=0 THEN n END), + SUM(CASE WHEN missing&` + b + `<>0 THEN n ELSE 0 END)` + } rows, err := s.history.QueryContext(ctx, halfOpenHistoryRange(historyTierUnion)+` - SELECT (ts_ms - ?) / ? AS bucket, - SUM(COALESCE(grid_w, 0)*n)/SUM(n), SUM(COALESCE(pv_w, 0)*n)/SUM(n), SUM(COALESCE(bat_w, 0)*n)/SUM(n), - `+historyMissingAggregate+` + SELECT (ts_ms - ?) / ? AS bucket, SUM(n), + `+flow("grid_w", MissingGrid)+`, + `+flow("pv_w", MissingPV)+`, + `+flow("bat_w", MissingBattery)+` FROM deduped GROUP BY bucket ORDER BY bucket`, fromMs, toMs, fromMs, toMs, fromMs, toMs, fromMs, toMs, fromMs, toMs, fromMs, bucketMs) if err != nil { @@ -48,11 +60,23 @@ func (s *Store) LoadPowerBuckets(ctx context.Context, fromMs, toMs, bucketMs int var out []PowerBucket for rows.Next() { var b PowerBucket - var index int64 - if err := rows.Scan(&index, &b.GridW, &b.PVW, &b.BatW, &b.Missing); err != nil { + var index, total int64 + var grid, pv, bat sql.NullFloat64 + var gridOff, pvOff, batOff int64 + if err := rows.Scan(&index, &total, &grid, &gridOff, &pv, &pvOff, &bat, &batOff); err != nil { return nil, err } b.StartMS = fromMs + index*bucketMs + take := func(mean sql.NullFloat64, off int64, bit HistoryMissing) float64 { + if !mean.Valid || off*100 > total*maxSourceDayUnknownShare { + b.Missing |= bit + return 0 + } + return mean.Float64 + } + b.GridW = take(grid, gridOff, MissingGrid) + b.PVW = take(pv, pvOff, MissingPV) + b.BatW = take(bat, batOff, MissingBattery) out = append(out, b) } return out, rows.Err() diff --git a/go/internal/state/history_power_buckets_test.go b/go/internal/state/history_power_buckets_test.go index ef025a7e8..4788f43d5 100644 --- a/go/internal/state/history_power_buckets_test.go +++ b/go/internal/state/history_power_buckets_test.go @@ -27,6 +27,7 @@ func TestLoadPowerBucketsLaysFixedBuckets(t *testing.T) { {base + step, -2000, -500}, // on the boundary: the second bucket's // nothing in the third bucket {base + 3*step + 1_000, -100, 700}, + {base + 4*step, -9000, 9000}, // at `to`: outside the range } { if err := s.RecordHistory(HistoryPoint{TsMs: r.at, PVW: r.pv, GridW: r.grid}); err != nil { t.Fatal(err) From 964a8da009c19f6997685b0a88036dd04e3f7e6e Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Sun, 25 Oct 2026 17:25:00 +0100 Subject: [PATCH 3/3] fix(app): a majority rule keeps a bucket through the minute roll-up Second review: Core flags Load on every tick, so all ticks are partial rows, and the day-old roll-up merges a stale reading's flag into its whole minute. One stale reading in five minutes grows from 3 % of the rows to 20 %, so under a tenth the closed bucket turned into a hole a day later. A flow now needs to miss more than half of a bucket's rows to lose its mean. TestPowerBucketSurvivesTheMinuteRollup writes ticks as Core does, rolls them up and fails under the old tenth. Co-Authored-By: Claude Opus 5.5 --- .changeset/app-history-measured-power.md | 2 +- go/internal/state/history_power_buckets.go | 15 +++++-- .../state/history_power_buckets_test.go | 40 +++++++++++++++++++ 3 files changed, 52 insertions(+), 5 deletions(-) diff --git a/.changeset/app-history-measured-power.md b/.changeset/app-history-measured-power.md index 720bd217c..af11336df 100644 --- a/.changeset/app-history-measured-power.md +++ b/.changeset/app-history-measured-power.md @@ -2,4 +2,4 @@ "ftw": patch --- -The app's history for solar, grid and battery now shows the measured power, the same as the box's own charts. Before, it came from the energy counters, which on a Sungrow move in 0.1 kWh steps, so each five minutes read 0 or 1.2 kW while the sun gave 0.4 kW. Home use is unchanged. Five minutes in which a flow went unmeasured for more than a tenth of the time is now a gap for that flow, not a lower value. +The app's history for solar, grid and battery now shows the measured power, the same as the box's own charts. Before, it came from the energy counters, which on a Sungrow move in 0.1 kWh steps, so each five minutes read 0 or 1.2 kW while the sun gave 0.4 kW. Home use is unchanged. Five minutes in which a flow went unmeasured for more than half the time is now a gap for that flow, not a lower value. diff --git a/go/internal/state/history_power_buckets.go b/go/internal/state/history_power_buckets.go index 7702a1fe5..2032b74b5 100644 --- a/go/internal/state/history_power_buckets.go +++ b/go/internal/state/history_power_buckets.go @@ -11,9 +11,9 @@ import ( // PowerBucket is the measured mean power over one fixed bucket, site-signed, // from the same stored rows /api/history draws. Each flow's mean is over the -// rows that measured it. Missing marks a flow left unmeasured for more than -// maxSourceDayUnknownShare of the bucket's rows, or for all of them: its mean -// is not a value then, as a source-era day's total is not. +// rows that measured it. Missing marks a flow left unmeasured in more than +// maxPowerBucketUnknownShare of the bucket's rows, or in all of them: its +// mean is not a value then. type PowerBucket struct { StartMS int64 GridW float64 @@ -68,7 +68,7 @@ func (s *Store) LoadPowerBuckets(ctx context.Context, fromMs, toMs, bucketMs int } b.StartMS = fromMs + index*bucketMs take := func(mean sql.NullFloat64, off int64, bit HistoryMissing) float64 { - if !mean.Valid || off*100 > total*maxSourceDayUnknownShare { + if !mean.Valid || off*100 > total*maxPowerBucketUnknownShare { b.Missing |= bit return 0 } @@ -82,6 +82,13 @@ func (s *Store) LoadPowerBuckets(ctx context.Context, fromMs, toMs, bucketMs int return out, rows.Err() } +// maxPowerBucketUnknownShare is the share of a bucket's rows, by weight, a +// flow may miss and still have a mean. Rows roll up after a day into minutes +// that carry any tick's flag, so one stale reading in five minutes grows +// from 3 % of the rows to 20 %. A majority rule keeps a closed bucket the +// same before and after; a tenth would turn it into a hole a day later. +const maxPowerBucketUnknownShare = 50 // percent + // halfOpenHistoryRange turns historyTierUnion's closed ranges into [from, to), // so a row on a bucket boundary belongs to one bucket only. func halfOpenHistoryRange(union string) string { diff --git a/go/internal/state/history_power_buckets_test.go b/go/internal/state/history_power_buckets_test.go index 4788f43d5..e46fac295 100644 --- a/go/internal/state/history_power_buckets_test.go +++ b/go/internal/state/history_power_buckets_test.go @@ -2,6 +2,8 @@ package state import ( "context" + "fmt" + "math" "path/filepath" "testing" "time" @@ -54,3 +56,41 @@ func TestLoadPowerBucketsLaysFixedBuckets(t *testing.T) { t.Fatal("an empty range must be refused") } } + +// One stale reading keeps its five minutes, and keeps them the same after +// the day-old ticks roll up into minutes that carry its flag. +func TestPowerBucketSurvivesTheMinuteRollup(t *testing.T) { + s := freshStore(t) + if err := s.EnableHistoryAggregation(); err != nil { + t.Fatal(err) + } + base := time.Now().UTC().Truncate(24 * time.Hour) + ms := base.UnixMilli() + const step = int64(300_000) + for i := int64(0); i < 150; i++ { + // As Core writes them: Load comes from the source accounting, so + // every tick is a partial row, and the roll-up merges the stale + // reading's flag into its whole minute. + p := HistoryPoint{TsMs: ms + i*2_000, PVW: -300, GridW: 100, Missing: MissingLoad} + if i == 40 { + p.PVW = 0 + p.Missing |= MissingPV + } + dashboardTick(t, s, fmt.Sprint(i), &p) + } + check := func(when string) { + t.Helper() + got, err := s.LoadPowerBuckets(context.Background(), ms, ms+step, step) + if err != nil { + t.Fatal(err) + } + if len(got) != 1 || got[0].Missing&MissingPV != 0 || math.Abs(got[0].PVW+300) > 1e-6 { + t.Fatalf("%s: %+v, want -300 W measured", when, got) + } + } + check("ten-second rows") + if err := s.maintainDashboard(context.Background(), base.Add(48*time.Hour)); err != nil { + t.Fatal(err) + } + check("minute rows") +}