Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/plan-from-band-edge.md
Original file line number Diff line number Diff line change
@@ -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.
13 changes: 7 additions & 6 deletions go/internal/mpc/energyplan_fault_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 {
Expand All @@ -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)
Expand Down
10 changes: 7 additions & 3 deletions go/internal/mpc/energyplan_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
26 changes: 10 additions & 16 deletions go/internal/mpc/import_hours_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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)
}
}

Expand Down
18 changes: 8 additions & 10 deletions go/internal/mpc/params_validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
137 changes: 59 additions & 78 deletions go/internal/mpc/params_validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading