From 30d1cb54885af3adc0ba9501e78bc1c8e2a958c7 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Sun, 15 Nov 2026 19:30:09 +0100 Subject: [PATCH 1/3] fix(control,mpc): a battery that may not cover the car makes it no room Under a binding import limit, battery discharge that only covers the house still let the car charge a watt more for each watt discharged. A field site on a 20 A fuse lost about two thirds of a night's discharge into the car this way. The car now gets the room the grid gives beside the house with the battery idle: in the Core DP, the reserve plan, ValidatePlan, the EV pulse check and the charger's fuse limit. A battery boost or battery_covers_ev still lets the battery help the car. Co-Authored-By: Claude Opus 5.5 --- .../battery-makes-no-room-for-the-car.md | 12 ++ .../control/ev_battery_cover_room_test.go | 42 ++++++ .../control/ev_battery_sequence_test.go | 3 +- go/internal/control/ev_fuse_budget.go | 44 +++++- go/internal/loadpoint/site_power.go | 15 ++ go/internal/loadpoint/site_power_test.go | 20 +++ .../mpc/battery_ev_import_limit_test.go | 134 ++++++++++++++++++ go/internal/mpc/ev_reserve.go | 14 +- go/internal/mpc/ev_reserve_test.go | 8 +- go/internal/mpc/external_optimizer.go | 6 + go/internal/mpc/import_hours.go | 17 +++ go/internal/mpc/mpc.go | 5 +- 12 files changed, 310 insertions(+), 10 deletions(-) create mode 100644 .changeset/battery-makes-no-room-for-the-car.md create mode 100644 go/internal/control/ev_battery_cover_room_test.go create mode 100644 go/internal/mpc/battery_ev_import_limit_test.go diff --git a/.changeset/battery-makes-no-room-for-the-car.md b/.changeset/battery-makes-no-room-for-the-car.md new file mode 100644 index 000000000..43f98c2a7 --- /dev/null +++ b/.changeset/battery-makes-no-room-for-the-car.md @@ -0,0 +1,12 @@ +--- +"ftw": patch +--- + +A home battery that may not cover the car no longer makes room for it under +the fuse or the import limit. Before, a plan could discharge the battery to +cover the house while the car charged against the fuse; the room that freed +went to the car, so battery energy charged the car although the battery +should cover only the house. The car now gets the room the grid gives beside +the house with the battery idle, in Core's planner, its reserve plan, the +check of every worker plan and the charger's fuse limit. A battery boost, or +the old site-wide battery cover, still lets the battery help the car. diff --git a/go/internal/control/ev_battery_cover_room_test.go b/go/internal/control/ev_battery_cover_room_test.go new file mode 100644 index 000000000..ddd6d5828 --- /dev/null +++ b/go/internal/control/ev_battery_cover_room_test.go @@ -0,0 +1,42 @@ +package control + +import ( + "fmt" + "testing" + "time" +) + +// A field night, 15 Nov 2026: the car charged against the fuse while the +// plan discharged the battery to cover the house. The meter showed the +// room the discharge made, and the car took it, so about two thirds of the +// battery's energy went into the car although the battery could cover only +// the house. A battery that may not cover the car leaves the car the room +// the grid gives with the battery idle. A battery that may cover it still +// lends it the room. +func TestPlannedDischargeIsRoomOnlyForACarTheBatteryMayCover(t *testing.T) { + const houseW, lineW = 10000.0, 16560.0 // 24 A on three phases + for _, covers := range []bool{false, true} { + t.Run(fmt.Sprintf("covers=%v", covers), func(t *testing.T) { + s := newEVBatterySite(t, houseW) + s.state.BatteryCoversEV = covers + start := s.now + discharge := SlotDirective{SlotStart: start, SlotEnd: start.Add(time.Hour), BatteryEnergyWh: -4000, Strategy: "arbitrage"} + s.state.SlotDirective = func(time.Time) (SlotDirective, bool) { return discharge, true } + s.run(10 * time.Minute) + t.Logf("offer %.0f W, battery %.0f W, grid %.0f W, highest grid %.0f W", s.offer(), s.batteryW, s.gridW(), s.maxGridW) + if s.batteryW > -3000 { + t.Fatalf("setup: the plan's discharge did not run: battery %.0f W", s.batteryW) + } + if s.maxGridW > lineW+1e-6 { + t.Fatalf("grid %.0f W over the %v W line", s.maxGridW, lineW) + } + gridRoomW := lineW - houseW + if !covers && s.offer() > gridRoomW { + t.Fatalf("the car took %.0f W, past the grid's %.0f W of room: the battery's discharge went into the car", s.offer(), gridRoomW) + } + if covers && s.offer() <= gridRoomW { + t.Fatalf("a battery that may cover the car left it at %.0f W, inside the grid's %.0f W of room", s.offer(), gridRoomW) + } + }) + } +} diff --git a/go/internal/control/ev_battery_sequence_test.go b/go/internal/control/ev_battery_sequence_test.go index 823538df4..19201f2ad 100644 --- a/go/internal/control/ev_battery_sequence_test.go +++ b/go/internal/control/ev_battery_sequence_test.go @@ -671,7 +671,8 @@ func TestReturningBatteryReliefCountsWholeAgain(t *testing.T) { } // Relief is only the discharge the fuse guard added: a cancelled charge or -// the planner's own discharge stays room for the car. +// the planner's own discharge stays out of it. Whether the planner's +// discharge is room for the car is evBatteryDischargeW's call. func TestFuseReliefIsOnlyAddedDischarge(t *testing.T) { s := &State{} s.recordFuseRelief( diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index c782d3819..8818d6365 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -996,8 +996,9 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea // show yet (in r). Between that level and the import limit the cap holds. // Battery discharge the fuse guard added ends once the site fits without // it, so it is no room: a car that took it would keep the battery - // feeding the car at the line. - if reliefW := s.evFuseReliefW(store); reliefW > 0 { + // feeding the car at the line. Where the battery may not cover the car, + // no discharge is room (evBatteryDischargeW). + if reliefW := s.evBatteryDischargeW(store); reliefW > 0 { r = s.evMeterRoom(meter, gridW, pool.phases, fuseMaxW, s.withBatteryOrders(s.pendingLoad(at), pending+reliefW)) } fuseRoom, importRoom := 0.0, 0.0 @@ -1045,11 +1046,48 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea // build on it. expireOfflineFuseRelief ends it evSettle after it went offline. func (s *State) evFuseReliefW(store *telemetry.Store) float64 { var w float64 + for _, relief := range s.evFuseReliefByDriver(store) { + w += relief + } + return w +} + +func (s *State) evFuseReliefByDriver(store *telemetry.Store) map[string]float64 { + out := make(map[string]float64, len(s.batteryFuseRelief)) for driver, relief := range s.batteryFuseRelief { if raw, _, ok := store.OnlineRawW(driver, telemetry.DerBattery); ok { relief = math.Min(relief, math.Max(0, -raw)) } - w += relief + out[driver] = relief + } + return out +} + +// evBatteryDischargeW is the battery discharge a car's room must not +// include. The fuse guard's relief always counts (evFuseReliefW). Where the +// battery may not cover the car, so does every discharge Core ordered, as +// far as a live reading shows it: the room a battery makes by covering the +// house would let the car charge faster on battery energy whenever the fuse +// or the import limit binds. A discharge Core did not order, such as one a +// battery holds across a restart, is the device's own and stays room, as +// before, until Core's next order replaces it. +func (s *State) evBatteryDischargeW(store *telemetry.Store) float64 { + if s.batteryMayCoverEV() { + return s.evFuseReliefW(store) + } + byDriver := s.evFuseReliefByDriver(store) + now := s.now() + for driver, log := range s.batteryCommands { + _, _, latest, sent := log.span(now) + raw, _, live := store.OnlineRawW(driver, telemetry.DerBattery) + if !sent || !live || latest >= 0 { + continue + } + byDriver[driver] = math.Max(byDriver[driver], math.Min(-latest, math.Max(0, -raw))) + } + var w float64 + for _, discharge := range byDriver { + w += discharge } return w } diff --git a/go/internal/loadpoint/site_power.go b/go/internal/loadpoint/site_power.go index 292ff1c9d..41e25902c 100644 --- a/go/internal/loadpoint/site_power.go +++ b/go/internal/loadpoint/site_power.go @@ -54,6 +54,21 @@ func BatteryDischargeFeedsEV(batteryW, evW, loadW, pvW float64) bool { return -batteryW > HouseResidualW(loadW, pvW)+SitePowerEpsW } +// BatteryDischargeFeedsEVUnderImport adds the site's import limit to +// BatteryDischargeFeedsEV. When the house and the car would not fit under +// maxImportW with the battery idle, the discharge is what lets the car +// charge that fast, so it puts battery energy into the car even while the +// house uses all of it. A maxImportW of 0 or less means no limit. +func BatteryDischargeFeedsEVUnderImport(batteryW, evW, loadW, pvW, maxImportW float64) bool { + if BatteryDischargeFeedsEV(batteryW, evW, loadW, pvW) { + return true + } + if evW <= 0 || batteryW >= 0 || maxImportW <= 0 { + return false + } + return GridW(loadW, pvW, 0, evW) > maxImportW+SitePowerEpsW +} + // PlannedSurplusForEVW is the near-term 3Φ-gate quantity: leftover PV // after house load, minus planned PV-soak battery charge. gridW is the // grid flow attributed to house+battery (planned GridW minus EV). diff --git a/go/internal/loadpoint/site_power_test.go b/go/internal/loadpoint/site_power_test.go index 040299bc0..a5b5c32b3 100644 --- a/go/internal/loadpoint/site_power_test.go +++ b/go/internal/loadpoint/site_power_test.go @@ -56,6 +56,26 @@ func TestBatteryDischargeFeedsEV(t *testing.T) { } } +func TestBatteryDischargeFeedsEVUnderImport(t *testing.T) { + for _, tc := range []struct { + name string + battery, ev, load, limit float64 + want bool + }{ + {"past the house", -4000, 4000, 500, 0, true}, + {"house cover, no limit", -3000, 8280, 3800, 0, false}, + {"house cover makes the car's room", -3000, 8280, 3800, 9250, true}, + {"car fits the grid alone", -3000, 5450, 3800, 9250, false}, + {"within the meter's noise", -3000, 5500, 3800, 9250, false}, + {"battery charging", 500, 8280, 3800, 9250, false}, + {"car idle", -3000, 0, 3800, 9250, false}, + } { + if got := BatteryDischargeFeedsEVUnderImport(tc.battery, tc.ev, tc.load, 0, tc.limit); got != tc.want { + t.Errorf("%s: got %v, want %v", tc.name, got, tc.want) + } + } +} + func TestEffectivePVWActiveZeroIsTrueCap(t *testing.T) { if got := EffectivePVW(-5000, 0, false); got != -5000 { t.Errorf("inactive = %.0f, want -5000", got) diff --git a/go/internal/mpc/battery_ev_import_limit_test.go b/go/internal/mpc/battery_ev_import_limit_test.go new file mode 100644 index 000000000..f900ed418 --- /dev/null +++ b/go/internal/mpc/battery_ev_import_limit_test.go @@ -0,0 +1,134 @@ +package mpc + +import ( + "testing" + + "github.com/srcfl/ftw/go/internal/loadpoint" +) + +// A field night, 15 Nov 2026: a 20 A fuse with 10 A of house load on one +// phase left the site 9,250 W of import. The house drew 3,800 W, the car had +// a goal it could not reach by morning, and the plan discharged the battery +// to cover the house. The grid room that freed went to the car. Every slot +// met the conservation rule, yet the battery charged the car. A battery +// that may not cover the car leaves it only the room the grid gives with +// the battery idle. +// +// The field plan came from the worker. Here the price makes the car's +// missed goal (four times the mean price) worth more than the battery's +// stored energy, so the Core DP would take the same room. +const fuseNightImportW = 9250 + +func fuseNightSlots() []Slot { + slots := make([]Slot, 8) + for i := range slots { + slots[i] = Slot{StartMs: 1_794_700_800_000 + int64(i)*60*60*1000, LenMin: 60, PriceOre: 100, SpotOre: 80, + LoadW: 3800, Limits: PowerLimits{MaxImportW: fuseNightImportW}} + } + return slots +} + +func fuseNightParams(mode Mode, noBatteryToEV bool) Params { + return Params{ + Mode: mode, SoCLevels: 41, ActionLevels: 41, + CapacityWh: 20000, SoCMin: .1, SoCMax: .95, InitialSoC: .6, + MaxChargeW: 10000, MaxDischargeW: 10000, + ChargeEfficiency: .95, DischargeEfficiency: .95, TerminalSoCPrice: 125, + Loadpoint: &LoadpointSpec{ + ID: "car", CapacityWh: 84000, Levels: 85, SoCMin: 0, SoCMax: 1, + InitialSoC: .3, PluggedIn: true, TargetSoC: 1, TargetSlotIdx: 7, + MinChargeW: 4140, MaxChargeW: 11040, ChargeEfficiency: .9, + AllowedStepsW: []float64{0, 4140, 4830, 5520, 6210, 6900, 7590, 8280, 8970, 9660, 10350, 11040}, + NoBatteryToEV: noBatteryToEV, + }, + } +} + +func TestBatteryThatMayNotCoverTheCarLeavesItTheGridsRoomAlone(t *testing.T) { + for _, mode := range []Mode{ModeArbitrage, ModePassiveArbitrage} { + t.Run(string(mode), func(t *testing.T) { + slots := fuseNightSlots() + plan := Optimize(slots, fuseNightParams(mode, true)) + for i, a := range plan.Actions { + t.Logf("slot %d: battery %.0f W car %.0f W grid %.0f W", i, a.BatteryW, a.LoadpointW, a.GridW) + if a.LoadpointW > 0 && a.BatteryW < -50 && slots[i].LoadW+a.LoadpointW > fuseNightImportW+loadpoint.SitePowerEpsW { + t.Errorf("slot %d: battery %.0f W makes the room for a %.0f W car beside a %.0f W house under %d W", + i, a.BatteryW, a.LoadpointW, slots[i].LoadW, fuseNightImportW) + } + } + }) + } +} + +// With the battery allowed to cover the car, the same night may use it. +func TestBatteryThatMayCoverTheCarStillHelpsItUnderTheLimit(t *testing.T) { + slots := fuseNightSlots() + plan := Optimize(slots, fuseNightParams(ModeArbitrage, false)) + helped := false + for i, a := range plan.Actions { + if a.LoadpointW > 0 && a.BatteryW < -50 && slots[i].LoadW+a.LoadpointW > fuseNightImportW { + helped = true + } + } + if !helped { + t.Fatal("a battery that may cover the car never helped it past the grid's room") + } +} + +func TestValidatePlanRejectsBatteryMakingRoomForTheCar(t *testing.T) { + slots := []Slot{{StartMs: 1, LenMin: 60, PriceOre: 15, SpotOre: 15, LoadW: 3800, + Limits: PowerLimits{MaxImportW: fuseNightImportW}}} + p := fuseNightParams(ModeArbitrage, true) + p.InitialSoC = .5 + p.Loadpoint.TargetSlotIdx = 0 + // Battery 3,000 W to the house, the car 8,280 W: grid 9,080 W fits the + // limit, and the house uses all the battery gives. With the battery idle + // the car could have had only 5,450 W. + evSoC := .3 + 8280*.9/84000 + plan := Plan{Mode: p.Mode, HorizonSlots: 1, CapacityWh: p.CapacityWh, InitialSoC: p.InitialSoC, Actions: []Action{{ + SlotStartMs: 1, SlotLenMin: 60, LoadW: 3800, PriceOre: 15, SpotOre: 15, + BatteryW: -3000, GridW: 9080, SoC: .5 - 3000/.95/20000, + LoadpointW: 8280, LoadpointSoC: evSoC, + }}} + plan.Actions[0].CostOre = reserveSlotCost(slots[0], p, plan.Actions[0]) + plan.TotalCostOre = plan.Actions[0].CostOre + if err := ValidatePlan(slots, p, &plan); err == nil { + t.Fatal("ValidatePlan accepted a battery making grid room for the car") + } + // The same plan with the battery allowed to cover the car stands. + p.Loadpoint.NoBatteryToEV = false + if err := ValidatePlan(slots, p, &plan); err != nil { + t.Fatalf("ValidatePlan rejected a battery that may cover the car: %v", err) + } +} + +// A battery that may cover the car still covers the 500 W house so the +// 11 kW car fits an 11,040 W limit. +func TestReservePlanLetsACoveredCarUseTheBatteryRoom(t *testing.T) { + slots, p := nearTargetReserveFixture() + for i := range slots { + slots[i].Limits.MaxImportW = 11040 + } + p.Loadpoint.NoBatteryToEV = false + plan := mustCoreReservePlan(t, slots, p) + if err := ValidatePlan(slots, p, &plan); err != nil { + t.Fatal(err) + } + if a := plan.Actions[0]; a.LoadpointMaxPowerW["easee"] != 11000 || a.BatteryW >= 0 { + t.Fatalf("covered car lost the battery's room: pulse %.0f W, battery %.0f W", a.LoadpointMaxPowerW["easee"], a.BatteryW) + } +} + +func TestReservePlanKeepsTheBatteryOutOfTheCarsRoom(t *testing.T) { + slots := fuseNightSlots() + plan, err := coreReservePlan(t.Context(), slots, fuseNightParams(ModeArbitrage, true)) + if err != nil { + t.Fatal(err) + } + for i, a := range plan.Actions { + peak := a.LoadpointMaxPowerW["car"] + if peak > 0 && a.BatteryW < -50 && slots[i].LoadW+peak > fuseNightImportW+loadpoint.SitePowerEpsW { + t.Errorf("slot %d: battery %.0f W makes the room for a %.0f W car pulse", i, a.BatteryW, peak) + } + } +} diff --git a/go/internal/mpc/ev_reserve.go b/go/internal/mpc/ev_reserve.go index e9c66cd0e..de48a3a44 100644 --- a/go/internal/mpc/ev_reserve.go +++ b/go/internal/mpc/ev_reserve.go @@ -73,6 +73,11 @@ func coreReservePlan(ctx context.Context, slots []Slot, p Params) (Plan, error) low, high = max(low, minBatteryW), min(high, maxBatteryW) if peak > 0 && lp != nil && lp.blocksBatteryToEV() { low = max(low, -max(0, house)) + // A pulse the grid cannot carry beside the house with the + // battery idle would charge on the battery's room. + if slot.Limits.MaxImportW > 0 && house+peak > slot.Limits.MaxImportW+loadpoint.SitePowerEpsW { + low = max(low, 0) + } } if low > high+1e-7 { return 0, false @@ -103,9 +108,10 @@ func coreReservePlan(ctx context.Context, slots []Slot, p Params) (Plan, error) continue } want := min(step, need/(eff*hours)) - if evAverageRoomW(capW, house+b, step) < want { - // The hour's import holds the car back: the battery - // covers the house to make room, never into export. + if evAverageRoomW(capW, house+b, step) < want && !lp.blocksBatteryToEV() { + // The hour's import holds the car back: a battery that + // may cover the car covers the house to make room, never + // into export. if covered, ok := chooseBattery(step, max(-max(0, house), capW-house-want)); ok { b = covered } @@ -297,7 +303,7 @@ func validateEVPulse(slot Slot, p Params, a Action, pvW float64, vehicleRules bo if lp.SurplusOnly { solarPeak += peak } - if vehicleRules && peak > 0 && lp.blocksBatteryToEV() && loadpoint.BatteryDischargeFeedsEV(a.BatteryW, peak, slot.LoadW, pvW) { + if vehicleRules && peak > 0 && lp.blocksBatteryToEV() && loadpoint.BatteryDischargeFeedsEVUnderImport(a.BatteryW, peak, slot.LoadW, pvW, slot.Limits.MaxImportW) { return fmt.Errorf("battery discharge feeds EV pulse") } } diff --git a/go/internal/mpc/ev_reserve_test.go b/go/internal/mpc/ev_reserve_test.go index e97277644..545dda45f 100644 --- a/go/internal/mpc/ev_reserve_test.go +++ b/go/internal/mpc/ev_reserve_test.go @@ -21,8 +21,11 @@ func nearTargetReserveFixture() ([]Slot, Params) { p.Loadpoint = &LoadpointSpec{ID: "easee", CapacityWh: 75000, InitialSoC: .7721774800618489, SoCMin: 0, SoCMax: .8, Levels: 11, PluggedIn: true, TargetSoC: .8, TargetSlotIdx: 11, MaxChargeW: 11000, ChargeEfficiency: .9, NoBatteryToEV: true} slots := make([]Slot, 193) start := time.Now().UTC().Truncate(15 * time.Minute) + // The house and the 11 kW car fit the import limit with the battery + // idle: a battery that may not cover the car makes it no room + // (TestReservePlanKeepsTheBatteryOutOfTheCarsRoom). for i := range slots { - slots[i] = Slot{StartMs: start.Add(time.Duration(i) * 15 * time.Minute).UnixMilli(), LenMin: 15, PriceOre: 100, SpotOre: 10, LoadW: 500, Limits: PowerLimits{MaxImportW: 11040, MaxExportW: 11040}} + slots[i] = Slot{StartMs: start.Add(time.Duration(i) * 15 * time.Minute).UnixMilli(), LenMin: 15, PriceOre: 100, SpotOre: 10, LoadW: 500, Limits: PowerLimits{MaxImportW: 11600, MaxExportW: 11040}} } return slots, p } @@ -125,6 +128,9 @@ func TestValidateEVPulseRejectsUnsafeOnPowerDespiteLegalAverage(t *testing.T) { func TestEVReserveUsesMinimumStepWhenHouseBlocksMaximum(t *testing.T) { slots, p := nearTargetReserveFixture() + for i := range slots { + slots[i].Limits.MaxImportW = 11040 // The 500 W house leaves the 11 kW car no room. + } p.Loadpoint.MinChargeW = 4140 p.InitialSoC = p.SoCMin plan := mustCoreReservePlan(t, slots, p) diff --git a/go/internal/mpc/external_optimizer.go b/go/internal/mpc/external_optimizer.go index 80489e278..bb4b9a37e 100644 --- a/go/internal/mpc/external_optimizer.go +++ b/go/internal/mpc/external_optimizer.go @@ -671,6 +671,12 @@ func validatePlan(slots []Slot, p Params, plan *Plan, vehicleRules bool) error { if vehicleRules && lp.blocksBatteryToEV() && loadpoint.BatteryDischargeFeedsEV(a.BatteryW, powerW, slot.LoadW, effectivePVW) { return fmt.Errorf("slot %d battery discharge feeds loadpoint %s", i, lp.ID) } + // The cars together must fit the import limit beside the house + // with the battery idle, or the discharge made their room. + if vehicleRules && lp.blocksBatteryToEV() && powerW > solverZeroPowerToleranceW && + loadpoint.BatteryDischargeFeedsEVUnderImport(a.BatteryW, totalLoadpointW, slot.LoadW, effectivePVW, slot.Limits.MaxImportW) { + return fmt.Errorf("slot %d battery discharge makes the import room for loadpoint %s", i, lp.ID) + } } if surplusOnlyExceedsHousePV(totalSurplusOnlyW, slot.LoadW, effectivePVW) { return fmt.Errorf("slot %d surplus-only EVs exceed shared leftover PV", i) diff --git a/go/internal/mpc/import_hours.go b/go/internal/mpc/import_hours.go index dfc502db1..2f176f599 100644 --- a/go/internal/mpc/import_hours.go +++ b/go/internal/mpc/import_hours.go @@ -119,6 +119,23 @@ func importHourCapsW(slots []Slot, p Params) (caps, carCaps []float64) { return caps, carCaps } +// carImportLimitW is the import a charging car shares with the house in slot +// t: the slot's limit and the hour's caps, whichever is lowest. 0 means no +// limit, as in PowerLimits. A cap with no room for a car stops it elsewhere. +func carImportLimitW(slot Slot, caps, carCaps []float64, t int) float64 { + limit := math.Inf(1) + if slot.Limits.MaxImportW > 0 { + limit = slot.Limits.MaxImportW + } + if caps != nil { + limit = min(limit, caps[t], carCaps[t]) + } + if math.IsInf(limit, 1) || limit <= 0 { + return 0 + } + return limit +} + // evAverageRoomW is the most mean EV power a slot holds under capW of mean // import, with baseW the rest of its grid flow and the car pulsing at // peakW. A pulse imports while it runs even when the slot exports between. diff --git a/go/internal/mpc/mpc.go b/go/internal/mpc/mpc.go index 8118f6f0c..bbbd067e3 100644 --- a/go/internal/mpc/mpc.go +++ b/go/internal/mpc/mpc.go @@ -862,7 +862,10 @@ func OptimizeContext(ctx context.Context, slots []Slot, p Params) (Plan, error) // conservation check as ValidatePlan and the runtime // clamp in control/dispatch.go (search CANONICAL // "battery may not feed EV"): loadpoint.BatteryDischargeFeedsEV. - if evActive && lp.blocksBatteryToEV() && loadpoint.BatteryDischargeFeedsEV(battW, evW, slot.LoadW, slot.PVW) { + // Under an import limit the car must also fit beside the + // house with the battery idle, as the runtime room does + // (control.evBatteryDischargeW). + if evActive && lp.blocksBatteryToEV() && loadpoint.BatteryDischargeFeedsEVUnderImport(battW, evW, slot.LoadW, slot.PVW, carImportLimitW(slot, importCaps, carImportCaps, t)) { continue } From f08ba17ed1ff790ee470f6bbaee283e2f2cceb80 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Sun, 15 Nov 2026 19:38:10 +0100 Subject: [PATCH 2/3] docs(contract): no_storage_to_load makes the car no import room Co-Authored-By: Claude Opus 5.5 --- docs/energyplan-contract.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/energyplan-contract.md b/docs/energyplan-contract.md index 4b56584b0..3451019b3 100644 --- a/docs/energyplan-contract.md +++ b/docs/energyplan-contract.md @@ -167,6 +167,13 @@ not establish the greatest reachable energy or the cheapest plan. slot's end is not sent. Validation must cover joint on/off pulse states, grid limits, surplus-only charging, battery-to-EV rules and the corresponding costs. +`no_storage_to_load` means storage may cover the house but never the car, +also not by making its room. While such a car is on, battery discharge may +not exceed `max(0, load_w + pv_w)`, and in a slot with `max_import_w` the +house and the on-steps of all charging cars must fit that limit with the +battery idle whenever the battery discharges. `surplus_only` keeps the same +rules. + For example, 1,000 Wh at efficiency 1 over a remaining 15 minutes requires 4,000 W mean. With steps `[0, 6000]`, the on-step is 6,000 W for ten minutes. A 5,000 W available import margin cannot admit that pulse merely because the From 1b8f9fd5f5089e32b1f31cc7ac9f44c547269caa Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Mon, 16 Nov 2026 09:43:16 +0100 Subject: [PATCH 3/3] fix(control): a boosted car may start on the battery's room The live boost watts that let the battery cover a car stay zero until the car draws, so the fuse limit removed Core's ordered discharge from the room of a boosted car that had not started. With the house near the line, that car never started. An active lease on a plugged-in loadpoint now counts from the start (BatteryBoostActive, HasActiveBatteryBoost). Found by the Codex review on #2023. Co-Authored-By: Claude Opus 5.5 --- .../battery-makes-no-room-for-the-car.md | 3 +- go/cmd/ftw/main.go | 2 ++ go/internal/control/dispatch.go | 5 +++ .../control/ev_battery_cover_room_test.go | 31 +++++++++++++++++ go/internal/control/ev_fuse_budget.go | 6 ++-- go/internal/loadpoint/battery_boost.go | 21 ++++++++++-- go/internal/loadpoint/battery_boost_test.go | 34 +++++++++++++++++++ 7 files changed, 97 insertions(+), 5 deletions(-) diff --git a/.changeset/battery-makes-no-room-for-the-car.md b/.changeset/battery-makes-no-room-for-the-car.md index 43f98c2a7..518ea86b6 100644 --- a/.changeset/battery-makes-no-room-for-the-car.md +++ b/.changeset/battery-makes-no-room-for-the-car.md @@ -9,4 +9,5 @@ went to the car, so battery energy charged the car although the battery should cover only the house. The car now gets the room the grid gives beside the house with the battery idle, in Core's planner, its reserve plan, the check of every worker plan and the charger's fuse limit. A battery boost, or -the old site-wide battery cover, still lets the battery help the car. +the old site-wide battery cover, still lets the battery help the car; a +boosted car may also start on the battery's room before it draws. diff --git a/go/cmd/ftw/main.go b/go/cmd/ftw/main.go index e5bef56c7..880df41ee 100644 --- a/go/cmd/ftw/main.go +++ b/go/cmd/ftw/main.go @@ -3233,6 +3233,7 @@ func main() { // resume charging. evCurtailHeadroomW := loadpoint.SurplusPotentialW(lpStatesSnapshot) boostEVW, boostReserveSoC := activeBatteryBoostTotals(lpController, lpStatesSnapshot, tickNow) + boostActive := lpController != nil && lpController.HasActiveBatteryBoost(lpStatesSnapshot, tickNow) var evFuseDemands []loadpoint.FuseDemand if lpController != nil { evFuseDemands = lpController.FuseDemands() @@ -3248,6 +3249,7 @@ func main() { ctrl.EVCurtailHeadroomW = evCurtailHeadroomW ctrl.BatteryBoostEVChargingW = boostEVW ctrl.BatteryBoostReserveSoC = boostReserveSoC + ctrl.BatteryBoostActive = boostActive ctrl.SetEVCommanded(lpStatesSnapshot) ctrl.SetEVFuseDemands(evFuseDemands) fuseMaxW = ctrl.SiteFuseAmps * ctrl.SiteFuseVoltage * float64(ctrl.SiteFusePhases) diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 88843fda2..83a2412e0 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -404,6 +404,11 @@ type State struct { // main.go refreshes both from loadpoint.Controller every dispatch tick. BatteryBoostEVChargingW float64 BatteryBoostReserveSoC float64 + // BatteryBoostActive reports a valid lease on a plugged-in loadpoint + // that is not surplus-only, whether or not its car draws yet. The room + // a battery makes counts for the car from the start + // (evBatteryDischargeW): the lease's draw is zero until the car starts. + BatteryBoostActive bool // EVCommandedW is the frozen sum of final charger offers from this tick. // It reserves site capacity before optional battery charging, even before // an EV ramps up and in modes without an accepted optimizer plan. diff --git a/go/internal/control/ev_battery_cover_room_test.go b/go/internal/control/ev_battery_cover_room_test.go index ddd6d5828..ff65309d1 100644 --- a/go/internal/control/ev_battery_cover_room_test.go +++ b/go/internal/control/ev_battery_cover_room_test.go @@ -40,3 +40,34 @@ func TestPlannedDischargeIsRoomOnlyForACarTheBatteryMayCover(t *testing.T) { }) } } + +// A boost lets the battery help the car, so the room its discharge makes is +// the car's from the start. The lease's live draw is zero until the car +// starts, so the lease itself counts: with the house near the line and the +// battery covering it, a boosted car that waited for its own draw would +// never start. Without a boost the car waits for the grid's own room. +func TestABoostedCarStartsOnTheBatterysRoom(t *testing.T) { + const houseW, lineW, minW = 13000.0, 16560.0, 4140.0 // grid room 3,560 W + for _, boosted := range []bool{false, true} { + t.Run(fmt.Sprintf("boosted=%v", boosted), func(t *testing.T) { + s := newEVBatterySite(t, houseW) + s.state.BatteryBoostActive = boosted + discharge := SlotDirective{SlotStart: s.now, SlotEnd: s.now.Add(time.Hour), BatteryEnergyWh: -4000, Strategy: "arbitrage"} + s.state.SlotDirective = func(time.Time) (SlotDirective, bool) { return discharge, true } + s.run(10 * time.Minute) + t.Logf("offer %.0f W, battery %.0f W, grid %.0f W, highest grid %.0f W", s.offer(), s.batteryW, s.gridW(), s.maxGridW) + if s.batteryW > -3000 { + t.Fatalf("setup: the plan's discharge did not run: battery %.0f W", s.batteryW) + } + if s.maxGridW > lineW+1e-6 { + t.Fatalf("grid %.0f W over the %v W line", s.maxGridW, lineW) + } + if boosted && s.offer() < minW { + t.Fatalf("a boosted car stayed at %.0f W beside %.0f W of battery discharge", s.offer(), -s.batteryW) + } + if !boosted && s.offer() > 0 { + t.Fatalf("the car started at %.0f W on the battery's room, with %.0f W of grid room", s.offer(), lineW-houseW) + } + }) + } +} diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index 8818d6365..85da24dcd 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -1070,9 +1070,11 @@ func (s *State) evFuseReliefByDriver(store *telemetry.Store) map[string]float64 // house would let the car charge faster on battery energy whenever the fuse // or the import limit binds. A discharge Core did not order, such as one a // battery holds across a restart, is the device's own and stays room, as -// before, until Core's next order replaces it. +// before, until Core's next order replaces it. An active boost lease lets +// the battery cover the car before its car draws, so a boosted car can +// start on that room. func (s *State) evBatteryDischargeW(store *telemetry.Store) float64 { - if s.batteryMayCoverEV() { + if s.batteryMayCoverEV() || s.BatteryBoostActive { return s.evFuseReliefW(store) } byDriver := s.evFuseReliefByDriver(store) diff --git a/go/internal/loadpoint/battery_boost.go b/go/internal/loadpoint/battery_boost.go index 40a2e2926..3f3400601 100644 --- a/go/internal/loadpoint/battery_boost.go +++ b/go/internal/loadpoint/battery_boost.go @@ -377,8 +377,8 @@ func (c *Controller) evaluateBatteryBoost(id string, now time.Time, connected, d // loadpoint snapshot from the current tick. func (c *Controller) ActiveBatteryBoostTotals(states []State, now time.Time) (powerW, reserveSoC float64) { for _, st := range states { - lease, status := c.BatteryBoost(st.ID, now) - if !status.Active || !st.PluggedIn || st.SurplusOnly { + lease, ok := c.servedBatteryBoost(st, now) + if !ok { continue } if st.CurrentPowerW > 0 { @@ -390,3 +390,20 @@ func (c *Controller) ActiveBatteryBoostTotals(states []State, now time.Time) (po } return powerW, reserveSoC } + +// HasActiveBatteryBoost reports whether a loadpoint in the snapshot has a +// lease ActiveBatteryBoostTotals would serve, whether or not its car draws +// yet: the lease's live watts stay zero until the car starts. +func (c *Controller) HasActiveBatteryBoost(states []State, now time.Time) bool { + for _, st := range states { + if _, ok := c.servedBatteryBoost(st, now); ok { + return true + } + } + return false +} + +func (c *Controller) servedBatteryBoost(st State, now time.Time) (BatteryBoostLease, bool) { + lease, status := c.BatteryBoost(st.ID, now) + return lease, status.Active && st.PluggedIn && !st.SurplusOnly +} diff --git a/go/internal/loadpoint/battery_boost_test.go b/go/internal/loadpoint/battery_boost_test.go index f28d886c9..a68ae379c 100644 --- a/go/internal/loadpoint/battery_boost_test.go +++ b/go/internal/loadpoint/battery_boost_test.go @@ -321,3 +321,37 @@ func TestBatteryBoostLeaseJSONRoundTripIsFraction(t *testing.T) { t.Fatalf("1.02 overflow = %v, want 1 (not 0.0102)", overflow.MinBatterySoC) } } + +// A lease counts before its car draws: the totals' live watts stay zero +// until the car starts, and Core must still let the battery make it room. +func TestHasActiveBatteryBoostBeforeTheCarDraws(t *testing.T) { + mgr := NewManager() + mgr.Load([]Config{{ID: "garage", DriverName: "garage"}, {ID: "street", DriverName: "street"}}) + mgr.Observe("garage", true, 0, 0, true) + mgr.Observe("street", true, 0, 0, true) + ctrl := NewController(mgr, nil, nil, nil) + now := time.Now() + if ctrl.HasActiveBatteryBoost(mgr.States(), now) { + t.Fatal("active without a lease") + } + if _, err := ctrl.EnableBatteryBoost("street", validBatteryBoost(now), now); err != nil { + t.Fatal(err) + } + mgr.Observe("street", false, 0, 0, true) + if ctrl.HasActiveBatteryBoost(mgr.States(), now) { + t.Fatal("active for a lease on a loadpoint with no car plugged in") + } + if _, err := ctrl.EnableBatteryBoost("garage", validBatteryBoost(now), now); err != nil { + t.Fatal(err) + } + if !ctrl.HasActiveBatteryBoost(mgr.States(), now) { + t.Fatal("not active for a lease on a plugged-in car that does not draw yet") + } + if power, _ := ctrl.ActiveBatteryBoostTotals(mgr.States(), now); power != 0 { + t.Fatalf("live boost watts = %.0f, want 0 before the car draws", power) + } + var none *Controller + if none.HasActiveBatteryBoost(mgr.States(), now) { + t.Fatal("a nil controller reports an active boost") + } +}