diff --git a/.changeset/plan-from-band-edge.md b/.changeset/plan-from-band-edge.md new file mode 100644 index 000000000..ba0b9d32c --- /dev/null +++ b/.changeset/plan-from-band-edge.md @@ -0,0 +1,11 @@ +--- +"ftw": patch +--- + +A battery that sits below its lowest allowed charge, or above its highest, +gets a plan again. Core now gives Energyplan the nearest allowed charge, as it +already did for its own planner. With a car in the plan, Energyplan had kept +such a battery idle for a whole day, even when cheap night power made +charging pay. If Energyplan fails in that state, Core now plans from that +charge, where its own planner can model the site, instead of keeping an old +plan. diff --git a/go/internal/mpc/energyplan_fault_test.go b/go/internal/mpc/energyplan_fault_test.go index 7b341ec41..554e56f75 100644 --- a/go/internal/mpc/energyplan_fault_test.go +++ b/go/internal/mpc/energyplan_fault_test.go @@ -74,8 +74,8 @@ func TestNativeEnergyplanEVRecoveryFallbackFaults(t *testing.T) { var previousBytes []byte if scenario == "infeasible_keep_previous" { previous = svc.Replan(context.Background()) - if previous == nil || previous.Solver == nil || previous.Solver.Fallback || previous.InitialSoC != measuredSoC { - t.Fatalf("native baseline did not publish from measured low SoC: %+v", previous) + if previous == nil || previous.Solver == nil || previous.Solver.Fallback || previous.InitialSoC != svc.Defaults.SoCMin { + t.Fatalf("native baseline did not publish from the floor: %+v", previous) } svc.shadowWG.Wait() if err := ValidatePlan(svc.lastSlots, svc.lastParams, previous); err != nil { @@ -101,8 +101,9 @@ func TestNativeEnergyplanEVRecoveryFallbackFaults(t *testing.T) { if len(request.Storages) != 1 || len(request.FlexLoads) != 1 { t.Fatalf("fault did not exercise battery+EV: storages=%d flex=%d", len(request.Storages), len(request.FlexLoads)) } - if math.Abs(request.Storages[0].InitialEnergyWh-measuredSoC*svc.Defaults.CapacityWh) > 1e-9 { - t.Fatalf("worker request clamped measured initial energy: %+v", request.Storages[0]) + // A battery below its floor reaches the worker on the floor (#2043). + if math.Abs(request.Storages[0].InitialEnergyWh-request.Storages[0].MinEnergyWh) > 1e-9 { + t.Fatalf("worker request did not start on the floor: %+v", request.Storages[0]) } if scenario != "feasible" { if previous == nil { @@ -128,8 +129,8 @@ func TestNativeEnergyplanEVRecoveryFallbackFaults(t *testing.T) { if !strings.Contains(plan.Solver.FallbackReason, reason) { t.Fatalf("wrong fallback reason: %+v", plan.Solver) } - if plan.InitialSoC != measuredSoC || svc.lastParams.InitialSoC != measuredSoC || svc.lastParams.InitialSoC >= svc.lastParams.SoCMin { - t.Fatalf("fallback clamped recovery start: plan=%g params=%g floor=%g", plan.InitialSoC, svc.lastParams.InitialSoC, svc.lastParams.SoCMin) + if plan.InitialSoC != svc.lastParams.SoCMin || svc.lastParams.InitialSoCUnclamped != measuredSoC { + t.Fatalf("fallback start: plan=%g floor=%g real=%g", plan.InitialSoC, svc.lastParams.SoCMin, svc.lastParams.InitialSoCUnclamped) } if err := ValidatePlan(svc.lastSlots, svc.lastParams, plan); err != nil { t.Fatalf("published fallback failed physical replay: %v", err) diff --git a/go/internal/mpc/energyplan_test.go b/go/internal/mpc/energyplan_test.go index df5bfffa4..9651b57e8 100644 --- a/go/internal/mpc/energyplan_test.go +++ b/go/internal/mpc/energyplan_test.go @@ -169,7 +169,9 @@ func TestCoreDPShadowDoesNotAttachToNewerPlan(t *testing.T) { } } -func TestNativeEnergyplanRecoveryKeepsRealBatteryEnergy(t *testing.T) { +// A battery outside its band reaches Energyplan on the band edge, and the +// real reading is kept beside it (#2043). +func TestNativeEnergyplanPlansFromTheBandEdge(t *testing.T) { for _, initial := range []float64{0, .025, .975, 1} { t.Run(fmt.Sprint(initial), func(t *testing.T) { o := nativeWorker(t, 500*time.Millisecond) @@ -178,8 +180,10 @@ func TestNativeEnergyplanRecoveryKeepsRealBatteryEnergy(t *testing.T) { svc.Defaults.InitialSoC = initial svc.Optimizer = &EnergyplanOptimizer{ExternalOptimizer: o} plan := svc.Replan(context.Background()) - if plan == nil || plan.Solver.Fallback || plan.Solver.Backend != "value_curve_rust" || plan.InitialSoC != initial { - t.Fatalf("Energyplan must plan from real SoC without fallback: %+v", plan) + edge := math.Min(math.Max(initial, svc.Defaults.SoCMin), svc.Defaults.SoCMax) + if plan == nil || plan.Solver.Fallback || plan.Solver.Backend != "value_curve_rust" || plan.InitialSoC != edge || + svc.lastParams.InitialSoCUnclamped != initial { + t.Fatalf("Energyplan must plan from the band edge without fallback: %+v", plan) } if err := ValidatePlan(svc.lastSlots, svc.lastParams, plan); err != nil { t.Fatal(err) diff --git a/go/internal/mpc/import_hours_test.go b/go/internal/mpc/import_hours_test.go index bd6f00f13..e12fe52c5 100644 --- a/go/internal/mpc/import_hours_test.go +++ b/go/internal/mpc/import_hours_test.go @@ -429,10 +429,9 @@ func (ceilinglessOptimizer) Optimize(ctx context.Context, slots []Slot, p Params func (ceilinglessOptimizer) Close() error { return nil } -// A worker plan that overruns an hour falls back to Core's own plan. When -// Core cannot plan the site itself, here a battery below its floor, the -// worker's plan is published as before the hours, with a warning, rather -// than no plan at all. +// A worker plan that overruns an hour falls back to Core's own plan. A +// battery below its floor no longer stops Core from planning (#2043), so the +// plan stays inside the hour there too. func TestImportCeilingWorkerPlanOverrunsAnHour(t *testing.T) { for _, soc := range []float64{.5, .05} { t.Run(fmt.Sprintf("battery %.0f %%", soc*100), func(t *testing.T) { @@ -444,30 +443,25 @@ func TestImportCeilingWorkerPlanOverrunsAnHour(t *testing.T) { snap := svc.PlanSnapshot() got := planImportWh(*snap.Plan, start.UnixMilli(), start.Add(time.Hour).UnixMilli()) warned := strings.Contains(strings.Join(snap.Warnings, " "), "Core cannot plan this site itself") - if soc == .5 { - if !snap.Plan.Solver.Fallback || got > 4155 || warned { - t.Fatalf("solver %+v, 09:00 imports %.0f Wh, warned %v; want Core's plan inside the hour", snap.Plan.Solver, got, warned) - } - return - } - if snap.Plan.Solver.Fallback || got <= 4155 || !warned { - t.Fatalf("solver %+v, 09:00 imports %.0f Wh, warnings %q; want the worker's plan with a warning", snap.Plan.Solver, got, snap.Warnings) + if !snap.Plan.Solver.Fallback || got > 4155 || warned { + t.Fatalf("solver %+v, 09:00 imports %.0f Wh, warned %v; want Core's plan inside the hour", snap.Plan.Solver, got, warned) } }) } } -func TestNativeImportCeilingWhenCoreCannotPlan(t *testing.T) { +func TestNativeImportCeilingBelowTheFloor(t *testing.T) { worker := nativeWorker(t, 1500*time.Millisecond) t.Cleanup(func() { _ = worker.Close() }) - svc, _ := importCeilingFieldService(t, worker, true) + svc, start := importCeilingFieldService(t, worker, true) soc := .05 svc.Tele.Update("sungrow", telemetry.DerBattery, 0, &soc, nil) if svc.Replan(context.Background()) == nil { t.Fatalf("no plan published: %+v", svc.PlanSnapshot()) } - if w := strings.Join(svc.PlanSnapshot().Warnings, " "); !strings.Contains(w, "Core cannot plan this site itself") { - t.Fatalf("warnings %q", w) + snap := svc.PlanSnapshot() + if got := planImportWh(*snap.Plan, start.UnixMilli(), start.Add(time.Hour).UnixMilli()); got > 4155 { + t.Fatalf("09:00 imports %.0f Wh, warnings %q", got, snap.Warnings) } } diff --git a/go/internal/mpc/params_validation.go b/go/internal/mpc/params_validation.go index 3f99d75e6..cb587802f 100644 --- a/go/internal/mpc/params_validation.go +++ b/go/internal/mpc/params_validation.go @@ -73,11 +73,10 @@ func validateBatteryFleetMembers(fleet []BatteryFleetMember) error { return nil } -// planningParamsRequireRecovery marks states the external model represents -// directly, with an operating-band recovery ratchet, and the discrete Go DP -// does not: the DP snaps its initial SoC onto the operating grid, so solving -// from an out-of-band start plans from energy the site does not have (or -// discards energy it does have). +// planningParamsRequireRecovery marks a start outside the operating band. +// Replan clamps it onto the band edge for every planner: the discrete Go DP +// snaps its initial SoC onto the operating grid, and Energyplan 0.7.0 with a +// car kept such a battery idle for a whole horizon (#2043). func planningParamsRequireRecovery(p Params) bool { if p.CapacityWh == 0 && len(p.Storages) == 0 { return false @@ -94,8 +93,8 @@ func planningParamsRequireRecovery(p Params) bool { } // clampParamsIntoOperatingBand pulls a battery that has drifted outside -// soc_min…soc_max back onto the nearest band edge so the Core planner can plan -// at all, and records the real reading in InitialSoCUnclamped. It reports +// soc_min…soc_max back onto the nearest band edge so every planner can plan +// from it, and records the real reading in InitialSoCUnclamped. It reports // whether anything moved, and whether the state was recoverable. // // Why clamping beats refusing, which is what a reviewer will ask. The clamp @@ -105,9 +104,8 @@ func planningParamsRequireRecovery(p Params) bool { // the driver's own discharge floor, which exist because planner output is // never sent directly to hardware. Refusing leaves the site executing a stale // plan for hours and then falling back to live balancing, which is the worse -// failure. That was tolerable only while reaching this path required a missing -// optimizer; Core is the planner now. The field case is a Ferroamp driver -// floor at 0.10 with the pack settling at 0.09 overnight. +// failure. The field cases are a Ferroamp driver floor at 0.10 with the pack +// settling at 0.09 overnight, and a Pixii settling at 0.097 (#2043). // // Non-finite or physically impossible readings — SoC outside 0..1, storage // energy outside 0..capacity — are broken telemetry rather than a recoverable diff --git a/go/internal/mpc/params_validation_test.go b/go/internal/mpc/params_validation_test.go index 7ee03ecd5..5d069378c 100644 --- a/go/internal/mpc/params_validation_test.go +++ b/go/internal/mpc/params_validation_test.go @@ -424,10 +424,12 @@ func (*physicsGateCountingOptimizer) Close() error { return nil } type physicsGateRecoveryOptimizer struct { calls atomic.Int32 + got atomic.Pointer[Params] } func (o *physicsGateRecoveryOptimizer) Optimize(_ context.Context, slots []Slot, p Params) (Plan, error) { o.calls.Add(1) + o.got.Store(&p) plan := Plan{ GeneratedAtMs: time.Now().UnixMilli(), Mode: p.Mode, HorizonSlots: len(slots), CapacityWh: p.CapacityWh, @@ -681,119 +683,98 @@ func TestReplanRejectsInvalidPhysicsBeforeGoDP(t *testing.T) { } } -func TestReplanRecoveryUsesExternalPlannerWithoutDPDerivedResults(t *testing.T) { +// A battery below its floor reaches the worker on the band edge, as it +// reaches Core's own planner (#2043). Energyplan 0.7.0, given a start just +// under the floor and a car, kept the battery idle for the whole horizon. +func TestReplanGivesTheWorkerAnInBandStart(t *testing.T) { tests := []struct { name string setup func(*Service) }{ - {"aggregate recovery", func(svc *Service) { svc.Defaults.InitialSoC = 0.05 }}, - {"storage member recovery", func(svc *Service) { configurePhysicsGateFleet(svc, 0.05, 0.55) }}, + {"aggregate below the floor", func(svc *Service) { svc.Defaults.InitialSoC = 0.097 }}, + {"aggregate far below the floor", func(svc *Service) { svc.Defaults.InitialSoC = 0.01 }}, + {"storage member below the floor", func(svc *Service) { configurePhysicsGateFleet(svc, 0.05, 0.55) }}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - st, err := state.Open(filepath.Join(t.TempDir(), "state.db")) - if err != nil { - t.Fatal(err) - } - defer st.Close() - now := time.Now().UTC().Truncate(time.Minute) - if err := st.SavePrices([]state.PricePoint{{ - Zone: "SE3", SlotTsMs: now.Add(-5 * time.Minute).UnixMilli(), SlotLenMin: 60, - SpotOreKwh: 50, TotalOreKwh: 100, Source: "test", FetchedAtMs: now.UnixMilli(), - }}); err != nil { - t.Fatal(err) - } - - p := validPlanningParams() - p.Mode = ModeArbitrage + svc := recoveryTestService(t) optimizer := &physicsGateRecoveryOptimizer{} - svc := New(st, nil, "SE3", p) - svc.BaseLoad = 500 svc.Optimizer = optimizer tc.setup(svc) plan := svc.Replan(context.Background()) if plan == nil || plan.Solver == nil || plan.Solver.Backend != "recovery" { - t.Fatalf("external recovery plan = %+v", plan) + t.Fatalf("worker plan = %+v", plan) } if optimizer.calls.Load() != 1 { - t.Fatalf("external optimizer calls = %d, want 1", optimizer.calls.Load()) + t.Fatalf("worker calls = %d, want 1", optimizer.calls.Load()) } - if plan.DPEvaluationShadow != nil || plan.DPShadow != nil || plan.Baselines != nil { - t.Fatalf("DP-derived results must be absent during recovery: evaluation=%+v downside=%+v baselines=%+v", - plan.DPEvaluationShadow, plan.DPShadow, plan.Baselines) + got := optimizer.got.Load() + if planningParamsRequireRecovery(*got) || got.InitialSoC < got.SoCMin { + t.Fatalf("worker got an out-of-band start: soc %.3f, min %.3f, storages %+v", got.InitialSoC, got.SoCMin, got.Storages) + } + if got.InitialSoCUnclamped == 0 { + t.Fatal("the real reading was not recorded") } }) } } -func TestReplanRecoveryKeepsPreviousPlanWhenDPWouldBeRequired(t *testing.T) { +// A worker that fails while the battery is below its floor must not leave +// the site on an old plan: Core plans from the band edge instead. (Core's +// planner cannot hold two storages at any charge, so a fleet keeps its +// previous plan either way.) +func TestReplanFallsBackToCoreWhenTheWorkerFailsBelowTheFloor(t *testing.T) { tests := []struct { - name string - baseline PlanOptimizer - recovery PlanOptimizer - wantFailCalls int32 - setupRecovery func(*Service) + name string + setup func(*Service) }{ - // Only the external-champion path still refuses: its operating-band - // recovery ratchet is what the DP cannot represent, so a failed primary - // must not silently become a DP plan solved from a snapped SoC. With - // Core as the configured planner the same state is clamped and planned - // — see TestCoreChampionClampsOutOfBandSoC. - {name: "aggregate failed primary", baseline: &physicsGateCountingOptimizer{}, recovery: &physicsGateFailingOptimizer{}, wantFailCalls: 1, - setupRecovery: func(svc *Service) { svc.Defaults.InitialSoC = 0.05 }}, - {name: "storage member failed primary", baseline: &physicsGateCountingOptimizer{}, recovery: &physicsGateFailingOptimizer{}, wantFailCalls: 1, - setupRecovery: func(svc *Service) { configurePhysicsGateFleet(svc, 0.05, 0.55) }}, + {"just below the floor", func(svc *Service) { svc.Defaults.InitialSoC = 0.097 }}, + {"far below the floor", func(svc *Service) { svc.Defaults.InitialSoC = 0.01 }}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - st, err := state.Open(filepath.Join(t.TempDir(), "state.db")) - if err != nil { - t.Fatal(err) - } - defer st.Close() - now := time.Now().UTC().Truncate(time.Minute) - if err := st.SavePrices([]state.PricePoint{{ - Zone: "SE3", SlotTsMs: now.Add(-5 * time.Minute).UnixMilli(), SlotLenMin: 60, - SpotOreKwh: 50, TotalOreKwh: 100, Source: "test", FetchedAtMs: now.UnixMilli(), - }}); err != nil { - t.Fatal(err) - } - - p := validPlanningParams() - svc := New(st, nil, "SE3", p) - svc.BaseLoad = 500 - svc.Optimizer = tc.baseline - var idCalls, saveCalls atomic.Int32 - svc.decisionIDFactory = func() string { - idCalls.Add(1) - return "00000000-0000-4000-8000-000000000098" - } - svc.SaveDiag = func(*Diagnostic, string) error { - saveCalls.Add(1) - return nil - } + svc := recoveryTestService(t) + svc.Optimizer = &physicsGateCountingOptimizer{} accepted := svc.Replan(context.Background()) - if accepted == nil || accepted.DecisionID == "" { - t.Fatalf("baseline plan = %+v", accepted) + if accepted == nil { + t.Fatal("no baseline plan") } - - tc.setupRecovery(svc) - svc.Optimizer = tc.recovery + failing := &physicsGateFailingOptimizer{} + svc.Optimizer = failing + tc.setup(svc) got := svc.Replan(context.Background()) - if got != accepted || svc.Latest() != accepted { - t.Fatalf("recovery replaced prior plan through Go DP: got=%p accepted=%p latest=%p", - got, accepted, svc.Latest()) + if got == nil || got == accepted || svc.Latest() != got { + t.Fatalf("site kept the old plan: got=%p accepted=%p latest=%p", got, accepted, svc.Latest()) } - if idCalls.Load() != 1 || saveCalls.Load() != 1 { - t.Fatalf("calls after recovery rejection: id=%d save=%d, want 1/1", idCalls.Load(), saveCalls.Load()) + if got.Solver == nil || !got.Solver.Fallback || got.InitialSoC < svc.lastParams.SoCMin { + t.Fatalf("fallback plan = %+v from soc %.3f", got.Solver, got.InitialSoC) } - if failing, ok := tc.recovery.(*physicsGateFailingOptimizer); ok && failing.calls.Load() != tc.wantFailCalls { - t.Fatalf("failing optimizer calls = %d, want %d", failing.calls.Load(), tc.wantFailCalls) + if failing.calls.Load() != 1 { + t.Fatalf("failing worker calls = %d, want 1", failing.calls.Load()) } }) } } +func recoveryTestService(t *testing.T) *Service { + t.Helper() + st, err := state.Open(filepath.Join(t.TempDir(), "state.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { st.Close() }) + now := time.Now().UTC().Truncate(time.Minute) + if err := st.SavePrices([]state.PricePoint{{ + Zone: "SE3", SlotTsMs: now.Add(-5 * time.Minute).UnixMilli(), SlotLenMin: 60, + SpotOreKwh: 50, TotalOreKwh: 100, Source: "test", FetchedAtMs: now.UnixMilli(), + }}); err != nil { + t.Fatal(err) + } + svc := New(st, nil, "SE3", validPlanningParams()) + svc.BaseLoad = 500 + return svc +} + func TestReplanSnapshotsPVUncertaintyOnce(t *testing.T) { st, err := state.Open(filepath.Join(t.TempDir(), "state.db")) if err != nil { diff --git a/go/internal/mpc/service.go b/go/internal/mpc/service.go index d05429713..abef59fba 100644 --- a/go/internal/mpc/service.go +++ b/go/internal/mpc/service.go @@ -1957,11 +1957,14 @@ func (s *Service) runReplan(request replanRequest) *Plan { slog.Error("mpc: invalid optimization parameters; keeping previous plan", "err", err) return fail("inputs", err.Error()) } - recoveryRequired := planningParamsRequireRecovery(p) - if recoveryRequired && s.Optimizer == nil { - // Core is the planner, so this state has to produce a plan. Clamp onto - // the band edge and record the real reading; the argument for clamping - // over refusing is in clampParamsIntoOperatingBand. + if planningParamsRequireRecovery(p) { + // A battery outside its band still needs a plan, whichever planner + // runs. Clamp onto the band edge and record the real reading; the + // argument for clamping over refusing is in + // clampParamsIntoOperatingBand. The worker gets the clamped state too: + // Energyplan 0.7.0, given a start 0.1 Wh under the floor and a car, + // published an idle battery for the whole horizon (#2043), and a + // failed worker could not fall back to Core from an out-of-band start. clamped, ok := clampParamsIntoOperatingBand(&p) if !ok { slog.Error("mpc: battery state is not physically possible; keeping previous plan", @@ -1979,8 +1982,7 @@ func (s *Service) runReplan(request replanRequest) *Plan { "soc_max", p.SoCMax) } // The state is inside the band now, so this is an ordinary solve: - // baselines and shadows apply as usual. - recoveryRequired = false + // baselines, shadows and the Core fallback apply as usual. } slog.Info("mpc: optimize params", @@ -2085,7 +2087,7 @@ func (s *Service) runReplan(request replanRequest) *Plan { return s.canceledReplan(request, "primary-solve") } if err == nil { - if recoveryRequired || downsidePrimary || coreDPModelError(p) != nil { + if downsidePrimary || coreDPModelError(p) != nil { candidate.DPEvaluationShadow = nil candidate.DPShadow = nil candidate.Baselines = nil @@ -2138,7 +2140,7 @@ func (s *Service) runReplan(request replanRequest) *Plan { } plan = candidate - } else if overrun := (*planOverrun)(nil); errors.As(err, &overrun) && (recoveryRequired && !downsidePrimary || coreDPModelError(p) != nil) { + } else if overrun := (*planOverrun)(nil); errors.As(err, &overrun) && coreDPModelError(p) != nil { // Core cannot plan this site itself. The worker's plan keeps // every rule but the hours or the car's room. The live limit // still holds each hour, and the charger's room leaves battery @@ -2166,14 +2168,6 @@ func (s *Service) runReplan(request replanRequest) *Plan { if request.wasCanceledByService() { return s.canceledReplan(request, "primary-fallback") } - if recoveryRequired && !downsidePrimary { - slog.Error("mpc: primary optimizer failed and Go DP cannot model operating-bound recovery; keeping previous plan", - "err", err, - "soc_start", p.InitialSoC, - "soc_min", p.SoCMin, - "soc_max", p.SoCMax) - return fail("core_fallback", "Optimizer failed: "+err.Error()) - } if modelErr := coreDPModelError(p); modelErr != nil { slog.Error("mpc: primary failed and fallback cannot represent this site; keeping previous plan", "err", err, "fallback", modelErr) return fail("core_fallback", "Optimizer failed: "+err.Error()+"; fallback unavailable: "+modelErr.Error()) @@ -2262,7 +2256,7 @@ func (s *Service) runReplan(request replanRequest) *Plan { // self-consumption mode: the SC baseline is the plan itself, which // makes the badge trivially zero and distracts from the price // signal. For SC runs the UI still has the plan cost on its own. - if p.Mode != ModeSelfConsumption && !recoveryRequired && coreDPModelError(p) == nil && (plan.Solver == nil || (!plan.Solver.Fallback && plan.Solver.Backend != "ev_reserve")) { + if p.Mode != ModeSelfConsumption && coreDPModelError(p) == nil && (plan.Solver == nil || (!plan.Solver.Fallback && plan.Solver.Backend != "ev_reserve")) { bl := ComputeBaselines(slots, p) plan.Baselines = &bl }