diff --git a/.changeset/app-history-measured-power.md b/.changeset/app-history-measured-power.md new file mode 100644 index 000000000..af11336df --- /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. 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/cmd/ftw/app_history_power_test.go b/go/cmd/ftw/app_history_power_test.go new file mode 100644 index 000000000..875cc3bcb --- /dev/null +++ b/go/cmd/ftw/app_history_power_test.go @@ -0,0 +1,123 @@ +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.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() + 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", "battery_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) + } + } + // 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 89aeba800..2b9e58206 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,31 +305,65 @@ 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}}, - } - - 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 + "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 }}, + } + + 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 // 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/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 new file mode 100644 index 000000000..2032b74b5 --- /dev/null +++ b/go/internal/state/history_power_buckets.go @@ -0,0 +1,97 @@ +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. Each flow's mean is over the +// 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 + 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() + // 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(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 { + return nil, err + } + defer rows.Close() + var out []PowerBucket + for rows.Next() { + var b PowerBucket + 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*maxPowerBucketUnknownShare { + 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() +} + +// 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 { + 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..e46fac295 --- /dev/null +++ b/go/internal/state/history_power_buckets_test.go @@ -0,0 +1,96 @@ +package state + +import ( + "context" + "fmt" + "math" + "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}, + {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) + } + } + 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") + } +} + +// 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") +} 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