From 8ad6aaa4436abda7eddfb919f12eff2475ff120b Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 14:11:56 +0100 Subject: [PATCH 01/68] fix(control): one log of FTW's own EV offers The battery side read a 20 s pool log of EV offers (State.evOffers), while the EV fuse limit keeps each charger's offers for its declared response time, or 180 s when it declares none. After 20 s the battery counted a slow charger's unshown raise as already in the meter and charged into that room; when the car started, a 25 A site read 32.6 A per phase for 3 s. Delete State.evOffers and its two writers. evInMeterW and clampEVBatteryHeadroom read evShownW, each charger's latest offer less what it may not show yet. The hourly peak in stepEVMeterLimit takes each charger's highest offer of the last evSettle from the same log. Co-Authored-By: Claude Opus 5.5 --- .changeset/a6-one-ev-offer-log.md | 5 +++ go/internal/control/dispatch.go | 16 +++------ go/internal/control/ev_battery_headroom.go | 8 ++--- .../control/ev_battery_headroom_test.go | 3 +- .../control/ev_battery_priority_test.go | 3 ++ go/internal/control/ev_fuse_budget.go | 26 ++++++++++++--- .../control/ev_slow_charger_battery_test.go | 33 +++++++++++++++++++ 7 files changed, 71 insertions(+), 23 deletions(-) create mode 100644 .changeset/a6-one-ev-offer-log.md create mode 100644 go/internal/control/ev_slow_charger_battery_test.go diff --git a/.changeset/a6-one-ev-offer-log.md b/.changeset/a6-one-ev-offer-log.md new file mode 100644 index 000000000..a11cc1905 --- /dev/null +++ b/.changeset/a6-one-ev-offer-log.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +Keep home battery charging out of the room a slow charger's raise still needs. The battery now counts a car's offer as not yet in the meter for the charger's own response time (180 s when it declares none), as the car's fuse limit already did, instead of 20 s. A charger that takes two minutes to start no longer pushes a 25 A phase to 32.6 A. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 3e01f1eea..395e52725 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -391,9 +391,8 @@ type State struct { evLimit evMeterLimit // fuseHeat is the main fuse's heat per phase, from site readings only. fuseHeat fuseHeat - // evOffers and batteryCommands are our own recent commands, the only - // device input the EV hard limit and the EV/battery split use. - evOffers commandLog + // batteryCommands and evLimit.offers are our own recent commands, the + // only device input the EV hard limit and the EV/battery split use. batteryCommands map[string]commandLog // PI controller (outer, site-level) @@ -2475,7 +2474,6 @@ func recordDispatchTargets(targets []DispatchTarget, state *State, updatePrevTar for _, t := range targets { state.batteryCommands[t.Driver] = state.batteryCommands[t.Driver].add(now, t.TargetW) } - state.evOffers = state.evOffers.add(now, math.Max(0, state.EVCommandedW)) } if updatePrevTargets { for _, t := range targets { @@ -4644,12 +4642,8 @@ func forceFuseDischargeWithSnapshot( } // evInMeterW is EV load the meter is sure to contain: the operator's declared -// load plus the lowest managed offer of the last evSettle. This tick's new -// offer is not in it yet. Charger readings take no part in the fuse share. +// load plus the managed offers already shown (evShownW). Charger readings +// take no part in the fuse share. func (s *State) evInMeterW() float64 { - low, _, _, ok := s.evOffers.span(s.now()) - if !ok { - low = 0 - } - return s.ManualEVChargingW + math.Max(0, low) + return s.ManualEVChargingW + s.evShownW(s.now()) } diff --git a/go/internal/control/ev_battery_headroom.go b/go/internal/control/ev_battery_headroom.go index 86c5cb597..f33b2a52d 100644 --- a/go/internal/control/ev_battery_headroom.go +++ b/go/internal/control/ev_battery_headroom.go @@ -10,17 +10,13 @@ import ( // still needs. It reads only the site meter and our own commands; no charger // reading takes part, and a battery's own reading only bounds how much of a // discharge we ordered it may keep. The EV still needs its demand less the -// lowest offer of the last evSettle, which the meter surely shows. +// offers the meter surely shows (evShownW). func clampEVBatteryHeadroom(targets []DispatchTarget, store *telemetry.Store, state *State, fuseMaxW float64) []DispatchTarget { if store == nil || state == nil || len(targets) == 0 || fuseMaxW <= 0 { return targets } now := state.now() - // This tick's new offer is not in the meter yet; the lowest logged one is. - offeredW, _, _, ok := state.evOffers.span(now) - if !ok { - offeredW = 0 - } + offeredW := state.evShownW(now) var demandW float64 phases := 3.0 // No phase placement promise for 1p or auto chargers. for _, demand := range state.evFuseDemands { diff --git a/go/internal/control/ev_battery_headroom_test.go b/go/internal/control/ev_battery_headroom_test.go index 9fafb4872..32b4af518 100644 --- a/go/internal/control/ev_battery_headroom_test.go +++ b/go/internal/control/ev_battery_headroom_test.go @@ -47,7 +47,8 @@ func sent(state *State, driver string, watts ...float64) { log = log.add(at, w) } if driver == "ev" { - state.evOffers, state.EVCommandedW = log, watts[len(watts)-1] + state.evLimit.offers = map[string]chargerOffers{"car": {log: log, settle: evSettle}} + state.EVCommandedW = watts[len(watts)-1] return } state.batteryCommands[driver] = log diff --git a/go/internal/control/ev_battery_priority_test.go b/go/internal/control/ev_battery_priority_test.go index f84b0d96c..3c3df469a 100644 --- a/go/internal/control/ev_battery_priority_test.go +++ b/go/internal/control/ev_battery_priority_test.go @@ -22,6 +22,9 @@ func issue1868Site(t *testing.T) (*telemetry.Store, *State, []loadpoint.State, [ tel.Update("battery", telemetry.DerBattery, 4000, &soc, nil) tel.RecordDriverSuccess("battery") sent(st, "ev", 4140) + // The car's 4140 W offer has run for longer than any charger's response time. + a, n := st.offerPhaseA(4140, 3) + st.evLimit.offers = map[string]chargerOffers{"rav4": {log: commandLog{{at: st.now().Add(-evUnknownSettle - time.Second), w: 4140, a: a, n: n}}}} sent(st, "battery", 4000) points := []loadpoint.State{{ID: "rav4", DriverName: "car", PluggedIn: true, CommandedKnown: true, CommandedW: 4140, CommandedPhases: 3}} configs := []loadpoint.Config{{ID: "rav4", DriverName: "car", PhaseMode: "3p", MinChargeW: 4140, MaxChargeW: 4140, AllowedStepsW: []float64{0, 4140}}} diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index e07c63e25..c3193fe8e 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -187,6 +187,21 @@ type pendingLoad struct { phaseA [3]float64 // on each phase } +// evShownW is the EV load a reading taken at `at` surely shows: each +// plugged charger's latest offer less what it may not show yet, kept for +// its own response time (recordEVOffers). The battery side reads this, so +// it waits for a slow charger's raise as long as the EV limit does. +func (s *State) evShownW(at time.Time) float64 { + var w float64 + for _, c := range s.evLimit.offers { + if n := len(c.log); n > 0 { + unshown, _ := c.log.unshown(at, c.settle) + w += math.Max(0, c.log[n-1].w-unshown) + } + } + return w +} + func (s *State) pendingLoad(at time.Time) pendingLoad { var p pendingLoad for _, c := range s.evLimit.offers { @@ -368,9 +383,6 @@ func EVFuseBudget(store *telemetry.Store, state *State, points []loadpoint.State *lim = evMeterLimit{} return 0, true } - if pool.offerKnown { - state.evOffers = state.evOffers.add(state.now(), pool.offerW) - } state.recordEVOffers(store, points) if !lim.set || meter.UpdatedAt.After(lim.readingAt) { state.stepEVMeterLimit(store, meter, gridW, pool, fuseMaxW) @@ -389,9 +401,13 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea } lim.set = true peakW := pool.offerW - if _, high, _, ok := s.evOffers.span(now); ok { - peakW = math.Max(peakW, high) + var logPeakW float64 + for _, c := range s.evLimit.offers { + if _, high, _, ok := c.log.span(now); ok { + logPeakW += high + } } + peakW = math.Max(peakW, logPeakW) // Our own battery orders the meter may not show yet count beside the // chargers' offers, in total import and on each phase. pending := s.pendingBatteryCommandsW(now) diff --git a/go/internal/control/ev_slow_charger_battery_test.go b/go/internal/control/ev_slow_charger_battery_test.go new file mode 100644 index 000000000..c8275988b --- /dev/null +++ b/go/internal/control/ev_slow_charger_battery_test.go @@ -0,0 +1,33 @@ +package control + +import ( + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/sitesim" +) + +// A charger that declares no response time and takes delay to start, beside +// a planned 9.4 kW battery charge on a 25 A site with 3 A of house load per +// phase. The car's 11 kW offer stays unshown until the charger applies it, +// and the battery must not take that room: when the car starts, no phase +// may pass the instant limit, and the car must not sit idle with room. +func TestSlowChargerUnshownOfferKeepsBatteryOut(t *testing.T) { + for _, delay := range []time.Duration{5 * time.Second, 30 * time.Second, 40 * time.Second, 2 * time.Minute} { + sc := simScenario{name: "slow charger", run: 15 * time.Minute, + plant: func(p *sitesim.Plant) { + p.HouseW, p.EVSE.Delay = houseA(3, 3, 3), delay + p.Battery = &sitesim.Battery{Phases: 3, MaxChargeW: 9400, MaxDischargeW: 9400, CapacityWh: 20000, SoC: .3, Latency: 3 * time.Second} + }, + setup: planBatteryCharge(9400)} + s := runSimScenario(sc, simStart) + t.Logf("delay %v: peak phase %.1f A, %v over %.0f A, idle with room %v, car %.0f W, battery %.0f W", + delay, s.peakA, s.overLimit, s.p.Fuse.RatingA-evPhaseMarginA, s.idleWithRoom, s.p.EVSE.DrawW, s.p.Battery.W) + if s.failure != "" { + t.Errorf("delay %v: %s", delay, s.failure) + } + if limitA := fuseInstantFactor * s.p.Fuse.RatingA; s.peakA > limitA { + t.Errorf("delay %v: peak phase %.1f A above the instant limit %.1f A", delay, s.peakA, limitA) + } + } +} From 8fe5dbb670f2ef74aa027172a10e6c4dc75df587 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 14:20:03 +0100 Subject: [PATCH 02/68] test(site): add P0 rig scenarios R1-R5 Stale meter, battery dropout, the planner floor, a SIGKILL restart and a start into a running site had no judged rig scenario. Add r1-25 to r5c-25 with their judges and known lines naming the Wave 1 items (A1, A3/A4, E1, D6). The rig gains stopFTW(sig), a planner soc_min field, a charger plugged at start and a delayed Core start. r1-25 is skipped until device-simulator can silence the site meter. Co-Authored-By: Claude Opus 5.5 --- go/test/site/README.md | 14 ++ go/test/site/catalog_test.go | 8 + go/test/site/evaluate_test.go | 96 +++++++- go/test/site/random_test.go | 3 +- go/test/site/rig_test.go | 16 +- go/test/site/scenarios_p0_test.go | 306 +++++++++++++++++++++++++ go/test/site/scenarios_p0_unit_test.go | 228 ++++++++++++++++++ go/test/site/scenarios_test.go | 6 +- go/test/site/stack_test.go | 20 +- go/test/site/verdicts_test.go | 258 +++++++++++++++++++++ 10 files changed, 943 insertions(+), 12 deletions(-) create mode 100644 go/test/site/scenarios_p0_test.go create mode 100644 go/test/site/scenarios_p0_unit_test.go diff --git a/go/test/site/README.md b/go/test/site/README.md index ee938f6a7..f1297bcfc 100644 --- a/go/test/site/README.md +++ b/go/test/site/README.md @@ -63,6 +63,10 @@ A criterion named in a scenario's `known` map fails on master for the finding it names. The run passes while it keeps failing, and fails once it passes: a fix deletes its line in the same pull request. +A scenario with a `skip` waits for a device-simulator change the pinned +commit lacks. `TestSite` reports it as `skip` with the knob it needs; the +pull request that pins a simulator with the knob deletes the skip. + ## The fault catalog Each scenario names the entries of FTW's field fault catalog it covers and @@ -102,3 +106,13 @@ tick as 2 s more. | `s14-25` One-phase car | an 11 kW charger with a one-phase car, a plan it cannot meet, 20 min | 3.4–3.8 kW over the last 10 min; never called not following | | | `s16-25` Import ceiling | 25 A, house 1.3 kW, battery idle at its floor, `peak_import_ceiling_w` 4 500, Charge now 16 A: house and the car's 4 140 W minimum are above the ceiling. Starts in an hour's first minutes or waits for :56, then runs one whole clock hour and 3 min | the car starts on the hour's room before :45; every clock hour's recorded import averages at most the ceiling + 1 %; the next hour stops the car within 60 s; while held it says `import_limit` 90 % of the time and never `fuse_limit`; fuse holds | | | `s17-25` Two equal batteries | 25 A, house 3 kW, no PV, two hybrids with 10 kWh at 74 % and 60 %, Energyplan whatever `FTW_SITE_ENGINE` says (Core DP plans one battery), a 6 h horizon (over 48 h the plan keeps the batteries for tomorrow's dearer hours). Waits up to an hour for a quarter the plan discharges, then 15 min | Energyplan's plan moves the batteries in half the polls (setup; tolerated, the day's prices decide); while the fleet moves 500 W or more, each battery takes at least a quarter of it 90 % of the time; while the plan moves them, the charge gap shrinks by over 0.2 points; fuse holds | | +| `r1-25` Meter silent, then offline | 25 A, 15 A per phase, battery at 50 %, Charge now 16 A; the site meter silent (Modbus timeouts) for 120 s, then gone for 90 s. **Skipped**: the pinned simulator cannot silence the site meter | the battery relieved the fuse (setup); while silent no offer rises and the battery order only moves toward 0 (**known**: A1); a 0 W order and the battery back on its own within 64 s; the meter never shows live; Charge now back within 95 s of each return; fuse holds | | +| `r2-25`, `r2-60-25` Battery drops out | 25 A, 20 A per phase, the battery held at a 3 kW discharge, a car taking 10 A on Charge now, the charger at once or 60 s late; the inverter gone for 180 s | the battery discharged (setup); fuse holds; over the limit at most the charger's delay + 7 s after the drop; no offer rises while it is gone; Home use shown as estimated throughout | | +| `r3-25` Planner floor | 25 A, 15 A per phase, battery at 12 %, planner `soc_min` 10 %, inverter floor 5 %, charger 60 s late, Charge now 16 A for 600 s | the battery reaches the floor (setup); no discharge ordered below it (**known**: A4); the battery order swings at most 100 W over the last 5 min (**known**: A3, A4); over fuse − 0.5 A at most the delay + 7 s (Core holds the phase at its own line, as in s3); fuse holds | | +| `r4-25` Hard kill | 25 A, 12 A per phase, the battery held at a 3 kW discharge, Charge now 16 A; once the day's Home use is known and 15 min more, SIGKILL for 20 s, and 2 min later for 120 s while the house steps to 16 A | Charge now back at its minimum within 60 s of each restart; the day's Home use kept within 1 % across the first kill; session energy counts again (**known**: E1); no state.db recovery in the log; fuse holds | | +| `r5a-25` Start beside a charging car | 25 A, 14 A per phase, a car charging on its own at 16 A for 60 s before Core starts | the car charged (setup); under the limit within 30 s of Core answering, and over it at most 3 s after; Home use shown within 30 s; fuse holds | | +| `r5b-25` Start on a stale plan | a goal 40 → 60 % 8 h out, Core stopped for 20 min | no positive order in the first 30 s before a fresh plan (**known**: D6); Home use shown within 30 s; fuse holds | | +| `r5c-25` Start into a new session | Charge now, Core stopped for 10 min while the car leaves and another plugs in | Core sees the car within 60 s; Home use shown within 30 s; fuse holds. Whether Charge now carries over is recorded, not judged: ev-088 waits for the owner | | + +The `r` scenarios are R1-R5 of the stable plan. A **known** line names the +Wave 1 item whose fix deletes it. diff --git a/go/test/site/catalog_test.go b/go/test/site/catalog_test.go index 87108f722..55cfd9988 100644 --- a/go/test/site/catalog_test.go +++ b/go/test/site/catalog_test.go @@ -52,6 +52,14 @@ var provenance = map[string]struct { "s15p-25": {nil, []string{"https://github.com/srcfl/ftw/pull/1804", "release blocker 22 Oct 2026: a one-phase charger, planned charging"}}, "s16-25": {nil, []string{"https://github.com/srcfl/ftw/pull/1828", "help report 25 Oct 2026: an idle car held at 0 W for an hour under a 4.5 kW import ceiling"}}, "s17-25": {nil, []string{"https://github.com/srcfl/ftw/pull/1814", "field report 23 Oct 2026, v0.155.1-beta.1: two equal Pixii batteries take turns"}}, + "r1-25": {[]string{"tel-001", "tel-006", "tel-007", "bat-074"}, []string{"stable plan 27 Oct 2026, R1"}}, + "r2-25": {[]string{"tel-007", "tel-022", "ev-090", "ev-075"}, []string{"stable plan 27 Oct 2026, R2"}}, + "r2-60-25": {[]string{"tel-007", "tel-022", "ev-090", "ev-075"}, []string{"stable plan 27 Oct 2026, R2"}}, + "r3-25": {[]string{"ev-099", "ev-090"}, []string{"stable plan 27 Oct 2026, R3"}}, + "r4-25": {[]string{"ev-085", "ev-091", "home-061", "home-074", "ocpp-008", "upd-051"}, []string{"stable plan 27 Oct 2026, R4", "https://github.com/srcfl/ftw/pull/1787"}}, + "r5a-25": {[]string{"ev-076", "dev-100"}, []string{"stable plan 27 Oct 2026, R5"}}, + "r5b-25": {[]string{"ev-076"}, []string{"stable plan 27 Oct 2026, R5", "https://github.com/srcfl/ftw/issues/1718"}}, + "r5c-25": {[]string{"ev-088"}, []string{"stable plan 27 Oct 2026, R5"}}, } func TestEveryScenarioSaysWhereItComesFrom(t *testing.T) { diff --git a/go/test/site/evaluate_test.go b/go/test/site/evaluate_test.go index 1e3caaee4..43e406549 100644 --- a/go/test/site/evaluate_test.go +++ b/go/test/site/evaluate_test.go @@ -42,18 +42,17 @@ type plantDevice struct { W float64 `json:"w"` // a charger's draw BatteryW float64 `json:"battery_w"` // an inverter's battery, + charging SoCPct float64 `json:"soc_pct"` - EMSCmd float64 `json:"ems_cmd"` // 170 charge, 187 discharge, 204 stop + EMSMode float64 `json:"ems_mode"` // 2 forced, as Core drives it + EMSCmd float64 `json:"ems_cmd"` // 170 charge, 187 discharge, 204 stop EMSSetW float64 `json:"ems_setpoint_w"` Connected bool `json:"connected"` } type ftwStatus struct { - Drivers map[string]struct { - Status string `json:"status"` - } `json:"drivers"` - LoadQuality *string `json:"load_quality"` - LoadReason *string `json:"load_reason"` - LoadW *float64 `json:"load_w"` + Drivers map[string]ftwDriver `json:"drivers"` + LoadQuality *string `json:"load_quality"` + LoadReason *string `json:"load_reason"` + LoadW *float64 `json:"load_w"` Energy struct { Today struct { LoadWh *float64 `json:"load_wh"` @@ -62,6 +61,11 @@ type ftwStatus struct { } `json:"energy"` } +type ftwDriver struct { + Status string `json:"status"` + EVSessionWh *float64 `json:"ev_session_wh"` // a charger's session energy +} + type ftwLoadpoint struct { ID string `json:"id"` Plugged bool `json:"plugged_in"` @@ -69,6 +73,7 @@ type ftwLoadpoint struct { Charger struct { Known bool `json:"known"` } `json:"charger"` + ManualActive bool `json:"manual_active"` CommandedReason string `json:"commanded_reason"` Manual struct { LimitReason string `json:"limit_reason"` // the clamp behind a limited Charge now @@ -687,3 +692,80 @@ func (d *runData) disconnects(t0, t1 float64) []float64 { }) return out } + +// ---- the battery, the charger's orders and the log, for R1-R5 ---- + +// batOrder is Core's battery order as the inverter holds it: + charge, - +// discharge, 0 when not forced. +func batOrder(r *sample) float64 { + if r.Bat.EMSMode != 2 { + return 0 + } + switch r.Bat.EMSCmd { + case 170: + return r.Bat.EMSSetW + case 187: + return -r.Bat.EMSSetW + } + return 0 +} + +// batForced is true while Core drives the battery: forced mode with a charge +// or discharge command. +func batForced(r *sample) bool { + return r.Bat.EMSMode == 2 && (r.Bat.EMSCmd == 170 || r.Bat.EMSCmd == 187) +} + +// offers is every SetChargingProfile on connector 1 of charger 0, timed in +// Unix seconds. +func (d *runData) offers() []profile { return connector1(profiles(d.frames, 0, math.Inf(1))) } + +// offerRises counts orders sent in [t0, t1) that offer more than the order +// before them. +func (d *runData) offerRises(t0, t1 float64) int { + n := 0 + prs := d.offers() + for i := 1; i < len(prs); i++ { + if prs[i].T >= t0 && prs[i].T < t1 && prs[i].offerW() > prs[i-1].offerW()+1 { + n++ + } + } + return n +} + +// firstOffer is the seconds from t0 to the first order from t0 on that +// satisfies pred, or nil. +func (d *runData) firstOffer(t0 float64, pred func(profile) bool) *float64 { + for _, p := range d.offers() { + if p.T >= t0 && pred(p) { + v := p.T - t0 + return &v + } + } + return nil +} + +// logLines are the lines of FTW's log that hold any of subs. +func (d *runData) logLines(subs ...string) []string { + var out []string + readLines(filepath.Join(d.dir, "ftw.log"), func(b []byte) { + for _, s := range subs { + if strings.Contains(string(b), s) { + out = append(out, string(b)) + return + } + } + }) + return out +} + +// todayLoadWh is the day's Home use FTW last showed in ws, or nil. +func todayLoadWh(ws []*sample) *float64 { + var v *float64 + for _, r := range ws { + if r.Status != nil && r.Status.Energy.Today.LoadWh != nil { + v = r.Status.Energy.Today.LoadWh + } + } + return v +} diff --git a/go/test/site/random_test.go b/go/test/site/random_test.go index aeaa2b10d..c0580d222 100644 --- a/go/test/site/random_test.go +++ b/go/test/site/random_test.go @@ -11,6 +11,7 @@ import ( "path/filepath" "sort" "strings" + "syscall" "time" ) @@ -155,7 +156,7 @@ func runPlan(c *runCtx, p randomPlan) (map[string]any, error) { case "plan": _, err = st.planTo("garage", a.SoCPct, a.GoalPct, time.Duration(a.ReadyMin*float64(time.Minute))) case "restart": - st.stopFTW() + st.stopFTW(syscall.SIGTERM) sleepS(a.DownS) err = st.startFTW() st.mark("ftw:up") diff --git a/go/test/site/rig_test.go b/go/test/site/rig_test.go index 35184ffb2..a2730cf71 100644 --- a/go/test/site/rig_test.go +++ b/go/test/site/rig_test.go @@ -204,12 +204,13 @@ func split(scs []scenario, n int) [][]scenario { type outcome struct { Name string `json:"name"` Dir string `json:"dir"` - Verdict string `json:"verdict"` // pass, known, fail + Verdict string `json:"verdict"` // pass, known, fail, skip DurationS float64 `json:"duration_s"` Criteria []criterion `json:"criteria"` Known []string `json:"known,omitempty"` Failures []string `json:"failures,omitempty"` Error string `json:"error,omitempty"` + Skipped string `json:"skipped,omitempty"` // what the simulator lacks } // TestSite runs the scenarios FTW_SITE names. FTW_SITE_LANES runs that many @@ -239,6 +240,16 @@ func TestSite(t *testing.T) { env := setup(t) var mu sync.Mutex var outcomes []outcome + var runnable []scenario + for _, sc := range scs { + if sc.skip == "" { + runnable = append(runnable, sc) + continue + } + t.Logf("%s skipped: %s", sc.name, sc.skip) + outcomes = append(outcomes, outcome{Name: sc.name, Dir: sc.dir, Verdict: "skip", Skipped: sc.skip}) + } + scs = runnable t.Run("lanes", func(t *testing.T) { for k, group := range split(scs, lanes) { k, group := k, group @@ -405,6 +416,9 @@ func writeSummary(t *testing.T, out string, outs []outcome) { if o.Error != "" { notes = append([]string{o.Error}, notes...) } + if o.Skipped != "" { + notes = append(notes, o.Skipped) + } fmt.Fprintf(&md, "| %s | %s | %s | %s |\n", o.Name, o.Verdict, (time.Duration(o.DurationS) * time.Second).String(), strings.ReplaceAll(strings.Join(notes, "; "), "|", "/")) } diff --git a/go/test/site/scenarios_p0_test.go b/go/test/site/scenarios_p0_test.go new file mode 100644 index 000000000..bf3c5c83e --- /dev/null +++ b/go/test/site/scenarios_p0_test.go @@ -0,0 +1,306 @@ +//go:build unix + +package site + +import ( + "encoding/json" + "os" + "path/filepath" + "syscall" + "time" +) + +// The P0 scenarios R1-R5 of the stable plan: a meter that stops answering, +// a battery that drops out, the planner's floor, a hard kill and a start +// into a running site. Their judges are in verdicts_test.go. A known line +// names the Wave 1 item whose fix deletes it. +func init() { + scenarios = append(scenarios, + scenario{name: "r1-25", dir: "r1-meter-silent-then-offline-25A", minutes: 10, run: func(c *runCtx) (map[string]any, error) { return r1(c, 25) }, + judge: judgeR1, skip: meterKnob, + known: map[string]string{"the battery order moves only toward 0 while the meter is silent": "A1: a failed poll keeps the held reading, and ComputeDispatch winds the battery against it (dispatch.go:1446-1449)"}}, + scenario{name: "r2-25", dir: "r2-battery-offline-25A", minutes: 8, run: func(c *runCtx) (map[string]any, error) { return r2(c, 25, 0) }, + judge: judgeR2}, + scenario{name: "r2-60-25", dir: "r2-battery-offline-slow60-25A", minutes: 10, run: func(c *runCtx) (map[string]any, error) { return r2(c, 25, 60) }, + judge: judgeR2}, + scenario{name: "r3-25", dir: "r3-planner-floor-25A", minutes: 13, run: func(c *runCtx) (map[string]any, error) { return r3(c, 25) }, + judge: judgeR3, + known: map[string]string{ + "no discharge ordered below the planner floor": "A4: fuse relief discharges to 5 %, below planner.soc_min (dispatch.go:4113-4124, 4495-4499)", + "the battery order swings at most 100 W over the last 5 min": "A3, A4: at the inverter's empty 5 % Core keeps ordering 3.9-5 kW of discharge (the slew step reopens it, dispatch.go:2148-2219)", + }}, + scenario{name: "r4-25", dir: "r4-sigkill-25A", minutes: 40, run: func(c *runCtx) (map[string]any, error) { return r4(c, 25) }, + judge: judgeR4, + known: map[string]string{"session energy counts again after each restart": "E1: a 1.6 transaction is not taken up after a restart, so session_wh stays 0 (handlers.go:615-617, #1787)"}}, + scenario{name: "r5a-25", dir: "r5a-start-car-charging-25A", minutes: 5, run: func(c *runCtx) (map[string]any, error) { return r5a(c, 25) }, + judge: judgeR5a}, + scenario{name: "r5b-25", dir: "r5b-start-stale-plan-25A", minutes: 27, run: func(c *runCtx) (map[string]any, error) { return r5b(c, 25) }, + judge: judgeR5b, + known: map[string]string{"no positive EV order in the first 30 s without a fresh plan": "D6: the deadline reserve orders full power whatever the slack (deadline_need.go:11-40, #1718)"}}, + scenario{name: "r5c-25", dir: "r5c-start-new-session-25A", minutes: 15, run: func(c *runCtx) (map[string]any, error) { return r5c(c, 25) }, + judge: judgeR5c}, + ) +} + +// ---- R1. The site meter goes silent, then offline, under Charge now ---- + +// meterKnob is the device-simulator change R1 waits for. +const meterKnob = "TODO(device-simulator): `silence` and `offline` must take the site meter " + + "(device \"meter\"); at the pinned commit they answer `no device \"meter\"`. Pin a commit " + + "that has it and delete this skip." + +// r1 puts Core's battery relief on a meter that stops answering: Modbus +// timeouts for 120 s, then, two minutes after it is back, a meter gone for +// 90 s. House 15 A per phase and Charge now 16 A put the site over the fuse +// unless the battery helps. +func r1(c *runCtx, fuse float64) (map[string]any, error) { + err := with(c, stackSpec{fuseA: fuse, loadsW: houseA(15), socPct: 50}, func(st *stack) error { + if err := st.plug(0); err != nil { + return err + } + sleepS(30) + st.mark("charge_now") + if err := st.chargeNow("garage", 16, "3p", 0); err != nil { + return err + } + sleepS(90) + st.mark("silent") + if err := st.event(houseEvent{Do: "silence", Device: "meter", ForS: 120}); err != nil { + return err + } + sleepS(120) + st.mark("back") + sleepS(120) + st.mark("offline") + if err := st.event(houseEvent{Do: "offline", Device: "meter", ForS: 90}); err != nil { + return err + } + sleepS(90) + st.mark("online") + sleepS(120) + st.mark("end") + return nil + }) + return map[string]any{"scenario": "r1", "fuse": fuse, "house_a": 15, "silent_s": 120, "offline_s": 90}, err +} + +// ---- R2. The battery drops out while the car's room rests on it ---- + +// r2 holds the battery at a 3 kW discharge under a 20 A house, so the car's +// room rests on it, then takes the inverter off the site for 180 s: each +// phase rises 4.3 A at once. The car takes at most 10 A, so its draw before +// Core's first profile keeps the site under 1.25 x the fuse. +func r2(c *runCtx, fuse, delayS float64) (map[string]any, error) { + err := with(c, stackSpec{fuseA: fuse, loadsW: houseA(20), socPct: 60, + chargers: []charger{{delayS: delayS, carMaxA: 10}}}, func(st *stack) error { + if err := st.plug(0); err != nil { + return err + } + st.mark("plug_wait") + sleepS(delayS + 20) + st.mark("battery_hold") + if err := st.post("/api/battery/manual_hold", map[string]any{"direction": "discharge", "power_w": 3000, "hold_s": 1800}, nil); err != nil { + return err + } + st.mark("charge_now") + if err := st.chargeNow("garage", 10, "3p", 0); err != nil { + return err + } + sleepS(delayS + 90) + st.mark("offline") + if err := st.event(houseEvent{Do: "offline", Device: "inverter"}); err != nil { + return err + } + sleepS(180) + st.mark("online") + if err := st.event(houseEvent{Do: "online", Device: "inverter"}); err != nil { + return err + } + sleepS(120) + st.mark("end") + return nil + }) + return map[string]any{"scenario": "r2", "fuse": fuse, "house_a": 20, "battery_hold_w": -3000, + "charger_delay_s": delayS, "offline_s": 180}, err +} + +// ---- R3. The battery near the planner's floor under fuse pressure ---- + +// r3 starts the battery at 12 % with the planner's floor at 10 % and the +// inverter's own at 5 %. House 15 A per phase and Charge now 16 A need the +// battery's help; the charger applies a profile 60 s late. +func r3(c *runCtx, fuse float64) (map[string]any, error) { + const delayS, floor = 60, 0.10 + err := with(c, stackSpec{fuseA: fuse, loadsW: houseA(15), socPct: 12, plannerSoCMin: floor, + chargers: []charger{{delayS: delayS}}}, func(st *stack) error { + if err := st.plug(0); err != nil { + return err + } + st.mark("plug_wait") + sleepS(delayS + 20) + st.mark("charge_now") + if err := st.chargeNow("garage", 16, "3p", 0); err != nil { + return err + } + sleepS(600) + st.mark("end") + return nil + }) + return map[string]any{"scenario": "r3", "fuse": fuse, "house_a": 15, "soc_pct": 12, + "planner_floor_pct": floor * 100, "charger_delay_s": delayS}, err +} + +// ---- R4. Core killed mid-charge and mid-discharge ---- + +// r4 kills Core with SIGKILL, as a power cut does: no driver cleanup, no +// history flush, an OCPP transaction left open. House 12 A per phase, the +// battery held at a 3 kW discharge, Charge now 16 A. The first kill lasts +// 20 s; two minutes later the second lasts 120 s, and the house steps to +// 16 A per phase while Core is gone. Like s7, the run first waits until the +// day's Home use is known, and long enough after it that one restart stays +// under the 10 % unknown-time rule. +func r4(c *runCtx, fuse float64) (map[string]any, error) { + var serial string + err := with(c, stackSpec{fuseA: fuse, loadsW: houseA(12), socPct: 60}, func(st *stack) error { + if err := st.plug(0); err != nil { + return err + } + serial = st.serial(0) + if err := st.post("/api/battery/manual_hold", map[string]any{"direction": "discharge", "power_w": 3000, "hold_s": 3600}, nil); err != nil { + return err + } + st.mark("charge_now") + if err := st.chargeNow("garage", 16, "3p", 0); err != nil { + return err + } + if waitUntil(900*time.Second, 5*time.Second, func() bool { + var s ftwStatus + return st.get("/api/status", &s) == nil && s.Energy.Today.LoadWh != nil + }) { + st.mark("today_known") + } + sleepS(900) + st.mark("kill1") + st.stopFTW(syscall.SIGKILL) + sleepS(20) + if err := st.startFTW(); err != nil { + return err + } + st.mark("up1") + sleepS(120) + st.mark("kill2") + st.stopFTW(syscall.SIGKILL) + st.mark("step") + if err := st.setLoadsA(16); err != nil { + return err + } + sleepS(120) + if err := st.startFTW(); err != nil { + return err + } + st.mark("up2") + sleepS(300) + st.mark("end") + return nil + }) + return map[string]any{"scenario": "r4", "fuse": fuse, "house_a": 12, "step_a": 16, "battery_hold_w": -3000, + "down_s": []float64{20, 120}, "charger": serial}, err +} + +// ---- R5. Core starts into a running site ---- + +// r5a starts Core while the car charges on its own: plugged when the house +// comes up, it starts a local transaction and draws all it can, 16 A on +// 14 A of house load. +func r5a(c *runCtx, fuse float64) (map[string]any, error) { + err := with(c, stackSpec{fuseA: fuse, loadsW: houseA(14), socPct: 50, startAfterS: 60, + chargers: []charger{{plugged: true}}}, func(st *stack) error { + st.mark("ftw_up") + sleepS(180) + st.mark("end") + return nil + }) + return map[string]any{"scenario": "r5a", "fuse": fuse, "house_a": 14}, err +} + +// r5b saves a goal with hours of slack, so no fresh plan need charge now, +// then stops Core for 20 min and starts it on the plan it saved. For the +// first minute the rig asks for the plan once a second (plan.jsonl). +func r5b(c *runCtx, fuse float64) (map[string]any, error) { + err := with(c, stackSpec{fuseA: fuse, loadsW: houseA(3), socPct: 50}, func(st *stack) error { + if err := st.plug(0); err != nil { + return err + } + if _, err := st.planTo("garage", 40, 60, 8*time.Hour); err != nil { + return err + } + st.mark("plan") + sleepS(120) + st.mark("ftw_stop") + st.stopFTW(syscall.SIGTERM) + sleepS(1200) + st.mark("ftw_start") + if err := st.startFTW(); err != nil { + return err + } + st.mark("ftw_up") + f, err := os.Create(filepath.Join(st.rundir, "plan.jsonl")) + if err != nil { + return err + } + defer f.Close() + for end := time.Now().Add(60 * time.Second); time.Now().Before(end); sleepS(1) { + var p struct { + Plan *struct { + GeneratedAtMs int64 `json:"generated_at_ms"` + } `json:"plan"` + } + if st.get("/api/mpc/plan", &p) == nil && p.Plan != nil { + b, _ := json.Marshal(map[string]any{"t": now(), "generated_at_ms": p.Plan.GeneratedAtMs}) + f.Write(append(b, '\n')) + } + } + sleepS(60) + st.mark("end") + return nil + }) + return map[string]any{"scenario": "r5b", "fuse": fuse, "house_a": 3, "down_s": 1200}, err +} + +// r5c holds Charge now on one car, stops Core for 10 min, in which that car +// leaves and another plugs in, and starts Core into the new session. +func r5c(c *runCtx, fuse float64) (map[string]any, error) { + err := with(c, stackSpec{fuseA: fuse, loadsW: houseA(3), socPct: 50}, func(st *stack) error { + if err := st.plug(0); err != nil { + return err + } + st.mark("charge_now") + if err := st.chargeNow("garage", 16, "3p", 0); err != nil { + return err + } + sleepS(60) + st.mark("ftw_stop") + st.stopFTW(syscall.SIGTERM) + sleepS(300) + off, on := false, true + st.mark("unplug") + if err := st.event(houseEvent{Do: "plug", Device: "garage", On: &off}); err != nil { + return err + } + sleepS(30) + st.mark("replug") + if err := st.event(houseEvent{Do: "plug", Device: "garage", On: &on}); err != nil { + return err + } + sleepS(270) + st.mark("ftw_start") + if err := st.startFTW(); err != nil { + return err + } + st.mark("ftw_up") + sleepS(180) + st.mark("end") + return nil + }) + return map[string]any{"scenario": "r5c", "fuse": fuse, "house_a": 3, "down_s": 600}, err +} diff --git a/go/test/site/scenarios_p0_unit_test.go b/go/test/site/scenarios_p0_unit_test.go new file mode 100644 index 000000000..ad7ddaf93 --- /dev/null +++ b/go/test/site/scenarios_p0_unit_test.go @@ -0,0 +1,228 @@ +//go:build unix + +package site + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" +) + +// Unit tests for the R1-R5 judges, on records made up here. They run in +// every go test, without a simulator. + +// synth is n one-second samples from t = 0: 10 A per phase, the car idle, +// the battery not forced. set changes sample i. +func synth(n int, marks map[string]float64, meta map[string]any, set func(i int, r *sample)) *runData { + d := &runData{marks: marks, meta: meta} + for i := 0; i < n; i++ { + r := &sample{T: float64(i), PhaseA: [3]float64{10, 10, 10}, CarW: []float64{0}} + if set != nil { + set(i, r) + } + d.samples = append(d.samples, r) + } + return d +} + +// order sets the battery's EMS registers to Core's order w (+ charge). +func order(r *sample, w float64) { + switch { + case w > 0: + r.Bat.EMSMode, r.Bat.EMSCmd, r.Bat.EMSSetW = 2, 170, w + case w < 0: + r.Bat.EMSMode, r.Bat.EMSCmd, r.Bat.EMSSetW = 2, 187, -w + default: + r.Bat.EMSMode, r.Bat.EMSCmd, r.Bat.EMSSetW = 0, 204, 0 + } +} + +// profileAt is a SetChargingProfile of limitA per phase on connector 1, +// sent at t. +func profileAt(t, limitA float64) frame { + b, _ := json.Marshal([]any{2, "id", "SetChargingProfile", map[string]any{"connectorId": 1, + "csChargingProfiles": map[string]any{"chargingProfilePurpose": "TxDefaultProfile", + "chargingSchedule": map[string]any{"chargingRateUnit": "A", + "chargingSchedulePeriod": []any{map[string]any{"limit": limitA}}}}}}) + return frame{T: t, Dir: "cs->cp", Frame: b} +} + +func verdictsOf(cs []criterion) map[string]bool { + out := map[string]bool{} + for _, c := range cs { + out[c.Name] = c.OK + } + return out +} + +func TestBatOrderReadsTheForcedCommand(t *testing.T) { + for _, w := range []float64{3000, -2500, 0} { + r := &sample{} + order(r, w) + if got := batOrder(r); got != w { + t.Errorf("order %v read as %v", w, got) + } + } + r := &sample{Bat: plantDevice{EMSMode: 0, EMSCmd: 187, EMSSetW: 3000}} + if batOrder(r) != 0 || batForced(r) { + t.Fatal("a discharge command outside forced mode is no order: the inverter runs on its own") + } +} + +func TestOfferRisesCountsOnlyRaisesInTheWindow(t *testing.T) { + d := &runData{frames: []frame{profileAt(10, 8), profileAt(20, 10), profileAt(30, 6), profileAt(40, 7), profileAt(60, 16)}} + if n := d.offerRises(15, 50); n != 2 { + t.Fatalf("rises in [15, 50): %d, want 2 (8→10 A at 20 s, 6→7 A at 40 s)", n) + } + if p := d.firstOffer(25, func(p profile) bool { return p.Limit < 7 }); p == nil || *p != 5 { + t.Fatalf("first offer under 7 A from 25 s: %v, want 5 s", p) + } +} + +// r1Run is R1's record: the meter silent from 100 to 220 s and offline from +// 340 to 430 s. Core discharges 3 kW until the silence and hands the +// battery back and stands the charger down 40 s into it; the meter reads +// degraded while silent; Charge now returns 30 s after each return. orderAt +// is Core's battery order during the silence before the hand-back. +func r1Run(orderAt func(t float64) float64) *runData { + marks := map[string]float64{"charge_now": 0, "silent": 100, "back": 220, "offline": 340, "online": 430, "end": 550} + d := synth(550, marks, map[string]any{"fuse": 25.0}, func(i int, r *sample) { + t := float64(i) + switch { + case t <= 100: + order(r, -3000) + case t < 140: + order(r, orderAt(t)) + } + meter := "ok" + if (t > 102 && t < 220) || (t > 342 && t < 430) { + meter = "degraded" + } + r.Status = &ftwStatus{Drivers: map[string]ftwDriver{"meter": {Status: meter}}} + if t < 140 || (t >= 250 && t < 380) || t >= 460 { + r.CarW[0] = 11040 + } + }) + d.frames = []frame{profileAt(50, 16), profileAt(140, 0), profileAt(240, 16), profileAt(390, 0), profileAt(450, 16)} + return d +} + +func TestJudgeR1(t *testing.T) { + _, cs := judgeR1(r1Run(func(t float64) float64 { return -3000 + 50*(t-100) })) + for name, ok := range verdictsOf(cs) { + if !ok { + t.Errorf("an order easing toward 0: %q fails", name) + } + } + _, cs = judgeR1(r1Run(func(t float64) float64 { return -3000 - 100*(t-100) })) + if v := verdictsOf(cs); v["the battery order moves only toward 0 while the meter is silent"] { + t.Error("an order winding from -3 kW toward -7 kW passes") + } + _, cs = judgeR1(r1Run(func(float64) float64 { return 1000 })) + if v := verdictsOf(cs); v["the battery order moves only toward 0 while the meter is silent"] { + t.Error("an order flipping from discharge to charge passes") + } + late := r1Run(func(float64) float64 { return -3000 }) + late.frames[1] = profileAt(170, 0) + _, cs = judgeR1(late) + if v := verdictsOf(cs); v["a 0 W charger order within 64 s of the silence"] { + t.Error("a standdown 70 s into the silence passes") + } +} + +func TestJudgeR2(t *testing.T) { + marks := map[string]float64{"charge_now": 0, "offline": 100, "online": 280, "end": 400} + run := func(frames []frame) map[string]bool { + d := synth(400, marks, map[string]any{"fuse": 25.0, "charger_delay_s": 0.0}, func(i int, r *sample) { + r.BatW = -3000 + q := "measured" + if i >= 100 && i < 280 { + q = "estimated" + } + w := 5000.0 + r.Status = &ftwStatus{LoadQuality: &q, LoadW: &w} + }) + d.frames = frames + _, cs := judgeR2(d) + return verdictsOf(cs) + } + if v := run([]frame{profileAt(50, 8), profileAt(120, 6)}); !v["no EV offer rises while the battery is offline"] || + !v["Home use shown as estimated throughout the outage"] || !v["the battery discharged 2 kW or more before the drop"] { + t.Fatalf("a cut while offline: %v", v) + } + if v := run([]frame{profileAt(50, 8), profileAt(120, 10)}); v["no EV offer rises while the battery is offline"] { + t.Fatal("a raise from 8 to 10 A while the battery is offline passes") + } +} + +func TestJudgeR3(t *testing.T) { + marks := map[string]float64{"plug": 0, "charge_now": 20, "end": 400} + run := func(set func(i int, r *sample)) map[string]bool { + _, cs := judgeR3(synth(400, marks, map[string]any{"fuse": 25.0, "charger_delay_s": 60.0, "planner_floor_pct": 10.0}, set)) + return verdictsOf(cs) + } + // SoC falls from 12 % to 8 % over the first 100 s. + soc := func(i int) float64 { return 12 - 4*float64(min(i, 100))/100 } + v := run(func(i int, r *sample) { r.Bat.SoCPct = soc(i); order(r, -3000) }) + if v["no discharge ordered below the planner floor"] || !v["the battery reached the planner floor"] { + t.Fatalf("discharge down to 8 %%: %v", v) + } + v = run(func(i int, r *sample) { + r.Bat.SoCPct = soc(i) + if r.Bat.SoCPct > 10 { + order(r, -3000) + } + }) + if !v["no discharge ordered below the planner floor"] || !v["the battery order swings at most 100 W over the last 5 min"] { + t.Fatalf("stopping at the floor: %v", v) + } + v = run(func(i int, r *sample) { r.Bat.SoCPct = 10; order(r, -3000*float64(i%2)) }) + if v["the battery order swings at most 100 W over the last 5 min"] { + t.Fatal("an order hunting between 0 and -3 kW passes") + } +} + +func TestJudgeR4SessionEnergy(t *testing.T) { + marks := map[string]float64{"charge_now": 0, "kill1": 100, "up1": 130, "kill2": 250, "up2": 400, "end": 600} + run := func(afterWh float64) map[string]bool { + d := synth(600, marks, map[string]any{"fuse": 25.0, "charger": "CP1"}, func(i int, r *sample) { + wh := 2000.0 + if (i >= 130 && i < 250) || i >= 400 { + wh = afterWh + } + r.Status = &ftwStatus{Drivers: map[string]ftwDriver{"CP1": {Status: "ok", EVSessionWh: &wh}}} + r.CarW[0] = 11040 + }) + _, cs := judgeR4(d) + return verdictsOf(cs) + } + if v := run(0); v["session energy counts again after each restart"] { + t.Fatal("session energy stuck at 0 after the restarts passes") + } + if v := run(150); !v["session energy counts again after each restart"] || !v["Charge now back at its minimum within 60 s of each restart"] { + t.Fatalf("session energy counting after the restarts: %v", v) + } +} + +func TestJudgeR5bAllowsChargingOnlyOnAFreshPlan(t *testing.T) { + dir := t.TempDir() + marks := map[string]float64{"ftw_start": 100, "ftw_up": 110, "end": 200} + // The rig sees the fresh plan, made at 115 s, at 116 s. + plan := `{"t": 111, "generated_at_ms": 40000}` + "\n" + `{"t": 116, "generated_at_ms": 115000}` + "\n" + if err := os.WriteFile(filepath.Join(dir, "plan.jsonl"), []byte(plan), 0o644); err != nil { + t.Fatal(err) + } + run := func(frames []frame) map[string]bool { + d := synth(200, marks, map[string]any{"fuse": 25.0}, nil) + d.dir, d.frames = dir, frames + _, cs := judgeR5b(d) + return verdictsOf(cs) + } + if v := run([]frame{profileAt(112, 16)}); v["no positive EV order in the first 30 s without a fresh plan"] { + t.Fatal("16 A before the fresh plan passes") + } + if v := run([]frame{profileAt(112, 0), profileAt(120, 16)}); !v["no positive EV order in the first 30 s without a fresh plan"] { + t.Fatal("0 A until the fresh plan, then 16 A, fails") + } +} diff --git a/go/test/site/scenarios_test.go b/go/test/site/scenarios_test.go index 8f987969d..5707f3b1b 100644 --- a/go/test/site/scenarios_test.go +++ b/go/test/site/scenarios_test.go @@ -9,6 +9,7 @@ import ( "os" "path/filepath" "strings" + "syscall" "time" ) @@ -27,6 +28,9 @@ type scenario struct { // tolerate names criteria that may fail for a known finding but need // not: random cases, where a seed may or may not reach it. tolerate map[string]string + // skip, when set, says what the pinned device-simulator lacks for this + // scenario: TestSite reports it skipped instead of running it. + skip string } var scenarios = []scenario{ @@ -412,7 +416,7 @@ func s7(c *runCtx, fuse float64, short bool) (map[string]any, error) { sleepS(900) } st.mark("ftw_stop") - st.stopFTW() + st.stopFTW(syscall.SIGTERM) sleepS(20) st.mark("ftw_start") if err := st.startFTW(); err != nil { diff --git a/go/test/site/stack_test.go b/go/test/site/stack_test.go index e45b6fc54..11c6b55be 100644 --- a/go/test/site/stack_test.go +++ b/go/test/site/stack_test.go @@ -208,6 +208,7 @@ type houseDevice struct { CarMaxA float64 `json:"car_max_a,omitempty"` CarPhases int `json:"car_phases,omitempty"` WiredPhases int `json:"wired_phases,omitempty"` + Plugged bool `json:"plugged,omitempty"` } // houseEvent is one change to the house (device-simulator's runEvent). @@ -247,6 +248,7 @@ type charger struct { carPhases int // 0: as many as offered wiredPhases int // 1: wired on L1 only, kw its rating there carMaxA float64 + plugged bool // a car on it when the house starts, charging on its own } type stackSpec struct { @@ -273,6 +275,11 @@ type stackSpec struct { engine string // horizonH is the planner's horizon_hours; 0 leaves Core's 48 h. horizonH int + // plannerSoCMin is the planner's soc_min (a fraction); 0 leaves Core's. + plannerSoCMin float64 + // startAfterS runs the house this long before FTW starts, as a site + // runs before Core boots; FTW's start is marked ftw_start. + startAfterS float64 } type stack struct { @@ -340,7 +347,7 @@ func (st *stack) houseSpec() houseSpec { h.Devices = append(h.Devices, houseDevice{ID: lpIDs[i], Driver: "ocpp", OCPPURL: fmt.Sprintf("ws://ftw:%s@127.0.0.1:%d/", ocppPass, st.lane.ftwOCPP()), MaxKW: kw, Vendor: "RigCo", Model: fmt.Sprintf("Rig%.0f", kw), PhaseSwitch: c.phaseSwitch, CommandResponseS: delay, - CarPhases: c.carPhases, CarMaxA: c.carMaxA, WiredPhases: c.wiredPhases, + CarPhases: c.carPhases, CarMaxA: c.carMaxA, WiredPhases: c.wiredPhases, Plugged: c.plugged, OCPPConfig: map[string]string{"HeartbeatInterval": "60", "MeterValueSampleInterval": "10"}}) } return h @@ -388,6 +395,10 @@ func (st *stack) up() error { return err } } + if st.spec.startAfterS > 0 { + sleepS(st.spec.startAfterS) + st.mark("ftw_start") + } if err := st.startFTW(); err != nil { return err } @@ -408,7 +419,9 @@ func (st *stack) startFTW() error { return waitHTTP(st.ftw+"/api/status", 90*time.Second) } -func (st *stack) stopFTW() { st.ps.stop("ftw", syscall.SIGTERM, 30*time.Second) } +// stopFTW stops FTW with sig: SIGTERM lets it clean up, SIGKILL is a power +// cut. +func (st *stack) stopFTW(sig syscall.Signal) { st.ps.stop("ftw", sig, 30*time.Second) } func (st *stack) down() { if st.rec != nil { @@ -566,6 +579,9 @@ func (st *stack) ftwConfig() (string, error) { if st.spec.horizonH > 0 { cfg["planner"].(map[string]any)["horizon_hours"] = st.spec.horizonH } + if st.spec.plannerSoCMin > 0 { + cfg["planner"].(map[string]any)["soc_min"] = st.spec.plannerSoCMin + } if st.spec.soc2Pct > 0 { cfg["drivers"] = append(cfg["drivers"].([]map[string]any), map[string]any{"name": "sungrow2", "lua": "drivers/sungrow.lua", "battery_capacity_wh": 10000, "capabilities": modbus("inverter2")}) diff --git a/go/test/site/verdicts_test.go b/go/test/site/verdicts_test.go index 9cb180db0..0920eefb9 100644 --- a/go/test/site/verdicts_test.go +++ b/go/test/site/verdicts_test.go @@ -3,7 +3,9 @@ package site import ( + "encoding/json" "math" + "path/filepath" "sort" ) @@ -551,3 +553,259 @@ func judgeS11(d *runData) (metrics, []criterion) { crit("fuse holds", !run["fuse_blown"].(bool)), } } + +// ---- R1-R5, the stable plan's P0 scenarios ---- + +// judgeR1: while the meter is silent Core raises nothing and its battery +// order only moves toward 0; within the 60 s watchdog and two ticks it +// stands the charger down and hands the battery back; it never shows the +// meter as live; Charge now returns after the meter does. +func judgeR1(d *runData) (metrics, []criterion) { + tCN, tS, tB, t1 := d.marks["charge_now"], d.marks["silent"], d.marks["back"], d.marks["end"] + tOff, tOn := d.marks["offline"], d.marks["online"] + var o0 float64 + if r := d.at(tS); r != nil { + o0 = batOrder(r) + } + wound := 0 + for _, r := range d.window(tS+2, tB) { + if o := batOrder(r); math.Abs(o) > math.Abs(o0)+50 || o*o0 < 0 { + wound++ + } + } + live := 0 + for _, w := range [][2]float64{{tS + 10, tB}, {tOff + 10, tOn}} { + for _, r := range d.window(w[0], w[1]) { + if dr, ok := status(r).Drivers["meter"]; ok && dr.Status == "ok" { + live++ + } + } + } + charging := func(r *sample) bool { return carW(r, 0) >= 0.95*minW } + standdown := d.firstOffer(tS, func(p profile) bool { return p.Limit == 0 }) + handBack := d.firstT(tS, func(r *sample) bool { return !batForced(r) }) + back1, back2 := d.firstT(tB, charging), d.firstT(tOn, charging) + rises := d.offerRises(tS, tB) + m := metrics{"battery_order_at_silence_w": math.Round(o0), "battery_wound_samples": wound, + "offer_rises_while_silent": rises, "standdown_s": roundp(standdown, 1), "battery_hand_back_s": roundp(handBack, 1), + "meter_live_while_stale_samples": live, "charge_now_back_s": []*float64{roundp(back1, 1), roundp(back2, 1)}} + return m, []criterion{ + crit("the battery relieved the fuse when the meter fell silent", o0 <= -500), // the setup + crit("no EV offer rises while the meter is silent", rises == 0), + crit("the battery order moves only toward 0 while the meter is silent", wound == 0), + crit("a 0 W charger order within 64 s of the silence", le(standdown, 64)), + crit("the battery back on its own within 64 s of the silence", le(handBack, 64)), + crit("the meter never shows live while it is silent or offline", live == 0), + crit("Charge now back at its minimum within 95 s of each return", le(back1, 95) && le(back2, 95)), + crit("fuse holds", !anyBlown(d.window(tCN, t1))), + } +} + +// judgeR2: when the battery that carried the car's room drops out, the fuse +// holds, the overage lasts no longer than the charger takes to answer, no +// offer counts the battery's last -3 kW as room, and Home use says it is +// estimated. +func judgeR2(d *runData) (metrics, []criterion) { + fuse, delay := d.metaF("fuse"), d.metaF("charger_delay_s") + tCN, tOff, tOn, t1 := d.marks["charge_now"], d.marks["offline"], d.marks["online"], d.marks["end"] + pre := meanOf(d.window(tOff-30, tOff), batSigned) + over, _ := d.runsOver(tOff, tOn+60, fuse-1) + during := summarize(d.window(tOff+15, tOn)) + marked := 0 + for k, v := range during.LoadQuality { + if k != "null" && k != "" && k != "measured" { + marked += v + } + } + allowed := delay + 7 + rises := d.offerRises(tOff, tOn) + m := metrics{"battery_w_before": math.Round(pre), "over_fuse_minus1_longest_s": over, "allowed_over_s": allowed, + "offer_rises_while_offline": rises, "during": during, + "max_i_after_drop": round(maxOf(d.window(tOff, tOn+60), maxAbsI), 2)} + return m, []criterion{ + crit("the battery discharged 2 kW or more before the drop", pre <= -2000), // the setup + crit("fuse holds", !anyBlown(d.window(tCN, t1))), + crit("over fuse - 1 A no longer than the charger's delay + 7 s after the drop", over <= allowed), + crit("no EV offer rises while the battery is offline", rises == 0), + crit("Home use shown as estimated throughout the outage", + during.Samples > 0 && during.LoadWShown == during.Samples && marked == during.Samples), + } +} + +// judgeR3: Core orders no discharge below the planner's floor, its battery +// order settles, and the car answers when the battery stops. +func judgeR3(d *runData) (metrics, []criterion) { + fuse, delay, floor := d.metaF("fuse"), d.metaF("charger_delay_s"), d.metaF("planner_floor_pct") + t0, tCN, t1 := d.marks["plug"], d.marks["charge_now"], d.marks["end"] + run := d.window(t0, t1) + below := 0 + for _, r := range run { + if batOrder(r) < -50 && r.Bat.SoCPct < floor-0.5 { + below++ + } + } + last := d.window(t1-300, t1) + swing := 0.0 + if len(last) > 0 { + lo, hi := math.Inf(1), math.Inf(-1) + for _, r := range last { + lo, hi = math.Min(lo, batOrder(r)), math.Max(hi, batOrder(r)) + } + swing = hi - lo + } + minSoC := minOf(run, func(r *sample) float64 { return r.Bat.SoCPct }) + // Once the car is the only lever, Core holds the worst phase at its own + // line, between fuse - 1 A and fuse - 0.5 A (see s3): the overage that + // counts is above fuse - 0.5 A; the one above fuse - 1 A is recorded. + over, _ := d.runsOver(tCN, t1, fuse-0.5) + over1, _ := d.runsOver(tCN, t1, fuse-1) + allowed := delay + 7 + m := metrics{"discharge_below_floor_samples": below, "battery_order_swing_last5min_w": math.Round(swing), + "soc_min_pct": round(minSoC, 2), "over_fuse_minus_half_longest_s": over, "over_fuse_minus1_longest_s": over1, + "allowed_over_s": allowed, "max_i": round(maxOf(run, maxAbsI), 2)} + return m, []criterion{ + crit("the battery reached the planner floor", len(run) > 0 && minSoC <= floor+0.5), // the setup + crit("no discharge ordered below the planner floor", below <= 10), + crit("the battery order swings at most 100 W over the last 5 min", len(last) > 0 && swing <= 100), + crit("over fuse - 0.5 A no longer than the charger's delay + 7 s", over <= allowed), + crit("fuse holds", !anyBlown(run)), + } +} + +// judgeR4: after each hard kill Charge now is back within a minute, the +// session energy counts again and state.db opens clean; the day's Home use +// survives the first kill. The second outage's 120 s would break the 10 % +// unknown-time rule on a run this short, so its day total is recorded only. +func judgeR4(d *runData) (metrics, []criterion) { + fuse := d.metaF("fuse") + tCN, k1, u1, k2, u2, t1 := d.marks["charge_now"], d.marks["kill1"], d.marks["up1"], d.marks["kill2"], d.marks["up2"], d.marks["end"] + charging := func(r *sample) bool { return carW(r, 0) >= 0.95*minW } + back1, back2 := d.firstT(u1, charging), d.firstT(u2, charging) + before, after := todayLoadWh(d.window(k1-30, k1)), todayLoadWh(d.window(u1, k2)) + nullAfter := 0 + for _, r := range d.window(u1, k2) { + if r.Status != nil && r.Status.Energy.Today.LoadWh == nil { + nullAfter++ + } + } + kept := before != nil && after != nil && nullAfter == 0 && *after >= 0.99**before + charger, _ := d.meta["charger"].(string) + session := func(t0, t1 float64) float64 { + v := 0.0 + for _, r := range d.window(t0, t1) { + if dr, ok := status(r).Drivers[charger]; ok && dr.EVSessionWh != nil { + v = math.Max(v, *dr.EVSessionWh) + } + } + return v + } + recovery := d.logLines("database corrupt", "INTEGRITY CHECK FAILED") + overAfter, _ := d.runsOver(u2, t1, fuse-1) + m := metrics{"charge_now_back_s": []*float64{roundp(back1, 1), roundp(back2, 1)}, + "today_load_wh_before_kill1": before, "today_load_wh_before_kill2": after, "today_load_wh_null_after_kill1": nullAfter, + "today_load_wh_end": todayLoadWh(d.window(u2, t1)), + "session_wh_before_kills": []float64{session(k1-30, k1), session(k2-30, k2)}, + "session_wh_90s_after_ups": []float64{session(u1, u1+90), session(u2, u2+90)}, + "recovery_log_lines": len(recovery), "over_fuse_minus1_longest_after_up2_s": overAfter} + return m, []criterion{ + crit("Charge now back at its minimum within 60 s of each restart", le(back1, 60) && le(back2, 60)), + crit("the day's Home use kept within 1 % across the first kill", kept), + crit("session energy counts again after each restart", session(u1, u1+90) > 0 && session(u2, u2+90) > 0), + crit("state.db opens with no recovery error", len(recovery) == 0), + crit("fuse holds", !anyBlown(d.window(tCN, t1))), + } +} + +// homeUseBack is the seconds from t0 to the first sample with Home use shown. +func (d *runData) homeUseBack(t0 float64) *float64 { + return d.firstT(t0, func(r *sample) bool { return status(r).LoadW != nil }) +} + +// judgeR5a: Core starting beside a car that already draws its maximum +// brings the site under the limit within 30 s and keeps it there. +func judgeR5a(d *runData) (metrics, []criterion) { + fuse := d.metaF("fuse") + tS, tUp, t1 := d.marks["ftw_start"], d.marks["ftw_up"], d.marks["end"] + pre := meanOf(d.window(tS-20, tS), func(r *sample) float64 { return carW(r, 0) }) + fit := d.firstT(tUp, func(r *sample) bool { return maxAbsI(r) <= fuse-1 }) + overAfter := 0.0 + if fit != nil { + overAfter, _ = d.runsOver(tUp+*fit, t1, fuse-1) + } + shown := d.homeUseBack(tUp) + m := metrics{"car_w_before_start": math.Round(pre), "under_limit_s": roundp(fit, 1), "over_after_that_longest_s": overAfter, + "home_use_shown_s": roundp(shown, 1), "max_i_before_start": round(maxOf(d.window(tS-20, tS), maxAbsI), 2)} + return m, []criterion{ + crit("the car charged before Core started", pre >= minW), // the setup + crit("under fuse - 1 A within 30 s of Core answering", le(fit, 30)), + crit("over fuse - 1 A at most 3 s once under it", fit != nil && overAfter <= 3), + crit("Home use shown within 30 s of Core answering", le(shown, 30)), + crit("fuse holds", !anyBlown(d.window(tS, t1))), + } +} + +// judgeR5b: a Core that starts on a stale plan orders no charge until a +// fresh plan asks for it, at least for its first 30 s. +func judgeR5b(d *runData) (metrics, []criterion) { + tS, tUp, t1 := d.marks["ftw_start"], d.marks["ftw_up"], d.marks["end"] + fresh, polls := math.Inf(1), 0 + readLines(filepath.Join(d.dir, "plan.jsonl"), func(b []byte) { + var l struct { + T float64 `json:"t"` + GeneratedAtMs int64 `json:"generated_at_ms"` + } + if json.Unmarshal(b, &l) != nil { + return + } + polls++ + if gen := float64(l.GeneratedAtMs) / 1000; gen >= tS { + fresh = math.Min(fresh, gen) + } + }) + early := 0 + for _, p := range d.offers() { + if p.T >= tS && p.T < tUp+30 && p.T < fresh && p.Limit > 0 { + early++ + } + } + shown := d.homeUseBack(tUp) + var freshS *float64 + if !math.IsInf(fresh, 1) { + v := round(fresh-tUp, 1) + freshS = &v + } + m := metrics{"plan_polls": polls, "fresh_plan_s": freshS, "positive_orders_before_fresh_plan": early, + "home_use_shown_s": roundp(shown, 1)} + return m, []criterion{ + crit("no positive EV order in the first 30 s without a fresh plan", early == 0), + crit("Home use shown within 30 s of Core answering", le(shown, 30)), + crit("fuse holds", !anyBlown(d.window(tS, t1))), + } +} + +// judgeR5c: Core starting into a session that began while it was away sees +// the car and shows Home use. Whether the new session keeps the old car's +// Charge now waits for the owner (ev-088): recorded, not judged. +func judgeR5c(d *runData) (metrics, []criterion) { + tS, tUp, t1 := d.marks["ftw_start"], d.marks["ftw_up"], d.marks["end"] + held, seen := 0, 0 + for _, r := range d.window(tUp+30, t1) { + if r.LPs == nil { + continue + } + seen++ + if firstLP(r).ManualActive { + held++ + } + } + plugged := d.firstT(tUp, func(r *sample) bool { return r.LPs != nil && firstLP(r).Plugged }) + shown := d.homeUseBack(tUp) + m := metrics{"charge_now_kept_samples": held, "samples": seen, "plugged_s": roundp(plugged, 1), + "home_use_shown_s": roundp(shown, 1), + "car_w_mean": math.Round(meanOf(d.window(tUp+30, t1), func(r *sample) float64 { return carW(r, 0) }))} + return m, []criterion{ + crit("Core sees the car plugged in within 60 s of answering", le(plugged, 60)), + crit("Home use shown within 30 s of Core answering", le(shown, 30)), + crit("fuse holds", !anyBlown(d.window(tS, t1))), + } +} From a840def5dd71e2c43681c9ece30047053947856e Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 14:26:19 +0100 Subject: [PATCH 03/68] fix(control): battery fuse guard reads each phase with its direction Delete perPhaseOverageW, perPhaseOverageReadingW and perPhaseReliefW. The battery fuse guard, the fuse saver and the forced discharge read the signed phase currents (phaseCurrentsA, with #1849's sum check and dead zone), count the batteries' own move on each phase, and relieve to the car's working limit, the fuse less max(1 A, safety_margin_a). Item A5 of the stable plan. Co-Authored-By: Claude Opus 5.5 --- .changeset/a5-battery-fuse-signed-phases.md | 5 + go/internal/control/dispatch.go | 231 +++++----------- .../control/ev_battery_priority_test.go | 5 +- .../control/ev_battery_sequence_test.go | 6 +- .../fuse_battery_phase_direction_test.go | 146 ++++++++++ go/internal/control/fuse_phase.go | 2 +- go/internal/control/fuse_saver_test.go | 126 ++++----- go/internal/control/golden_dump_test.go | 7 +- go/internal/control/peak_limit_test.go | 2 +- .../golden/early_exit_protections.json | 66 ++--- .../control/testdata/golden/seeded_fuse.json | 261 +++++++++--------- .../control/testdata/golden/slew_limiter.json | 10 +- .../testdata/golden/targeted_invariants.json | 24 +- 13 files changed, 477 insertions(+), 414 deletions(-) create mode 100644 .changeset/a5-battery-fuse-signed-phases.md create mode 100644 go/internal/control/fuse_battery_phase_direction_test.go diff --git a/.changeset/a5-battery-fuse-signed-phases.md b/.changeset/a5-battery-fuse-signed-phases.md new file mode 100644 index 000000000..9d5f66132 --- /dev/null +++ b/.changeset/a5-battery-fuse-signed-phases.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +The home battery now protects each fuse phase in the direction its current flows. It no longer discharges into a phase that already exports past the fuse, and no longer cuts a discharge that keeps an importing phase under it. It counts its own share of each phase, so it holds a steady relief instead of switching between full relief and none on every dispatch. It now relieves to the same limit the car uses: the fuse less 1 A, or less the safety margin when that is larger. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 3e01f1eea..ed19b5165 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -3592,7 +3592,7 @@ func applyFuseGuard(targets []DispatchTarget, store *telemetry.Store, state *Sta // replacement target would double-remove their contribution and miss // fuse overages. seenBat := make(map[string]struct{}, len(targets)) - var currentBat float64 + var currentBat, rawBat float64 for _, t := range targets { if _, seen := seenBat[t.Driver]; seen { continue @@ -3600,12 +3600,14 @@ func applyFuseGuard(targets []DispatchTarget, store *telemetry.Store, state *Sta seenBat[t.Driver] = struct{}{} if r := store.Get(t.Driver, telemetry.DerBattery); r != nil { currentBat += r.SmoothedW + rawBat += r.RawW } } var currentGrid float64 + var meter *telemetry.DerReading if siteMeter != "" { - if r := store.Get(siteMeter, telemetry.DerMeter); r != nil { - currentGrid = r.SmoothedW + if meter = store.Get(siteMeter, telemetry.DerMeter); meter != nil { + currentGrid = meter.SmoothedW } } var sumTarget float64 @@ -3614,22 +3616,9 @@ func applyFuseGuard(targets []DispatchTarget, store *telemetry.Store, state *Sta } predicted := currentGrid - currentBat + sumTarget - // Per-phase relief: the worst single-phase amperage above the fuse - // trip threshold (less the safety margin), converted by - // perPhaseReliefW into the AGGREGATE battery action needed to bring - // it back — the site's configured phase count does that conversion. - // - // This guard uses relief in BOTH directions. `perPhaseOverageW` is - // direction-agnostic — phase amps from the meter are absolute - // magnitudes. Attribute to whichever side the AGGREGATE METER is - // currently flowing (currentGrid), not to the post-target - // `predicted`. Per-phase amps and currentGrid are read from the - // same DerMeter sample, so they're internally consistent; - // `predicted` mixes in `sumTarget` (a hypothetical future state) - // and can swing across 0 on a large planner request, attributing - // a current-export overage to the import path (or vice versa) and - // pushing the grid further into the violating direction. - perPhase := perPhaseReliefW(store, state) + // Per phase, each way, once the targets replace the batteries' power + // in the same raw reading. + phaseImportW, phaseExportW := phaseFuseReliefW(meter, state, sumTarget-rawBat) // Aggregate budget honours the safety margin too — keep dispatch // commands strictly inside the breaker envelope so the inverter's // own per-phase limiter doesn't fire first and cause a flap. @@ -3641,19 +3630,8 @@ func applyFuseGuard(targets []DispatchTarget, store *telemetry.Store, state *Sta // (recurring Ferroamp 0x8030 fault). Both share one enforcement surface. effImportW := state.effectiveImportCeilingW(fuseMaxW) effExportW := state.effectiveExportCeilingW(fuseMaxW) - importOverage := predicted - effImportW - exportOverage := -effExportW - predicted - if perPhase > 0 { - if currentGrid >= 0 { - if perPhase > importOverage { - importOverage = perPhase - } - } else { - if perPhase > exportOverage { - exportOverage = perPhase - } - } - } + importOverage := math.Max(predicted-effImportW, phaseImportW) + exportOverage := math.Max(-effExportW-predicted, phaseExportW) out := make([]DispatchTarget, len(targets)) copy(out, targets) @@ -3844,106 +3822,55 @@ func (s *State) effectiveExportCeilingW(fuseMaxW float64) float64 { return eff } -// perPhaseOverageW returns the wattage by which the worst single phase -// exceeds the per-phase fuse amperage (less the safety margin). 0 when -// within limits, when per-phase data isn't available, or when the -// per-phase clamp is disabled (state.SiteFuseAmps == 0). The meter -// driver must emit l1_a / l2_a / l3_a in DerReading.Data — Pixii, -// Ferroamp, and Sungrow all do this today. -// -// Only the configured phases are read, in L1/L2/L3 order, matching -// sitePhaseCurrentsAt in cmd/ftw: a 1Φ site has no L2, so a stray -// l2_a in the meter payload is not a breaker this site owns. -// -// Same law as fuseSafetyMarginW: amps become watts only through the -// configured per-phase voltage. No hardcoded 230 V here — a site whose -// fuse description is incomplete gets no per-phase clamp rather than an -// invented one. Config fills both fields (fuse.voltage defaults to 230, -// fuse.phases to 3, and validation rejects <= 0), so this only affects -// harnesses that wire SiteFuseAmps alone. -// -// Direction-agnostic: phase amps from the meter are absolute magnitudes, -// so this function reports overage regardless of whether the breaker is -// being approached on the import or export side. The caller attributes -// the overage to whichever direction the aggregate grid is flowing. -func perPhaseOverageW(store *telemetry.Store, state *State) float64 { - if state == nil || state.SiteFuseAmps <= 0 || state.SiteMeterDriver == "" { - return 0 - } - r := store.Get(state.SiteMeterDriver, telemetry.DerMeter) - return perPhaseOverageReadingW(r, state) -} - -// perPhaseOverageReadingW is the snapshot form used when one control decision -// must keep the aggregate reading and its phase data from the same meter sample. -func perPhaseOverageReadingW(r *telemetry.DerReading, state *State) float64 { - if state == nil || state.SiteFuseAmps <= 0 || state.SiteFuseVoltage <= 0 || state.SiteFusePhases <= 0 { - return 0 - } - if r == nil || len(r.Data) == 0 { - return 0 - } - var d struct { - L1A *float64 `json:"l1_a"` - L2A *float64 `json:"l2_a"` - L3A *float64 `json:"l3_a"` - } - if err := json.Unmarshal(r.Data, &d); err != nil { - return 0 - } - // Use absolute magnitude — drivers like Pixii decode per-phase amps - // as signed i16, so export shows up as negative numbers and a naive - // `*p > maxA` walk starting from 0 leaves maxA = 0 (no fire) even - // when a phase is at -17 A. The fuse trips on current magnitude - // regardless of direction, and the caller attributes the overage - // to the active aggregate-grid direction. - phaseAmps := [...]*float64{d.L1A, d.L2A, d.L3A} - phases := state.SiteFusePhases - if phases > len(phaseAmps) { - phases = len(phaseAmps) - } - maxA := 0.0 - for i := 0; i < phases; i++ { - p := phaseAmps[i] - if p == nil { - continue - } - a := math.Abs(*p) - if a > maxA { - maxA = a - } - } - threshold := state.SiteFuseAmps - state.SiteFuseSafetyA - if threshold < 0 { - threshold = 0 - } - if maxA <= threshold { - return 0 - } - return (maxA - threshold) * state.SiteFuseVoltage -} - -// perPhaseReliefW converts a worst-phase overage into the AGGREGATE -// battery action needed to clear it. One conversion, one law: a battery -// spreads its action evenly across the site's phases, so each watt of -// aggregate action relieves 1/SiteFusePhases watts on the worst phase, -// and an overage of N watts needs N × SiteFusePhases watts of action. -// -// The phase count is the site's, from config — not the constant 3 the -// two call sites used to carry separately. On a 1Φ site the aggregate -// meter and the single phase are the same wire, so demanding 3 × N -// there overshoots by 2 × N and can push the grid through zero into a -// violation on the opposite side. +// phaseFuseReliefW is the aggregate battery move that brings every phase +// inside the working limit: the fuse less the car's 1 A margin, or less +// safety_margin_a when that is larger. importW asks for less charge or more +// discharge, exportW for the reverse. moveW is the batteries' change from +// the power this reading already holds; like the relief, it spreads evenly +// over the site's phases. // -// Conservative for a 1Φ battery on a 3Φ site (Pixii Home etc.): it -// over-corrects on the phases it does not sit on — less import/export -// there, still safe. -func perPhaseReliefW(store *telemetry.Store, state *State) float64 { - overage := perPhaseOverageW(store, state) - if overage <= 0 { - return 0 - } - return overage * float64(state.SiteFusePhases) +// The phases are the meter's signed currents (phaseCurrentsA). When no +// phase reads as export while the total does, the meter gives no direction +// per phase, and the phases take the total's. When no move fits every +// phase, the move leaves the worst phase least over, so a move never +// raises the current on the phase it protects. 0, 0 without usable phase +// currents. +func phaseFuseReliefW(meter *telemetry.DerReading, state *State, moveW float64) (importW, exportW float64) { + if meter == nil || state == nil { + return 0, 0 + } + amps, _, valid := phaseCurrentsA(meter, state, meter.RawW) + if !valid || len(amps) == 0 { + return 0, 0 + } + perA := state.SiteFuseVoltage * float64(state.SiteFusePhases) // aggregate W per phase ampere + limitA := math.Max(0, state.SiteFuseAmps-math.Max(evPhaseMarginA, state.SiteFuseSafetyA)) + exports := meter.RawW < 0 + for _, a := range amps { + exports = exports && a >= 0 + } + hi, lo := math.Inf(-1), math.Inf(1) + for _, a := range amps { + if exports { + a = -a + } + a += moveW / perA + hi, lo = math.Max(hi, a), math.Min(lo, a) + } + // The smallest shift that keeps every phase inside, or the middle one. + shiftA := math.Max(-limitA-lo, math.Min(0, limitA-hi)) + if -limitA-lo > limitA-hi { + shiftA = -(hi + lo) / 2 + } + importW, exportW = math.Max(0, -shiftA)*perA, math.Max(0, shiftA)*perA + // A target that fills the limit exactly can land a rounding error past it. + if importW < 1 { + importW = 0 + } + if exportW < 1 { + exportW = 0 + } + return importW, exportW } // applyPlanSignFloor enforces "executed battery total must agree in sign @@ -4431,7 +4358,7 @@ func fuseSaverFromLivePower( // site is safe. Preserve the deadband in that case: this early-return path // exists to answer a fuse condition, not to take control of an externally // moved battery merely because its reading sits outside a command cap. - requiredRelief := fuseReliefFromSnapshot(rawLive, batteryReadings, meter, state, fuseMaxW, false) + requiredRelief := fuseReliefFromSnapshot(rawLive, batteryReadings, meter, state, fuseMaxW) if requiredRelief <= 0 { return nil } @@ -4449,7 +4376,7 @@ func fuseSaverFromLivePower( if len(safeBaseline) == 0 { return nil } - out := forceFuseDischargeWithSnapshot(safeBaseline, batteryReadings, meter, state, driverCapacities, fuseMaxW, true) + out := forceFuseDischargeWithSnapshot(safeBaseline, batteryReadings, meter, state, driverCapacities, fuseMaxW) rawByDriver := make(map[string]DispatchTarget, len(rawLive)) for _, t := range rawLive { rawByDriver[t.Driver] = t @@ -4474,45 +4401,34 @@ func fuseReliefFromSnapshot( meter *telemetry.DerReading, state *State, fuseMaxW float64, - accountPhaseTargetDelta bool, ) float64 { if fuseMaxW <= 0 || len(targets) == 0 || state == nil { return 0 } - currentBat, sumTarget, predicted := predictedGridFromSnapshot(targets, batteryReadings, meter) - currentGrid := 0.0 - if meter != nil { - currentGrid = meter.SmoothedW - } + _, sumTarget, predicted := predictedGridFromSnapshot(targets, batteryReadings, meter) // The fuse acts on every reading. The hour's import limit is a budget: // the part of its overage that an EV cut we sent will remove waits for // that cut while the meter may not show it yet. Relief for the same watts // would discharge the battery into export once the cut lands (#1674). - // Per-phase relief remains fuse-only and may act only while the matching - // aggregate meter sample is on the import side. + // Per-phase relief is fuse-only. fuseW := math.Max(0, fuseMaxW-state.fuseSafetyMarginW()) overage := predicted - fuseW if ceilingW := state.effectiveImportCeilingW(fuseMaxW); ceilingW < fuseW { overage = math.Max(overage, predicted-ceilingW-state.pendingEVCutW()) } - if currentGrid >= 0 { - relief := perPhaseOverageReadingW(meter, state) * float64(state.SiteFusePhases) - if relief > 0 && accountPhaseTargetDelta { - // The early fuse baseline can only hold or reduce each included - // target. Count that import reduction against the raw phase relief so - // a command-cap clamp is not followed by the same correction twice. - relief += sumTarget - currentBat - if relief < 0 { - relief = 0 - } - } - if relief > overage { - overage = relief + // The phases are raw, so the batteries' move is from their raw power. + moveW := sumTarget + seen := make(map[string]bool, len(targets)) + for _, t := range targets { + if r := batteryReadings[t.Driver]; r != nil && !seen[t.Driver] { + moveW -= r.RawW } + seen[t.Driver] = true } - return overage + phaseW, _ := phaseFuseReliefW(meter, state, moveW) + return math.Max(overage, phaseW) } // predictedGridFromSnapshot holds non-targeted site power constant and replaces @@ -4564,7 +4480,7 @@ func forceFuseDischarge( readings[target.Driver] = store.Get(target.Driver, telemetry.DerBattery) } meter := store.Get(state.SiteMeterDriver, telemetry.DerMeter) - return forceFuseDischargeWithSnapshot(targets, readings, meter, state, driverCapacities, fuseMaxW, false) + return forceFuseDischargeWithSnapshot(targets, readings, meter, state, driverCapacities, fuseMaxW) } // forceFuseDischargeWithSnapshot keeps all math for one decision on the same @@ -4577,12 +4493,11 @@ func forceFuseDischargeWithSnapshot( state *State, driverCapacities map[string]float64, fuseMaxW float64, - accountPhaseTargetDelta bool, ) []DispatchTarget { if fuseMaxW <= 0 || len(targets) == 0 || state == nil { return targets } - overage := fuseReliefFromSnapshot(targets, batteryReadings, meter, state, fuseMaxW, accountPhaseTargetDelta) + overage := fuseReliefFromSnapshot(targets, batteryReadings, meter, state, fuseMaxW) if overage <= 0 { return targets } diff --git a/go/internal/control/ev_battery_priority_test.go b/go/internal/control/ev_battery_priority_test.go index f84b0d96c..582a67eee 100644 --- a/go/internal/control/ev_battery_priority_test.go +++ b/go/internal/control/ev_battery_priority_test.go @@ -47,7 +47,10 @@ func TestIssue1868BatteryChargeYieldsBeforeTheCar(t *testing.T) { if target.TargetW > 3931.001 { t.Fatalf("%s left the car's relief in the battery: %+v", mode, target) } - if mode == ModeCharge && target.TargetW < 3800 { + // Charge mode asks for a raise. The fuse guard caps it at L1's + // working limit less half the margin (3758.5 W), and the car's + // headroom then takes the same 69 W again. + if mode == ModeCharge && target.TargetW < 3600 { t.Fatalf("small overage needlessly stopped battery charging: %+v", target) } } diff --git a/go/internal/control/ev_battery_sequence_test.go b/go/internal/control/ev_battery_sequence_test.go index aa46d4acc..d94da1831 100644 --- a/go/internal/control/ev_battery_sequence_test.go +++ b/go/internal/control/ev_battery_sequence_test.go @@ -556,7 +556,7 @@ func TestFuseReliefLeavesOnlyCeilingWattsToCommandedEVCut(t *testing.T) { targets := []DispatchTarget{{Driver: "pixii"}} batteries := map[string]*telemetry.DerReading{"pixii": {}} meter := &telemetry.DerReading{SmoothedW: tc.gridW, Data: tc.data} - got := fuseReliefFromSnapshot(targets, batteries, meter, st, 17250, false) + got := fuseReliefFromSnapshot(targets, batteries, meter, st, 17250) if math.Abs(math.Max(0, got)-tc.wantW) > 1e-6 { t.Errorf("%s: relief %.0f W, want %.0f W", tc.name, got, tc.wantW) } @@ -597,7 +597,7 @@ func TestUnpluggedCarIsNoCutTheBatteryWaitsFor(t *testing.T) { st.SetEVCommanded(points) targets := []DispatchTarget{{Driver: "pixii"}} batteries := map[string]*telemetry.DerReading{"pixii": {}} - return math.Max(0, fuseReliefFromSnapshot(targets, batteries, &telemetry.DerReading{SmoothedW: gridW}, st, 17250, false)) + return math.Max(0, fuseReliefFromSnapshot(targets, batteries, &telemetry.DerReading{SmoothedW: gridW}, st, 17250)) } // 400 W over the ceiling, less than a step: the guard waits. if got := tick(7900, true, 5520); math.Abs(got-400) > 1e-6 { @@ -661,7 +661,7 @@ func TestCutOnStayingCarStillWaitsWhenAnotherLeaves(t *testing.T) { st.SetEVCommanded(points) targets := []DispatchTarget{{Driver: "pixii"}} batteries := map[string]*telemetry.DerReading{"pixii": {SmoothedW: batteryW}} - relief := fuseReliefFromSnapshot(targets, batteries, &telemetry.DerReading{SmoothedW: gridW}, st, 17250, false) + relief := fuseReliefFromSnapshot(targets, batteries, &telemetry.DerReading{SmoothedW: gridW}, st, 17250) batteryW = -math.Max(0, relief) // The battery follows within a tick. if batteryW < 0 && tick < 10 { t.Fatalf("%ds: battery %.0f W for watts a's stop removes; pending cut %.0f W", tick, batteryW, st.pendingEVCutW()) diff --git a/go/internal/control/fuse_battery_phase_direction_test.go b/go/internal/control/fuse_battery_phase_direction_test.go new file mode 100644 index 000000000..111c03ee3 --- /dev/null +++ b/go/internal/control/fuse_battery_phase_direction_test.go @@ -0,0 +1,146 @@ +package control + +import ( + "encoding/json" + "math" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// The battery fuse paths read each phase with its direction and count the +// batteries' own move. 16 A fuse, 230 V, 3 phases; the working limit is +// 15 A. + +func phaseDirectionStore(t *testing.T, gridW, batW float64, data map[string]any) *telemetry.Store { + t.Helper() + s := telemetry.NewStore() + raw, err := json.Marshal(data) + if err != nil { + t.Fatal(err) + } + s.Update("meter", telemetry.DerMeter, gridW, nil, raw) + s.DriverHealthMut("meter").RecordSuccess() + soc := 0.6 + s.Update("bat", telemetry.DerBattery, batW, &soc, nil) + s.DriverHealthMut("bat").RecordSuccess() + return s +} + +func phaseDirectionState(safetyA float64) *State { + st := NewState(0, 50, "meter") + st.SiteFuseAmps, st.SiteFuseVoltage, st.SiteFusePhases, st.SiteFuseSafetyA = 16, 230, 3, safetyA + st.DriverLimits = map[string]PowerLimits{"bat": {MaxChargeW: 10000, MaxDischargeW: 10000}} + return st +} + +// L1 exports 20 A, L2/L3 import 12 A, the total imports 920 W. No phase +// imports over the limit, and a discharge adds export on L1. +var exportingL1 = map[string]any{"l1_a": 20.0, "l2_a": 12.0, "l3_a": 12.0, + "l1_w": -4600.0, "l2_w": 2760.0, "l3_w": 2760.0} + +func TestFuseSaverDoesNotDischargeIntoExportingPhase(t *testing.T) { + store := phaseDirectionStore(t, 920, 0, exportingL1) + out := fuseSaverFromLivePower(store, phaseDirectionState(0.5), map[string]float64{"bat": 15200}, 16*230*3) + for _, o := range out { + if o.TargetW < 0 { + t.Fatalf("fuse saver ordered %.0f W discharge; L1 export 20.0 A -> %.1f A on a 16 A fuse", o.TargetW, 20+(-o.TargetW)/690) + } + } +} + +func TestIdleDispatchDoesNotDischargeIntoExportingPhase(t *testing.T) { + store := phaseDirectionStore(t, 920, 0, exportingL1) + st := phaseDirectionState(0.5) + st.Mode = ModeIdle + out := ComputeDispatch(store, st, map[string]float64{"bat": 15200}, 16*230*3) + for _, o := range out { + if o.TargetW < 0 { + t.Fatalf("Idle ComputeDispatch ordered %.0f W discharge; L1 export 20.0 A -> %.1f A", o.TargetW, 20+(-o.TargetW)/690) + } + } +} + +// L1 imports 22 A, L2/L3 export 15 A, the battery discharges 3 kW and the +// total exports. Cutting the discharge raises L1's import. +func TestFuseGuardKeepsDischargeThatRelievesImportingPhase(t *testing.T) { + store := phaseDirectionStore(t, (22-30)*230, -3000, map[string]any{ + "l1_a": 22.0, "l2_a": 15.0, "l3_a": 15.0, + "l1_w": 5060.0, "l2_w": -3450.0, "l3_w": -3450.0}) + st := phaseDirectionState(0.5) + out := applyFuseGuard([]DispatchTarget{{Driver: "bat", TargetW: -3000}}, store, st, 16*230*3) + if out[0].TargetW > -3000+1 { + t.Fatalf("fuse guard cut discharge -3000 -> %.0f W; L1 import 22.0 -> %.1f A; hold max discharge %.0f W until +%v", + out[0].TargetW, 22+(out[0].TargetW+3000)/690, st.FuseHoldMaxDischargeW, st.FuseHoldUntil.Sub(st.now())) + } +} + +// L1 exports 18 A (one-phase PV), L2/L3 import 14 A, the total imports +// 2300 W. Charging relieves L1 and loads L2/L3. +var exportingL1Charge = map[string]any{"l1_a": 18.0, "l2_a": 14.0, "l3_a": 14.0, + "l1_w": -4140.0, "l2_w": 3220.0, "l3_w": 3220.0} + +func TestFuseSaverIgnoresExportingPhaseUnderImportTotal(t *testing.T) { + store := phaseDirectionStore(t, 2300, 0, exportingL1Charge) + if out := fuseSaverFromLivePower(store, phaseDirectionState(0), map[string]float64{"bat": 15200}, 11040); out != nil { + t.Errorf("fuseSaverFromLivePower = %.0f W; discharging pushes exporting L1 further past the fuse", out[0].TargetW) + } +} + +// No charge fits both sides: 3000 W takes L2/L3 to 18.3 A, none leaves L1 +// at 18 A of export. The guard leaves the charge where the worst phase is +// least over: 1380 W, with every phase at 16 A. +func TestFuseGuardChargeBalancesExportingAndImportingPhases(t *testing.T) { + store := phaseDirectionStore(t, 2300, 0, exportingL1Charge) + got := applyFuseGuard([]DispatchTarget{{Driver: "bat", TargetW: 3000}}, store, phaseDirectionState(0), 11040) + l1, l2 := -18+got[0].TargetW/690, 14+got[0].TargetW/690 + if worst := math.Max(math.Abs(l1), math.Abs(l2)); worst > 16.01 { + t.Errorf("applyFuseGuard charge 3000 -> %.0f W leaves L1 %.2f A, L2/L3 %.2f A; want every phase at or below 16 A", got[0].TargetW, l1, l2) + } +} + +// The relief counts the battery's own share of the phase it reads. A +// battery that follows its order keeps L1 at the working limit on every +// tick instead of returning to 0 W when the overage stops showing. +func TestPerPhaseFuseReliefHoldsWhileOverloadPersists(t *testing.T) { + st := phaseDirectionState(0.5) + st.Mode = ModeIdle + now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) + st.clock = func() time.Time { return now } + + store := telemetry.NewStore() + house := [3]float64{20, 5, 5} // A per phase, import + batW := 0.0 // battery follows its last order within a tick + caps := map[string]float64{"bat": 15200} + var targets, l1 []float64 + for tick := 0; tick < 10; tick++ { + a := house + for i := range a { + a[i] += batW / (230 * 3) // a three-phase battery spreads evenly + } + raw, _ := json.Marshal(map[string]any{"l1_a": a[0], "l2_a": a[1], "l3_a": a[2]}) + store.Update("meter", telemetry.DerMeter, (a[0]+a[1]+a[2])*230, nil, raw) + store.DriverHealthMut("meter").RecordSuccess() + soc := 0.6 + store.Update("bat", telemetry.DerBattery, batW, &soc, nil) + store.DriverHealthMut("bat").RecordSuccess() + + out := ComputeDispatch(store, st, caps, 16*230*3) + w := 0.0 + for _, o := range out { + if o.Driver == "bat" { + w = o.TargetW + } + } + targets = append(targets, math.Round(w)) + l1 = append(l1, math.Round(a[0]*10)/10) + batW = w + now = now.Add(5 * time.Second) + } + for i := 1; i < len(l1); i++ { + if l1[i] > 15 { + t.Fatalf("tick %d: L1 %.1f A over the 15 A working limit while the overload persists; targets %v, L1 %v", i, l1[i], targets, l1) + } + } +} diff --git a/go/internal/control/fuse_phase.go b/go/internal/control/fuse_phase.go index da041b83e..cf70ef9c3 100644 --- a/go/internal/control/fuse_phase.go +++ b/go/internal/control/fuse_phase.go @@ -17,7 +17,7 @@ import ( // Meters report phase magnitudes, so the mean uses |aggregate|. Phases // flowing in opposite directions make the gap look smaller than it is; the // per-phase fuse guards still act on a real overage. A single-phase battery -// or charger is outside this model, as it is for perPhaseReliefW. +// or charger is outside this model, as it is for phaseFuseReliefW. func phaseImbalanceA(r *telemetry.DerReading, state *State) (float64, bool) { if state == nil || state.SiteFuseAmps <= 0 || state.SiteFuseVoltage <= 0 || state.SiteFusePhases <= 1 { return 0, false diff --git a/go/internal/control/fuse_saver_test.go b/go/internal/control/fuse_saver_test.go index 0e2f48476..205e25505 100644 --- a/go/internal/control/fuse_saver_test.go +++ b/go/internal/control/fuse_saver_test.go @@ -300,19 +300,19 @@ func setupPerPhaseSite(phases int, voltage float64, aggGridW float64, l1A, l2A, func TestPerPhaseClampScalesChargingOnImbalance(t *testing.T) { // Isolate the per-phase case: aggregate predicted (7000 + 4000 = // 11000 W) is under the 11040 W fuse, so the legacy aggregate - // branch wouldn't fire. But L1 alone is at 18 A × 230 V = 4140 W - // (over the 16 A fuse on that phase) — only the per-phase clamp - // can catch it. - store, state, _ := setupPerPhase(7000, 18, 12, 8, 0.6, 10000) + // branch wouldn't fire. But the 4000 W charge adds 4000 / 690 = + // 5.8 A to each phase, which takes L1 from 13 A to 18.8 A, over the + // 15 A working limit (16 A fuse less 1 A) — only the per-phase + // clamp can catch it. + store, state, _ := setupPerPhase(7000, 13, 12, 8, 0.6, 10000) targets := []DispatchTarget{{Driver: "bat", TargetW: 4000}} guarded := applyFuseGuard(targets, store, state, 11040) if !guarded[0].Clamped { t.Errorf("Clamped flag must mark per-phase response") } - // Per-phase overage = (18 − 16) × 230 = 460 W on the worst phase. - // Balanced-3Φ assumption ⇒ 460 × 3 = 1380 W of total battery - // reduction needed. Charge 4000 → 4000 − 1380 = 2620 W. - expected := 2620.0 + // L1 has (15 − 13) × 690 = 1380 W of room for a balanced-3Φ + // charge. Charge 4000 → 1380 W. + expected := 1380.0 if math.Abs(guarded[0].TargetW-expected) > 1 { t.Errorf("charge after per-phase clamp = %.0f W, want %.0f W", guarded[0].TargetW, expected) @@ -333,9 +333,9 @@ func TestPerPhaseClampFiresFuseSaverFromIdle(t *testing.T) { if out[0].TargetW >= 0 { t.Errorf("expected discharge target, got %.0f W", out[0].TargetW) } - // Same math as the charging test: 460 W × 3 = 1380 W. From idle - // (target 0), full discharge of 1380 W. - expected := -1380.0 + // L1 is (18 − 15) A over the working limit: 3 × 690 = 2070 W of + // discharge from idle. + expected := -2070.0 if math.Abs(out[0].TargetW-expected) > 1 { t.Errorf("forced discharge = %.0f W, want %.0f W", out[0].TargetW, expected) } @@ -365,13 +365,14 @@ func TestPerPhaseClampDisabledWhenSiteFuseAmpsZero(t *testing.T) { // huge imbalance, per-phase × 3 dominates. func TestPerPhaseClampDominatesAggregateWhenLarger(t *testing.T) { // Aggregate over by 500 W (predicted = 11540 vs 11040). But L1 is - // at 22 A → over by 6 A × 230 = 1380 W per-phase × 3 = 4140 W. + // at 22 A → over the 15 A working limit by 7 A × 230 = 1610 W + // per-phase × 3 = 4830 W. store, state, caps := setupPerPhase(11540, 22, 14, 8, 0.6, 10000) out := fuseSaverFromLivePower(store, state, caps, 11040) if out == nil { t.Fatalf("expected discharge, got nil") } - expected := -4140.0 + expected := -4830.0 if math.Abs(out[0].TargetW-expected) > 1 { t.Errorf("forced discharge = %.0f W, want %.0f W (per-phase × 3)", out[0].TargetW, expected) @@ -384,11 +385,12 @@ func TestPerPhaseClampDominatesAggregateWhenLarger(t *testing.T) { // trigger forceFuseDischarge, which would push more power out and // worsen the over-current phase. Regression for PR #219 review S1. func TestPerPhaseClampFiresOnExportImbalance(t *testing.T) { - // Aggregate gridW = -7000 W (heavy export). Phases (magnitude): - // L2 = 18 A (over the 16 A fuse), L1 = 12, L3 = 8. Per-phase - // overage = (18 − 16) × 230 × 3 = 1380 W of discharge to shrink. - // Battery is currently discharging −5000 W; the target reduces - // magnitude to bring L2 back under fuse. + // Aggregate gridW = -7000 W (heavy export). Phases (magnitude, no + // phase power, so they take the total's direction): L2 = 18 A (over + // the 15 A working limit), L1 = 12, L3 = 8. Per-phase overage = + // (18 − 15) × 230 × 3 = 2070 W of discharge to shrink. Battery is + // currently discharging −5000 W; the target reduces magnitude to + // bring L2 back under the limit. store, state, _ := setupPerPhase(-7000, 12, 18, 8, 0.6, 10000) // Set the live battery reading so applyFuseGuard's "predicted" // reflects the current discharge state. @@ -401,8 +403,8 @@ func TestPerPhaseClampFiresOnExportImbalance(t *testing.T) { if !guarded[0].Clamped { t.Errorf("export-side per-phase overage must clamp the discharge target") } - // New discharge magnitude: 5000 − 1380 = 3620 W → target = −3620 W. - expected := -3620.0 + // New discharge magnitude: 5000 − 2070 = 2930 W → target = −2930 W. + expected := -2930.0 if math.Abs(guarded[0].TargetW-expected) > 1 { t.Errorf("discharge after export-side per-phase clamp = %.0f W, want %.0f W", guarded[0].TargetW, expected) @@ -460,43 +462,42 @@ func TestForceFuseDischargeIgnoresExportSidePerPhase(t *testing.T) { // inverter's own per-phase limiter trips first and causes a flap). // Regression for PR #219 — the bug class motivating the safety margin. func TestPerPhaseClampHonorsSafetyMargin(t *testing.T) { - // Phases (15.5, 12, 8). MaxAmps = 16, SafetyA = 1.0 → effective - // threshold = 15 A. L1 at 15.5 A is OVER the effective threshold - // (under the raw 16 A). Per-phase overage = (15.5 − 15) × 230 × 3 - // = 345 W of charge to shrink. - store, state, _ := setupPerPhase(7000, 15.5, 12, 8, 0.6, 10000) - state.SiteFuseSafetyA = 1.0 + // Phases (10, 7, 5). MaxAmps = 16, SafetyA = 2.0 → effective + // threshold = 14 A, below the 1 A working margin's 15 A. The + // 4000 W charge adds 5.8 A per phase, so L1 reaches 15.8 A: over + // 14 A by 1.8 A, 1240 W of charge to shrink. Without the margin it + // would be 550 W. + store, state, _ := setupPerPhase(5000, 10, 7, 5, 0.6, 10000) + state.SiteFuseSafetyA = 2.0 state.SiteFusePhases = 3 targets := []DispatchTarget{{Driver: "bat", TargetW: 4000}} guarded := applyFuseGuard(targets, store, state, 11040) if !guarded[0].Clamped { - t.Errorf("safety margin should pull the threshold under L1 = 15.5 A") - } - // Aggregate effFuseW = 11040 − 1.0×230×3 = 10350. Predicted = - // 7000 + 4000 − 0 = 11000 → aggregate overage = 11000 − 10350 = 650. - // Per-phase overage × 3 = 345. Aggregate wins (650 > 345). - // Buffer = half-margin = 0.5×1×230×3 = 345 W (post-fix headroom). - // Charge 4000 − 650 − 345 = 3005. - expected := 3005.0 + t.Errorf("safety margin should pull the threshold under L1") + } + // Aggregate effFuseW = 11040 − 2×230×3 = 9660. Predicted = + // 5000 + 4000 − 0 = 9000 → no aggregate overage. Per-phase wins. + // Buffer = half-margin = 0.5×2×230×3 = 690 W (post-fix headroom). + // Charge 4000 − 1240 − 690 = 2070. + expected := 2070.0 if math.Abs(guarded[0].TargetW-expected) > 1 { t.Errorf("charge after safety-margin clamp = %.0f W, want %.0f W", guarded[0].TargetW, expected) } } -// SafetyMarginA = 0 must produce identical output to the pre-PR -// behaviour (locks the back-compat contract every existing per-phase -// test relies on by leaving the field unset). +// SafetyMarginA = 0 keeps the 1 A working margin the car uses (every +// existing per-phase test relies on it by leaving the field unset). func TestPerPhaseClampSafetyMarginZeroIsBackCompat(t *testing.T) { - store, state, _ := setupPerPhase(7000, 18, 12, 8, 0.6, 10000) + store, state, _ := setupPerPhase(7000, 13, 12, 8, 0.6, 10000) state.SiteFuseSafetyA = 0 state.SiteFusePhases = 3 targets := []DispatchTarget{{Driver: "bat", TargetW: 4000}} guarded := applyFuseGuard(targets, store, state, 11040) // Same math as TestPerPhaseClampScalesChargingOnImbalance. - expected := 2620.0 + expected := 1380.0 if math.Abs(guarded[0].TargetW-expected) > 1 { - t.Errorf("safety_margin_a=0 must match pre-PR behaviour: got %.0f W, want %.0f W", + t.Errorf("safety_margin_a=0 must keep the 1 A working margin: got %.0f W, want %.0f W", guarded[0].TargetW, expected) } } @@ -508,9 +509,9 @@ func TestPerPhaseClampSafetyMarginZeroIsBackCompat(t *testing.T) { // phase count, and on a 1Φ site the aggregate meter and the single // phase are the same wire — relief there is 1 × the overage, not 3 ×. // -// A 1Φ site at 24 A on a 16 A fuse (0.5 A margin ⇒ 15.5 A threshold, -// 230 V): fuse budget 3680 W, aggregate ceiling 3565 W, meter at -// 5520 W. Worst-phase overage = (24 − 15.5) × 230 = 1955 W, which on +// A 1Φ site at 24 A on a 16 A fuse (1 A margin ⇒ 15 A threshold, +// 230 V): fuse budget 3680 W, aggregate ceiling 3450 W, meter at +// 5520 W. Worst-phase overage = (24 − 15) × 230 = 2070 W, which on // this site is also exactly the aggregate overage — the two numbers // must agree when there is only one phase. @@ -518,21 +519,21 @@ func TestPerPhaseClampSafetyMarginZeroIsBackCompat(t *testing.T) { // once, and leaves the meter on the import side of zero. func TestPerPhaseReliefMatchesSinglePhaseSiteOnImport(t *testing.T) { store, state, caps := setupPerPhaseSite(1, 230, 5520, 24, 0, 0, 0.6, 10000) - state.SiteFuseSafetyA = 0.5 + state.SiteFuseSafetyA = 1 fuseMaxW := 16 * 230.0 * 1 out := fuseSaverFromLivePower(store, state, caps, fuseMaxW) if out == nil { t.Fatalf("1Φ site at 24 A on a 16 A fuse: expected a forced discharge") } - expected := -1955.0 + expected := -2070.0 if math.Abs(out[0].TargetW-expected) > 1 { t.Fatalf("forced discharge = %.0f W, want %.0f W (overage × 1 phase, "+ "not × 3)", out[0].TargetW, expected) } // The site has one phase, so the post-dispatch meter is that - // phase. Demanding 3 × 1955 W would have driven 5520 W of import - // to 345 W of export: relief the site never needed, pushing the + // phase. Demanding 3 × 2070 W would have driven 5520 W of import + // to 690 W of export: relief the site never needed, pushing the // same breaker up the other way. if postGridW := 5520 + out[0].TargetW; postGridW < 0 { t.Errorf("post-dispatch grid = %.0f W: relief overshot through zero "+ @@ -547,7 +548,7 @@ func TestPerPhaseReliefMatchesSinglePhaseSiteOnExport(t *testing.T) { // Meter magnitudes mirror the import case: 5520 W out, 24 A on the // one phase. Pixii-style signed per-phase amps, so L1 reads −24. store, state, _ := setupPerPhaseSite(1, 230, -5520, -24, 0, 0, 0.6, 10000) - state.SiteFuseSafetyA = 0.5 + state.SiteFuseSafetyA = 1 fuseMaxW := 16 * 230.0 * 1 // The battery is already discharging what the meter shows, and the @@ -560,10 +561,10 @@ func TestPerPhaseReliefMatchesSinglePhaseSiteOnExport(t *testing.T) { if !guarded[0].Clamped { t.Fatalf("export-side per-phase overage must clamp the discharge target") } - // Discharge 5000 − overage 1955 − buffer (half the 115 W margin) - // = 2987.5 W. Demanding 1955 × 3 leaves nothing: the discharge is + // Discharge 5000 − overage 2070 − buffer (half the 230 W margin) + // = 2815 W. Demanding 2070 × 3 leaves nothing: the discharge is // zeroed and the site swings to 520 W of import. - expected := -2987.5 + expected := -2815.0 if math.Abs(guarded[0].TargetW-expected) > 1 { t.Errorf("discharge after 1Φ export clamp = %.1f W, want %.1f W", guarded[0].TargetW, expected) @@ -599,15 +600,15 @@ func TestPerPhaseClampReadsConfiguredPhasesOnly(t *testing.T) { // Per-phase watts come from the configured voltage, the same source // fuseSafetyMarginW uses. A 240 V site converts its amps at 240 V. func TestPerPhaseClampUsesConfiguredVoltage(t *testing.T) { - store, state, _ := setupPerPhaseSite(3, 240, 7000, 18, 12, 8, 0.6, 10000) + store, state, _ := setupPerPhaseSite(3, 240, 7000, 13, 12, 8, 0.6, 10000) targets := []DispatchTarget{{Driver: "bat", TargetW: 4000}} guarded := applyFuseGuard(targets, store, state, 16*240.0*3) if !guarded[0].Clamped { - t.Fatalf("L1 at 18 A on a 16 A fuse must clamp") + t.Fatalf("a 4000 W charge on L1 at 13 A on a 16 A fuse must clamp") } - // (18 − 16) × 240 = 480 W per phase × 3 = 1440 W of relief. - // Charge 4000 → 2560. At the old hardcoded 230 V it would be 2620. - expected := 2560.0 + // L1 has (15 − 13) A of room below the working limit: 2 × 240 × 3 + // = 1440 W of charge. At the old hardcoded 230 V it would be 1380. + expected := 1440.0 if math.Abs(guarded[0].TargetW-expected) > 1 { t.Errorf("charge after per-phase clamp on a 240 V site = %.0f W, "+ "want %.0f W", guarded[0].TargetW, expected) @@ -914,9 +915,10 @@ func TestDeadbandExitDefendsPerPhaseBreaker(t *testing.T) { t.Fatalf("L1 at 18 A on a 16 A fuse inside the aggregate deadband: " + "expected a forced discharge, got no targets") } - // Per-phase overage = (18 − 16) × 230 = 460 W on the worst phase, - // × 3 under the balanced-3Φ assumption = 1380 W from idle. - expected := -1380.0 + // Per-phase overage = (18 − 15) × 230 = 690 W over the working + // limit on the worst phase, × 3 under the balanced-3Φ assumption + // = 2070 W from idle. + expected := -2070.0 if math.Abs(out[0].TargetW-expected) > 1 { t.Errorf("forced discharge = %.0f W, want %.0f W", out[0].TargetW, expected) } @@ -932,7 +934,7 @@ func TestDeadbandExitPerPhaseReliefPreservesLiveDischarge(t *testing.T) { const ( liveBatteryW = -5000.0 liveWorstA = 18.0 - fuseA = 16.0 + fuseA = 15.0 // 16 A fuse less the 1 A working margin phases = 3.0 voltage = 230.0 ) @@ -969,7 +971,7 @@ func TestDeadbandExitPerPhaseReliefStartsFromLiveCharge(t *testing.T) { const ( liveBatteryW = 5000.0 liveWorstA = 18.0 - fuseA = 16.0 + fuseA = 15.0 // 16 A fuse less the 1 A working margin phases = 3.0 voltage = 230.0 ) @@ -1380,7 +1382,7 @@ func TestDeadbandExitUsesOnlyRemainingPerPhaseReliefAfterChargeCap(t *testing.T) liveBatteryW = 5000.0 maxChargeW = 4500.0 liveWorstA = 18.0 - fuseA = 16.0 + fuseA = 15.0 // 16 A fuse less the 1 A working margin phaseReliefW = (liveWorstA - fuseA) * 230 * 3 ) store, state, caps := setupPerPhase(0, liveWorstA, 4, 4, 0.6, 10000) diff --git a/go/internal/control/golden_dump_test.go b/go/internal/control/golden_dump_test.go index ae96c9960..32636555b 100644 --- a/go/internal/control/golden_dump_test.go +++ b/go/internal/control/golden_dump_test.go @@ -331,7 +331,12 @@ func runGoldenScenarioAt(sc goldenScenario, scenarioNow time.Time, slotDirective // Pre-dispatch attribution reads (pure). intent := planSignIntent(st) - perPhase := perPhaseOverageW(store, st) + // The worst phase's overage either way, in watts on that phase. + var perPhase float64 + importW, exportW := phaseFuseReliefW(store.Get(st.SiteMeterDriver, telemetry.DerMeter), st, 0) + if st.SiteFusePhases > 0 { + perPhase = math.Max(importW, exportW) / float64(st.SiteFusePhases) + } effImp := st.effectiveImportCeilingW(sc.Inputs.FuseMaxW) effExp := st.effectiveExportCeilingW(sc.Inputs.FuseMaxW) diff --git a/go/internal/control/peak_limit_test.go b/go/internal/control/peak_limit_test.go index 596212a4e..d8a7be220 100644 --- a/go/internal/control/peak_limit_test.go +++ b/go/internal/control/peak_limit_test.go @@ -122,7 +122,7 @@ func TestSetPeakLimitRejectsNonFinite(t *testing.T) { } // An undescribed fuse yields no ceiling rather than an invented one — -// the same back-compat rule fuseSafetyMarginW and perPhaseOverageW keep +// the same back-compat rule fuseSafetyMarginW and phaseFuseReliefW keep // for harnesses that wire only some of the fuse fields. func TestSetPeakLimitWithoutFuseChecksOnlyTheSign(t *testing.T) { st := NewState(0, 50, "ferroamp") // no SiteFuse* wired diff --git a/go/internal/control/testdata/golden/early_exit_protections.json b/go/internal/control/testdata/golden/early_exit_protections.json index e1147757e..6344bac47 100644 --- a/go/internal/control/testdata/golden/early_exit_protections.json +++ b/go/internal/control/testdata/golden/early_exit_protections.json @@ -1,7 +1,7 @@ { "family": "early_exit_protections", "generated_by": "FTW_GOLDEN_DUMP=1 go test ./internal/control/ -run TestGoldenDump", - "ftw_commit": "68c5b6125898bb9da70728b8921259c87e96171d", + "ftw_commit": "83c2b24ccdb730278a9c4e6ef778bab5f9499167", "record_count": 21, "records": [ { @@ -519,7 +519,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1380, + "target_w": -2070, "clamped": true } ], @@ -536,7 +536,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 460, + "per_phase_overage_w": 690, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -544,9 +544,9 @@ }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -1380, + "battery_target_sum_w": -2070, "raw_grid_w": 0, - "projected_grid_w": -1380 + "projected_grid_w": -2070 } }, { @@ -775,7 +775,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 2300, + "per_phase_overage_w": 2530, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -841,7 +841,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1610, + "target_w": -1840, "clamped": true } ], @@ -858,17 +858,17 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1610, + "per_phase_overage_w": 1840, "effective_import_ceiling_w": 5750, "effective_export_ceiling_w": 5750, - "import_ceiling_binding": true, + "import_ceiling_binding": false, "export_ceiling_binding": false }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -1610, + "battery_target_sum_w": -1840, "raw_grid_w": 7360, - "projected_grid_w": 5750 + "projected_grid_w": 5520 } }, { @@ -1009,7 +1009,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -2070, + "target_w": -2760, "clamped": true } ], @@ -1026,7 +1026,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 690, + "per_phase_overage_w": 920, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -1034,9 +1034,9 @@ }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -2070, + "battery_target_sum_w": -2760, "raw_grid_w": 20, - "projected_grid_w": -2050 + "projected_grid_w": -2740 } }, { @@ -1170,7 +1170,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -2760, + "target_w": -3450, "clamped": true } ], @@ -1187,7 +1187,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 920, + "per_phase_overage_w": 1150, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -1195,9 +1195,9 @@ }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -2760, + "battery_target_sum_w": -3450, "raw_grid_w": 1000, - "projected_grid_w": -1760 + "projected_grid_w": -2450 } }, { @@ -1253,7 +1253,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1150, + "target_w": -1380, "clamped": true } ], @@ -1270,17 +1270,17 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1150, + "per_phase_overage_w": 1380, "effective_import_ceiling_w": 5750, "effective_export_ceiling_w": 5750, - "import_ceiling_binding": true, + "import_ceiling_binding": false, "export_ceiling_binding": false }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -1150, + "battery_target_sum_w": -1380, "raw_grid_w": 6900, - "projected_grid_w": 5750 + "projected_grid_w": 5520 } }, { @@ -1495,7 +1495,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -3450, + "target_w": -4140, "clamped": true } ], @@ -1512,7 +1512,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1150, + "per_phase_overage_w": 1380, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -1520,9 +1520,9 @@ }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -3450, + "battery_target_sum_w": -4140, "raw_grid_w": 2000, - "projected_grid_w": -1450 + "projected_grid_w": -2140 } }, { @@ -1578,7 +1578,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1610, + "target_w": -1840, "clamped": true } ], @@ -1595,17 +1595,17 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1610, + "per_phase_overage_w": 1840, "effective_import_ceiling_w": 5750, "effective_export_ceiling_w": 5750, - "import_ceiling_binding": true, + "import_ceiling_binding": false, "export_ceiling_binding": false }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -1610, + "battery_target_sum_w": -1840, "raw_grid_w": 7360, - "projected_grid_w": 5750 + "projected_grid_w": 5520 } }, { diff --git a/go/internal/control/testdata/golden/seeded_fuse.json b/go/internal/control/testdata/golden/seeded_fuse.json index 0100f4d67..9862640e4 100644 --- a/go/internal/control/testdata/golden/seeded_fuse.json +++ b/go/internal/control/testdata/golden/seeded_fuse.json @@ -1,7 +1,7 @@ { "family": "seeded_fuse", "generated_by": "FTW_GOLDEN_DUMP=1 go test ./internal/control/ -run TestGoldenDump", - "ftw_commit": "303f86818a95f056f68e0b652db131a33074a421", + "ftw_commit": "83c2b24ccdb730278a9c4e6ef778bab5f9499167", "record_count": 80, "records": [ { @@ -69,20 +69,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -3245.228082551051, - "clamped": true + "target_w": -1530.5555555555554, + "clamped": false }, { "driver": "sungrow", - "target_w": -3647.771917448948, - "clamped": true + "target_w": -2326.4444444444443, + "clamped": false } ], "clamp_attributions": { - "clamped_drivers": [ - "ferroamp", - "sungrow" - ], + "clamped_drivers": [], "all_targets_zero_clamped": false, "plan_sign_intent": 0, "plan_sign_floor_zeroed": false, @@ -100,9 +97,9 @@ }, "site_totals": { "battery_current_w": 1432, - "battery_target_sum_w": -6892.999999999999, + "battery_target_sum_w": -3857, "raw_grid_w": 8815, - "projected_grid_w": 490.0000000000009 + "projected_grid_w": 3526 } }, { @@ -213,7 +210,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1195.9999999999998, + "per_phase_overage_w": 1425.9999999999998, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -580,7 +577,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 253.00000000000034, + "per_phase_overage_w": 483.0000000000003, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -663,7 +660,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1035, + "per_phase_overage_w": 1265, "effective_import_ceiling_w": 4300, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -757,12 +754,12 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": 0, + "target_w": -0, "clamped": true }, { "driver": "sungrow", - "target_w": 0, + "target_w": -0, "clamped": true } ], @@ -780,7 +777,7 @@ "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 184.00000000000017, + "per_phase_overage_w": 414.00000000000017, "effective_import_ceiling_w": 17250, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -870,13 +867,13 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -2534.523809523809, - "clamped": true + "target_w": -2017.0238095238092, + "clamped": false }, { "driver": "pixii", - "target_w": -2534.523809523809, - "clamped": true + "target_w": -2017.0238095238092, + "clamped": false }, { "driver": "sungrow", @@ -886,8 +883,6 @@ ], "clamp_attributions": { "clamped_drivers": [ - "ferroamp", - "pixii", "sungrow" ], "all_targets_zero_clamped": false, @@ -899,7 +894,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 345, + "per_phase_overage_w": 460, "effective_import_ceiling_w": 10695, "effective_export_ceiling_w": 10695, "import_ceiling_binding": false, @@ -907,9 +902,9 @@ }, "site_totals": { "battery_current_w": -3018, - "battery_target_sum_w": -10069.047619047618, + "battery_target_sum_w": -9034.047619047618, "raw_grid_w": 11913, - "projected_grid_w": 4861.952380952382 + "projected_grid_w": 5896.952380952382 } }, { @@ -1081,7 +1076,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 598.0000000000003, + "per_phase_overage_w": 713.0000000000003, "effective_import_ceiling_w": 16905, "effective_export_ceiling_w": 16905, "import_ceiling_binding": true, @@ -1688,20 +1683,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -3402.6442494330904, - "clamped": true + "target_w": -1518.5290322580647, + "clamped": false }, { "driver": "sungrow", - "target_w": -3145.9557505669086, - "clamped": true + "target_w": -959.0709677419356, + "clamped": false } ], "clamp_attributions": { - "clamped_drivers": [ - "ferroamp", - "sungrow" - ], + "clamped_drivers": [], "all_targets_zero_clamped": false, "plan_sign_intent": 0, "plan_sign_floor_zeroed": false, @@ -1711,7 +1703,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1356.9999999999998, + "per_phase_overage_w": 1586.9999999999998, "effective_import_ceiling_w": 5311, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -1719,9 +1711,9 @@ }, "site_totals": { "battery_current_w": 2317, - "battery_target_sum_w": -6548.5999999999985, + "battery_target_sum_w": -2477.6000000000004, "raw_grid_w": 7991, - "projected_grid_w": -874.5999999999985 + "projected_grid_w": 3196.3999999999996 } }, { @@ -1883,17 +1875,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -644.0000000000001, + "target_w": -323.0000000000004, "clamped": true }, { "driver": "pixii", - "target_w": -644.0000000000001, + "target_w": -323.0000000000004, "clamped": true }, { "driver": "sungrow", - "target_w": -644.0000000000001, + "target_w": -323.0000000000004, "clamped": true } ], @@ -1912,7 +1904,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 644.0000000000001, + "per_phase_overage_w": 759.0000000000001, "effective_import_ceiling_w": 16905, "effective_export_ceiling_w": 16905, "import_ceiling_binding": false, @@ -1920,9 +1912,9 @@ }, "site_totals": { "battery_current_w": 1308, - "battery_target_sum_w": -1932.0000000000005, + "battery_target_sum_w": -969.0000000000011, "raw_grid_w": 13971, - "projected_grid_w": 10731 + "projected_grid_w": 11693.999999999998 } }, { @@ -2290,7 +2282,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 505.99999999999983, + "per_phase_overage_w": 735.9999999999999, "effective_import_ceiling_w": 6067, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -2480,20 +2472,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -2820.0999999999995, - "clamped": true + "target_w": -1026.1, + "clamped": false }, { "driver": "sungrow", - "target_w": -2820.0999999999995, - "clamped": true + "target_w": -1026.1, + "clamped": false } ], "clamp_attributions": { - "clamped_drivers": [ - "ferroamp", - "sungrow" - ], + "clamped_drivers": [], "all_targets_zero_clamped": false, "plan_sign_intent": 0, "plan_sign_floor_zeroed": false, @@ -2503,7 +2492,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1195.9999999999998, + "per_phase_overage_w": 1310.9999999999998, "effective_import_ceiling_w": 10695, "effective_export_ceiling_w": 10695, "import_ceiling_binding": false, @@ -2511,9 +2500,9 @@ }, "site_totals": { "battery_current_w": 4591, - "battery_target_sum_w": -5640.199999999999, + "battery_target_sum_w": -2052.2, "raw_grid_w": 11072, - "projected_grid_w": 840.8000000000011 + "projected_grid_w": 4428.8 } }, { @@ -3365,7 +3354,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 206.99999999999966, + "per_phase_overage_w": 436.9999999999997, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -3564,17 +3553,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": 0, + "target_w": -0, "clamped": true }, { "driver": "pixii", - "target_w": 0, + "target_w": -0, "clamped": true }, { "driver": "sungrow", - "target_w": 0, + "target_w": -0, "clamped": true } ], @@ -3593,7 +3582,7 @@ "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 275.99999999999983, + "per_phase_overage_w": 505.99999999999983, "effective_import_ceiling_w": 5718, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -3812,7 +3801,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1334.0000000000002, + "per_phase_overage_w": 1449.0000000000002, "effective_import_ceiling_w": 10695, "effective_export_ceiling_w": 10695, "import_ceiling_binding": false, @@ -4800,7 +4789,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1550, + "target_w": -0, "clamped": true } ], @@ -4808,16 +4797,16 @@ "clamped_drivers": [ "ferroamp" ], - "all_targets_zero_clamped": false, + "all_targets_zero_clamped": true, "plan_sign_intent": -1, - "plan_sign_floor_zeroed": false, + "plan_sign_floor_zeroed": true, "plan_stale": false, "fuse_saturated": false, "fuse_ev_max_w": 0, "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, - "fuse_hold_max_discharge_w": 1550, - "per_phase_overage_w": 1150, + "fuse_hold_max_discharge_w": 0, + "per_phase_overage_w": 1380, "effective_import_ceiling_w": 4886, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -4825,9 +4814,9 @@ }, "site_totals": { "battery_current_w": -3716, - "battery_target_sum_w": -1550, + "battery_target_sum_w": 0, "raw_grid_w": -15970, - "projected_grid_w": -13804 + "projected_grid_w": -12254 } }, { @@ -4895,20 +4884,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -5000, - "clamped": true + "target_w": -3102.7, + "clamped": false }, { "driver": "sungrow", - "target_w": -5000, - "clamped": true + "target_w": -3102.7, + "clamped": false } ], "clamp_attributions": { - "clamped_drivers": [ - "ferroamp", - "sungrow" - ], + "clamped_drivers": [], "all_targets_zero_clamped": false, "plan_sign_intent": 0, "plan_sign_floor_zeroed": false, @@ -4918,7 +4904,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1288.0000000000002, + "per_phase_overage_w": 1518.0000000000002, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -4926,9 +4912,9 @@ }, "site_totals": { "battery_current_w": 2407, - "battery_target_sum_w": -10000, + "battery_target_sum_w": -6205.4, "raw_grid_w": 14354, - "projected_grid_w": 1947 + "projected_grid_w": 5741.6 } }, { @@ -5313,20 +5299,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1645.1999999999998, - "clamped": true + "target_w": -782.6999999999998, + "clamped": false }, { "driver": "sungrow", - "target_w": -1645.1999999999998, - "clamped": true + "target_w": -782.6999999999998, + "clamped": false } ], "clamp_attributions": { - "clamped_drivers": [ - "ferroamp", - "sungrow" - ], + "clamped_drivers": [], "all_targets_zero_clamped": false, "plan_sign_intent": 0, "plan_sign_floor_zeroed": false, @@ -5344,9 +5327,9 @@ }, "site_totals": { "battery_current_w": 3297, - "battery_target_sum_w": -3290.3999999999996, + "battery_target_sum_w": -1565.3999999999996, "raw_grid_w": 8104, - "projected_grid_w": 1516.6000000000004 + "projected_grid_w": 3241.6000000000004 } }, { @@ -6292,7 +6275,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 184.00000000000017, + "per_phase_overage_w": 414.00000000000017, "effective_import_ceiling_w": 7497, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -6513,17 +6496,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -2088.5, + "target_w": -1335.8333333333328, "clamped": true }, { "driver": "pixii", - "target_w": -2088.5, + "target_w": -1335.8333333333328, "clamped": true }, { "driver": "sungrow", - "target_w": -2088.5, + "target_w": -1335.8333333333328, "clamped": true } ], @@ -6541,8 +6524,8 @@ "fuse_ev_max_w": 0, "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, - "fuse_hold_max_discharge_w": 6265.5, - "per_phase_overage_w": 0, + "fuse_hold_max_discharge_w": 4007.499999999998, + "per_phase_overage_w": 23.000000000000327, "effective_import_ceiling_w": 16905, "effective_export_ceiling_w": 16905, "import_ceiling_binding": false, @@ -6550,9 +6533,9 @@ }, "site_totals": { "battery_current_w": -4249, - "battery_target_sum_w": -6265.5, + "battery_target_sum_w": -4007.499999999998, "raw_grid_w": -14716, - "projected_grid_w": -16732.5 + "projected_grid_w": -14474.499999999998 } }, { @@ -6625,7 +6608,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1150, + "per_phase_overage_w": 1380, "effective_import_ceiling_w": 6574, "effective_export_ceiling_w": 7458, "import_ceiling_binding": false, @@ -6896,12 +6879,12 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1720.5, + "target_w": -1592, "clamped": true }, { "driver": "sungrow", - "target_w": -1720.5, + "target_w": -1592, "clamped": true } ], @@ -6918,18 +6901,18 @@ "fuse_ev_max_w": 0, "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, - "fuse_hold_max_discharge_w": 3441, - "per_phase_overage_w": 0, + "fuse_hold_max_discharge_w": 3184, + "per_phase_overage_w": 45.99999999999984, "effective_import_ceiling_w": 17250, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, - "export_ceiling_binding": true + "export_ceiling_binding": false }, "site_totals": { "battery_current_w": -3322, - "battery_target_sum_w": -3441, + "battery_target_sum_w": -3184, "raw_grid_w": -17131, - "projected_grid_w": -17250 + "projected_grid_w": -16993 } }, { @@ -7099,7 +7082,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1080.9999999999998, + "per_phase_overage_w": 1195.9999999999998, "effective_import_ceiling_w": 10695, "effective_export_ceiling_w": 10695, "import_ceiling_binding": false, @@ -7165,7 +7148,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -3174.000000000001, + "target_w": -1139.0000000000014, "clamped": true } ], @@ -7182,7 +7165,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1058.0000000000002, + "per_phase_overage_w": 1288.0000000000002, "effective_import_ceiling_w": 17250, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -7190,9 +7173,9 @@ }, "site_totals": { "battery_current_w": 2725, - "battery_target_sum_w": -3174.000000000001, + "battery_target_sum_w": -1139.0000000000014, "raw_grid_w": 14295, - "projected_grid_w": 8396 + "projected_grid_w": 10430.999999999998 } }, { @@ -7475,7 +7458,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 184.00000000000017, + "per_phase_overage_w": 414.00000000000017, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -7683,12 +7666,12 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": 0, + "target_w": -0, "clamped": true }, { "driver": "sungrow", - "target_w": 0, + "target_w": -0, "clamped": true } ], @@ -7706,7 +7689,7 @@ "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 345, + "per_phase_overage_w": 460, "effective_import_ceiling_w": 16905, "effective_export_ceiling_w": 16905, "import_ceiling_binding": false, @@ -7917,30 +7900,34 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": 5000, - "clamped": false + "target_w": 4493.333333333333, + "clamped": true }, { "driver": "pixii", - "target_w": 5000, - "clamped": false + "target_w": 4493.333333333333, + "clamped": true }, { "driver": "sungrow", - "target_w": 5000, - "clamped": false + "target_w": 4493.333333333333, + "clamped": true } ], "clamp_attributions": { - "clamped_drivers": [], + "clamped_drivers": [ + "ferroamp", + "pixii", + "sungrow" + ], "all_targets_zero_clamped": false, "plan_sign_intent": 0, "plan_sign_floor_zeroed": false, "plan_stale": false, "fuse_saturated": false, "fuse_ev_max_w": 0, - "fuse_hold_latched": false, - "fuse_hold_max_charge_w": 0, + "fuse_hold_latched": true, + "fuse_hold_max_charge_w": 13480, "fuse_hold_max_discharge_w": 0, "per_phase_overage_w": 0, "effective_import_ceiling_w": 10350, @@ -7950,9 +7937,9 @@ }, "site_totals": { "battery_current_w": 853, - "battery_target_sum_w": 15000, + "battery_target_sum_w": 13480, "raw_grid_w": -7899, - "projected_grid_w": 6248 + "projected_grid_w": 4728 } }, { @@ -8025,7 +8012,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 0, + "per_phase_overage_w": 206.99999999999966, "effective_import_ceiling_w": 4624, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -8131,17 +8118,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -716.6666666666667, + "target_w": -0, "clamped": true }, { "driver": "pixii", - "target_w": -716.6666666666667, + "target_w": -0, "clamped": true }, { "driver": "sungrow", - "target_w": -716.6666666666667, + "target_w": -0, "clamped": true } ], @@ -8151,26 +8138,26 @@ "pixii", "sungrow" ], - "all_targets_zero_clamped": false, + "all_targets_zero_clamped": true, "plan_sign_intent": -1, - "plan_sign_floor_zeroed": false, + "plan_sign_floor_zeroed": true, "plan_stale": false, "fuse_saturated": false, "fuse_ev_max_w": 0, "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, - "fuse_hold_max_discharge_w": 2150, - "per_phase_overage_w": 1173.0000000000002, + "fuse_hold_max_discharge_w": 0, + "per_phase_overage_w": 1403.0000000000002, "effective_import_ceiling_w": 17250, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, - "export_ceiling_binding": true + "export_ceiling_binding": false }, "site_totals": { "battery_current_w": 1653, - "battery_target_sum_w": -2150, + "battery_target_sum_w": 0, "raw_grid_w": -13447, - "projected_grid_w": -17250 + "projected_grid_w": -15100 } } ] diff --git a/go/internal/control/testdata/golden/slew_limiter.json b/go/internal/control/testdata/golden/slew_limiter.json index 896d7f298..0c5efa302 100644 --- a/go/internal/control/testdata/golden/slew_limiter.json +++ b/go/internal/control/testdata/golden/slew_limiter.json @@ -1,7 +1,7 @@ { "family": "slew_limiter", "generated_by": "FTW_GOLDEN_DUMP=1 go test ./internal/control/ -run TestGoldenDump", - "ftw_commit": "15f9edc3b973d7b9151e88d63575a9b7d615a0b3", + "ftw_commit": "83c2b24ccdb730278a9c4e6ef778bab5f9499167", "record_count": 127, "records": [ { @@ -3225,7 +3225,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -2760, + "target_w": -1949.9999999999995, "clamped": true } ], @@ -3242,7 +3242,7 @@ "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 920, + "per_phase_overage_w": 1150, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -3250,9 +3250,9 @@ }, "site_totals": { "battery_current_w": 1500, - "battery_target_sum_w": -2760, + "battery_target_sum_w": -1949.9999999999995, "raw_grid_w": 1000, - "projected_grid_w": -3260 + "projected_grid_w": -2449.9999999999995 } }, { diff --git a/go/internal/control/testdata/golden/targeted_invariants.json b/go/internal/control/testdata/golden/targeted_invariants.json index 467ca3418..b44f92069 100644 --- a/go/internal/control/testdata/golden/targeted_invariants.json +++ b/go/internal/control/testdata/golden/targeted_invariants.json @@ -1,7 +1,7 @@ { "family": "targeted_invariants", "generated_by": "FTW_GOLDEN_DUMP=1 go test ./internal/control/ -run TestGoldenDump", - "ftw_commit": "68c5b6125898bb9da70728b8921259c87e96171d", + "ftw_commit": "83c2b24ccdb730278a9c4e6ef778bab5f9499167", "record_count": 18, "records": [ { @@ -683,7 +683,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -3360, + "target_w": -3450, "clamped": true } ], @@ -700,7 +700,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 920, + "per_phase_overage_w": 1150, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -708,9 +708,9 @@ }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -3360, + "battery_target_sum_w": -3450, "raw_grid_w": 1000, - "projected_grid_w": -2360 + "projected_grid_w": -2450 } }, { @@ -782,7 +782,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -2240, + "target_w": -0, "clamped": true } ], @@ -790,16 +790,16 @@ "clamped_drivers": [ "ferroamp" ], - "all_targets_zero_clamped": false, + "all_targets_zero_clamped": true, "plan_sign_intent": -1, - "plan_sign_floor_zeroed": false, + "plan_sign_floor_zeroed": true, "plan_stale": false, "fuse_saturated": false, "fuse_ev_max_w": 0, "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, - "fuse_hold_max_discharge_w": 2240, - "per_phase_overage_w": 920, + "fuse_hold_max_discharge_w": 0, + "per_phase_overage_w": 1150, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -807,9 +807,9 @@ }, "site_totals": { "battery_current_w": -2000, - "battery_target_sum_w": -2240, + "battery_target_sum_w": 0, "raw_grid_w": -6000, - "projected_grid_w": -6240 + "projected_grid_w": -4000 } }, { From 0af26e04610349f00d303d3e99e9932249829d27 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 15:53:58 +0100 Subject: [PATCH 04/68] fix(control): battery waits only for a declared charger response time The first A6 change gave the battery side the EV limit's 180 s guess for every charger that declares no response time. Only Easee Cloud declares one, so on every other charger the battery reserved the car's whole demand on top of a reading that already showed the car, and stopped charging for 3 minutes after each car start or raise. On the #1868 shape (rig s18) battery charge stayed at 0 W until 180 s. evShownW now uses the charger's declared power_max_age_s, and evSettle when it declares none, as master did. Easee Cloud declares 180 s, so the slow-charger case stays fixed. Tests: the slow-charger test now declares 180 s, and a new plant test runs the s18 shape with a fast charger that declares nothing. Co-Authored-By: Claude Opus 5.5 --- .changeset/a6-one-ev-offer-log.md | 2 +- go/internal/control/ev_fuse_budget.go | 24 +++++-- .../control/ev_slow_charger_battery_test.go | 65 +++++++++++++++++-- go/internal/control/sitesim_field_test.go | 5 +- go/internal/control/sitesim_test.go | 3 + 5 files changed, 85 insertions(+), 14 deletions(-) diff --git a/.changeset/a6-one-ev-offer-log.md b/.changeset/a6-one-ev-offer-log.md index a11cc1905..8779c2a08 100644 --- a/.changeset/a6-one-ev-offer-log.md +++ b/.changeset/a6-one-ev-offer-log.md @@ -2,4 +2,4 @@ "ftw": patch --- -Keep home battery charging out of the room a slow charger's raise still needs. The battery now counts a car's offer as not yet in the meter for the charger's own response time (180 s when it declares none), as the car's fuse limit already did, instead of 20 s. A charger that takes two minutes to start no longer pushes a 25 A phase to 32.6 A. +Keep home battery charging out of the room a slow charger's raise still needs. When a charger's driver declares its response time, as Easee Cloud declares 180 s, the battery now counts a car's offer as not yet in the meter for that time, as the car's fuse limit already did, instead of 20 s. A charger that takes two minutes to start no longer pushes a 25 A phase to 32.6 A. A charger that declares no response time keeps the 20 s, so the battery and a car on a local charger still charge together within a minute of the car's start. diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index c3193fe8e..b74b81115 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -170,6 +170,9 @@ func (l commandLog) toCome(from, at time.Time, before sentCommand) (w, a float64 type chargerOffers struct { log commandLog settle time.Duration + // declared is true when the driver declares that time; settle is then + // not evUnknownSettle's guess (evShownW). + declared bool // found is the offer in force before the limit's first site reading, // after a restart: Core did not send it in this run. A rise counts the // charger as 0 before it; a cut takes it as shown, since the reading is @@ -188,14 +191,23 @@ type pendingLoad struct { } // evShownW is the EV load a reading taken at `at` surely shows: each -// plugged charger's latest offer less what it may not show yet, kept for -// its own response time (recordEVOffers). The battery side reads this, so -// it waits for a slow charger's raise as long as the EV limit does. +// plugged charger's latest offer less what it may not show yet. The battery +// side reads this. A raise stays unshown for the response time the +// charger's driver declares, so the battery waits for a slow charger's raise +// as long as the EV limit does. A charger that declares none gets evSettle, +// not evUnknownSettle: the battery would otherwise reserve a local charger's +// raise on top of the reading that already shows it, and stop charging for +// three minutes after each one. Easee Cloud, the slow charger we know, +// declares its 180 s. func (s *State) evShownW(at time.Time) float64 { var w float64 for _, c := range s.evLimit.offers { if n := len(c.log); n > 0 { - unshown, _ := c.log.unshown(at, c.settle) + settle := evSettle + if c.declared { + settle = c.settle + } + unshown, _ := c.log.unshown(at, settle) w += math.Max(0, c.log[n-1].w-unshown) } } @@ -273,10 +285,10 @@ func (s *State) recordEVOffers(store *telemetry.Store, points []loadpoint.State) continue } c := s.evLimit.offers[point.ID] - c.settle = evUnknownSettle + c.settle, c.declared = evUnknownSettle, false if r := store.Get(point.DriverName, telemetry.DerEV); r != nil { if declared := telemetry.DeclaredPowerMaxAge(r.Data); declared > 0 { - c.settle = max(evSettle, declared) + c.settle, c.declared = max(evSettle, declared), true } } w := math.Max(0, point.CommandedW) diff --git a/go/internal/control/ev_slow_charger_battery_test.go b/go/internal/control/ev_slow_charger_battery_test.go index c8275988b..91b583532 100644 --- a/go/internal/control/ev_slow_charger_battery_test.go +++ b/go/internal/control/ev_slow_charger_battery_test.go @@ -1,17 +1,20 @@ package control import ( + "fmt" "testing" "time" + "github.com/srcfl/ftw/go/internal/loadpoint" "github.com/srcfl/ftw/go/internal/sitesim" ) -// A charger that declares no response time and takes delay to start, beside -// a planned 9.4 kW battery charge on a 25 A site with 3 A of house load per -// phase. The car's 11 kW offer stays unshown until the charger applies it, -// and the battery must not take that room: when the car starts, no phase -// may pass the instant limit, and the car must not sit idle with room. +// A charger that declares a 180 s response time, as Easee Cloud does, and +// takes delay to start, beside a planned 9.4 kW battery charge on a 25 A +// site with 3 A of house load per phase. The car's 11 kW offer stays +// unshown until the charger applies it, and the battery must not take that +// room: when the car starts, no phase may pass the instant limit, and the +// car must not sit idle with room. func TestSlowChargerUnshownOfferKeepsBatteryOut(t *testing.T) { for _, delay := range []time.Duration{5 * time.Second, 30 * time.Second, 40 * time.Second, 2 * time.Minute} { sc := simScenario{name: "slow charger", run: 15 * time.Minute, @@ -19,7 +22,10 @@ func TestSlowChargerUnshownOfferKeepsBatteryOut(t *testing.T) { p.HouseW, p.EVSE.Delay = houseA(3, 3, 3), delay p.Battery = &sitesim.Battery{Phases: 3, MaxChargeW: 9400, MaxDischargeW: 9400, CapacityWh: 20000, SoC: .3, Latency: 3 * time.Second} }, - setup: planBatteryCharge(9400)} + setup: func(s *simSite) { + s.evMaxAge = evUnknownSettle + planBatteryCharge(9400)(s) + }} s := runSimScenario(sc, simStart) t.Logf("delay %v: peak phase %.1f A, %v over %.0f A, idle with room %v, car %.0f W, battery %.0f W", delay, s.peakA, s.overLimit, s.p.Fuse.RatingA-evPhaseMarginA, s.idleWithRoom, s.p.EVSE.DrawW, s.p.Battery.W) @@ -31,3 +37,50 @@ func TestSlowChargerUnshownOfferKeepsBatteryOut(t *testing.T) { } } } + +// #1868's rig shape (s18): a 16 A site with 3 A of house load, a local +// charger that declares no response time and draws within 2 s, a car that +// takes only [0, 4140] W, and a 6000 W battery charge. Once the car draws, +// the reading shows it, and the battery shares the rest of the fuse well +// before evUnknownSettle; s18's judge needs it above 1000 W 100-120 s after +// Charge now. +func TestFastChargerYoungOfferLetsBatteryShare(t *testing.T) { + for _, tc := range []struct { + name string + setup func(*simSite) + }{ + {"manual hold", func(s *simSite) { + s.state.SetBatteryManualHold(BatteryManualHold{PowerW: 6000, ExpiresAt: s.p.Now.Add(time.Hour)}) + }}, + {"plan", planBatteryCharge(6000)}, + } { + t.Run(tc.name, func(t *testing.T) { + var expect []simExpect + for _, at := range []time.Duration{60 * time.Second, 100 * time.Second, 120 * time.Second, 170 * time.Second} { + expect = append(expect, simExpect{at, func(s *simSite) error { + if s.p.EVSE.DrawW < 4100 || s.p.Battery.W < 3000 { + return fmt.Errorf("car %.0f W and battery %.0f W at %v; both should charge", s.p.EVSE.DrawW, s.p.Battery.W, at) + } + return nil + }}) + } + sc := simScenario{name: "s18 " + tc.name, run: 4 * time.Minute, + plant: func(p *sitesim.Plant) { + p.Fuse.RatingA, p.HouseW, p.EVSE.Delay, p.EVSE.ReadbackLag = 16, houseA(3, 3, 3), 2*time.Second, 0 + p.Battery = &sitesim.Battery{Phases: 3, MaxChargeW: 6000, MaxDischargeW: 6000, CapacityWh: 20000, SoC: .4, Latency: 2 * time.Second} + }, + lp: func(c *loadpoint.Config) { + c.MinChargeW, c.MaxChargeW, c.AllowedStepsW = 4140, 4140, []float64{0, 4140} + }, + setup: tc.setup, + expect: expect} + s := runSimScenario(sc, simStart) + if s.failure != "" { + t.Error(s.failure) + } + if limitA := fuseInstantFactor * s.p.Fuse.RatingA; s.peakA > limitA { + t.Errorf("peak phase %.1f A above the instant limit %.1f A", s.peakA, limitA) + } + }) + } +} diff --git a/go/internal/control/sitesim_field_test.go b/go/internal/control/sitesim_field_test.go index 29263817c..7ea788beb 100644 --- a/go/internal/control/sitesim_field_test.go +++ b/go/internal/control/sitesim_field_test.go @@ -460,7 +460,7 @@ func (s *simSite) coreEvery() time.Duration { func (s *simSite) declaredMaxAge() time.Duration { if s.field == nil { - return 0 + return s.evMaxAge } return s.field.c.timing.declared } @@ -468,6 +468,9 @@ func (s *simSite) declaredMaxAge() time.Duration { // evData is what a charger driver adds to its reading. func (s *simSite) evData() map[string]any { if s.field == nil { + if s.evMaxAge > 0 { + return map[string]any{"power_max_age_s": s.evMaxAge.Seconds()} + } return nil } d := map[string]any{"connected": s.ev.Plugged, "control_power_confirmed": true} diff --git a/go/internal/control/sitesim_test.go b/go/internal/control/sitesim_test.go index 6022cd157..0d37b6d47 100644 --- a/go/internal/control/sitesim_test.go +++ b/go/internal/control/sitesim_test.go @@ -39,6 +39,9 @@ type simSite struct { every time.Duration // control_interval_s; zero: simCoreEvery field *fieldRun // the field matrix's own checks; nil outside it + // evMaxAge is the power_max_age_s the charger driver declares outside + // the field matrix; zero declares none. + evMaxAge time.Duration downUntil, nextTick time.Time meter sitesim.MeterReading From 2f793d8fe87535cb8d0cc0a27107c862da360571 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 15:57:50 +0100 Subject: [PATCH 05/68] fix(control): fuse guard reads phases after the hold caps the targets The guard took the phase relief from the original request, then the 30 s fuse hold capped that request and the relief came off again. A charge limited by one phase switched between 1380 W and 0 W on every dispatch. Predict the aggregate and the phases from the held targets instead. The phase reader now takes the meter's raw total from OnlineMeterW, the same reading as its currents, so an offline meter's cached phases drive no relief. The batteries' raw power is read in one helper. dispatch.go keeps its 41 cached telemetry reads. Co-Authored-By: Claude Opus 5.5 --- go/internal/control/dispatch.go | 148 +++++++++++------- .../control/ev_battery_sequence_test.go | 6 +- .../fuse_battery_phase_direction_test.go | 75 +++++++++ go/internal/control/golden_dump_test.go | 2 +- 4 files changed, 172 insertions(+), 59 deletions(-) diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index ed19b5165..9089ffe5f 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -3591,48 +3591,26 @@ func applyFuseGuard(targets []DispatchTarget, store *telemetry.Store, state *Sta // reflected in currentGrid; subtracting them here without adding a // replacement target would double-remove their contribution and miss // fuse overages. - seenBat := make(map[string]struct{}, len(targets)) - var currentBat, rawBat float64 + batteries := make(map[string]*telemetry.DerReading, len(targets)) + var currentBat float64 for _, t := range targets { - if _, seen := seenBat[t.Driver]; seen { + if _, seen := batteries[t.Driver]; seen { continue } - seenBat[t.Driver] = struct{}{} - if r := store.Get(t.Driver, telemetry.DerBattery); r != nil { + r := store.Get(t.Driver, telemetry.DerBattery) + batteries[t.Driver] = r + if r != nil { currentBat += r.SmoothedW - rawBat += r.RawW } } var currentGrid float64 - var meter *telemetry.DerReading + var phases phaseSample if siteMeter != "" { - if meter = store.Get(siteMeter, telemetry.DerMeter); meter != nil { + if meter := store.Get(siteMeter, telemetry.DerMeter); meter != nil { currentGrid = meter.SmoothedW + phases = livePhaseSample(store, siteMeter, meter) } } - var sumTarget float64 - for _, t := range targets { - sumTarget += t.TargetW - } - predicted := currentGrid - currentBat + sumTarget - - // Per phase, each way, once the targets replace the batteries' power - // in the same raw reading. - phaseImportW, phaseExportW := phaseFuseReliefW(meter, state, sumTarget-rawBat) - // Aggregate budget honours the safety margin too — keep dispatch - // commands strictly inside the breaker envelope so the inverter's - // own per-phase limiter doesn't fire first and cause a flap. - // - // Import ceiling is the tighter of (fuse − safety margin) and the - // clock hour's import limit; export ceiling is the tighter of (fuse − - // safety margin) and the operator's max_export_w protection limit — - // set when an inverter trips on sustained export below the breaker - // (recurring Ferroamp 0x8030 fault). Both share one enforcement surface. - effImportW := state.effectiveImportCeilingW(fuseMaxW) - effExportW := state.effectiveExportCeilingW(fuseMaxW) - importOverage := math.Max(predicted-effImportW, phaseImportW) - exportOverage := math.Max(-effExportW-predicted, phaseExportW) - out := make([]DispatchTarget, len(targets)) copy(out, targets) @@ -3685,6 +3663,32 @@ func applyFuseGuard(targets []DispatchTarget, store *telemetry.Store, state *Sta state.FuseHoldUntil = time.Time{} } + // Predict from the held targets. Relief taken from the request would + // count the hold's cut a second time, and a charge limited by one phase + // would switch between the cap and 0 on every dispatch. + var sumTarget float64 + for _, t := range out { + sumTarget += t.TargetW + } + predicted := currentGrid - currentBat + sumTarget + + // Per phase, each way, once the targets replace the batteries' power + // in the same raw reading. + phaseImportW, phaseExportW := phaseFuseReliefW(phases, state, phaseMoveW(out, batteries)) + // Aggregate budget honours the safety margin too — keep dispatch + // commands strictly inside the breaker envelope so the inverter's + // own per-phase limiter doesn't fire first and cause a flap. + // + // Import ceiling is the tighter of (fuse − safety margin) and the + // clock hour's import limit; export ceiling is the tighter of (fuse − + // safety margin) and the operator's max_export_w protection limit — + // set when an inverter trips on sustained export below the breaker + // (recurring Ferroamp 0x8030 fault). Both share one enforcement surface. + effImportW := state.effectiveImportCeilingW(fuseMaxW) + effExportW := state.effectiveExportCeilingW(fuseMaxW) + importOverage := math.Max(predicted-effImportW, phaseImportW) + exportOverage := math.Max(-effExportW-predicted, phaseExportW) + if importOverage <= 0 && exportOverage <= 0 { return out } @@ -3822,30 +3826,70 @@ func (s *State) effectiveExportCeilingW(fuseMaxW float64) float64 { return eff } +// phaseSample is one meter reading's phase currents with the raw total of +// the same reading. The zero value has no phases. +type phaseSample struct { + meter *telemetry.DerReading + totalW float64 +} + +// livePhaseSample pairs meter with its raw total while the meter still +// reports. A watchdog-offline meter gives no phases, since its cached +// currents are no longer the site. So does a store that has moved on to a +// newer reading, since its total no longer matches meter's currents. +func livePhaseSample(store *telemetry.Store, driver string, meter *telemetry.DerReading) phaseSample { + if store == nil || meter == nil { + return phaseSample{} + } + totalW, at, ok := store.OnlineMeterW(driver) + if !ok || !at.Equal(meter.UpdatedAt) { + return phaseSample{} + } + return phaseSample{meter: meter, totalW: totalW} +} + +// phaseMoveW is the batteries' change from the raw power their readings hold +// to the targets. The phase currents are raw, so the move is too. +func phaseMoveW(targets []DispatchTarget, batteries map[string]*telemetry.DerReading) float64 { + var moveW float64 + seen := make(map[string]bool, len(targets)) + for _, t := range targets { + moveW += t.TargetW + if r := batteries[t.Driver]; r != nil && !seen[t.Driver] { + moveW -= r.RawW + } + seen[t.Driver] = true + } + return moveW +} + // phaseFuseReliefW is the aggregate battery move that brings every phase // inside the working limit: the fuse less the car's 1 A margin, or less // safety_margin_a when that is larger. importW asks for less charge or more // discharge, exportW for the reverse. moveW is the batteries' change from -// the power this reading already holds; like the relief, it spreads evenly -// over the site's phases. +// the power this reading already holds (phaseMoveW); like the relief, it +// spreads evenly over the site's phases. // // The phases are the meter's signed currents (phaseCurrentsA). When no // phase reads as export while the total does, the meter gives no direction // per phase, and the phases take the total's. When no move fits every -// phase, the move leaves the worst phase least over, so a move never -// raises the current on the phase it protects. 0, 0 without usable phase -// currents. -func phaseFuseReliefW(meter *telemetry.DerReading, state *State, moveW float64) (importW, exportW float64) { - if meter == nil || state == nil { +// phase, the move leaves the worst phase least over, so on a meter that +// gives each phase's direction a move never raises the current on the phase +// it protects. Two limits remain: a meter without phase power that mixes +// directions under an exporting total, where an importing phase is read as +// export, and a battery on one phase, which is read as balanced. 0, 0 +// without usable phase currents. +func phaseFuseReliefW(p phaseSample, state *State, moveW float64) (importW, exportW float64) { + if p.meter == nil || state == nil { return 0, 0 } - amps, _, valid := phaseCurrentsA(meter, state, meter.RawW) + amps, _, valid := phaseCurrentsA(p.meter, state, p.totalW) if !valid || len(amps) == 0 { return 0, 0 } perA := state.SiteFuseVoltage * float64(state.SiteFusePhases) // aggregate W per phase ampere limitA := math.Max(0, state.SiteFuseAmps-math.Max(evPhaseMarginA, state.SiteFuseSafetyA)) - exports := meter.RawW < 0 + exports := p.totalW < 0 for _, a := range amps { exports = exports && a >= 0 } @@ -4358,7 +4402,8 @@ func fuseSaverFromLivePower( // site is safe. Preserve the deadband in that case: this early-return path // exists to answer a fuse condition, not to take control of an externally // moved battery merely because its reading sits outside a command cap. - requiredRelief := fuseReliefFromSnapshot(rawLive, batteryReadings, meter, state, fuseMaxW) + phases := livePhaseSample(store, state.SiteMeterDriver, meter) + requiredRelief := fuseReliefFromSnapshot(rawLive, batteryReadings, meter, phases, state, fuseMaxW) if requiredRelief <= 0 { return nil } @@ -4376,7 +4421,7 @@ func fuseSaverFromLivePower( if len(safeBaseline) == 0 { return nil } - out := forceFuseDischargeWithSnapshot(safeBaseline, batteryReadings, meter, state, driverCapacities, fuseMaxW) + out := forceFuseDischargeWithSnapshot(safeBaseline, batteryReadings, meter, phases, state, driverCapacities, fuseMaxW) rawByDriver := make(map[string]DispatchTarget, len(rawLive)) for _, t := range rawLive { rawByDriver[t.Driver] = t @@ -4399,6 +4444,7 @@ func fuseReliefFromSnapshot( targets []DispatchTarget, batteryReadings map[string]*telemetry.DerReading, meter *telemetry.DerReading, + phases phaseSample, state *State, fuseMaxW float64, ) float64 { @@ -4406,7 +4452,7 @@ func fuseReliefFromSnapshot( return 0 } - _, sumTarget, predicted := predictedGridFromSnapshot(targets, batteryReadings, meter) + _, _, predicted := predictedGridFromSnapshot(targets, batteryReadings, meter) // The fuse acts on every reading. The hour's import limit is a budget: // the part of its overage that an EV cut we sent will remove waits for @@ -4418,16 +4464,7 @@ func fuseReliefFromSnapshot( if ceilingW := state.effectiveImportCeilingW(fuseMaxW); ceilingW < fuseW { overage = math.Max(overage, predicted-ceilingW-state.pendingEVCutW()) } - // The phases are raw, so the batteries' move is from their raw power. - moveW := sumTarget - seen := make(map[string]bool, len(targets)) - for _, t := range targets { - if r := batteryReadings[t.Driver]; r != nil && !seen[t.Driver] { - moveW -= r.RawW - } - seen[t.Driver] = true - } - phaseW, _ := phaseFuseReliefW(meter, state, moveW) + phaseW, _ := phaseFuseReliefW(phases, state, phaseMoveW(targets, batteryReadings)) return math.Max(overage, phaseW) } @@ -4480,7 +4517,7 @@ func forceFuseDischarge( readings[target.Driver] = store.Get(target.Driver, telemetry.DerBattery) } meter := store.Get(state.SiteMeterDriver, telemetry.DerMeter) - return forceFuseDischargeWithSnapshot(targets, readings, meter, state, driverCapacities, fuseMaxW) + return forceFuseDischargeWithSnapshot(targets, readings, meter, livePhaseSample(store, state.SiteMeterDriver, meter), state, driverCapacities, fuseMaxW) } // forceFuseDischargeWithSnapshot keeps all math for one decision on the same @@ -4490,6 +4527,7 @@ func forceFuseDischargeWithSnapshot( targets []DispatchTarget, batteryReadings map[string]*telemetry.DerReading, meter *telemetry.DerReading, + phases phaseSample, state *State, driverCapacities map[string]float64, fuseMaxW float64, @@ -4497,7 +4535,7 @@ func forceFuseDischargeWithSnapshot( if fuseMaxW <= 0 || len(targets) == 0 || state == nil { return targets } - overage := fuseReliefFromSnapshot(targets, batteryReadings, meter, state, fuseMaxW) + overage := fuseReliefFromSnapshot(targets, batteryReadings, meter, phases, state, fuseMaxW) if overage <= 0 { return targets } diff --git a/go/internal/control/ev_battery_sequence_test.go b/go/internal/control/ev_battery_sequence_test.go index d94da1831..b631054a6 100644 --- a/go/internal/control/ev_battery_sequence_test.go +++ b/go/internal/control/ev_battery_sequence_test.go @@ -556,7 +556,7 @@ func TestFuseReliefLeavesOnlyCeilingWattsToCommandedEVCut(t *testing.T) { targets := []DispatchTarget{{Driver: "pixii"}} batteries := map[string]*telemetry.DerReading{"pixii": {}} meter := &telemetry.DerReading{SmoothedW: tc.gridW, Data: tc.data} - got := fuseReliefFromSnapshot(targets, batteries, meter, st, 17250) + got := fuseReliefFromSnapshot(targets, batteries, meter, phaseSample{meter: meter, totalW: meter.RawW}, st, 17250) if math.Abs(math.Max(0, got)-tc.wantW) > 1e-6 { t.Errorf("%s: relief %.0f W, want %.0f W", tc.name, got, tc.wantW) } @@ -597,7 +597,7 @@ func TestUnpluggedCarIsNoCutTheBatteryWaitsFor(t *testing.T) { st.SetEVCommanded(points) targets := []DispatchTarget{{Driver: "pixii"}} batteries := map[string]*telemetry.DerReading{"pixii": {}} - return math.Max(0, fuseReliefFromSnapshot(targets, batteries, &telemetry.DerReading{SmoothedW: gridW}, st, 17250)) + return math.Max(0, fuseReliefFromSnapshot(targets, batteries, &telemetry.DerReading{SmoothedW: gridW}, phaseSample{}, st, 17250)) } // 400 W over the ceiling, less than a step: the guard waits. if got := tick(7900, true, 5520); math.Abs(got-400) > 1e-6 { @@ -661,7 +661,7 @@ func TestCutOnStayingCarStillWaitsWhenAnotherLeaves(t *testing.T) { st.SetEVCommanded(points) targets := []DispatchTarget{{Driver: "pixii"}} batteries := map[string]*telemetry.DerReading{"pixii": {SmoothedW: batteryW}} - relief := fuseReliefFromSnapshot(targets, batteries, &telemetry.DerReading{SmoothedW: gridW}, st, 17250) + relief := fuseReliefFromSnapshot(targets, batteries, &telemetry.DerReading{SmoothedW: gridW}, phaseSample{}, st, 17250) batteryW = -math.Max(0, relief) // The battery follows within a tick. if batteryW < 0 && tick < 10 { t.Fatalf("%ds: battery %.0f W for watts a's stop removes; pending cut %.0f W", tick, batteryW, st.pendingEVCutW()) diff --git a/go/internal/control/fuse_battery_phase_direction_test.go b/go/internal/control/fuse_battery_phase_direction_test.go index 111c03ee3..2e740b1f8 100644 --- a/go/internal/control/fuse_battery_phase_direction_test.go +++ b/go/internal/control/fuse_battery_phase_direction_test.go @@ -144,3 +144,78 @@ func TestPerPhaseFuseReliefHoldsWhileOverloadPersists(t *testing.T) { } } } + +// chargeLoop repeats a 4000 W charge request against house loads of +// 13/7/5 A on a 0 A margin, with a three-phase battery that follows each +// order. dispatch returns the battery's next target. +func chargeLoop(t *testing.T, ticks int, dispatch func(*telemetry.Store, *State) float64) (targets, l1 []float64) { + t.Helper() + st := phaseDirectionState(0) + now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) + st.clock = func() time.Time { return now } + store := telemetry.NewStore() + batW := 0.0 + for tick := 0; tick < ticks; tick++ { + a := [3]float64{13, 7, 5} + for i := range a { + a[i] += batW / 690 + } + raw, _ := json.Marshal(map[string]any{"l1_a": a[0], "l2_a": a[1], "l3_a": a[2], + "l1_w": a[0] * 230, "l2_w": a[1] * 230, "l3_w": a[2] * 230}) + store.Update("meter", telemetry.DerMeter, (a[0]+a[1]+a[2])*230, nil, raw) + store.DriverHealthMut("meter").RecordSuccess() + soc := 0.5 + store.Update("bat", telemetry.DerBattery, batW, &soc, nil) + store.DriverHealthMut("bat").RecordSuccess() + batW = dispatch(store, st) + targets = append(targets, math.Round(batW)) + l1 = append(l1, math.Round(a[0]*100)/100) + now = now.Add(5 * time.Second) + } + return targets, l1 +} + +// The fuse hold caps the request before the guard reads the phases, so the +// hold's cut is not taken off again. The charge settles at 1380 W with L1 +// at 15 A instead of switching between 1380 W and 0 W. +func TestFuseGuardHeldChargeHoldsSteady(t *testing.T) { + assertSteady := func(name string, targets, l1 []float64) { + t.Helper() + for i := 1; i < len(targets); i++ { + if math.Abs(targets[i]-targets[i-1]) > 50 || l1[i] > 15.01 { + t.Fatalf("%s: tick %d charge %v -> %v W; targets %v, L1 %v", name, i, targets[i-1], targets[i], targets, l1) + } + } + } + targets, l1 := chargeLoop(t, 10, func(store *telemetry.Store, st *State) float64 { + return applyFuseGuard([]DispatchTarget{{Driver: "bat", TargetW: 4000}}, store, st, 16*230*3)[0].TargetW + }) + assertSteady("applyFuseGuard", targets, l1) + + targets, l1 = chargeLoop(t, 12, func(store *telemetry.Store, st *State) float64 { + st.Mode = ModeCharge + st.DriverLimits = map[string]PowerLimits{"bat": {MaxChargeW: 4000, MaxDischargeW: 4000}} + for _, o := range ComputeDispatch(store, st, map[string]float64{"bat": 15200}, 16*230*3) { + if o.Driver == "bat" { + return o.TargetW + } + } + return 0 + }) + assertSteady("Charge mode", targets, l1) +} + +// A watchdog-offline meter's cached phases are not the site: they drive no +// phase relief. +func TestPhaseReliefSkipsOfflineMeter(t *testing.T) { + store := phaseDirectionStore(t, 20*230, 0, map[string]any{"l1_a": 20.0, "l2_a": 0.0, "l3_a": 0.0, + "l1_w": 4600.0, "l2_w": 0.0, "l3_w": 0.0}) + meter := store.Get("meter", telemetry.DerMeter) + if imp, _ := phaseFuseReliefW(livePhaseSample(store, "meter", meter), phaseDirectionState(0), 0); imp <= 0 { + t.Fatalf("online meter: import relief %.0f W, want > 0 for L1 at 20 A", imp) + } + store.DriverHealthMut("meter").SetOffline() + if imp, exp := phaseFuseReliefW(livePhaseSample(store, "meter", meter), phaseDirectionState(0), 0); imp != 0 || exp != 0 { + t.Fatalf("offline meter: relief %.0f/%.0f W, want none", imp, exp) + } +} diff --git a/go/internal/control/golden_dump_test.go b/go/internal/control/golden_dump_test.go index 32636555b..07a6f8f4d 100644 --- a/go/internal/control/golden_dump_test.go +++ b/go/internal/control/golden_dump_test.go @@ -333,7 +333,7 @@ func runGoldenScenarioAt(sc goldenScenario, scenarioNow time.Time, slotDirective intent := planSignIntent(st) // The worst phase's overage either way, in watts on that phase. var perPhase float64 - importW, exportW := phaseFuseReliefW(store.Get(st.SiteMeterDriver, telemetry.DerMeter), st, 0) + importW, exportW := phaseFuseReliefW(livePhaseSample(store, st.SiteMeterDriver, store.Get(st.SiteMeterDriver, telemetry.DerMeter)), st, 0) if st.SiteFusePhases > 0 { perPhase = math.Max(importW, exportW) / float64(st.SiteFusePhases) } From 3dc080fb7c90c222bac968923d8e1e78bf0f2dcb Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 16:01:45 +0100 Subject: [PATCH 06/68] test(site): make R2, R4, R5a and R5b judge what Core does on master Review fixes for W0-4: - r4: Core refuses a battery hold over 1800 s, so the 3600 s hold made the run error before any kill. Post a 1800 s hold 300 s before the first kill; it outlasts both. - r2: the site stays under 1.2 x the fuse, where Core cuts the car on its documented 60 s heat budget (control/fuse_heat.go), not at once. Judge that contract: over 1.2 x the fuse at most the charger's delay + 7 s, and the 60 s heat under 1.13 x the fuse. Record the time over fuse - 1 A and when Core sends the cut. - r5a: start the battery at its 5 % floor so the site runs 30 A before Core starts, check that as setup, and judge against fuse - 0.5 A, Core's own line (as r3 does). - r5b: drop the D6 known line. The saved plan is younger than MaxPlanAge and a fresh plan lands within seconds, so the deadline reserve never acts and the run does not reach D6. - r1, r4: Charge now counts as back only once it runs unbroken to the next event, so a stop that starts after the restart is seen. - README: move the r rows off the s17 line #1875 edits. Co-Authored-By: Claude Opus 5.5 --- go/test/site/README.md | 21 +++-- go/test/site/evaluate_test.go | 18 ++++ go/test/site/scenarios_p0_test.go | 33 +++++--- go/test/site/scenarios_p0_unit_test.go | 113 ++++++++++++++++++++++++- go/test/site/verdicts_test.go | 67 ++++++++++----- 5 files changed, 205 insertions(+), 47 deletions(-) diff --git a/go/test/site/README.md b/go/test/site/README.md index f1297bcfc..a632f1832 100644 --- a/go/test/site/README.md +++ b/go/test/site/README.md @@ -61,7 +61,9 @@ that touch control, loadpoint, OCPP or telemetry code), `siterig/full` A criterion named in a scenario's `known` map fails on master for the finding it names. The run passes while it keeps failing, and fails once it -passes: a fix deletes its line in the same pull request. +passes: a fix deletes its line in the same pull request. The `r` +scenarios are R1-R5 of the stable plan; their known lines name the Wave 1 +item whose fix deletes them. A scenario with a `skip` waits for a device-simulator change the pinned commit lacks. `TestSite` reports it as `skip` with the knob it needs; the @@ -104,15 +106,12 @@ tick as 2 s more. | `s15bat-16` One-phase charger, battery rising | 16 A, 3 A per phase, the s15 charger, battery at 50 % following its EMS 8 s late; PV 2.1 kW rising every 30 s (+2.5 kW, then 1.5 kW) so Core charges the battery in steps; Charge now 6 s after the second step, while the raise is on its way | the battery order rose over 1 150 W in the 20 s before (setup check); car charging within 10 s; fuse holds; over the limit at most 3 s | | | `s15p-25` One-phase charger, planned | as s15, a plan for 600 Wh by the first quarter hour 15 min out | fuse holds; 90 % of the plan by the ready time; never called not following | | | `s14-25` One-phase car | an 11 kW charger with a one-phase car, a plan it cannot meet, 20 min | 3.4–3.8 kW over the last 10 min; never called not following | | -| `s16-25` Import ceiling | 25 A, house 1.3 kW, battery idle at its floor, `peak_import_ceiling_w` 4 500, Charge now 16 A: house and the car's 4 140 W minimum are above the ceiling. Starts in an hour's first minutes or waits for :56, then runs one whole clock hour and 3 min | the car starts on the hour's room before :45; every clock hour's recorded import averages at most the ceiling + 1 %; the next hour stops the car within 60 s; while held it says `import_limit` 90 % of the time and never `fuse_limit`; fuse holds | | -| `s17-25` Two equal batteries | 25 A, house 3 kW, no PV, two hybrids with 10 kWh at 74 % and 60 %, Energyplan whatever `FTW_SITE_ENGINE` says (Core DP plans one battery), a 6 h horizon (over 48 h the plan keeps the batteries for tomorrow's dearer hours). Waits up to an hour for a quarter the plan discharges, then 15 min | Energyplan's plan moves the batteries in half the polls (setup; tolerated, the day's prices decide); while the fleet moves 500 W or more, each battery takes at least a quarter of it 90 % of the time; while the plan moves them, the charge gap shrinks by over 0.2 points; fuse holds | | -| `r1-25` Meter silent, then offline | 25 A, 15 A per phase, battery at 50 %, Charge now 16 A; the site meter silent (Modbus timeouts) for 120 s, then gone for 90 s. **Skipped**: the pinned simulator cannot silence the site meter | the battery relieved the fuse (setup); while silent no offer rises and the battery order only moves toward 0 (**known**: A1); a 0 W order and the battery back on its own within 64 s; the meter never shows live; Charge now back within 95 s of each return; fuse holds | | -| `r2-25`, `r2-60-25` Battery drops out | 25 A, 20 A per phase, the battery held at a 3 kW discharge, a car taking 10 A on Charge now, the charger at once or 60 s late; the inverter gone for 180 s | the battery discharged (setup); fuse holds; over the limit at most the charger's delay + 7 s after the drop; no offer rises while it is gone; Home use shown as estimated throughout | | +| `r1-25` Meter silent, then offline | 25 A, 15 A per phase, battery at 50 %, Charge now 16 A; the site meter silent (Modbus timeouts) for 120 s, then gone for 90 s. **Skipped**: the pinned simulator cannot silence the site meter | the battery relieved the fuse (setup); while silent no offer rises and the battery order only moves toward 0 (**known**: A1); a 0 W order and the battery back on its own within 64 s; the meter never shows live; Charge now back within 95 s of each return and held until the next event; fuse holds | | +| `r2-25`, `r2-60-25` Battery drops out | 25 A, 20 A per phase, the battery held at a 3 kW discharge, a car taking 10 A on Charge now, the charger at once or 60 s late; the inverter gone for 180 s. The site stays under 1.2 × the fuse, where Core cuts the car on its 60 s heat budget, not at once | the battery discharged (setup); fuse holds; over 1.2 × the fuse at most the charger's delay + 7 s; the 60 s heat under 1.13 × the fuse; no offer rises while it is gone; Home use shown as estimated throughout. The time over fuse − 1 A and when Core sends the cut are recorded | | | `r3-25` Planner floor | 25 A, 15 A per phase, battery at 12 %, planner `soc_min` 10 %, inverter floor 5 %, charger 60 s late, Charge now 16 A for 600 s | the battery reaches the floor (setup); no discharge ordered below it (**known**: A4); the battery order swings at most 100 W over the last 5 min (**known**: A3, A4); over fuse − 0.5 A at most the delay + 7 s (Core holds the phase at its own line, as in s3); fuse holds | | -| `r4-25` Hard kill | 25 A, 12 A per phase, the battery held at a 3 kW discharge, Charge now 16 A; once the day's Home use is known and 15 min more, SIGKILL for 20 s, and 2 min later for 120 s while the house steps to 16 A | Charge now back at its minimum within 60 s of each restart; the day's Home use kept within 1 % across the first kill; session energy counts again (**known**: E1); no state.db recovery in the log; fuse holds | | -| `r5a-25` Start beside a charging car | 25 A, 14 A per phase, a car charging on its own at 16 A for 60 s before Core starts | the car charged (setup); under the limit within 30 s of Core answering, and over it at most 3 s after; Home use shown within 30 s; fuse holds | | -| `r5b-25` Start on a stale plan | a goal 40 → 60 % 8 h out, Core stopped for 20 min | no positive order in the first 30 s before a fresh plan (**known**: D6); Home use shown within 30 s; fuse holds | | +| `r4-25` Hard kill | 25 A, 12 A per phase, Charge now 16 A; once the day's Home use is known and 10 min more, the battery held at a 3 kW discharge; 5 min later SIGKILL for 20 s, and 2 min after that for 120 s while the house steps to 16 A | Charge now back at its minimum within 60 s of each restart and held until the next kill or the end; the day's Home use kept within 1 % across the first kill; session energy counts again (**known**: E1); no state.db recovery in the log; fuse holds | | +| `r5a-25` Start beside a charging car | 25 A, 14 A per phase, battery at its 5 % floor, a car charging on its own at 16 A: 30 A per phase for 60 s before Core starts | the car charged and the site was over the fuse (setup); under fuse − 0.5 A within 30 s of Core answering, and over it at most 3 s after; Home use shown within 30 s; fuse holds | | +| `r5b-25` Start on a stale plan | a goal 40 → 60 % 8 h out, Core stopped for 20 min | no positive order in the first 30 s before a fresh plan; Home use shown within 30 s; fuse holds. It does not reach D6 on master: the saved plan is younger than 30 min and a fresh one lands within seconds | | | `r5c-25` Start into a new session | Charge now, Core stopped for 10 min while the car leaves and another plugs in | Core sees the car within 60 s; Home use shown within 30 s; fuse holds. Whether Charge now carries over is recorded, not judged: ev-088 waits for the owner | | - -The `r` scenarios are R1-R5 of the stable plan. A **known** line names the -Wave 1 item whose fix deletes it. +| `s16-25` Import ceiling | 25 A, house 1.3 kW, battery idle at its floor, `peak_import_ceiling_w` 4 500, Charge now 16 A: house and the car's 4 140 W minimum are above the ceiling. Starts in an hour's first minutes or waits for :56, then runs one whole clock hour and 3 min | the car starts on the hour's room before :45; every clock hour's recorded import averages at most the ceiling + 1 %; the next hour stops the car within 60 s; while held it says `import_limit` 90 % of the time and never `fuse_limit`; fuse holds | | +| `s17-25` Two equal batteries | 25 A, house 3 kW, no PV, two hybrids with 10 kWh at 74 % and 60 %, Energyplan whatever `FTW_SITE_ENGINE` says (Core DP plans one battery), a 6 h horizon (over 48 h the plan keeps the batteries for tomorrow's dearer hours). Waits up to an hour for a quarter the plan discharges, then 15 min | Energyplan's plan moves the batteries in half the polls (setup; tolerated, the day's prices decide); while the fleet moves 500 W or more, each battery takes at least a quarter of it 90 % of the time; while the plan moves them, the charge gap shrinks by over 0.2 points; fuse holds | | diff --git a/go/test/site/evaluate_test.go b/go/test/site/evaluate_test.go index 43e406549..7dc1a7a36 100644 --- a/go/test/site/evaluate_test.go +++ b/go/test/site/evaluate_test.go @@ -345,6 +345,24 @@ func (d *runData) firstT(t0 float64, pred func(*sample) bool) *float64 { return nil } +// holdsFrom is the seconds from t0 to the start of the unbroken run of +// samples satisfying pred that lasts until t1, or nil when the last sample +// before t1 does not. A stop that begins after t0 resets it, so a car still +// running at t0 and stopped later does not count as back. +func (d *runData) holdsFrom(t0, t1 float64, pred func(*sample) bool) *float64 { + var from *float64 + for _, r := range d.window(t0, t1) { + switch { + case !pred(r): + from = nil + case from == nil: + v := r.T - t0 + from = &v + } + } + return from +} + // runsOver is the longest contiguous stretch and the total seconds with the // worst phase above limit. func (d *runData) runsOver(t0, t1, limit float64) (longest, total float64) { diff --git a/go/test/site/scenarios_p0_test.go b/go/test/site/scenarios_p0_test.go index bf3c5c83e..a2a68c4cf 100644 --- a/go/test/site/scenarios_p0_test.go +++ b/go/test/site/scenarios_p0_test.go @@ -35,8 +35,7 @@ func init() { scenario{name: "r5a-25", dir: "r5a-start-car-charging-25A", minutes: 5, run: func(c *runCtx) (map[string]any, error) { return r5a(c, 25) }, judge: judgeR5a}, scenario{name: "r5b-25", dir: "r5b-start-stale-plan-25A", minutes: 27, run: func(c *runCtx) (map[string]any, error) { return r5b(c, 25) }, - judge: judgeR5b, - known: map[string]string{"no positive EV order in the first 30 s without a fresh plan": "D6: the deadline reserve orders full power whatever the slack (deadline_need.go:11-40, #1718)"}}, + judge: judgeR5b}, scenario{name: "r5c-25", dir: "r5c-start-new-session-25A", minutes: 15, run: func(c *runCtx) (map[string]any, error) { return r5c(c, 25) }, judge: judgeR5c}, ) @@ -88,8 +87,9 @@ func r1(c *runCtx, fuse float64) (map[string]any, error) { // r2 holds the battery at a 3 kW discharge under a 20 A house, so the car's // room rests on it, then takes the inverter off the site for 180 s: each -// phase rises 4.3 A at once. The car takes at most 10 A, so its draw before -// Core's first profile keeps the site under 1.25 x the fuse. +// phase rises 4-6 A at once. The car takes at most 10 A, so the site stays +// under 1.2 x the fuse, where Core's 60 s heat budget, not an instant cut, +// decides when the car stops (control/fuse_heat.go). func r2(c *runCtx, fuse, delayS float64) (map[string]any, error) { err := with(c, stackSpec{fuseA: fuse, loadsW: houseA(20), socPct: 60, chargers: []charger{{delayS: delayS, carMaxA: 10}}}, func(st *stack) error { @@ -158,7 +158,8 @@ func r3(c *runCtx, fuse float64) (map[string]any, error) { // 20 s; two minutes later the second lasts 120 s, and the house steps to // 16 A per phase while Core is gone. Like s7, the run first waits until the // day's Home use is known, and long enough after it that one restart stays -// under the 10 % unknown-time rule. +// under the 10 % unknown-time rule. Core holds a battery for at most +// 1800 s, so the hold starts 300 s before the first kill and outlasts both. func r4(c *runCtx, fuse float64) (map[string]any, error) { var serial string err := with(c, stackSpec{fuseA: fuse, loadsW: houseA(12), socPct: 60}, func(st *stack) error { @@ -166,9 +167,6 @@ func r4(c *runCtx, fuse float64) (map[string]any, error) { return err } serial = st.serial(0) - if err := st.post("/api/battery/manual_hold", map[string]any{"direction": "discharge", "power_w": 3000, "hold_s": 3600}, nil); err != nil { - return err - } st.mark("charge_now") if err := st.chargeNow("garage", 16, "3p", 0); err != nil { return err @@ -179,7 +177,12 @@ func r4(c *runCtx, fuse float64) (map[string]any, error) { }) { st.mark("today_known") } - sleepS(900) + sleepS(600) + st.mark("battery_hold") + if err := st.post("/api/battery/manual_hold", map[string]any{"direction": "discharge", "power_w": 3000, "hold_s": 1800}, nil); err != nil { + return err + } + sleepS(300) st.mark("kill1") st.stopFTW(syscall.SIGKILL) sleepS(20) @@ -211,21 +214,25 @@ func r4(c *runCtx, fuse float64) (map[string]any, error) { // r5a starts Core while the car charges on its own: plugged when the house // comes up, it starts a local transaction and draws all it can, 16 A on -// 14 A of house load. +// 14 A of house load. The battery sits at the inverter's 5 % floor, so it +// cannot carry the car: the site runs 30 A per phase until Core acts. func r5a(c *runCtx, fuse float64) (map[string]any, error) { - err := with(c, stackSpec{fuseA: fuse, loadsW: houseA(14), socPct: 50, startAfterS: 60, + err := with(c, stackSpec{fuseA: fuse, loadsW: houseA(14), socPct: 5, startAfterS: 60, chargers: []charger{{plugged: true}}}, func(st *stack) error { st.mark("ftw_up") sleepS(180) st.mark("end") return nil }) - return map[string]any{"scenario": "r5a", "fuse": fuse, "house_a": 14}, err + return map[string]any{"scenario": "r5a", "fuse": fuse, "house_a": 14, "soc_pct": 5}, err } // r5b saves a goal with hours of slack, so no fresh plan need charge now, // then stops Core for 20 min and starts it on the plan it saved. For the -// first minute the rig asks for the plan once a second (plan.jsonl). +// first minute the rig asks for the plan once a second (plan.jsonl). On +// master it does not reach D6: the saved plan is younger than MaxPlanAge +// (30 min) and a fresh one lands within seconds, so the deadline reserve +// never acts. D6's proof is its unit repro; this run guards the start. func r5b(c *runCtx, fuse float64) (map[string]any, error) { err := with(c, stackSpec{fuseA: fuse, loadsW: houseA(3), socPct: 50}, func(st *stack) error { if err := st.plug(0); err != nil { diff --git a/go/test/site/scenarios_p0_unit_test.go b/go/test/site/scenarios_p0_unit_test.go index ad7ddaf93..0e5b0fd88 100644 --- a/go/test/site/scenarios_p0_unit_test.go +++ b/go/test/site/scenarios_p0_unit_test.go @@ -200,7 +200,7 @@ func TestJudgeR4SessionEnergy(t *testing.T) { if v := run(0); v["session energy counts again after each restart"] { t.Fatal("session energy stuck at 0 after the restarts passes") } - if v := run(150); !v["session energy counts again after each restart"] || !v["Charge now back at its minimum within 60 s of each restart"] { + if v := run(150); !v["session energy counts again after each restart"] || !v["Charge now back at its minimum within 60 s of each restart, and held"] { t.Fatalf("session energy counting after the restarts: %v", v) } } @@ -226,3 +226,114 @@ func TestJudgeR5bAllowsChargingOnlyOnAFreshPlan(t *testing.T) { t.Fatal("0 A until the fresh plan, then 16 A, fails") } } + +func TestHoldsFromResetsOnALaterStop(t *testing.T) { + d := synth(100, nil, nil, func(i int, r *sample) { + if i < 20 || i >= 50 { + r.CarW[0] = 11040 + } + }) + charging := func(r *sample) bool { return carW(r, 0) >= 0.95*minW } + if p := d.holdsFrom(10, 100, charging); p == nil || *p != 40 { + t.Fatalf("charging at 10 s, stopped 20-49 s, back from 50 s: %v, want 40", p) + } + if p := d.holdsFrom(10, 40, charging); p != nil { + t.Fatalf("stopped at the window's end: %v, want nil", *p) + } +} + +// The car still draws at the restart, then Core stops it 20 s later for +// 50 s. A judge that takes the first charging sample calls it back at once. +func TestJudgeR4SeesAStopAfterTheRestart(t *testing.T) { + marks := map[string]float64{"charge_now": 0, "kill1": 100, "up1": 130, "kill2": 250, "up2": 400, "end": 600} + wh := 150.0 + d := synth(600, marks, map[string]any{"fuse": 25.0, "charger": "CP1"}, func(i int, r *sample) { + r.Status = &ftwStatus{Drivers: map[string]ftwDriver{"CP1": {Status: "ok", EVSessionWh: &wh}}} + if i < 150 || i >= 200 { + r.CarW[0] = 11040 + } + }) + m, cs := judgeR4(d) + if verdictsOf(cs)["Charge now back at its minimum within 60 s of each restart, and held"] { + t.Fatalf("a stop from 20 to 70 s after the restart passes: %v", m["charge_now_back_s"]) + } +} + +// r2Run is R2's record: the battery offline from 100 to 280 s, the site at +// 24.015 A (Core's own line) before the drop and after the return, and +// overA per phase for the first overS s of the drop, then 20 A. +func r2Run(overA float64, overS int) *runData { + marks := map[string]float64{"charge_now": 0, "offline": 100, "online": 280, "end": 400} + d := synth(400, marks, map[string]any{"fuse": 25.0, "charger_delay_s": 0.0}, func(i int, r *sample) { + r.BatW = -3000 + q, w := "measured", 5000.0 + if i >= 100 && i < 280 { + q = "estimated" + } + r.Status = &ftwStatus{LoadQuality: &q, LoadW: &w} + switch { + case i >= 100 && i < 100+overS: + r.PhaseA = [3]float64{overA, overA, overA} + case i >= 100 && i < 280: + r.PhaseA = [3]float64{20, 20, 20} + default: + r.PhaseA = [3]float64{24.015, 24.015, 24.015} + } + }) + d.frames = []frame{profileAt(50, 8), profileAt(float64(100+overS-2), 0), profileAt(285, 8)} + return d +} + +func TestJudgeR2Overage(t *testing.T) { + const instant = "over 1.2 x the fuse no longer than the charger's delay + 7 s after the drop" + const heat = "the 60 s heat stays under 1.13 x the fuse" + // A short overage, then Core's own line after the return (the review's + // edge case), and the heat budget spent at 29.95 A for 18 s, as on + // master. + for _, c := range []struct { + a float64 + s int + }{{28, 4}, {29.95, 18}} { + _, cs := judgeR2(r2Run(c.a, c.s)) + if v := verdictsOf(cs); !v[instant] || !v[heat] { + t.Errorf("%.2f A for %d s, then Core's line: %v", c.a, c.s, v) + } + } + _, cs := judgeR2(r2Run(31, 12)) + if verdictsOf(cs)[instant] { + t.Error("31 A, over 1.2 x 25 A, for 12 s passes") + } + _, cs = judgeR2(r2Run(29.95, 180)) + if verdictsOf(cs)[heat] { + t.Error("a car never cut at 29.95 A for the whole outage passes") + } +} + +// r5aRun is R5a's record: Core starts at 60 s and answers at 70 s; the site +// runs preA per phase with the car at 16 A until 80 s, then Core's own line +// with the car at 10 A. +func r5aRun(preA float64) *runData { + marks := map[string]float64{"ftw_start": 60, "ftw_up": 70, "end": 250} + return synth(250, marks, map[string]any{"fuse": 25.0}, func(i int, r *sample) { + w := 3000.0 + r.Status = &ftwStatus{LoadW: &w} + if i < 80 { + r.PhaseA, r.CarW[0] = [3]float64{preA, preA, preA}, 11040 + return + } + r.PhaseA, r.CarW[0] = [3]float64{24.015, 24.015, 24.015}, 6900 + }) +} + +func TestJudgeR5a(t *testing.T) { + _, cs := judgeR5a(r5aRun(30)) + for name, ok := range verdictsOf(cs) { + if !ok { + t.Errorf("30 A cut to Core's own 24.015 A line 10 s after it answers: %q fails", name) + } + } + _, cs = judgeR5a(r5aRun(22.75)) + if verdictsOf(cs)["the site was over the fuse before Core started"] { + t.Error("a site at 22.75 A before Core starts passes the setup: the run proves nothing") + } +} diff --git a/go/test/site/verdicts_test.go b/go/test/site/verdicts_test.go index 0920eefb9..e8790eb05 100644 --- a/go/test/site/verdicts_test.go +++ b/go/test/site/verdicts_test.go @@ -556,10 +556,17 @@ func judgeS11(d *runData) (metrics, []criterion) { // ---- R1-R5, the stable plan's P0 scenarios ---- +// fuseInstantFactor is Core's: above this multiple of the fuse it cuts the +// car at once, with no heat budget (control/fuse_heat.go). mcbHourFactor is +// the current a miniature circuit breaker carries for an hour without a +// trip, the lower of the two ratings Core's heat model keeps under. +const fuseInstantFactor, mcbHourFactor = 1.2, 1.13 + // judgeR1: while the meter is silent Core raises nothing and its battery // order only moves toward 0; within the 60 s watchdog and two ticks it // stands the charger down and hands the battery back; it never shows the -// meter as live; Charge now returns after the meter does. +// meter as live; Charge now returns after the meter does and runs until the +// next event. func judgeR1(d *runData) (metrics, []criterion) { tCN, tS, tB, t1 := d.marks["charge_now"], d.marks["silent"], d.marks["back"], d.marks["end"] tOff, tOn := d.marks["offline"], d.marks["online"] @@ -584,7 +591,7 @@ func judgeR1(d *runData) (metrics, []criterion) { charging := func(r *sample) bool { return carW(r, 0) >= 0.95*minW } standdown := d.firstOffer(tS, func(p profile) bool { return p.Limit == 0 }) handBack := d.firstT(tS, func(r *sample) bool { return !batForced(r) }) - back1, back2 := d.firstT(tB, charging), d.firstT(tOn, charging) + back1, back2 := d.holdsFrom(tB, tOff, charging), d.holdsFrom(tOn, t1, charging) rises := d.offerRises(tS, tB) m := metrics{"battery_order_at_silence_w": math.Round(o0), "battery_wound_samples": wound, "offer_rises_while_silent": rises, "standdown_s": roundp(standdown, 1), "battery_hand_back_s": roundp(handBack, 1), @@ -596,20 +603,27 @@ func judgeR1(d *runData) (metrics, []criterion) { crit("a 0 W charger order within 64 s of the silence", le(standdown, 64)), crit("the battery back on its own within 64 s of the silence", le(handBack, 64)), crit("the meter never shows live while it is silent or offline", live == 0), - crit("Charge now back at its minimum within 95 s of each return", le(back1, 95) && le(back2, 95)), + crit("Charge now back at its minimum within 95 s of each return, and held", le(back1, 95) && le(back2, 95)), crit("fuse holds", !anyBlown(d.window(tCN, t1))), } } // judgeR2: when the battery that carried the car's room drops out, the fuse -// holds, the overage lasts no longer than the charger takes to answer, no -// offer counts the battery's last -3 kW as room, and Home use says it is -// estimated. +// holds, no offer counts the battery's last -3 kW as room, and Home use says +// it is estimated (the stable plan's R2). Under 1.2 x the fuse Core spends a +// 60 s heat budget before it cuts the car (control/fuse_heat.go), so the +// overage is judged by that contract: above 1.2 x it lasts no longer than +// the charger takes to answer, and the 60 s heat stays under the 1.13 x a +// miniature circuit breaker carries for an hour. How long the site stays +// over fuse - 1 A and when Core sends the cut are recorded. func judgeR2(d *runData) (metrics, []criterion) { fuse, delay := d.metaF("fuse"), d.metaF("charger_delay_s") tCN, tOff, tOn, t1 := d.marks["charge_now"], d.marks["offline"], d.marks["online"], d.marks["end"] pre := meanOf(d.window(tOff-30, tOff), batSigned) - over, _ := d.runsOver(tOff, tOn+60, fuse-1) + allowed := delay + 7 + instant, _ := d.runsOver(tOff, tOn+60, fuseInstantFactor*fuse) + over1, _ := d.runsOver(tOff, tOn+60, fuse-1) + heatOver, heatPeak := d.i2Over(tOff-60, tOn+60, mcbHourFactor*fuse) during := summarize(d.window(tOff+15, tOn)) marked := 0 for k, v := range during.LoadQuality { @@ -617,15 +631,18 @@ func judgeR2(d *runData) (metrics, []criterion) { marked += v } } - allowed := delay + 7 rises := d.offerRises(tOff, tOn) - m := metrics{"battery_w_before": math.Round(pre), "over_fuse_minus1_longest_s": over, "allowed_over_s": allowed, + cut := d.firstOffer(tOff, func(p profile) bool { return p.Limit == 0 }) + m := metrics{"battery_w_before": math.Round(pre), "allowed_over_s": allowed, + "over_fuse_x1_2_longest_s": instant, "over_fuse_minus1_longest_s": over1, + "heat_peak_a": heatPeak, "heat_over_x1_13_s": heatOver, "cut_sent_s": roundp(cut, 1), "offer_rises_while_offline": rises, "during": during, "max_i_after_drop": round(maxOf(d.window(tOff, tOn+60), maxAbsI), 2)} return m, []criterion{ crit("the battery discharged 2 kW or more before the drop", pre <= -2000), // the setup crit("fuse holds", !anyBlown(d.window(tCN, t1))), - crit("over fuse - 1 A no longer than the charger's delay + 7 s after the drop", over <= allowed), + crit("over 1.2 x the fuse no longer than the charger's delay + 7 s after the drop", instant <= allowed), + crit("the 60 s heat stays under 1.13 x the fuse", heatOver == 0), crit("no EV offer rises while the battery is offline", rises == 0), crit("Home use shown as estimated throughout the outage", during.Samples > 0 && during.LoadWShown == during.Samples && marked == during.Samples), @@ -672,15 +689,17 @@ func judgeR3(d *runData) (metrics, []criterion) { } } -// judgeR4: after each hard kill Charge now is back within a minute, the -// session energy counts again and state.db opens clean; the day's Home use +// judgeR4: after each hard kill Charge now is back within a minute and runs +// until the next kill or the end (a car still drawing from before the kill +// and stopped later is not back), the session energy counts again and +// state.db opens clean; the day's Home use // survives the first kill. The second outage's 120 s would break the 10 % // unknown-time rule on a run this short, so its day total is recorded only. func judgeR4(d *runData) (metrics, []criterion) { fuse := d.metaF("fuse") tCN, k1, u1, k2, u2, t1 := d.marks["charge_now"], d.marks["kill1"], d.marks["up1"], d.marks["kill2"], d.marks["up2"], d.marks["end"] charging := func(r *sample) bool { return carW(r, 0) >= 0.95*minW } - back1, back2 := d.firstT(u1, charging), d.firstT(u2, charging) + back1, back2 := d.holdsFrom(u1, k2, charging), d.holdsFrom(u2, t1, charging) before, after := todayLoadWh(d.window(k1-30, k1)), todayLoadWh(d.window(u1, k2)) nullAfter := 0 for _, r := range d.window(u1, k2) { @@ -708,7 +727,7 @@ func judgeR4(d *runData) (metrics, []criterion) { "session_wh_90s_after_ups": []float64{session(u1, u1+90), session(u2, u2+90)}, "recovery_log_lines": len(recovery), "over_fuse_minus1_longest_after_up2_s": overAfter} return m, []criterion{ - crit("Charge now back at its minimum within 60 s of each restart", le(back1, 60) && le(back2, 60)), + crit("Charge now back at its minimum within 60 s of each restart, and held", le(back1, 60) && le(back2, 60)), crit("the day's Home use kept within 1 % across the first kill", kept), crit("session energy counts again after each restart", session(u1, u1+90) > 0 && session(u2, u2+90) > 0), crit("state.db opens with no recovery error", len(recovery) == 0), @@ -721,24 +740,28 @@ func (d *runData) homeUseBack(t0 float64) *float64 { return d.firstT(t0, func(r *sample) bool { return status(r).LoadW != nil }) } -// judgeR5a: Core starting beside a car that already draws its maximum -// brings the site under the limit within 30 s and keeps it there. +// judgeR5a: Core starting beside a car that already draws its maximum, with +// the site over the fuse, brings the site under the limit within 30 s and +// keeps it there. Core holds the worst phase at its own line, between +// fuse - 1 A and fuse - 0.5 A (see s3, r3), so the limit is fuse - 0.5 A. func judgeR5a(d *runData) (metrics, []criterion) { fuse := d.metaF("fuse") tS, tUp, t1 := d.marks["ftw_start"], d.marks["ftw_up"], d.marks["end"] pre := meanOf(d.window(tS-20, tS), func(r *sample) float64 { return carW(r, 0) }) - fit := d.firstT(tUp, func(r *sample) bool { return maxAbsI(r) <= fuse-1 }) + preI := maxOf(d.window(tS-20, tS), maxAbsI) + fit := d.firstT(tUp, func(r *sample) bool { return maxAbsI(r) <= fuse-0.5 }) overAfter := 0.0 if fit != nil { - overAfter, _ = d.runsOver(tUp+*fit, t1, fuse-1) + overAfter, _ = d.runsOver(tUp+*fit, t1, fuse-0.5) } shown := d.homeUseBack(tUp) m := metrics{"car_w_before_start": math.Round(pre), "under_limit_s": roundp(fit, 1), "over_after_that_longest_s": overAfter, - "home_use_shown_s": roundp(shown, 1), "max_i_before_start": round(maxOf(d.window(tS-20, tS), maxAbsI), 2)} + "home_use_shown_s": roundp(shown, 1), "max_i_before_start": round(preI, 2)} return m, []criterion{ - crit("the car charged before Core started", pre >= minW), // the setup - crit("under fuse - 1 A within 30 s of Core answering", le(fit, 30)), - crit("over fuse - 1 A at most 3 s once under it", fit != nil && overAfter <= 3), + crit("the car charged before Core started", pre >= minW), // the setup + crit("the site was over the fuse before Core started", preI > fuse), // the setup + crit("under fuse - 0.5 A within 30 s of Core answering", le(fit, 30)), + crit("over fuse - 0.5 A at most 3 s once under it", fit != nil && overAfter <= 3), crit("Home use shown within 30 s of Core answering", le(shown, 30)), crit("fuse holds", !anyBlown(d.window(tS, t1))), } From 6803ab22643992a5bf7e8b707219d492af77121c Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 17:33:38 +0100 Subject: [PATCH 07/68] test(site): judge R2-R5a at the fuse rating, not fuse - 0.5 A or - 1 A Core's working limit is the fuse rating less safety_margin_a, which is opt-in (owner rule of 27 Oct). R3 and R5a now judge the overage above the fuse, R2 and R4 record it there, and the fixtures put Core's own line at 25.0 A on a 25 A fuse. New cases hold exactly 25.0 A (passes) and 25.1 A beyond the time budget (fails) for R3 and R5a. Co-Authored-By: Claude Opus 5.5 --- go/test/site/README.md | 6 +-- go/test/site/scenarios_p0_unit_test.go | 74 ++++++++++++++++++++++---- go/test/site/verdicts_test.go | 34 ++++++------ 3 files changed, 84 insertions(+), 30 deletions(-) diff --git a/go/test/site/README.md b/go/test/site/README.md index a632f1832..c11ed80cd 100644 --- a/go/test/site/README.md +++ b/go/test/site/README.md @@ -107,10 +107,10 @@ tick as 2 s more. | `s15p-25` One-phase charger, planned | as s15, a plan for 600 Wh by the first quarter hour 15 min out | fuse holds; 90 % of the plan by the ready time; never called not following | | | `s14-25` One-phase car | an 11 kW charger with a one-phase car, a plan it cannot meet, 20 min | 3.4–3.8 kW over the last 10 min; never called not following | | | `r1-25` Meter silent, then offline | 25 A, 15 A per phase, battery at 50 %, Charge now 16 A; the site meter silent (Modbus timeouts) for 120 s, then gone for 90 s. **Skipped**: the pinned simulator cannot silence the site meter | the battery relieved the fuse (setup); while silent no offer rises and the battery order only moves toward 0 (**known**: A1); a 0 W order and the battery back on its own within 64 s; the meter never shows live; Charge now back within 95 s of each return and held until the next event; fuse holds | | -| `r2-25`, `r2-60-25` Battery drops out | 25 A, 20 A per phase, the battery held at a 3 kW discharge, a car taking 10 A on Charge now, the charger at once or 60 s late; the inverter gone for 180 s. The site stays under 1.2 × the fuse, where Core cuts the car on its 60 s heat budget, not at once | the battery discharged (setup); fuse holds; over 1.2 × the fuse at most the charger's delay + 7 s; the 60 s heat under 1.13 × the fuse; no offer rises while it is gone; Home use shown as estimated throughout. The time over fuse − 1 A and when Core sends the cut are recorded | | -| `r3-25` Planner floor | 25 A, 15 A per phase, battery at 12 %, planner `soc_min` 10 %, inverter floor 5 %, charger 60 s late, Charge now 16 A for 600 s | the battery reaches the floor (setup); no discharge ordered below it (**known**: A4); the battery order swings at most 100 W over the last 5 min (**known**: A3, A4); over fuse − 0.5 A at most the delay + 7 s (Core holds the phase at its own line, as in s3); fuse holds | | +| `r2-25`, `r2-60-25` Battery drops out | 25 A, 20 A per phase, the battery held at a 3 kW discharge, a car taking 10 A on Charge now, the charger at once or 60 s late; the inverter gone for 180 s. The site stays under 1.2 × the fuse, where Core cuts the car on its 60 s heat budget, not at once | the battery discharged (setup); fuse holds; over 1.2 × the fuse at most the charger's delay + 7 s; the 60 s heat under 1.13 × the fuse; no offer rises while it is gone; Home use shown as estimated throughout. The time over the fuse and when Core sends the cut are recorded | | +| `r3-25` Planner floor | 25 A, 15 A per phase, battery at 12 %, planner `soc_min` 10 %, inverter floor 5 %, charger 60 s late, Charge now 16 A for 600 s | the battery reaches the floor (setup); no discharge ordered below it (**known**: A4); the battery order swings at most 100 W over the last 5 min (**known**: A3, A4); over the fuse at most the delay + 7 s; fuse holds | | | `r4-25` Hard kill | 25 A, 12 A per phase, Charge now 16 A; once the day's Home use is known and 10 min more, the battery held at a 3 kW discharge; 5 min later SIGKILL for 20 s, and 2 min after that for 120 s while the house steps to 16 A | Charge now back at its minimum within 60 s of each restart and held until the next kill or the end; the day's Home use kept within 1 % across the first kill; session energy counts again (**known**: E1); no state.db recovery in the log; fuse holds | | -| `r5a-25` Start beside a charging car | 25 A, 14 A per phase, battery at its 5 % floor, a car charging on its own at 16 A: 30 A per phase for 60 s before Core starts | the car charged and the site was over the fuse (setup); under fuse − 0.5 A within 30 s of Core answering, and over it at most 3 s after; Home use shown within 30 s; fuse holds | | +| `r5a-25` Start beside a charging car | 25 A, 14 A per phase, battery at its 5 % floor, a car charging on its own at 16 A: 30 A per phase for 60 s before Core starts | the car charged and the site was over the fuse (setup); under the fuse within 30 s of Core answering, and over it at most 3 s after; Home use shown within 30 s; fuse holds | | | `r5b-25` Start on a stale plan | a goal 40 → 60 % 8 h out, Core stopped for 20 min | no positive order in the first 30 s before a fresh plan; Home use shown within 30 s; fuse holds. It does not reach D6 on master: the saved plan is younger than 30 min and a fresh one lands within seconds | | | `r5c-25` Start into a new session | Charge now, Core stopped for 10 min while the car leaves and another plugs in | Core sees the car within 60 s; Home use shown within 30 s; fuse holds. Whether Charge now carries over is recorded, not judged: ev-088 waits for the owner | | | `s16-25` Import ceiling | 25 A, house 1.3 kW, battery idle at its floor, `peak_import_ceiling_w` 4 500, Charge now 16 A: house and the car's 4 140 W minimum are above the ceiling. Starts in an hour's first minutes or waits for :56, then runs one whole clock hour and 3 min | the car starts on the hour's room before :45; every clock hour's recorded import averages at most the ceiling + 1 %; the next hour stops the car within 60 s; while held it says `import_limit` 90 % of the time and never `fuse_limit`; fuse holds | | diff --git a/go/test/site/scenarios_p0_unit_test.go b/go/test/site/scenarios_p0_unit_test.go index 0e5b0fd88..b0756b8c5 100644 --- a/go/test/site/scenarios_p0_unit_test.go +++ b/go/test/site/scenarios_p0_unit_test.go @@ -260,7 +260,7 @@ func TestJudgeR4SeesAStopAfterTheRestart(t *testing.T) { } // r2Run is R2's record: the battery offline from 100 to 280 s, the site at -// 24.015 A (Core's own line) before the drop and after the return, and +// 25.0 A (Core's own line, the fuse) before the drop and after the return, and // overA per phase for the first overS s of the drop, then 20 A. func r2Run(overA float64, overS int) *runData { marks := map[string]float64{"charge_now": 0, "offline": 100, "online": 280, "end": 400} @@ -277,7 +277,7 @@ func r2Run(overA float64, overS int) *runData { case i >= 100 && i < 280: r.PhaseA = [3]float64{20, 20, 20} default: - r.PhaseA = [3]float64{24.015, 24.015, 24.015} + r.PhaseA = [3]float64{25.0, 25.0, 25.0} } }) d.frames = []frame{profileAt(50, 8), profileAt(float64(100+overS-2), 0), profileAt(285, 8)} @@ -310,9 +310,9 @@ func TestJudgeR2Overage(t *testing.T) { } // r5aRun is R5a's record: Core starts at 60 s and answers at 70 s; the site -// runs preA per phase with the car at 16 A until 80 s, then Core's own line -// with the car at 10 A. -func r5aRun(preA float64) *runData { +// runs preA per phase with the car at 16 A until 80 s, then afterA(i) with +// the car at 10 A. +func r5aRun(preA float64, afterA func(i int) float64) *runData { marks := map[string]float64{"ftw_start": 60, "ftw_up": 70, "end": 250} return synth(250, marks, map[string]any{"fuse": 25.0}, func(i int, r *sample) { w := 3000.0 @@ -321,19 +321,75 @@ func r5aRun(preA float64) *runData { r.PhaseA, r.CarW[0] = [3]float64{preA, preA, preA}, 11040 return } - r.PhaseA, r.CarW[0] = [3]float64{24.015, 24.015, 24.015}, 6900 + a := afterA(i) + r.PhaseA, r.CarW[0] = [3]float64{a, a, a}, 6900 }) } +// atFuse is Core's own line on a 25 A fuse: the rating itself. +func atFuse(int) float64 { return 25.0 } + func TestJudgeR5a(t *testing.T) { - _, cs := judgeR5a(r5aRun(30)) + _, cs := judgeR5a(r5aRun(30, atFuse)) for name, ok := range verdictsOf(cs) { if !ok { - t.Errorf("30 A cut to Core's own 24.015 A line 10 s after it answers: %q fails", name) + t.Errorf("30 A cut to Core's own 25.0 A line 10 s after it answers: %q fails", name) } } - _, cs = judgeR5a(r5aRun(22.75)) + _, cs = judgeR5a(r5aRun(22.75, atFuse)) if verdictsOf(cs)["the site was over the fuse before Core started"] { t.Error("a site at 22.75 A before Core starts passes the setup: the run proves nothing") } } + +// R5a judges at the fuse: exactly 25.0 A on a 25 A fuse passes, and 0.1 A +// over it for longer than the 3 s budget fails. +func TestJudgeR5aJudgesAtTheFuse(t *testing.T) { + const under, over = "under the fuse within 30 s of Core answering", "over the fuse at most 3 s once under it" + judge := func(afterA func(int) float64) map[string]bool { + _, cs := judgeR5a(r5aRun(30, afterA)) + return verdictsOf(cs) + } + if v := judge(atFuse); !v[under] || !v[over] { + t.Errorf("held at exactly 25.0 A: %v", v) + } + // Under the fuse at 80 s, then 25.1 A from 100 to 109 s. + v := judge(func(i int) float64 { + if i >= 100 && i < 110 { + return 25.1 + } + return 25.0 + }) + if v[over] { + t.Error("25.1 A for 9 s once under the fuse passes") + } + if v := judge(func(int) float64 { return 25.1 }); v[under] { + t.Error("held at 25.1 A after Core answers passes") + } +} + +// R3 allows the charger's delay + 7 s (67 s here) over the fuse: exactly +// 25.0 A throughout passes, and 25.1 A for 80 s fails. +func TestJudgeR3JudgesAtTheFuse(t *testing.T) { + const over = "over the fuse no longer than the charger's delay + 7 s" + marks := map[string]float64{"plug": 0, "charge_now": 20, "end": 400} + judge := func(a func(int) float64) bool { + d := synth(400, marks, map[string]any{"fuse": 25.0, "charger_delay_s": 60.0, "planner_floor_pct": 10.0}, func(i int, r *sample) { + v := a(i) + r.PhaseA = [3]float64{v, v, v} + }) + _, cs := judgeR3(d) + return verdictsOf(cs)[over] + } + if !judge(atFuse) { + t.Error("held at exactly 25.0 A fails") + } + if judge(func(i int) float64 { + if i >= 100 && i < 180 { + return 25.1 + } + return 25.0 + }) { + t.Error("25.1 A for 80 s passes") + } +} diff --git a/go/test/site/verdicts_test.go b/go/test/site/verdicts_test.go index e8790eb05..a087ddd76 100644 --- a/go/test/site/verdicts_test.go +++ b/go/test/site/verdicts_test.go @@ -615,14 +615,14 @@ func judgeR1(d *runData) (metrics, []criterion) { // overage is judged by that contract: above 1.2 x it lasts no longer than // the charger takes to answer, and the 60 s heat stays under the 1.13 x a // miniature circuit breaker carries for an hour. How long the site stays -// over fuse - 1 A and when Core sends the cut are recorded. +// over the fuse and when Core sends the cut are recorded. func judgeR2(d *runData) (metrics, []criterion) { fuse, delay := d.metaF("fuse"), d.metaF("charger_delay_s") tCN, tOff, tOn, t1 := d.marks["charge_now"], d.marks["offline"], d.marks["online"], d.marks["end"] pre := meanOf(d.window(tOff-30, tOff), batSigned) allowed := delay + 7 instant, _ := d.runsOver(tOff, tOn+60, fuseInstantFactor*fuse) - over1, _ := d.runsOver(tOff, tOn+60, fuse-1) + overFuse, _ := d.runsOver(tOff, tOn+60, fuse) heatOver, heatPeak := d.i2Over(tOff-60, tOn+60, mcbHourFactor*fuse) during := summarize(d.window(tOff+15, tOn)) marked := 0 @@ -634,7 +634,7 @@ func judgeR2(d *runData) (metrics, []criterion) { rises := d.offerRises(tOff, tOn) cut := d.firstOffer(tOff, func(p profile) bool { return p.Limit == 0 }) m := metrics{"battery_w_before": math.Round(pre), "allowed_over_s": allowed, - "over_fuse_x1_2_longest_s": instant, "over_fuse_minus1_longest_s": over1, + "over_fuse_x1_2_longest_s": instant, "over_fuse_longest_s": overFuse, "heat_peak_a": heatPeak, "heat_over_x1_13_s": heatOver, "cut_sent_s": roundp(cut, 1), "offer_rises_while_offline": rises, "during": during, "max_i_after_drop": round(maxOf(d.window(tOff, tOn+60), maxAbsI), 2)} @@ -671,20 +671,18 @@ func judgeR3(d *runData) (metrics, []criterion) { swing = hi - lo } minSoC := minOf(run, func(r *sample) float64 { return r.Bat.SoCPct }) - // Once the car is the only lever, Core holds the worst phase at its own - // line, between fuse - 1 A and fuse - 0.5 A (see s3): the overage that - // counts is above fuse - 0.5 A; the one above fuse - 1 A is recorded. - over, _ := d.runsOver(tCN, t1, fuse-0.5) - over1, _ := d.runsOver(tCN, t1, fuse-1) + // Core may work up to the fuse rating; safety_margin_a is a site's + // opt-in, so the overage that counts is above the fuse. + over, _ := d.runsOver(tCN, t1, fuse) allowed := delay + 7 m := metrics{"discharge_below_floor_samples": below, "battery_order_swing_last5min_w": math.Round(swing), - "soc_min_pct": round(minSoC, 2), "over_fuse_minus_half_longest_s": over, "over_fuse_minus1_longest_s": over1, + "soc_min_pct": round(minSoC, 2), "over_fuse_longest_s": over, "allowed_over_s": allowed, "max_i": round(maxOf(run, maxAbsI), 2)} return m, []criterion{ crit("the battery reached the planner floor", len(run) > 0 && minSoC <= floor+0.5), // the setup crit("no discharge ordered below the planner floor", below <= 10), crit("the battery order swings at most 100 W over the last 5 min", len(last) > 0 && swing <= 100), - crit("over fuse - 0.5 A no longer than the charger's delay + 7 s", over <= allowed), + crit("over the fuse no longer than the charger's delay + 7 s", over <= allowed), crit("fuse holds", !anyBlown(run)), } } @@ -719,13 +717,13 @@ func judgeR4(d *runData) (metrics, []criterion) { return v } recovery := d.logLines("database corrupt", "INTEGRITY CHECK FAILED") - overAfter, _ := d.runsOver(u2, t1, fuse-1) + overAfter, _ := d.runsOver(u2, t1, fuse) m := metrics{"charge_now_back_s": []*float64{roundp(back1, 1), roundp(back2, 1)}, "today_load_wh_before_kill1": before, "today_load_wh_before_kill2": after, "today_load_wh_null_after_kill1": nullAfter, "today_load_wh_end": todayLoadWh(d.window(u2, t1)), "session_wh_before_kills": []float64{session(k1-30, k1), session(k2-30, k2)}, "session_wh_90s_after_ups": []float64{session(u1, u1+90), session(u2, u2+90)}, - "recovery_log_lines": len(recovery), "over_fuse_minus1_longest_after_up2_s": overAfter} + "recovery_log_lines": len(recovery), "over_fuse_longest_after_up2_s": overAfter} return m, []criterion{ crit("Charge now back at its minimum within 60 s of each restart, and held", le(back1, 60) && le(back2, 60)), crit("the day's Home use kept within 1 % across the first kill", kept), @@ -742,17 +740,17 @@ func (d *runData) homeUseBack(t0 float64) *float64 { // judgeR5a: Core starting beside a car that already draws its maximum, with // the site over the fuse, brings the site under the limit within 30 s and -// keeps it there. Core holds the worst phase at its own line, between -// fuse - 1 A and fuse - 0.5 A (see s3, r3), so the limit is fuse - 0.5 A. +// keeps it there. The limit is the fuse: Core may work up to the rating, +// and safety_margin_a is a site's opt-in. func judgeR5a(d *runData) (metrics, []criterion) { fuse := d.metaF("fuse") tS, tUp, t1 := d.marks["ftw_start"], d.marks["ftw_up"], d.marks["end"] pre := meanOf(d.window(tS-20, tS), func(r *sample) float64 { return carW(r, 0) }) preI := maxOf(d.window(tS-20, tS), maxAbsI) - fit := d.firstT(tUp, func(r *sample) bool { return maxAbsI(r) <= fuse-0.5 }) + fit := d.firstT(tUp, func(r *sample) bool { return maxAbsI(r) <= fuse }) overAfter := 0.0 if fit != nil { - overAfter, _ = d.runsOver(tUp+*fit, t1, fuse-0.5) + overAfter, _ = d.runsOver(tUp+*fit, t1, fuse) } shown := d.homeUseBack(tUp) m := metrics{"car_w_before_start": math.Round(pre), "under_limit_s": roundp(fit, 1), "over_after_that_longest_s": overAfter, @@ -760,8 +758,8 @@ func judgeR5a(d *runData) (metrics, []criterion) { return m, []criterion{ crit("the car charged before Core started", pre >= minW), // the setup crit("the site was over the fuse before Core started", preI > fuse), // the setup - crit("under fuse - 0.5 A within 30 s of Core answering", le(fit, 30)), - crit("over fuse - 0.5 A at most 3 s once under it", fit != nil && overAfter <= 3), + crit("under the fuse within 30 s of Core answering", le(fit, 30)), + crit("over the fuse at most 3 s once under it", fit != nil && overAfter <= 3), crit("Home use shown within 30 s of Core answering", le(shown, 30)), crit("fuse holds", !anyBlown(d.window(tS, t1))), } From 51997bcf7438bc16e61b16c9a33054f29673286b Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 17:38:50 +0100 Subject: [PATCH 08/68] test(site): pin R5a's 3 s clock to the first sample at the fuse R5a's second criterion now starts its clock at the first sample at or under the fuse, not under fuse - 0.5 A. So a site that dips to 24.8 A and then holds 26 A for 10 s fails, where the old judge passed. Add that case so the clock start cannot drift back. Co-Authored-By: Claude Opus 5.5 --- go/test/site/scenarios_p0_unit_test.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/go/test/site/scenarios_p0_unit_test.go b/go/test/site/scenarios_p0_unit_test.go index b0756b8c5..be1d59704 100644 --- a/go/test/site/scenarios_p0_unit_test.go +++ b/go/test/site/scenarios_p0_unit_test.go @@ -363,6 +363,20 @@ func TestJudgeR5aJudgesAtTheFuse(t *testing.T) { if v[over] { t.Error("25.1 A for 9 s once under the fuse passes") } + // The 3 s clock starts at the first sample at or under the fuse, not + // under fuse - 0.5 A: 24.8 A at 80 s, then 26 A from 85 to 94 s, fails. + v = judge(func(i int) float64 { + switch { + case i < 85: + return 24.8 + case i < 95: + return 26 + } + return 24 + }) + if !v[under] || v[over] { + t.Errorf("a dip to 24.8 A, then 26 A for 10 s: %v", v) + } if v := judge(func(int) float64 { return 25.1 }); v[under] { t.Error("held at 25.1 A after Core answers passes") } From f2ee596f9476d46d7fecbd9dcb2fb4e49959e5d1 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 17:42:05 +0100 Subject: [PATCH 09/68] test(site): the rig's "over the limit" is above the fuse, not fuse - 1 A Core's working limit per phase is the fuse rating less safety_margin_a, and the margin is opt-in (owner rule of 27 Oct). The invariants judge, the overage helper behind S9-S11, S3, S8 and S15bat now count a phase as over the limit only above the fuse rating. The fuse - 1 A and fuse - 0.5 A metrics go; the I2 and back-under metrics read at the fuse. Time budgets stay as they were. This only loosens the judges, so Core that still holds In - 1 A passes. Room expectations (S1, S12, the random roomA) stay at fuse - 1 A for now. Co-Authored-By: Claude Opus 5.5 --- go/test/site/README.md | 2 +- go/test/site/evaluate_test.go | 3 +-- go/test/site/random_test.go | 6 ++--- go/test/site/rig_unit_test.go | 47 +++++++++++++++++++++++++++++++++- go/test/site/scenarios_test.go | 8 +++--- go/test/site/verdicts_test.go | 35 +++++++++++-------------- 6 files changed, 70 insertions(+), 31 deletions(-) diff --git a/go/test/site/README.md b/go/test/site/README.md index c11ed80cd..b650a9e04 100644 --- a/go/test/site/README.md +++ b/go/test/site/README.md @@ -77,7 +77,7 @@ its sources (`provenance` in [catalog_test.go](catalog_test.go)). ## Scenarios -"Over the limit" is the worst phase above the fuse − 1 A, measured through +"Over the limit" is the worst phase above the fuse rating, measured through the fuse. A device's response time counts as 2 s, the meter and control tick as 2 s more. diff --git a/go/test/site/evaluate_test.go b/go/test/site/evaluate_test.go index 7dc1a7a36..0ab41b730 100644 --- a/go/test/site/evaluate_test.go +++ b/go/test/site/evaluate_test.go @@ -673,8 +673,7 @@ func le(p *float64, limit float64) bool { return p != nil && *p <= limit } func (d *runData) overage(t0, t1, fuse float64) metrics { w := d.window(t0, t1) m := metrics{"max_i": round(maxOf(w, maxAbsI), 2)} - m["over_limit_longest_s"], m["over_limit_total_s"] = d.runsOver(t0, t1, fuse-1) - m["over_fuse_longest_s"], _ = d.runsOver(t0, t1, fuse) + m["over_limit_longest_s"], m["over_limit_total_s"] = d.runsOver(t0, t1, fuse) m["fuse_damage_max"] = round(maxOf(w, damage), 4) m["fuse_blown"] = anyBlown(w) return m diff --git a/go/test/site/random_test.go b/go/test/site/random_test.go index c0580d222..b1b71e6c5 100644 --- a/go/test/site/random_test.go +++ b/go/test/site/random_test.go @@ -218,7 +218,6 @@ type eventWindow struct{ from, to float64 } func judgeInvariants(d *runData) (metrics, []criterion) { fuse := d.metaF("fuse") - limit := fuse - 1 h := d.timing() t0, t1 := d.marks["start"], d.marks["end"] run := d.window(t0, t1) @@ -270,7 +269,7 @@ func judgeInvariants(d *runData) (metrics, []criterion) { var firstBad float64 var start *sample for i, r := range run { - over := maxAbsI(r) > limit + over := maxAbsI(r) > fuse if over && start == nil { start = r } @@ -368,7 +367,8 @@ func judgeInvariants(d *runData) (metrics, []criterion) { for _, hw := range holds { run4 = 0 for i, r := range d.window(hw.from+grace, hw.to) { - roomA := limit - (maxAbsI(r) - carW(r, 0)/(3*volt)) + // Room below fuse - 1 A, the car's line in Core. + roomA := fuse - 1 - (maxAbsI(r) - carW(r, 0)/(3*volt)) bad := carW(r, 0) < 0.5*1380 && roomA >= 7 && !inFault(r.T) && !nearRestart(r.T) if bad && i > 0 { run4++ diff --git a/go/test/site/rig_unit_test.go b/go/test/site/rig_unit_test.go index 7e921c2ad..17dae5d8c 100644 --- a/go/test/site/rig_unit_test.go +++ b/go/test/site/rig_unit_test.go @@ -4,6 +4,7 @@ package site import ( "encoding/json" + "slices" "testing" ) @@ -113,7 +114,7 @@ func TestInvariantsTellStepsFromOwnRaises(t *testing.T) { for i := 0; i <= 100; i++ { a := 10.0 if i >= 50 && i < 56 { - a = 26 // 6 s over the 24 A limit + a = 26 // 6 s over the 25 A fuse } d.samples = append(d.samples, &sample{T: float64(i), PhaseA: [3]float64{a, a, a}, Bat: plantDevice{SoCPct: 50}}) } @@ -139,3 +140,47 @@ func TestInvariantsTellStepsFromOwnRaises(t *testing.T) { t.Fatalf("without a step: %v", f) } } + +// The limit is the fuse rating: a phase may sit at exactly the fuse until +// the end of the run, and 0.1 A above it fails once the time budget is up. +func TestInvariantsJudgeAtTheFuse(t *testing.T) { + const fuse = 25.0 + const own = "over the limit at most 3 s after FTW's own raise" + const step = "over the limit no longer than an outside step allows" + for _, c := range []struct { + name string + a float64 + to int // the level holds from 50 s until this second + withStep bool + want []string + }{ + {"at the fuse", fuse, 101, false, nil}, + {"at the fuse after a step", fuse, 101, true, nil}, + // 20 s is past the 3 s for FTW's own raise, and past the + // 2 + 2 + 3 s a step allows while the battery can answer. + {"0.1 A over", fuse + 0.1, 70, false, []string{own}}, + {"0.1 A over after a step", fuse + 0.1, 70, true, []string{step}}, + } { + d := &runData{marks: map[string]float64{"start": 0, "end": 100}, meta: map[string]any{"fuse": fuse}} + for i := 0; i <= 100; i++ { + a := 10.0 + if i >= 50 && i < c.to { + a = c.a + } + d.samples = append(d.samples, &sample{T: float64(i), PhaseA: [3]float64{a, a, a}, Bat: plantDevice{SoCPct: 50}}) + } + if c.withStep { + d.events = append(d.events, houseEventLine{T: 49.5, Event: houseEvent{Do: "loads"}}) + } + var failed []string + _, cs := judgeInvariants(d) + for _, x := range cs { + if !x.OK { + failed = append(failed, x.Name) + } + } + if !slices.Equal(failed, c.want) { + t.Errorf("%s: failed %v, want %v", c.name, failed, c.want) + } + } +} diff --git a/go/test/site/scenarios_test.go b/go/test/site/scenarios_test.go index 5707f3b1b..82629c5a8 100644 --- a/go/test/site/scenarios_test.go +++ b/go/test/site/scenarios_test.go @@ -1015,7 +1015,7 @@ func judgeS15bat(d *runData) (metrics, []criterion) { start := d.firstT(t0, func(r *sample) bool { return carW(r, 0) >= 0.95*1380 }) over, longest := 0.0, 0.0 for _, r := range d.window(t0, t1) { - if maxAbsI(r) > fuse-1 { + if maxAbsI(r) > fuse { over++ longest = math.Max(longest, over) } else { @@ -1023,13 +1023,13 @@ func judgeS15bat(d *runData) (metrics, []criterion) { } } m := metrics{"battery_rise_w_20s_before": math.Round(rise), "car_start_s": roundp(start, 1), - "car_w_last60": math.Round(meanOf(d.window(t1-60, t1), func(r *sample) float64 { return carW(r, 0) })), - "over_fuse_minus1_longest_s": longest, "max_abs_i": round(maxOf(d.window(t0, t1), maxAbsI), 1)} + "car_w_last60": math.Round(meanOf(d.window(t1-60, t1), func(r *sample) float64 { return carW(r, 0) })), + "over_fuse_longest_s": longest, "max_abs_i": round(maxOf(d.window(t0, t1), maxAbsI), 1)} return m, []criterion{ crit("the battery order rose over 1 150 W in the 20 s before Charge now", rise > 1150), // the setup crit("car charging within 10 s of Charge now", le(start, 10)), crit("fuse holds", !anyBlown(d.window(t0, t1))), - crit("over fuse - 1 A at most 3 s", longest <= 3), + crit("over the fuse at most 3 s", longest <= 3), } } diff --git a/go/test/site/verdicts_test.go b/go/test/site/verdicts_test.go index a087ddd76..a621c463b 100644 --- a/go/test/site/verdicts_test.go +++ b/go/test/site/verdicts_test.go @@ -87,11 +87,10 @@ func judgeS3(d *runData) (metrics, []criterion) { "pre_step_max_i": round(maxOf(pre, maxAbsI), 2), } m["post_step_max_i"] = round(maxOf(d.window(tStep, tBack), maxAbsI), 2) - m["over_fuse_longest_s"], m["over_fuse_total_s"] = d.runsOver(tStep, tBack, fuse) - overLongest, overTotal := d.runsOver(tStep, tBack, fuse-1) - m["over_fuse_minus1_longest_s"], m["over_fuse_minus1_total_s"] = overLongest, overTotal - m["i2_over_fuse_minus1_s"], m["i2_peak_a"] = d.i2Over(tCN, t1, fuse-1) - m["back_under_fuse_minus1_s"] = roundp(d.firstT(tStep, func(r *sample) bool { return maxAbsI(r) <= fuse-1 && r.T > tStep+1 }), 1) + overLongest, overTotal := d.runsOver(tStep, tBack, fuse) + m["over_fuse_longest_s"], m["over_fuse_total_s"] = overLongest, overTotal + m["i2_over_fuse_s"], m["i2_peak_a"] = d.i2Over(tCN, t1, fuse) + m["back_under_fuse_s"] = roundp(d.firstT(tStep, func(r *sample) bool { return maxAbsI(r) <= fuse && r.T > tStep+1 }), 1) last := d.window(tBack-60, tBack) m["post_step_car_w_last60"] = math.Round(meanOf(last, func(r *sample) float64 { return carW(r, 0) })) m["post_step_bat_w_last60"] = math.Round(meanOf(last, batSigned)) @@ -107,15 +106,12 @@ func judgeS3(d *runData) (metrics, []criterion) { // Device response + meter and tick (2 + 2 s) + 3 s. allowed := d.metaF("charger_delay_s") + 2 + 2 + 3 m["allowed_over_s"] = allowed - m["run_over_fuse_minus1_longest_s"], _ = d.runsOver(tCN, t1, fuse-1) + m["run_over_fuse_longest_s"], _ = d.runsOver(tCN, t1, fuse) m["run_max_i"] = round(maxOf(after, maxAbsI), 2) - // Before the step, layers with different margins may hold a phase - // between fuse - 1 A and fuse - 0.5 A; reported, not judged. - m["pre_step_over_fuse_minus1_longest_s"], _ = d.runsOver(tCN, tStep, fuse-1) - m["pre_step_over_fuse_minus_half_longest_s"], _ = d.runsOver(tCN, tStep, fuse-0.5) + m["pre_step_over_fuse_longest_s"], _ = d.runsOver(tCN, tStep, fuse) return m, []criterion{ crit("fuse holds", !isBlown), - crit("over fuse - 1 A no longer than the response time + 3 s after the step", overLongest <= allowed), + crit("over the fuse no longer than the response time + 3 s after the step", overLongest <= allowed), } } @@ -414,10 +410,9 @@ func judgeS8(d *runData) (metrics, []criterion) { fuse := d.metaF("fuse") t0, t1 := d.marks["charge_now"], d.marks["end"] m := d.carSummary(t0, t1, maxW) - m["over_fuse_longest_s"], m["over_fuse_total_s"] = d.runsOver(t0, t1, fuse) - overLongest, overTotal := d.runsOver(t0, t1, fuse-1) - m["over_fuse_minus1_longest_s"], m["over_fuse_minus1_total_s"] = overLongest, overTotal - m["i2_over_fuse_minus1_s"], m["i2_peak_a"] = d.i2Over(t0, t1, fuse-1) + overLongest, overTotal := d.runsOver(t0, t1, fuse) + m["over_fuse_longest_s"], m["over_fuse_total_s"] = overLongest, overTotal + m["i2_over_fuse_s"], m["i2_peak_a"] = d.i2Over(t0, t1, fuse) var prs [][2]float64 for i, p := range connector1(profiles(d.frames, t0, t1)) { if i >= 20 { @@ -435,7 +430,7 @@ func judgeS8(d *runData) (metrics, []criterion) { } return m, []criterion{ crit("fuse holds", !m["fuse_blown"].(bool)), - crit("over fuse - 1 A no longer than the charger's delay + 7 s", overLongest <= allowed), + crit("over the fuse no longer than the charger's delay + 7 s", overLongest <= allowed), } } @@ -461,8 +456,8 @@ func judgeS9(d *runData) (metrics, []criterion) { m["profiles_after_switch"] = seq return m, []criterion{ crit("fuse holds", !before["fuse_blown"].(bool) && !after["fuse_blown"].(bool)), - crit("over fuse - 1 A at most 3 s on 3p", before["over_limit_longest_s"].(float64) <= 3), - crit("over fuse - 1 A at most 3 s after the switch to 1p", after["over_limit_longest_s"].(float64) <= 3), + crit("over the fuse at most 3 s on 3p", before["over_limit_longest_s"].(float64) <= 3), + crit("over the fuse at most 3 s after the switch to 1p", after["over_limit_longest_s"].(float64) <= 3), } } @@ -502,7 +497,7 @@ func judgeS10(d *runData) (metrics, []criterion) { } return m, []criterion{ crit("fuse holds", !before["fuse_blown"].(bool) && !after["fuse_blown"].(bool)), - crit("over fuse - 1 A at most 3 s after the step", after["over_limit_longest_s"].(float64) <= 3), + crit("over the fuse at most 3 s after the step", after["over_limit_longest_s"].(float64) <= 3), } } @@ -549,7 +544,7 @@ func judgeS11(d *runData) (metrics, []criterion) { } return m, []criterion{ crit("an offer within 60 s of the restart", le(firstPosS, 60)), - crit("over fuse - 1 A at most 3 s", run["over_limit_longest_s"].(float64) <= 3), + crit("over the fuse at most 3 s", run["over_limit_longest_s"].(float64) <= 3), crit("fuse holds", !run["fuse_blown"].(bool)), } } From 8274e40465d37e5ad31549623f89d39607648f94 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 17:47:20 +0100 Subject: [PATCH 10/68] test(site): the rig expects the room the fuse rating gives S1 targets floor(fuse - house) in 1 A steps (8 970 W on 16 A with a 3 A house, was 8 280 W). S12 counts a cut on room alone while every phase is under fuse - 0.1 A and records fuse_limit with 6 A of room under the fuse. The random judge measures Charge now room against the fuse, with the car's 6 A minimum as the threshold. The stack pins safety_margin_a to 0 so the rig does not depend on Core's default. This tightens the rig: it passes only once Core works to the rating. Co-Authored-By: Claude Opus 5.5 --- go/test/site/README.md | 2 +- go/test/site/random_test.go | 7 ++-- go/test/site/rig_unit_test.go | 77 ++++++++++++++++++++++++++++++++++ go/test/site/scenarios_test.go | 8 ++-- go/test/site/stack_test.go | 4 +- go/test/site/verdicts_test.go | 5 ++- 6 files changed, 92 insertions(+), 11 deletions(-) diff --git a/go/test/site/README.md b/go/test/site/README.md index b650a9e04..b1a75ca3c 100644 --- a/go/test/site/README.md +++ b/go/test/site/README.md @@ -85,7 +85,7 @@ tick as 2 s more. |---|---|---|---| | `s0-25` Idle charger | 25 A, 3 A per phase, a charger with no car, heartbeat 60 s, 300 s | Home use `measured` in 95 % of samples; no OCPP disconnect | yes | | `s0b-25` | as s0, Core's heartbeat | as s0 | | -| `s1-16`, `s1-25` Charge now | 3 A per phase, Charge now 16 A for 180 s | the room the fuse gives (25 A: 11 040 W) within 60 s; held 95 %; fuse holds; on 25 A no `fuse_limit` | yes | +| `s1-16`, `s1-25` Charge now | 3 A per phase, Charge now 16 A for 180 s | the room the fuse gives (16 A: 8 970 W; 25 A: 11 040 W) within 60 s; held 95 %; fuse holds; on 25 A no `fuse_limit` | yes | | `s2-16` Charge now during export | 16 A, 1 A house, 7 kW PV, full battery: 9.1 A export per phase | car starts within 60 s (**known**: export counted as import); fuse holds | | | `s3-16`, `s3-25` Load step | car and a 3 kW battery hold charging, then 13 A (16 A) or 21 A (25 A) per phase for 180 s | fuse holds; over the limit at most 7 s after the step | yes | | `s4-25`, `s4b-25` Saved unlock | `surplus_unlock_bat_soc` 0.9 saved, not armed; Charge now 3p, and bare (s4b) | no stops; no offer drops to 0 W; full power over the last minute | | diff --git a/go/test/site/random_test.go b/go/test/site/random_test.go index b1b71e6c5..537ac7cca 100644 --- a/go/test/site/random_test.go +++ b/go/test/site/random_test.go @@ -367,9 +367,10 @@ func judgeInvariants(d *runData) (metrics, []criterion) { for _, hw := range holds { run4 = 0 for i, r := range d.window(hw.from+grace, hw.to) { - // Room below fuse - 1 A, the car's line in Core. - roomA := fuse - 1 - (maxAbsI(r) - carW(r, 0)/(3*volt)) - bad := carW(r, 0) < 0.5*1380 && roomA >= 7 && !inFault(r.T) && !nearRestart(r.T) + // Room below the fuse, the car's line in Core; 6 A is the car's + // minimum on three phases. + roomA := fuse - (maxAbsI(r) - carW(r, 0)/(3*volt)) + bad := carW(r, 0) < 0.5*1380 && roomA >= 6 && !inFault(r.T) && !nearRestart(r.T) if bad && i > 0 { run4++ idle = math.Max(idle, run4) diff --git a/go/test/site/rig_unit_test.go b/go/test/site/rig_unit_test.go index 17dae5d8c..6ceab9e1c 100644 --- a/go/test/site/rig_unit_test.go +++ b/go/test/site/rig_unit_test.go @@ -184,3 +184,80 @@ func TestInvariantsJudgeAtTheFuse(t *testing.T) { } } } + +// S1 expects the room the fuse rating gives: on 16 A with a 3 A house that +// is 13 A per phase, 8 970 W. The old line at fuse - 1 A (8 280 W) falls +// short of it. +func TestJudgeS1ExpectsTheRoomAtTheFuse(t *testing.T) { + const name = "target within 60 s" + for _, c := range []struct { + carW float64 + want bool + }{{8970, true}, {8280, false}} { + d := synth(181, map[string]float64{"charge_now": 0, "end": 180}, map[string]any{"fuse": 16.0, "house_a": 3}, + func(i int, r *sample) { + if i >= 10 { + r.CarW = []float64{c.carW} + } + }) + m, cs := judgeS1(d) + if m["target_w"] != 8970.0 { + t.Fatalf("target_w = %v, want 8970", m["target_w"]) + } + if got := verdictsOf(cs)[name]; got != c.want { + t.Errorf("car at %v W: %q = %v, want %v", c.carW, name, got, c.want) + } + } +} + +// S12 counts a cut as one on room alone while every phase is under the fuse +// by more than 0.1 A, and records fuse_limit while the worst phase has 6 A. +func TestJudgeS12MeasuresRoomAtTheFuse(t *testing.T) { + const fuse = 20.0 + for _, c := range []struct { + name string + a float64 // the worst phase when the order drops + cuts, limit int + }{ + {"at the fuse", fuse, 0, 0}, + {"0.1 A under", fuse - 0.1, 0, 0}, + {"0.5 A under", fuse - 0.5, 1, 0}, + {"5.5 A under", fuse - 5.5, 1, 0}, + {"6.5 A under", fuse - 6.5, 1, 1}, + } { + d := synth(121, map[string]float64{"plan": 0, "ready": 100, "end": 120}, map[string]any{"fuse": fuse, "plan_wh": 6600.0}, + func(i int, r *sample) { + r.PhaseA = [3]float64{c.a, c.a - 1, c.a - 2} + if i == 30 { + r.LPs = []ftwLoadpoint{{CommandedReason: "fuse_limit"}} + } + }) + d.frames = []frame{profileAt(10, 16), profileAt(20, 10)} + m, _ := judgeS12(d) + if m["cuts_with_room"] != c.cuts || m["fuse_limit_with_room_s"] != c.limit { + t.Errorf("%s: cuts %v, fuse_limit %v; want %d, %d", c.name, m["cuts_with_room"], m["fuse_limit_with_room_s"], c.cuts, c.limit) + } + } +} + +// During Charge now an idle car is a fault once the house leaves the car's +// 6 A minimum under the fuse; with less room it is not. +func TestInvariantsChargeNowRoomAtTheFuse(t *testing.T) { + const fuse = 25.0 + const name = "Charge now charges when there is room" + for _, c := range []struct { + houseA float64 + want bool + }{{fuse - 6, false}, {fuse - 5.5, true}} { + d := synth(201, map[string]float64{"start": 0, "end": 200}, map[string]any{"fuse": fuse}, + func(_ int, r *sample) { + r.PhaseA = [3]float64{c.houseA, c.houseA, c.houseA} + r.Bat.SoCPct = 50 + }) + d.allMarks = []markLine{{T: 1, Label: "ftw:charge_now"}, {T: 200, Label: "end"}} + _, cs := judgeInvariants(d) + if got := verdictsOf(cs)[name]; got != c.want { + t.Errorf("house %v A: %q = %v, want %v", c.houseA, name, got, c.want) + } + } +} diff --git a/go/test/site/scenarios_test.go b/go/test/site/scenarios_test.go index 82629c5a8..13e672eaa 100644 --- a/go/test/site/scenarios_test.go +++ b/go/test/site/scenarios_test.go @@ -712,10 +712,10 @@ func judgeS12(d *runData) (metrics, []criterion) { if p.Limit > 0 && p.phasesOr3() == 1 { ones++ } - // A lower order while every phase has room is a cut on room alone, - // unless the plan itself asked for less (a pause between slots). + // A lower order while every phase is under the fuse is a cut on room + // alone, unless the plan itself asked for less (a pause between slots). if i > 0 && p.offerW() < prs[i-1].offerW()-1 { - if r := d.at(t0 + p.T); r != nil && maxAbsI(r) < fuse-1-0.5 { + if r := d.at(t0 + p.T); r != nil && maxAbsI(r) < fuse-0.1 { if after := d.at(t0 + p.T + 2); after == nil || firstLP(after).CommandedReason != "plan" { cuts++ } @@ -726,7 +726,7 @@ func judgeS12(d *runData) (metrics, []criterion) { // recorded, not judged, since a slow charger's pending order may hold it. limited := 0 for _, r := range w { - if r.LPs != nil && firstLP(r).CommandedReason == "fuse_limit" && maxAbsI(r) < fuse-1-6 { + if r.LPs != nil && firstLP(r).CommandedReason == "fuse_limit" && maxAbsI(r) < fuse-6 { limited++ } } diff --git a/go/test/site/stack_test.go b/go/test/site/stack_test.go index 11c6b55be..ac597c872 100644 --- a/go/test/site/stack_test.go +++ b/go/test/site/stack_test.go @@ -558,7 +558,9 @@ func (st *stack) ftwConfig() (string, error) { cfg := map[string]any{ "site": map[string]any{"name": "rig", "control_interval_s": 2, "grid_target_w": 0, "grid_tolerance_w": 42, "watchdog_timeout_s": 60}, - "fuse": map[string]any{"max_amps": st.spec.fuseA, "phases": 3, "voltage": 230}, + // safety_margin_a pinned at 0 so the rig judges Core at the rating + // whatever the default. + "fuse": map[string]any{"max_amps": st.spec.fuseA, "phases": 3, "voltage": 230, "safety_margin_a": 0}, "drivers": []map[string]any{ {"name": "meter", "lua": "drivers/sdm630.lua", "is_site_meter": true, "capabilities": modbus("meter")}, {"name": "sungrow", "lua": "drivers/sungrow.lua", "battery_capacity_wh": 10000, "capabilities": modbus("inverter")}, diff --git a/go/test/site/verdicts_test.go b/go/test/site/verdicts_test.go index a621c463b..d26bfc9bd 100644 --- a/go/test/site/verdicts_test.go +++ b/go/test/site/verdicts_test.go @@ -45,8 +45,9 @@ func judgeS1(d *runData) (metrics, []criterion) { fuse := d.metaF("fuse") target := maxW if fuse < 25 { - // Room on a 16 A fuse: fuse - 1 A margin - house, in 1 A steps. - target = math.Min(maxW, math.Floor(fuse-1-d.metaF("house_a"))*volt*3) + // Room on a 16 A fuse: fuse - house, in 1 A steps. Core works to + // the rating; safety_margin_a is a site's opt-in and the rig sets 0. + target = math.Min(maxW, math.Floor(fuse-d.metaF("house_a"))*volt*3) } m := d.carSummary(t0, t1, target) m["target_w"] = target From b899d5261b9dcacf7b2a661bc3a232dc8edfb6f1 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 17:56:16 +0100 Subject: [PATCH 11/68] test(site): say S1-16's target is a floor while the battery covers the house A run on a Core that stops at fuse - 1 A gave the car 9 590 W with the battery at -5 000 W, above the 8 970 W target. S1-16 does not catch the old line. Co-Authored-By: Claude Opus 5.5 --- go/test/site/verdicts_test.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/go/test/site/verdicts_test.go b/go/test/site/verdicts_test.go index d26bfc9bd..428f985c8 100644 --- a/go/test/site/verdicts_test.go +++ b/go/test/site/verdicts_test.go @@ -47,6 +47,8 @@ func judgeS1(d *runData) (metrics, []criterion) { if fuse < 25 { // Room on a 16 A fuse: fuse - house, in 1 A steps. Core works to // the rating; safety_margin_a is a site's opt-in and the rig sets 0. + // The target is a floor, not the line: the battery (SoC 50) covers + // the house, so a Core that stops at fuse - 1 A also passes. target = math.Min(maxW, math.Floor(fuse-d.metaF("house_a"))*volt*3) } m := d.carSummary(t0, t1, target) From ae502127376563f15917197076e36ffbfc37ff10 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 17:57:46 +0100 Subject: [PATCH 12/68] fix(control): car and battery-beside-car work to the fuse rating less safety_margin_a The EV phase limit was In - 1 A, fixed in code. It is now fuseLineA(): In - safety_margin_a, with no floor. A rise moves one step once it fits under the line, a start takes all the room, and battery charge beside a car uses the same line. The hour's import limit keeps its own margins. Starts and per-phase cuts round down to whole charger amps, since chargers round offers to the nearest amp. Step 3 (PR b) of the fuse-at-rating plan (owner rule of 27 Oct). Co-Authored-By: Claude Opus 5.5 --- .changeset/b-ev-fuse-line-at-rating.md | 5 + docs/safety.md | 7 +- go/internal/control/ev_battery_headroom.go | 4 +- go/internal/control/ev_battery_priority.go | 9 +- .../control/ev_battery_priority_test.go | 30 +- .../control/ev_battery_sequence_test.go | 11 +- .../control/ev_deadline_runtime_test.go | 2 +- go/internal/control/ev_fuse_budget.go | 80 +++-- go/internal/control/ev_fuse_budget_test.go | 64 ++-- .../control/ev_fuse_cut_netting_test.go | 14 +- .../control/ev_fuse_idle_start_test.go | 13 +- .../control/ev_fuse_phase_room_test.go | 18 +- .../control/ev_priority_sitesim_test.go | 2 +- .../control/ev_slow_charger_battery_test.go | 4 +- go/internal/control/fuse_heat.go | 9 +- go/internal/control/fuse_heat_test.go | 45 ++- .../control/fuse_line_property_test.go | 310 ++++++++++++++++++ go/internal/control/fuse_phase.go | 8 + go/internal/control/import_hour.go | 4 +- go/internal/control/sitesim_field_test.go | 17 +- go/internal/control/sitesim_property_test.go | 10 +- go/internal/control/sitesim_test.go | 35 +- .../loadpoint/controller_fuse_phase_test.go | 2 +- .../loadpoint/controller_phase_choice_test.go | 4 +- 24 files changed, 566 insertions(+), 141 deletions(-) create mode 100644 .changeset/b-ev-fuse-line-at-rating.md create mode 100644 go/internal/control/fuse_line_property_test.go diff --git a/.changeset/b-ev-fuse-line-at-rating.md b/.changeset/b-ev-fuse-line-at-rating.md new file mode 100644 index 000000000..9d8504a29 --- /dev/null +++ b/.changeset/b-ev-fuse-line-at-rating.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +The car now charges up to the fuse rating less `fuse.safety_margin_a`, not a fixed 1 A below it. A charging car rises one step once that step fits under the line, instead of needing two steps of room and keeping one free; an idle car starts with all the room it has. Home battery charge beside a car uses the same line, with no 1 A floor. On a three-phase site with the default 0.5 A margin, a car near the fuse gets 0.5 A to 1.5 A more on each phase. Cuts above the line still wait for the fuse's heat budget, and the hour's import limit keeps its own margins. diff --git a/docs/safety.md b/docs/safety.md index c53c4ae6b..5d6009432 100644 --- a/docs/safety.md +++ b/docs/safety.md @@ -51,8 +51,11 @@ available battery energy and hardware power capability. The EV hard limit treats the main fuse as heat, not as one reading. It low-passes each phase's I² from the site meter with a 60 s time constant. -A phase over the fuse less 1 A cuts the EVs once that filtered current -passes the same limit, and at once above 1.2 × the fuse. A running car's +Each phase's working limit is the fuse rating less `fuse.safety_margin_a`; +no amps are held back beyond that setting. A phase over the limit cuts the +EVs once that filtered current passes the same limit, and at once above +1.2 × the fuse. A running car rises one step, or the rest of its demand, +only when that step fits under the limit, and not within 20 s of a cut. Its rise reads the higher of the reading and that filtered current. An idle car's start reads each phase as it is, plus its new current; the filtered current holds it back only while it is over the limit. Where the meter diff --git a/go/internal/control/ev_battery_headroom.go b/go/internal/control/ev_battery_headroom.go index f33b2a52d..0ea1d3201 100644 --- a/go/internal/control/ev_battery_headroom.go +++ b/go/internal/control/ev_battery_headroom.go @@ -171,8 +171,8 @@ func evBatteryPhaseSpareW(meter *telemetry.DerReading, state *State, gridW, evIn if !valid { return math.Inf(-1), true } - margin := math.Max(1, state.SiteFuseSafetyA) // Same working margin as the EV phase guard. - return (state.SiteFuseAmps - margin - worst - evIncreaseA) * state.SiteFuseVoltage * float64(state.SiteFusePhases), true + // The same working limit as the EV phase guard, with no floor under it. + return (state.fuseLineA() - worst - evIncreaseA) * state.SiteFuseVoltage * float64(state.SiteFusePhases), true } func floorPositiveEVBatteryTargets(targets []DispatchTarget) []DispatchTarget { diff --git a/go/internal/control/ev_battery_priority.go b/go/internal/control/ev_battery_priority.go index 29bee0621..c585c92e4 100644 --- a/go/internal/control/ev_battery_priority.go +++ b/go/internal/control/ev_battery_priority.go @@ -9,8 +9,8 @@ import ( ) // evBatteryYield lets an existing car offer wait for a battery charge cut. -// It never grants a car rise, never runs outside the measured fuse rating, -// and cannot renew while the site remains over its working limit. +// It never grants a car rise, never runs above the fuse's working limit +// (fuseLineA), and cannot renew while the site remains over its working limit. type evBatteryYield struct { tried bool until time.Time @@ -35,12 +35,13 @@ func (s *State) yieldBatteryBeforeEVCut(store *telemetry.Store, meter *telemetry // This hold uses only the installation's existing current allowance. // Include offers still on their way; a cut never funds a car increase. amps, present, valid := phaseCurrentsA(meter, s, gridW) - if !present || !valid || gridW+rise.w+pendingBatteryW > s.SiteFuseAmps*s.SiteFuseVoltage*float64(s.SiteFusePhases) { + lineA := s.fuseLineA() + if !present || !valid || gridW+rise.w+pendingBatteryW > lineA*s.SiteFuseVoltage*float64(s.SiteFusePhases) { return false } pendingA := pendingBatteryW / (s.SiteFuseVoltage * float64(s.SiteFusePhases)) for i, a := range amps { - if math.Max(a, math.Sqrt(s.fuseHeat.sq[i]))+rise.phaseA[i]+pendingA > s.SiteFuseAmps { + if math.Max(a, math.Sqrt(s.fuseHeat.sq[i]))+rise.phaseA[i]+pendingA > lineA { return false } } diff --git a/go/internal/control/ev_battery_priority_test.go b/go/internal/control/ev_battery_priority_test.go index 3c3df469a..18474dba7 100644 --- a/go/internal/control/ev_battery_priority_test.go +++ b/go/internal/control/ev_battery_priority_test.go @@ -10,12 +10,20 @@ import ( "github.com/srcfl/ftw/go/internal/telemetry" ) -// #1868: 16 A, 6 A on all three car phases, and a 0.1 A working-limit -// overage. The 4 kW battery is the continuous load that can yield first. +// #1868: 16 A, 6 A on all three car phases, and 15.1 A on L1, then 0.1 A +// over the fuse less 1 A. The phase line is now the fuse less +// safety_margin_a, 15.5 A here, so the same readings leave 0.4 A of room +// (TestIssue1868ReadingsSitUnderTheLine). The car may wait for the battery +// only while every phase stays under that line, so the wait now serves the +// hour's import limit: the fixture is 69 W over a 9,015 W limit. The 4 kW +// battery is the continuous load that can yield first. +const issue1868CeilingW = 9015 + func issue1868Site(t *testing.T) (*telemetry.Store, *State, []loadpoint.State, []loadpoint.Config) { t.Helper() tel, st := evSplitFixture(t, 9084, []float64{15.1, 12.5, 11.9}, 4140, "3p") st.SiteFuseAmps, st.SiteFuseSafetyA = 16, .5 + st.PeakImportCeilingW = issue1868CeilingW st.Mode = ModeCharge st.DriverLimits = map[string]PowerLimits{"battery": {MaxChargeW: 6000, MaxDischargeW: 6000}} soc := .4 @@ -50,7 +58,8 @@ func TestIssue1868BatteryChargeYieldsBeforeTheCar(t *testing.T) { if target.TargetW > 3931.001 { t.Fatalf("%s left the car's relief in the battery: %+v", mode, target) } - if mode == ModeCharge && target.TargetW < 3800 { + // The import guard trims its own buffer as well (dispatch.go). + if mode == ModeCharge && target.TargetW < 3600 { t.Fatalf("small overage needlessly stopped battery charging: %+v", target) } } @@ -63,6 +72,17 @@ func TestIssue1868BatteryChargeYieldsBeforeTheCar(t *testing.T) { } } +// With no import limit, #1868's readings sit 0.4 A under the 15.5 A line: +// nothing cuts the car and nothing waits for the battery. +func TestIssue1868ReadingsSitUnderTheLine(t *testing.T) { + tel, st, points, configs := issue1868Site(t) + st.PeakImportCeilingW = 0 + cap, known := EVFuseBudget(tel, st, points, configs, 11040) + if !known || cap < 4140 || st.evLimit.batteryYield.active { + t.Fatalf("cap=%v known=%v yield=%+v, want the 4140 W offer kept with no wait", cap, known, st.evLimit.batteryYield) + } +} + func TestEVPriorityCannotSpendUnmeasuredBatteryRelief(t *testing.T) { tel, st, points, configs := issue1868Site(t) st.SetEVFuseDemands([]loadpoint.FuseDemand{{DriverName: "car", PowerW: 10350, PhaseMode: "3p"}}) @@ -84,8 +104,8 @@ func TestEVPriorityFallsBackWhenTheBatteryCannotYield(t *testing.T) { {"stale meter", func(tel *telemetry.Store, _ *State) { tel.Get("meter", telemetry.DerMeter).UpdatedAt = time.Now().Add(-time.Minute) }}, - {"past fuse rating", func(tel *telemetry.Store, _ *State) { - tel.Update("meter", telemetry.DerMeter, 10000, nil, []byte(`{"l1_a":16.1,"l2_a":12.5,"l3_a":11.9}`)) + {"over the working limit", func(tel *telemetry.Store, _ *State) { + tel.Update("meter", telemetry.DerMeter, 9000, nil, []byte(`{"l1_a":15.6,"l2_a":12.5,"l3_a":11.9}`)) }}, {"unseen battery rise", func(_ *telemetry.Store, st *State) { sent(st, "battery", 0, 4000) }}, } { diff --git a/go/internal/control/ev_battery_sequence_test.go b/go/internal/control/ev_battery_sequence_test.go index aa46d4acc..b60f0d2e5 100644 --- a/go/internal/control/ev_battery_sequence_test.go +++ b/go/internal/control/ev_battery_sequence_test.go @@ -518,8 +518,15 @@ func TestFuseOverageGetsBatteryReliefUntilEVCutShows(t *testing.T) { t.Fatalf("%v: meter %.0f W, want within the 25 A breaker and no export", m.at.Sub(stepAt), m.w) } } - if s.offer() >= 10350 || s.batteryW != 0 { - t.Fatalf("after the cut: offer %.0f W battery %.0f W, want a cut car and an idle battery", s.offer(), s.batteryW) + // The car rises one step once that step fits under the 24 A line, and + // the reading it rises on still holds part of the battery's relief. + // Ending a discharge needs room after the car's raise (EV first), so + // the battery keeps less than that step and the phase sits at the line. + if s.offer() >= 10350 || s.batteryW < -690 || s.batteryW > 0 { + t.Fatalf("after the cut: offer %.0f W battery %.0f W, want a cut car and at most one car step of battery relief", s.offer(), s.batteryW) + } + if a := s.gridW() / 690; a > 24+1e-6 { + t.Fatalf("after the cut: %.2f A on each phase, over the 24 A line", a) } } diff --git a/go/internal/control/ev_deadline_runtime_test.go b/go/internal/control/ev_deadline_runtime_test.go index 1fef8a8fa..4a2fdcd7b 100644 --- a/go/internal/control/ev_deadline_runtime_test.go +++ b/go/internal/control/ev_deadline_runtime_test.go @@ -88,7 +88,7 @@ func TestJoinedNoBatteryNoPlanGoalContinuity(t *testing.T) { legal = true } } - if !legal || 6000+got > 17250.001 || phaseA+got/(3*230) > 24.001 { + if !legal || 6000+got > 17250.001 || phaseA+got/(3*230) > st.fuseLineA()+.001 { t.Fatalf("unsafe or illegal EV offer=%v, grid=%v phaseA=%v", got, 6000+got, phaseA+got/(3*230)) } if svc.Latest() != nil { diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index b74b81115..21408151c 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -32,10 +32,10 @@ const evUnknownSettle = 3 * time.Minute // pool starts again. It stays above Easee's ~30 s contactor minimum. const evRestartDwell = 35 * time.Second -// evPhaseMarginA is the working margin below the breaker on each phase. One -// amp on the pool's phases is also the rise step and the gap between the cut -// and rise thresholds. -const evPhaseMarginA = 1.0 +// evStepA is the EV rise step: one amp on each of the pool's phases. It is +// the size of the next move, never current held back below the fuse's +// working limit (fuseLineA). +const evStepA = 1.0 // fuseHourFactor is the phase current, as a multiple of the fuse rating, // that a gG fuse of 16-63 A carries for an hour. A cut on its way covers the @@ -319,7 +319,7 @@ func (s *State) offerPhaseA(w float64, phases int) (float64, int) { } // EVFusePhaseRoomA is the current the chargers may still add on the -// busiest phase: below the fuse less its margin, the last reading's +// busiest phase: below the fuse's working limit (fuseLineA), the last reading's // current or heat, and every charger's offers that reading may not show. // For an idle pool the heat counts only over the working limit, as the // start reads it. false when the site meter reports no phase currents. @@ -364,7 +364,8 @@ type evPool struct { // shared freshness gate must already allow dispatch. A fuse overage in total // import cuts at once; a phase overage cuts once that phase's heat budget is // spent, or at once above fuseInstantFactor. Otherwise the cap holds; it -// rises one step on a fresh reading with room for two, at least evSettle +// rises one step, or the rest of the demand when that is less, on a fresh +// reading with room for that rise below the working limit, at least evSettle // after the last cut. Room counts every // offer sent above what the reading may show as flowing until its charger // can have applied it; a cut never frees room before the meter shows it. @@ -437,7 +438,7 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea lim.phaseRoomA = r.startRoomA // The split between idle cars reads the start's room. } } - step := evPhaseMarginA * s.SiteFuseVoltage * pool.phases + step := evStepA * s.SiteFuseVoltage * pool.phases // The label follows whichever limit leaves less room. lim.byImport = math.Min(r.limitW, r.riseW) < r.fuseW // The fuse cuts on every reading over it, by its heat budget where the @@ -475,6 +476,11 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea over, capW, byImport := r.fuseOverW > 0, math.Inf(1), false if over { capW = latestW - math.Max(0, fuseCutW) + if r.perPhase { + // A charger rounds to the nearest amp, so a cut that leaves + // half an amp would round back up and stay over the line. + capW = wholeStepsW(capW, step) + } } if r.limitW >= 0 { lim.overSince = time.Time{} @@ -514,10 +520,11 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea // An increase needs a fresh reading and room below the level increases // may reach, left after our own battery commands that the meter may not // show yet (in r). Between that level and the import limit the cap holds. - room := 0.0 + fuseRoom, importRoom := 0.0, 0.0 if fresh { - room = math.Max(0, math.Min(r.fuseW, r.riseW)) + fuseRoom, importRoom = math.Max(0, r.fuseW), math.Max(0, r.riseW) } + room := math.Min(fuseRoom, importRoom) if pool.offerW <= 0 { s.stepEVIdleStart(r, gridW, pool, first, gap, fresh, at, prevAt, pending, step) return @@ -526,18 +533,42 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea // within what this reading measured. lim.capW, lim.roomSince = math.Min(prev, peakW+room), time.Time{} // Right after a cut the meter may show battery relief that covers it. - if lim.capW < pool.wantW && room >= 2*step && now.Sub(lim.cutAt) >= evSettle { - // One step at most, and a step of room stays free. - lim.capW = math.Max(lim.capW, math.Min(lim.capW+step, peakW+room-step)) - } - // The battery leaves room for the car's demand, not a further unused - // step. Let the last step use that measured room below the working - // limit, or concurrent battery charge can keep the car short forever. - if remaining := pool.wantW - peakW; s.hasBatteryCharge() && remaining > 0 && remaining <= step && room+1e-6 >= remaining && now.Sub(lim.cutAt) >= evSettle { + remaining := pool.wantW - peakW + if lim.capW < pool.wantW && remaining > 0 && now.Sub(lim.cutAt) >= evSettle { + // The fuse: a rise moves one step, or the rest of the demand when + // that is less, once that move fits under the working limit. No + // room is held back below the line; evSettle after a cut and the + // heat the rise reads keep it from undoing a cut. + fits, riseW := fuseRoom+1e-6 >= math.Min(step, remaining), math.Min(lim.capW+step, peakW+fuseRoom) + // The hour's import limit keeps its own margin: a rise needs room + // for two steps, and one stays free. + if !math.IsInf(importRoom, 1) { + fits, riseW = fits && importRoom >= 2*step, math.Min(riseW, peakW+importRoom-step) + } + if fits { + lim.capW = math.Max(lim.capW, riseW) + } + } + // The import limit's rise keeps a step free, but the battery leaves room + // for the car's demand, not a further unused step. Let the last step use + // that measured room, or concurrent battery charge can keep the car + // short forever. Under the fuse alone the rise above already does this. + if s.hasBatteryCharge() && remaining > 0 && remaining <= step && room+1e-6 >= remaining && now.Sub(lim.cutAt) >= evSettle { lim.capW = math.Max(lim.capW, pool.wantW) } } +// wholeStepsW rounds w down to whole charger amps on the pool's phases, one +// step each. Chargers round an offer to the nearest amp, so a cap at the +// line's exact room could land half an amp over it. This is step +// quantisation, not a margin: a cap that is already whole amps stays. +func wholeStepsW(w, step float64) float64 { + if !(step > 0) || math.IsInf(w, 0) { + return w + } + return math.Floor(w/step+1e-9) * step +} + // stepEVIdleStart starts an idle pool once the meter has kept showing room // for evRestartDwell: room on every reading for its minimum below the // fuse's working limit. Under a measured hour, the ceiling's part is judged on the @@ -559,11 +590,14 @@ func (s *State) stepEVIdleStart(r evMeterRoom, gridW float64, pool evPool, first if fresh { room = math.Max(0, perReadingW) // r holds our battery orders. } - minimumRoom := pool.minW + // The fuse holds back nothing below its working limit: the charger + // rounds the cap down to a step it can draw. The hour's import limit + // keeps its separate rise margin. + keepW := 0.0 if !r.hourly && r.riseW < r.startW { - minimumRoom += step // Keep the hour's separate rise margin. + keepW = step } - if room+1e-6 < minimumRoom { + if room+1e-6 < pool.minW+keepW { lim.roomSince = time.Time{} return } @@ -580,7 +614,7 @@ func (s *State) stepEVIdleStart(r evMeterRoom, gridW float64, pool evPool, first if dwell < evRestartDwell { return } - lim.capW = math.Max(pool.minW, room-step) + lim.capW = math.Max(pool.minW, wholeStepsW(room-keepW, step)) if !r.hourly { return } @@ -605,7 +639,7 @@ func EVLimitReason(state *State) string { // evMeterRoom is the measured room in EV watts. The fuse's part holds on // every reading. The import ceiling's parts are +Inf while it is off. type evMeterRoom struct { - fuseW float64 // below the fuse less its margin and the worst phase, read or heat, and what we sent; rises + fuseW float64 // below the working limit (fuseLineA) and the worst phase, read or heat, and what we sent; rises fuseOverW float64 // the fuse's measured overage that cuts now, 0 under it; see fuseHeat fuseOverA float64 // the same on the worst phase, with perPhase perPhase bool // the phase currents measure the fuse @@ -643,7 +677,7 @@ func (s *State) evMeterRoom(meter *telemetry.DerReading, gridW, phases, fuseMaxW } r.measured = true if present { - limitA := s.SiteFuseAmps - evPhaseMarginA + limitA := s.fuseLineA() for _, a := range amps { r.worstA = math.Max(r.worstA, a) } diff --git a/go/internal/control/ev_fuse_budget_test.go b/go/internal/control/ev_fuse_budget_test.go index 0f1fa537d..3c7e56ac4 100644 --- a/go/internal/control/ev_fuse_budget_test.go +++ b/go/internal/control/ev_fuse_budget_test.go @@ -457,7 +457,7 @@ func TestEVHardLimitSlowChargerRisesDoNotStack(t *testing.T) { t.Run(fmt.Sprintf("declared_%.0fs/delay_%v", declaredS, delay), func(t *testing.T) { s := newEVMeterSite(t, 0, 15*690) s.chargerDelay, s.chargerMaxAgeS = delay, declaredS - limitA := s.state.SiteFuseAmps - evPhaseMarginA + limitA := s.state.fuseLineA() var maxA float64 var overSince time.Time watch := func(d time.Duration) { @@ -478,15 +478,15 @@ func TestEVHardLimitSlowChargerRisesDoNotStack(t *testing.T) { } } watch(10 * time.Minute) - // 24 - 15 A leaves 9 A; one step stays free. - if s.offer() != 5520 || s.evW != 5520 { - t.Fatalf("offer %.0f W draw %.0f W, want 5,520 W", s.offer(), s.evW) + // 24.5 - 15 A leaves 9.5 A: 9 A fits under the line. + if s.offer() != 6210 || s.evW != 6210 { + t.Fatalf("offer %.0f W draw %.0f W, want 6,210 W", s.offer(), s.evW) } s.setHouse(10 * 690) watch(15 * time.Minute) - // 24 - 10 A leaves 14 A; one step stays free. - if s.offer() != 8970 || s.evW != 8970 { - t.Fatalf("after the house fell: offer %.0f W draw %.0f W, want 8,970 W", s.offer(), s.evW) + // 24.5 - 10 A leaves 14.5 A: 14 A fits under the line. + if s.offer() != 9660 || s.evW != 9660 { + t.Fatalf("after the house fell: offer %.0f W draw %.0f W, want 9,660 W", s.offer(), s.evW) } t.Logf("worst phase peaked at %.1f A", maxA) }) @@ -505,15 +505,15 @@ func TestEVHardLimitUndeclaredFastChargerTakesRoomAtOnce(t *testing.T) { } startedAt := s.now s.run(s.chargerDelay + 2*time.Second) - // 24 - 15 A leaves 9 A; one step stays free. - if s.offer() != 5520 || s.evW != 5520 { - t.Fatalf("started at %.0f W, drawing %.0f W; want the 5,520 W room in one move", s.offer(), s.evW) + // 24.5 - 15 A leaves 9.5 A: 9 A fits under the line. + if s.offer() != 6210 || s.evW != 6210 { + t.Fatalf("started at %.0f W, drawing %.0f W; want the 6,210 W room in one move", s.offer(), s.evW) } - // 23.5 A measured, under the 24 A working limit, while the start still - // counts as flowing. - s.setHouse(15.5 * 690) + // 24.25 A measured, under the 24.5 A working limit, while the start + // still counts as flowing. + s.setHouse(15.25 * 690) s.run(time.Minute) - if got := offerWatts(s.offersSince(startedAt)); slices.Min(got) != 5520 { + if got := offerWatts(s.offersSince(startedAt)); slices.Min(got) != 6210 { t.Fatalf("the pending start cut the car: %v", got) } @@ -703,14 +703,14 @@ func evMeterBudgetFixture(t *testing.T, gridW float64, phaseA []float64, offerW return store, state, points, configs } -// A 3p car offered 15 A beside 11 A of house load on L1: 26 A on a 24 A -// working limit. With no earlier reading the fuse heat starts at 26 A, so -// two amps on three phases come off the offer at once. +// A 3p car offered 15 A beside 11 A of house load on L1: 26 A on the 25 A +// working limit (no safety margin). With no earlier reading the fuse heat +// starts at 26 A, so one amp on three phases comes off the offer at once. func TestEVHardLimitTrimsPhaseOverageFromOffer(t *testing.T) { store, state, points, configs := evMeterBudgetFixture(t, 8280, []float64{26, 20, 20}, 10350, "3p") got, known := EVFuseBudget(store, state, points, configs, 17250) - if !known || math.Abs(got-8970) > .01 { - t.Fatalf("cap %.1f W, want 10,350 - 2 A x 690 = 8,970 W", got) + if !known || math.Abs(got-9660) > .01 { + t.Fatalf("cap %.1f W, want 10,350 - 1 A x 690 = 9,660 W", got) } } @@ -727,20 +727,22 @@ func TestEVHardLimitStopsOnlyWhenOverageExceedsOfferLessMinimum(t *testing.T) { } } -// An idle car's minimum must fit below the working limit, and a -// single-phase or auto car may land its whole offer on the worst phase. +// An idle car's minimum must fit below the working limit, the 25 A fuse +// with no safety margin, and a single-phase or auto car may land its whole +// offer on the worst phase. The start takes the whole room: the charger +// rounds it down to a step. func TestEVHardLimitIdleStartNeedsRoomOnDeclaredPhases(t *testing.T) { for _, tc := range []struct { name, phase string worstA float64 want float64 }{ - {"3p_room", "3p", 5, (24 - 5 - 1) * 690}, - {"legacy_default", "", 5, (24 - 5 - 1) * 690}, - {"1p_room", "1p", 5, (24 - 5 - 1) * 230}, - {"auto_room", "auto", 5, (24 - 5 - 1) * 230}, - {"3p_minimum_fits", "3p", 21.5, 1380}, - {"3p_below_minimum", "3p", 22.5, 0}, // 1,035 W < 1,380 W + {"3p_room", "3p", 5, (25 - 5) * 690}, + {"legacy_default", "", 5, (25 - 5) * 690}, + {"1p_room", "1p", 5, (25 - 5) * 230}, + {"auto_room", "auto", 5, (25 - 5) * 230}, + {"3p_minimum_fits", "3p", 23, 1380}, // exactly the minimum + {"3p_below_minimum", "3p", 23.5, 0}, // 1,035 W < 1,380 W } { t.Run(tc.name, func(t *testing.T) { store, state, points, configs := evMeterBudgetFixture(t, tc.worstA*690, []float64{tc.worstA, tc.worstA, tc.worstA}, 0, tc.phase) @@ -765,9 +767,9 @@ func TestEVHardLimitBatteryOrderCountsOnEachPhase(t *testing.T) { phase string want float64 }{ - {"1p", (24 - 0.68 - 4703.0/690 - 1) * 230}, - {"auto", (24 - 0.68 - 4703.0/690 - 1) * 230}, - {"3p", (24 - 0.68 - 4703.0/690 - 1) * 690}, + {"1p", math.Floor(25-0.68-4703.0/690) * 230}, + {"auto", math.Floor(25-0.68-4703.0/690) * 230}, + {"3p", math.Floor(25-0.68-4703.0/690) * 690}, } { t.Run(tc.phase, func(t *testing.T) { store, state, points, configs := evMeterBudgetFixture(t, -466, []float64{-0.68, -0.68, -0.68}, 0, tc.phase) @@ -828,7 +830,7 @@ func TestEVHardLimitIgnoresChargerReadings(t *testing.T) { points[0].CommandedKnown = false store.Update("charger", telemetry.DerEV, 10242, nil, nil) store.RecordDriverSuccess("charger") - if got, _ := EVFuseBudget(store, state, points, configs, 17250); got > (24-20.45-1)*690+.01 { + if got, _ := EVFuseBudget(store, state, points, configs, 17250); got > (25-20.45)*690+.01 { t.Fatalf("a car reading earned %.1f W before our first command", got) } } diff --git a/go/internal/control/ev_fuse_cut_netting_test.go b/go/internal/control/ev_fuse_cut_netting_test.go index 575c8ad5b..c1eb1ac2f 100644 --- a/go/internal/control/ev_fuse_cut_netting_test.go +++ b/go/internal/control/ev_fuse_cut_netting_test.go @@ -108,10 +108,10 @@ func (r *cutRig) deliver(gridW float64, data []byte) float64 { } // A raise on its way adds to the cut. The car draws 10 A while its 14 A -// raise travels, and the house adds 8 A on L1: 26 A on the 24 A working -// limit. Once the heat budget is spent, the cut takes the 2 A the meter -// shows and the 4 A it does not show yet, so L1 ends at 24 A when the raise -// lands. Taking the overage from the raise alone left L1 at 28 A. +// raise travels, and the house adds 8 A on L1: 26 A on the 25 A working +// limit. Once the heat budget is spent, the cut takes the 1 A the meter +// shows and the 4 A it does not show yet, so L1 ends at 25 A when the raise +// lands. Taking the overage from the raise alone left L1 at 29 A. func TestEVFuseRaiseOnItsWayAddsToCut(t *testing.T) { r := newCutRig(t, 6900, 180) for range 300 { @@ -124,11 +124,11 @@ func TestEVFuseRaiseOnItsWayAddsToCut(t *testing.T) { r.read([3]float64{26, 15, 15}) cutAt = i } - if r.offerW != 5520 { - t.Fatalf("offer %.0f W after %d s over, want 9,660 W less 2 A measured and 4 A on its way = 5,520 W", r.offerW, cutAt) + if r.offerW != 6210 { + t.Fatalf("offer %.0f W after %d s over, want 9,660 W less 1 A measured and 4 A on its way = 6,210 W", r.offerW, cutAt) } for range 60 { - if r.read([3]float64{26, 15, 15}); r.offerW != 5520 { + if r.read([3]float64{26, 15, 15}); r.offerW != 6210 { t.Fatalf("cut again to %.0f W while the first cut travels", r.offerW) } } diff --git a/go/internal/control/ev_fuse_idle_start_test.go b/go/internal/control/ev_fuse_idle_start_test.go index b8f8ffff6..33cc2fb70 100644 --- a/go/internal/control/ev_fuse_idle_start_test.go +++ b/go/internal/control/ev_fuse_idle_start_test.go @@ -23,10 +23,11 @@ func (s *evMeterSite) firstOfferSince(at time.Time) evTimed { // stopped. Its next start read the heat its own current had left on top of // the start it asked for: the cap stayed at 0 for 84 s, then gave 9 A. A // start reads the phases now plus the car's new current; the heat, under the -// working limit, does not hold it back. +// working limit, does not hold it back. Here the car runs at 14 A beside +// 10.5 A on L1, exactly the 24.5 A working limit. func TestEVIdleStartReadsThePhasesNotTheCarsOwnHeat(t *testing.T) { s := newEVMeterSite(t, 0, 0) - s.housePhaseA, s.houseW = [3]float64{8.9, 2, 2}, (8.9+2+2)*230 + s.housePhaseA, s.houseW = [3]float64{10.5, 2, 2}, (10.5+2+2)*230 s.run(10 * time.Minute) if s.offer() != 9660 || s.evW != 9660 { t.Fatalf("setup: offer %.0f, draw %.0f W, want 14 A on L1's working limit", s.offer(), s.evW) @@ -45,7 +46,7 @@ func TestEVIdleStartReadsThePhasesNotTheCarsOwnHeat(t *testing.T) { } // The 35 s restart dwell runs from the car's stop, 15 s before the ask. if wait := start.at.Sub(askedAt); wait > 25*time.Second || start.w < 8970 { - t.Fatalf("start %.0f W after %v with L1 at 8.9 A and 24 A to the working limit", start.w, wait) + t.Fatalf("start %.0f W after %v with L1 at 10.5 A and 24.5 A to the working limit", start.w, wait) } else { t.Logf("start %.0f W after %v", start.w, wait) } @@ -68,9 +69,9 @@ func TestEVIdleStartWaitsForTheHeatOfARealOverage(t *testing.T) { if start.at.IsZero() { t.Fatalf("no start within 3 min of the drop: offers %v", offerWatts(s.offersSince(droppedAt))) } - // L1's filtered current stays over 24 A for about 11 s after the drop; - // the dwell starts only then. - if wait := start.at.Sub(droppedAt); wait < evRestartDwell+10*time.Second { + // L1's filtered current stays over the 24.5 A line for about 8 s after + // the drop: 60 s × ln((26² - 8²)/(24.5² - 8²)). The dwell starts only then. + if wait := start.at.Sub(droppedAt); wait < evRestartDwell+7*time.Second { t.Fatalf("started %.0f W %v after the drop, before the heat of a 26 A overage had cooled", start.w, wait) } else { t.Logf("start %.0f W after %v", start.w, wait) diff --git a/go/internal/control/ev_fuse_phase_room_test.go b/go/internal/control/ev_fuse_phase_room_test.go index c2347ac39..f35cb207a 100644 --- a/go/internal/control/ev_fuse_phase_room_test.go +++ b/go/internal/control/ev_fuse_phase_room_test.go @@ -137,11 +137,11 @@ func (s *roomSite) run(d time.Duration) { } } -// requireWithinLimit fails when a phase passed the 24 A working limit. +// requireWithinLimit fails when a phase passed the working limit (fuseLineA). func (s *roomSite) requireWithinLimit(after string) { s.t.Helper() - if limitA := s.state.SiteFuseAmps - evPhaseMarginA; s.worstA > limitA+1e-6 { - s.t.Fatalf("%s: a phase reached %.1f A, over the %.0f A working limit", after, s.worstA, limitA) + if limitA := s.state.fuseLineA(); s.worstA > limitA+1e-6 { + s.t.Fatalf("%s: a phase reached %.1f A, over the %.1f A working limit", after, s.worstA, limitA) } } @@ -244,16 +244,16 @@ func TestEVFusePhaseRoomHoldsOnSilentMeter(t *testing.T) { } return roomA } - if got := room(); math.Abs(got-9) > 1e-9 { - t.Fatalf("room %.2f A beside 15 A, want 9 A", got) + if got := room(); math.Abs(got-10) > 1e-9 { + t.Fatalf("room %.2f A beside 15 A, want 10 A", got) } points[0].CommandedW = 5520 now = now.Add(time.Second) - if got := room(); math.Abs(got-1) > 1e-9 { - t.Fatalf("room %.2f A after an 8 A offer, want 1 A", got) + if got := room(); math.Abs(got-2) > 1e-9 { + t.Fatalf("room %.2f A after an 8 A offer, want 2 A", got) } now = now.Add(10 * time.Minute) - if got := room(); math.Abs(got-1) > 1e-9 { - t.Fatalf("room %.2f A after ten silent minutes, want 1 A", got) + if got := room(); math.Abs(got-2) > 1e-9 { + t.Fatalf("room %.2f A after ten silent minutes, want 2 A", got) } } diff --git a/go/internal/control/ev_priority_sitesim_test.go b/go/internal/control/ev_priority_sitesim_test.go index a93519da8..028bed013 100644 --- a/go/internal/control/ev_priority_sitesim_test.go +++ b/go/internal/control/ev_priority_sitesim_test.go @@ -71,7 +71,7 @@ func TestIssue1868ClosedLoopPriorityAndRecovery(t *testing.T) { if s.p.Fuse.Blown != [3]bool{} { t.Fatalf("fuse opened: %+v", s.p.Fuse) } - // Outside house steps may exceed the working margin during device + // Outside house steps may exceed the working limit during device // response. The fixture checks unsafe raises and sustained overages. if s.failure != "" { t.Fatal(s.failure) diff --git a/go/internal/control/ev_slow_charger_battery_test.go b/go/internal/control/ev_slow_charger_battery_test.go index 91b583532..dfef0c33c 100644 --- a/go/internal/control/ev_slow_charger_battery_test.go +++ b/go/internal/control/ev_slow_charger_battery_test.go @@ -27,8 +27,8 @@ func TestSlowChargerUnshownOfferKeepsBatteryOut(t *testing.T) { planBatteryCharge(9400)(s) }} s := runSimScenario(sc, simStart) - t.Logf("delay %v: peak phase %.1f A, %v over %.0f A, idle with room %v, car %.0f W, battery %.0f W", - delay, s.peakA, s.overLimit, s.p.Fuse.RatingA-evPhaseMarginA, s.idleWithRoom, s.p.EVSE.DrawW, s.p.Battery.W) + t.Logf("delay %v: peak phase %.1f A, %v over %.1f A, idle with room %v, car %.0f W, battery %.0f W", + delay, s.peakA, s.overLimit, s.state.fuseLineA(), s.idleWithRoom, s.p.EVSE.DrawW, s.p.Battery.W) if s.failure != "" { t.Errorf("delay %v: %s", delay, s.failure) } diff --git a/go/internal/control/fuse_heat.go b/go/internal/control/fuse_heat.go index 80db61c75..32d646946 100644 --- a/go/internal/control/fuse_heat.go +++ b/go/internal/control/fuse_heat.go @@ -20,10 +20,11 @@ const fuseInstantFactor = 1.2 // fuseHeat models each phase of the main fuse as a first-order low-pass on // I², fed only by the site meter's phase currents. A breaker and a fuse both // trip on heat, not on one reading. FTW does not know which one a site has, -// so the EV hard limit holds the filtered current under the working limit, -// below both types' one-hour ratings (a miniature circuit breaker does not -// trip at 1.13 × In, a gG fuse does not blow at 1.25 × In), and gives no -// budget above fuseInstantFactor. +// so the EV hard limit holds the filtered current at or under the working +// limit, the rating less the user's optional margin (fuseLineA). That is at +// or below both types' one-hour ratings (a miniature circuit breaker does not +// trip at 1.13 × In, a gG fuse does not blow at 1.25 × In). A reading above +// the line spends heat budget first; above fuseInstantFactor there is none. // // A reading stands for the time until the next one. A meter gap counts at // the last current seen: the reading after it neither fills the gap with its diff --git a/go/internal/control/fuse_heat_test.go b/go/internal/control/fuse_heat_test.go index 1264c2c17..b8ddd1038 100644 --- a/go/internal/control/fuse_heat_test.go +++ b/go/internal/control/fuse_heat_test.go @@ -118,10 +118,12 @@ func TestFuseHeatStartsAtFirstReadingAfterRestart(t *testing.T) { // fuseHeatSite charges at 15 A beside 5 A of house load on each phase of a // 25 A fuse with no import ceiling: 20 A per phase, long enough for the heat -// to settle there. +// to settle there. The site opts into a 1 A safety margin, so the working +// limit is 24 A. func fuseHeatSite(t *testing.T) *evMeterSite { t.Helper() s := newEVMeterSite(t, 0, 3450) + s.state.SiteFuseSafetyA = 1 s.run(10 * time.Minute) if s.offer() != 10350 || s.evW != 10350 || math.Abs(s.state.fuseHeat.worstA()-20) > .01 { t.Fatalf("setup: offer %.0f draw %.0f heat %.2f A", s.offer(), s.evW, s.state.fuseHeat.worstA()) @@ -339,11 +341,14 @@ func TestFuseHeatSixteenAmpPeaks(t *testing.T) { } // fuse16Site is Fredrik's case end to end: a 16 A fuse, 4 A of house load -// and the car at 10 A on each phase, 14 A in all, settled. +// and the car at 10 A on each phase, 14 A in all, settled. The site opts +// into a 1 A safety margin, so the working limit is 15 A, and the car asks +// for 10 A: a rise that fits under the line would otherwise fill it. func fuse16Site(t *testing.T) *evMeterSite { t.Helper() s := newEVMeterSite(t, 0, 2760) - s.state.SiteFuseAmps = 16 + s.state.SiteFuseAmps, s.state.SiteFuseSafetyA = 16, 1 + s.ctrl.SetManualHold("garage", loadpoint.ManualHold{PowerW: 6900, PhaseMode: "3p", Persistent: true}) s.ctrl.SetSiteFuse(loadpoint.SiteFuse{MaxAmps: 16, Voltage: 230, PhaseCnt: 3}) s.ctrl.SetFuseEVMax(func() (float64, bool) { return EVFuseBudget(s.store, s.state, s.mgr.States(), s.mgr.Configs(), 16*690) @@ -357,22 +362,27 @@ func fuse16Site(t *testing.T) *evMeterSite { // The same peaks on L1 with the car charging: patterns whose heat stays // under 15 A while the meter shows a peak never move the offer; the others -// cut once when the budget is spent and settle where the peaks fit. A rise reads the heat as well as -// the reading, so the car does not climb back between peaks and cut again. +// cut when the budget is spent. A rise reads the heat as well as the +// reading, and needs its whole step under the line, so the car climbs back +// only once the heat has cooled a step under it. Where the pattern's heat +// sits right at the line (17 A for 10 s, 14 A for 20 s: 15.07 A rms at +// 10 A) the car steps up and down slowly, about once in five minutes, and +// never stops. func TestEVHardLimitSixteenAmpPeaksCutOnceAndSettle(t *testing.T) { for _, tc := range []struct { name string gap time.Duration // 0: the 17 A stays cutAfter time.Duration // 0: never - settleW float64 + maxCuts int + settleW float64 // 0: not judged }{ - {"14A_50s", 50 * time.Second, 0, 6900}, + {"14A_50s", 50 * time.Second, 0, 0, 6900}, // The heat passes 15 A only as the peak ends, when the meter // already shows 14 A: nothing is left to cut. - {"14A_30s", 30 * time.Second, 0, 6900}, - {"14A_20s", 20 * time.Second, 98 * time.Second, 6210}, - {"14A_10s", 10 * time.Second, 48 * time.Second, 5520}, - {"steady_17A", 0, 23 * time.Second, 5520}, + {"14A_30s", 30 * time.Second, 0, 0, 6900}, + {"14A_20s", 20 * time.Second, 98 * time.Second, 3, 0}, + {"14A_10s", 10 * time.Second, 48 * time.Second, 1, 6210}, + {"steady_17A", 0, 23 * time.Second, 1, 5520}, } { t.Run(tc.name, func(t *testing.T) { s := fuse16Site(t) @@ -401,12 +411,13 @@ func TestEVHardLimitSixteenAmpPeaksCutOnceAndSettle(t *testing.T) { cuts = append(cuts, offers[i]) } } - want := 0 - if tc.cutAfter > 0 { - want = 1 + if len(cuts) > tc.maxCuts || tc.cutAfter > 0 && len(cuts) == 0 { + t.Fatalf("cuts %v, want 1 to %d", offerWatts(cuts), tc.maxCuts) } - if len(cuts) != want { - t.Fatalf("cuts %v, want %d", offerWatts(cuts), want) + for _, o := range offers { + if o.w <= 0 { + t.Fatalf("the peaks stopped the car: %v", offerWatts(offers)) + } } if tc.cutAfter > 0 { // From the first reading of the first peak. @@ -414,7 +425,7 @@ func TestEVHardLimitSixteenAmpPeaksCutOnceAndSettle(t *testing.T) { t.Errorf("cut after %v, want ~%v", took, tc.cutAfter) } } - if s.offer() != tc.settleW { + if tc.settleW > 0 && s.offer() != tc.settleW { t.Errorf("settled at %.0f W, want %.0f W", s.offer(), tc.settleW) } if maxHeat > 15.2 { diff --git a/go/internal/control/fuse_line_property_test.go b/go/internal/control/fuse_line_property_test.go new file mode 100644 index 000000000..d375d9e7a --- /dev/null +++ b/go/internal/control/fuse_line_property_test.go @@ -0,0 +1,310 @@ +package control + +import ( + "encoding/json" + "fmt" + "math" + "math/rand/v2" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/loadpoint" + "github.com/srcfl/ftw/go/internal/sitesim" + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// lineRig feeds EVFuseBudget one site reading a second, every configured +// phase at the same current, with one car whose offer the test sets. +type lineRig struct { + t *testing.T + store *telemetry.Store + state *State + now time.Time + phases int + stepW, fuseMaxW float64 + offerW float64 + configs []loadpoint.Config + lastRoom evMeterRoom + lastGridW, lastCapW float64 +} + +func newLineRig(t *testing.T, inA float64, phases int, marginA, offerW float64) *lineRig { + t.Helper() + r := &lineRig{t: t, store: telemetry.NewStore(), state: NewState(0, 0, "meter"), now: time.Unix(1_800_000_000, 0), + phases: phases, stepW: evStepA * 230 * float64(phases), fuseMaxW: inA * 230 * float64(phases), offerW: offerW} + r.state.clock = func() time.Time { return r.now } + r.state.SiteFuseAmps, r.state.SiteFuseVoltage, r.state.SiteFusePhases, r.state.SiteFuseSafetyA = inA, 230, phases, marginA + // The charger declares a response time under evSettle, so an offer is + // shown evSettle after it is sent. + data, _ := json.Marshal(map[string]any{"power_max_age_s": 1}) + r.store.Update("charger", telemetry.DerEV, 0, nil, data) + mode := "3p" + if phases == 1 { + mode = "1p" + } + r.configs = []loadpoint.Config{{ID: "car", DriverName: "charger", PhaseMode: mode, + MinChargeW: 6 * 230 * float64(phases), MaxChargeW: 32 * 230 * float64(phases)}} + return r +} + +// heat sets the fuse model as if each phase had run at levelA, and holds +// heldA until the next reading. +func (r *lineRig) heat(levelA, heldA float64) { + r.state.fuseHeat = fuseHeat{set: true, at: r.now} + for i := range r.phases { + r.state.fuseHeat.sq[i], r.state.fuseHeat.amps[i] = levelA*levelA, heldA + } +} + +// read delivers one reading a second after the last, with every phase at +// a, and returns the cap. +func (r *lineRig) read(a float64) float64 { + r.t.Helper() + r.now = r.now.Add(time.Second) + data := map[string]any{"control_power_available": true, "control_power_observed_at": r.now.Format(time.RFC3339Nano)} + for _, key := range []string{"l1_a", "l2_a", "l3_a"}[:r.phases] { + data[key] = a + } + raw, _ := json.Marshal(data) + r.lastGridW = a * 230 * float64(r.phases) + r.store.Update("meter", telemetry.DerMeter, r.lastGridW, nil, raw) + r.store.Get("meter", telemetry.DerMeter).UpdatedAt = r.now + r.store.RecordDriverSuccess("meter") + points := []loadpoint.State{{ID: "car", DriverName: "charger", PluggedIn: true, CommandedKnown: true, + CommandedW: r.offerW, CommandedPhases: r.phases}} + r.lastCapW, _ = EVFuseBudget(r.store, r.state, points, r.configs, r.fuseMaxW) + r.lastRoom = r.state.evMeterRoom(r.store.Get("meter", telemetry.DerMeter), r.lastGridW, float64(r.phases), r.fuseMaxW, pendingLoad{}) + return r.lastCapW +} + +// The owner's rule of 27 Oct 2026: each phase's working limit is the fuse +// rating less safety_margin_a, with nothing held back below it. Core cuts +// above the line by the heat model and raises only when the next step fits +// under it. +func TestFuseLineProperty(t *testing.T) { + for _, inA := range []float64{16, 20, 25, 35} { + for _, phases := range []int{1, 3} { + for _, marginA := range []float64{0, .5, 1.2} { + lineA := inA - marginA + t.Run(fmt.Sprintf("%gA/%dp/margin_%gA", inA, phases, marginA), func(t *testing.T) { + testFuseLineAtTheLimit(t, inA, phases, marginA, lineA) + testFuseLineJustOver(t, inA, phases, marginA, lineA) + testFuseLineExactFit(t, inA, phases, marginA, lineA) + testFuseLineIdleStart(t, inA, phases, marginA, lineA) + }) + } + } + } +} + +// At the line, with its heat at the line, nothing is over and the cap +// holds for ten minutes. +func testFuseLineAtTheLimit(t *testing.T, inA float64, phases int, marginA, lineA float64) { + t.Helper() + r := newLineRig(t, inA, phases, marginA, 0) + r.offerW = 6 * r.stepW + r.heat(lineA, lineA) + for i := range 600 { + if capW := r.read(lineA); capW != r.offerW { + t.Fatalf("at the line: reading %d cut the cap to %.1f W from %.1f W", i+1, capW, r.offerW) + } + if r.lastRoom.fuseOverA != 0 || r.lastRoom.overLimit { + t.Fatalf("at the line: reading %d over by %.3f A (overLimit %v)", i+1, r.lastRoom.fuseOverA, r.lastRoom.overLimit) + } + } +} + +// 0.1 A over the line: from a cold fuse the cut waits for the heat budget +// and lands on the first reading after it is spent; from a hot fuse it +// lands on the next reading; above 1.2 × In it lands on the same reading. +// Each cut takes at least the 0.1 A and at most one step. +func testFuseLineJustOver(t *testing.T, inA float64, phases int, marginA, lineA float64) { + t.Helper() + overA := lineA + .1 + offerW := 10 * evStepA * 230 * float64(phases) + checkCut := func(name string, r *lineRig, capW float64) { + t.Helper() + if cutW := offerW - capW; cutW < .1*r.stepW-1e-6 || cutW > r.stepW+1e-6 { + t.Fatalf("%s: cut %.1f W, want 0.1 A to one step (%.0f W)", name, cutW, r.stepW) + } + } + + r := newLineRig(t, inA, phases, marginA, offerW) + coldA := lineA - 2 + r.heat(coldA, overA) + tStar := -fuseHeatTau.Seconds() * math.Log(1-(lineA*lineA-coldA*coldA)/(overA*overA-coldA*coldA)) + for k := 1; ; k++ { + capW := r.read(overA) + if float64(k) < tStar { + if capW != offerW { + t.Fatalf("cold: cut to %.1f W at %d s, before the budget is spent at %.1f s", capW, k, tStar) + } + continue + } + if capW >= offerW { + t.Fatalf("cold: no cut at %d s, the first reading after the budget (%.1f s)", k, tStar) + } + checkCut("cold", r, capW) + break + } + + r = newLineRig(t, inA, phases, marginA, offerW) + r.heat(lineA, overA) + if capW := r.read(overA); capW >= offerW { + t.Fatal("hot: no cut on the next reading") + } else { + checkCut("hot", r, capW) + } + + r = newLineRig(t, inA, phases, marginA, offerW) + r.heat(coldA, coldA) + if capW := r.read(fuseInstantFactor*inA + .1); capW >= offerW { + t.Fatalf("above %.1f × In: no cut on the same reading", fuseInstantFactor) + } +} + +// A rise moves one step when level + step is exactly the line, and not +// when it is 0.01 A over. A demand less than a step rises when the room +// equals it, with or without battery charge. +func testFuseLineExactFit(t *testing.T, inA float64, phases int, marginA, lineA float64) { + t.Helper() + settled := func(houseA float64) *lineRig { + t.Helper() + r := newLineRig(t, inA, phases, marginA, 0) + r.offerW = 6 * r.stepW + r.heat(lineA, lineA) + for range 30 { // The offer shows; no room. + r.read(lineA) + } + r.heat(houseA, houseA) // The house fell, and its heat has cooled. + return r + } + r := settled(lineA - evStepA) + if capW := r.read(lineA - evStepA); math.Abs(capW-(r.offerW+r.stepW)) > 1e-6 { + t.Fatalf("level + step = line: cap %.1f W, want one step over the %.0f W offer", capW, r.offerW) + } + r = settled(lineA - evStepA + .01) + if capW := r.read(lineA - evStepA + .01); capW != r.offerW { + t.Fatalf("level + step = line + 0.01 A: cap %.1f W, want the %.0f W offer", capW, r.offerW) + } + for _, charging := range []bool{false, true} { + r = settled(lineA - evStepA/2) + wantW := r.offerW + r.stepW/2 + r.state.SetEVFuseDemands([]loadpoint.FuseDemand{{DriverName: "charger", PowerW: wantW, PhaseMode: r.configs[0].PhaseMode}}) + if charging { + r.state.batteryCommands = map[string]commandLog{"battery": commandLog{}.add(r.now.Add(-time.Minute), 2000)} + } + if capW := r.read(lineA - evStepA/2); math.Abs(capW-wantW) > 1e-6 { + t.Fatalf("half a step to go, room for it, battery charging %v: cap %.1f W, want %.1f W", charging, capW, wantW) + } + } +} + +// An idle car with room for exactly its minimum starts at the minimum +// once the meter has shown that room for evRestartDwell. +func testFuseLineIdleStart(t *testing.T, inA float64, phases int, marginA, lineA float64) { + t.Helper() + r := newLineRig(t, inA, phases, marginA, 0) + minW := r.configs[0].MinChargeW + r.heat(lineA, lineA) + if capW := r.read(lineA); capW != 0 { + t.Fatalf("idle start with no room: cap %.1f W", capW) + } + levelA := lineA - minW/(230*float64(phases)) + for k := 1; k <= 60; k++ { + capW := r.read(levelA) + switch at := time.Duration(k-1) * time.Second; { + case at < evRestartDwell && capW != 0: + t.Fatalf("idle start: %.1f W after %v of room, before the %v dwell", capW, at, evRestartDwell) + case at >= evRestartDwell: + if capW != minW { + t.Fatalf("idle start: cap %.1f W after %v of room for exactly %.0f W", capW, at, minW) + } + return + } + } +} + +// fitScenario runs a 3 × 16 A site, safety margin 0.5 A, with 3.5 A of +// house on each phase: twelve steps of the car fit exactly under the 15.5 A +// line. The car asks for 16 A. +func fitScenario(noise func() float64) *simSite { + sc := simScenario{name: "exact fit", run: 30 * time.Minute, + plant: func(p *sitesim.Plant) { + p.Fuse.RatingA = 16 + p.HouseW = houseA(3.5, 3.5, 3.5) + }, + setup: func(s *simSite) { s.meterNoise = noise }} + return runSimScenario(sc, simStart) +} + +// Closed loop: the car climbs to the line and stays there for 30 min. +func TestSiteSimCarEndsAtTheLine(t *testing.T) { + s := fitScenario(nil) + if s.failure != "" { + t.Fatal(s.failure) + } + lineA := s.state.fuseLineA() + if want := (lineA - 3.5) * 690; s.p.EVSE.DrawW != want || s.peakA > lineA+1e-6 { + t.Fatalf("car %.0f W, peak phase %.3f A; want %.0f W with every phase at most %.1f A", s.p.EVSE.DrawW, s.peakA, want, lineA) + } + var last float64 + for _, c := range s.commands { + if c.device == "evse" { + if c.w < last { + t.Fatalf("cut to %v with every phase at or under the line", c) + } + last = c.w + } + } +} + +// Closed loop with 0.1 A of meter noise on each phase: the car steps at +// most once per settle time plus the heat's cooling, no phase passes +// 1.2 × In, and the plant's gG fuse holds. +func TestSiteSimNoisyLineDoesNotHunt(t *testing.T) { + rng := rand.New(rand.NewPCG(1, 0)) + s := fitScenario(func() float64 { return .1 * rng.NormFloat64() }) + if s.failure != "" { + t.Fatal(s.failure) + } + if s.peakA > fuseInstantFactor*s.p.Fuse.RatingA || s.p.Fuse.AnyBlown() { + t.Fatalf("peak phase %.2f A, fuse %+v", s.peakA, s.p.Fuse) + } + var moves []simCommand + last := 0.0 + for _, c := range s.commands { + if c.device == "evse" && c.w != last { + moves, last = append(moves, c), c.w + } + } + // The start, then the climb to the line: one step per reading. + climb := 0 + for climb+1 < len(moves) && moves[climb+1].w > moves[climb].w { + climb++ + } + after := moves[climb+1:] + perHour := float64(len(after)) / s.p.Now.Sub(moves[climb].at).Hours() + if limit := time.Hour.Seconds() / (evSettle + fuseHeatTau).Seconds(); perHour > limit { + t.Fatalf("%d moves after the climb (%.0f an hour, limit %.0f): %v", len(after), perHour, limit, after) + } + for i := 1; i < len(after); i++ { + if after[i].w > after[i-1].w && after[i].at.Sub(after[i-1].at) < evSettle { + t.Fatalf("rose %v after a cut: %v then %v", after[i].at.Sub(after[i-1].at), after[i-1], after[i]) + } + } + t.Logf("car %.0f W, peak phase %.2f A, %d moves after the climb", s.p.EVSE.DrawW, s.peakA, len(after)) +} + +// With no safety margin, battery charge may fill a phase to exactly the +// rating beside a car that wants nothing more. +func TestEVBatteryChargeFillsPhaseToTheRating(t *testing.T) { + store, state := evSplitFixture(t, (20+18+18)*230, []float64{20, 18, 18}, 4140, "3p") + state.SiteFuseSafetyA = 0 + sent(state, "ev", 4140) + sent(state, "first", 0) + out := clampEVBatteryHeadroom([]DispatchTarget{{Driver: "first", TargetW: 8000}}, store, state, 17250) + if got, want := targetW(out, "first"), (25.0-20)*690; math.Abs(got-want) > .01 { + t.Fatalf("battery %.1f W, want %.1f W: L1 from 20 A to exactly 25 A", got, want) + } +} diff --git a/go/internal/control/fuse_phase.go b/go/internal/control/fuse_phase.go index da041b83e..05541c5d5 100644 --- a/go/internal/control/fuse_phase.go +++ b/go/internal/control/fuse_phase.go @@ -8,6 +8,14 @@ import ( "github.com/srcfl/ftw/go/internal/telemetry" ) +// fuseLineA is each phase's working limit: the fuse rating less the user's +// optional safety margin, never below 0. Every per-phase fuse decision reads +// it. Anti-hunting lives in timers and in the size of the next step, never in +// amps held back below this line. +func (s *State) fuseLineA() float64 { + return math.Max(0, s.SiteFuseAmps-math.Max(0, s.SiteFuseSafetyA)) +} + // phaseImbalanceA is how far the worst phase sits above the mean phase // current of one meter sample. The aggregate fuse budget assumes balanced // phases, but the breaker, and a charger's own load balancer, act on the diff --git a/go/internal/control/import_hour.go b/go/internal/control/import_hour.go index 77b0b83af..a510b624c 100644 --- a/go/internal/control/import_hour.go +++ b/go/internal/control/import_hour.go @@ -178,7 +178,7 @@ func (s *State) stepHourImportLimits(at time.Time, gap bool) { "imported_wh", h.importedWh, "limit_w", rateW, "was_w", h.limitW) } h.limitW, h.riseW, h.changedAt = rateW, math.Min(h.riseW, rateW), at - step := evPhaseMarginA * s.SiteFuseVoltage * float64(s.SiteFusePhases) + step := evStepA * s.SiteFuseVoltage * float64(s.SiteFusePhases) left := h.start.Add(time.Hour).Sub(at) if gap || !(step > 0) || at.Sub(h.cutAt) < importHourRiseGap || left < importHourRiseMinLeft || rateW < h.riseW+2*step { return @@ -241,7 +241,7 @@ func PlanningImportCeiling(s *State) mpc.ImportCeiling { if h := &s.importHour; s.importHourMeasured() { elapsedWh = h.importedWh + ceiling*h.unknown.Hours() } - step := evPhaseMarginA * s.SiteFuseVoltage * float64(s.SiteFusePhases) + step := evStepA * s.SiteFuseVoltage * float64(s.SiteFusePhases) return mpc.ImportCeiling{W: ceiling, MeanW: max(0, ceiling-step/2), HourStart: start, ElapsedWh: elapsedWh} } diff --git a/go/internal/control/sitesim_field_test.go b/go/internal/control/sitesim_field_test.go index 7ea788beb..83de1bf02 100644 --- a/go/internal/control/sitesim_field_test.go +++ b/go/internal/control/sitesim_field_test.go @@ -502,7 +502,7 @@ func (f *fieldRun) harvest(s *simSite, kind string) { } } -func (f *fieldRun) limitA(s *simSite) float64 { return s.p.Fuse.RatingA - evPhaseMarginA } +func (f *fieldRun) limitA(s *simSite) float64 { return s.state.fuseLineA() } // send records the command as the driver registry does and checks a cut. func (f *fieldRun) send(ctx context.Context, s *simSite, driver string, payload []byte) error { @@ -555,7 +555,7 @@ func (f *fieldRun) checkCut(s *simSite, w float64) { over = over || math.Abs(a) >= limit || s.heat[i] >= limit*limit } if !over { - f.fail(s, failCut, "cut the car %.0f -> %.0f W for the fuse with every phase under %.0f A (meter %.1f A)", + f.fail(s, failCut, "cut the car %.0f -> %.0f W for the fuse with every phase under %.1f A (meter %.1f A)", s.offerW, w, limit, s.meter.PhaseA) return } @@ -563,6 +563,11 @@ func (f *fieldRun) checkCut(s *simSite, w float64) { if !queued || e.DrawW <= 0 { return } + // Past the current a gG fuse carries for an hour, no cut on its way + // holds back the next one (fuseHourFactor). + if hourA := fuseHourFactor * s.p.Fuse.RatingA; max(s.heat[0], s.heat[1], s.heat[2]) > hourA*hourA { + return + } drawA := e.DrawW / s.p.Voltage / float64(e.DrawPhases) carA := s.p.Car.MaxW / s.p.Voltage / float64(min(max(queuedPhases, 1), e.Phases, s.p.Car.Phases)) covered := true @@ -580,7 +585,7 @@ func (f *fieldRun) checkCut(s *simSite, w float64) { } } if covered { - f.fail(s, failOverCut, "cut the car %.0f -> %.0f W while a cut to %.0f A it has not applied covers the overage (meter %.1f A, limit %.0f A)", + f.fail(s, failOverCut, "cut the car %.0f -> %.0f W while a cut to %.0f A it has not applied covers the overage (meter %.1f A, limit %.1f A)", s.offerW, w, queuedA, s.meter.PhaseA, limit) } } @@ -598,7 +603,7 @@ func (f *fieldRun) wantsCharge(s *simSite, baseW float64) bool { if level > 0 { level = math.Max(level, math.Sqrt(s.heat[i])) } - room = room && level+p.EVSE.MinA+evPhaseMarginA <= limit + room = room && level+p.EVSE.MinA <= limit+1e-9 } switch { case !room: @@ -695,7 +700,7 @@ func fieldRoomW(c fieldCase, e *sitesim.EVSE, car *sitesim.Car) float64 { for i := range phases { worst = math.Max(worst, c.house[i]) } - roomA := math.Min(c.fuseA-evPhaseMarginA-worst, e.MaxA) + roomA := math.Min(c.fuseA-simFuseSafetyA-worst, e.MaxA) if roomA < e.MinA { return 0 } @@ -800,7 +805,7 @@ func runFieldCase(c fieldCase, trace func(string, ...any)) (*simSite, *fieldRun) // Export steps up and down, never past the fuse with the car off. houseW, maxPVW := p.HouseW[0]+p.HouseW[1]+p.HouseW[2], math.Inf(1) for _, a := range c.house { - maxPVW = math.Min(maxPVW, 3*230*(c.fuseA-2*evPhaseMarginA+a)) + maxPVW = math.Min(maxPVW, 3*230*(c.fuseA-simFuseSafetyA+a)) } exports := []float64{2500, 6000, 9000, 3000} if len(c.exportW) > 0 { diff --git a/go/internal/control/sitesim_property_test.go b/go/internal/control/sitesim_property_test.go index 057fa8c84..519a18fbc 100644 --- a/go/internal/control/sitesim_property_test.go +++ b/go/internal/control/sitesim_property_test.go @@ -19,11 +19,11 @@ import ( var randomHouseKnown = map[uint64]map[string]string{} // Core keeps a random house under the fuse. For each fixed seed the house -// load on each phase steps at random to anywhere up to the fuse less 2 A, +// load on each phase steps at random to anywhere up to the working limit, // with the fuse warm from the first load, while a car charges on Charge now // through a charger that answers in 2, 5 or 40 s. simSite.check holds the // fuse's invariants every plant second for an hour: the fuse never blows, -// and no phase stays over the fuse less its margin longer than the +// and no phase stays over the working limit longer than the // charger's response plus 3 s, or 3 s after a raise of Core's own. Idle // time with room is logged, not judged: the field matrix judges it with the // fuse's own memory. @@ -38,7 +38,7 @@ func TestSiteSimRandomHouse(t *testing.T) { house := func() [3]float64 { var a [3]float64 for i := range a { - a[i] = rng.Float64() * (p.Fuse.RatingA - 2) + a[i] = rng.Float64() * (p.Fuse.RatingA - simFuseSafetyA) // up to the line } return a } @@ -70,8 +70,8 @@ func TestSiteSimRandomHouse(t *testing.T) { steps++ } } - t.Logf("%.0f A fuse, charger %v, %d house steps: peak phase %.1f A, %v over %.0f A, fuse damage at most %.2f, car idle with room %v, %.1f kWh to the car", - p.Fuse.RatingA, p.EVSE.Delay, steps, s.peakA, s.overLimit, p.Fuse.RatingA-evPhaseMarginA, damage, s.idleWithRoom, p.EVSE.SessionWh/1000) + t.Logf("%.0f A fuse, charger %v, %d house steps: peak phase %.1f A, %v over %.1f A, fuse damage at most %.2f, car idle with room %v, %.1f kWh to the car", + p.Fuse.RatingA, p.EVSE.Delay, steps, s.peakA, s.overLimit, s.state.fuseLineA(), damage, s.idleWithRoom, p.EVSE.SessionWh/1000) delete(failures, failIdle) known := randomHouseKnown[seed] for _, k := range slices.Sorted(maps.Keys(failures)) { diff --git a/go/internal/control/sitesim_test.go b/go/internal/control/sitesim_test.go index 0d37b6d47..caa84aa04 100644 --- a/go/internal/control/sitesim_test.go +++ b/go/internal/control/sitesim_test.go @@ -20,6 +20,9 @@ import ( // simCoreEvery is control_interval_s's default. The plant steps every second. const simCoreEvery = 2 * time.Second +// simFuseSafetyA is the site's fuse.safety_margin_a, the config default. +const simFuseSafetyA = .5 + // simSite runs Core's control tick against a sitesim.Plant in main.go's // order: site import, charger tick, then battery dispatch. Core's settings // are the config defaults. Every plant second it checks the invariants and @@ -42,6 +45,9 @@ type simSite struct { // evMaxAge is the power_max_age_s the charger driver declares outside // the field matrix; zero declares none. evMaxAge time.Duration + // meterNoise is added to each phase current Core reads, not to the + // plant's own; nil reads the plant exactly. + meterNoise func() float64 downUntil, nextTick time.Time meter sitesim.MeterReading @@ -86,7 +92,7 @@ func (s *simSite) boot() { s.state = NewState(0, 42, "meter") s.state.clock = func() time.Time { return s.p.Now } s.state.SlewRateW, s.state.MinDispatchIntervalS = 3000, 2 - s.state.SiteFuseAmps, s.state.SiteFuseVoltage, s.state.SiteFusePhases, s.state.SiteFuseSafetyA = s.p.Fuse.RatingA, s.p.Voltage, 3, .5 + s.state.SiteFuseAmps, s.state.SiteFuseVoltage, s.state.SiteFusePhases, s.state.SiteFuseSafetyA = s.p.Fuse.RatingA, s.p.Voltage, 3, simFuseSafetyA if b := s.p.Battery; b != nil { s.state.DriverLimits = map[string]PowerLimits{"battery": {MaxChargeW: b.MaxChargeW, MaxDischargeW: b.MaxDischargeW}} } @@ -218,8 +224,17 @@ func (s *simSite) step() { } if s.downUntil.IsZero() { if m := tick.Meter; m != nil { - s.emit("meter", telemetry.DerMeter, m.W, nil, map[string]any{"l1_a": m.PhaseA[0], "l2_a": m.PhaseA[1], "l3_a": m.PhaseA[2], - "l1_w": m.PhaseW[0], "l2_w": m.PhaseW[1], "l3_w": m.PhaseW[2]}) + read := *m + if s.meterNoise != nil { + for i := range read.PhaseA { + n := s.meterNoise() + read.PhaseA[i] += n + read.PhaseW[i] += n * s.p.Voltage + read.W += n * s.p.Voltage + } + } + s.emit("meter", telemetry.DerMeter, read.W, nil, map[string]any{"l1_a": read.PhaseA[0], "l2_a": read.PhaseA[1], "l3_a": read.PhaseA[2], + "l1_w": read.PhaseW[0], "l2_w": read.PhaseW[1], "l3_w": read.PhaseW[2]}) } if b := tick.Battery; b != nil { s.emit("battery", telemetry.DerBattery, b.W, &b.SoC, nil) @@ -329,8 +344,10 @@ func (s *simSite) check() { // fuseHeat reads the meter, may break for the fastest response time plus // 3 s: a phase may sit above the fuse less its margin only while its // I²-filtered current is under it, and never above the instant limit. + // A phase exactly at the line is under it; 1 µA absorbs the rounding of + // summed watts. fuseA := p.Fuse.RatingA - limitA, k := fuseA-evPhaseMarginA, -math.Expm1(-sitesim.Step.Seconds()/fuseHeatTau.Seconds()) + limitA, k := s.state.fuseLineA()+1e-6, -math.Expm1(-sitesim.Step.Seconds()/fuseHeatTau.Seconds()) over, overLimit := false, false for i, a := range p.A { if s.heatSet { @@ -353,7 +370,7 @@ func (s *simSite) check() { s.limitSince = time.Time{} } if s.ownRaise && !s.limitSince.IsZero() && now.Sub(s.limitSince) > 3*time.Second { - s.fail("a raise we sent kept a phase over %.0f A for more than 3 s", limitA) + s.fail("a raise we sent kept a phase over %.1f A for more than 3 s", limitA) } if !over { s.overSince = time.Time{} @@ -361,7 +378,7 @@ func (s *simSite) check() { s.overSince = now } if allow := s.responseTime(false) + 3*time.Second; !s.overSince.IsZero() && now.Sub(s.overSince) > allow { - s.fail("over Core's limit for more than %v (heat %.1f A, limit %.0f A)", allow, math.Sqrt(max(s.heat[0], s.heat[1], s.heat[2])), limitA) + s.fail("over Core's limit for more than %v (heat %.1f A, limit %.1f A)", allow, math.Sqrt(max(s.heat[0], s.heat[1], s.heat[2])), limitA) } // (b) With the meter on schedule, room for the car's minimum and a car // that asks, the car draws within a minute plus the charger's delay @@ -395,7 +412,7 @@ func (s *simSite) wantsCharge() bool { } // After a real overload, an idle car must wait for the fuse to cool. // Its recovery deadline starts when that heat no longer blocks a start. - if e.DrawW <= 0 && max(s.heat[0], s.heat[1], s.heat[2]) > math.Pow(p.Fuse.RatingA-evPhaseMarginA, 2) { + if e.DrawW <= 0 && max(s.heat[0], s.heat[1], s.heat[2]) > math.Pow(s.state.fuseLineA(), 2) { return false } phases := min(e.Phases, p.Car.Phases) @@ -403,7 +420,7 @@ func (s *simSite) wantsCharge() bool { for i, houseW := range p.HouseW { w := houseW + p.PVW/3 baseW += w - if i < phases && math.Abs(w/p.Voltage+e.MinA) > p.Fuse.RatingA-evPhaseMarginA { + if i < phases && math.Abs(w/p.Voltage+e.MinA) > s.state.fuseLineA() { return false } } @@ -804,7 +821,7 @@ func TestSiteSimScenarios(t *testing.T) { start = simStart } s := runSimScenario(sc, start) - t.Logf("peak phase %.1f A, %v over %.0f A; car idle with room %v", s.peakA, s.overLimit, s.p.Fuse.RatingA-evPhaseMarginA, s.idleWithRoom) + t.Logf("peak phase %.1f A, %v over %.1f A; car idle with room %v", s.peakA, s.overLimit, s.state.fuseLineA(), s.idleWithRoom) switch { case sc.known == "" && s.failure != "": t.Fatal(s.failure) diff --git a/go/internal/loadpoint/controller_fuse_phase_test.go b/go/internal/loadpoint/controller_fuse_phase_test.go index f5ad4fd59..3a52bb642 100644 --- a/go/internal/loadpoint/controller_fuse_phase_test.go +++ b/go/internal/loadpoint/controller_fuse_phase_test.go @@ -48,7 +48,7 @@ func TestSharedFuseGuardUsesCommandPhase(t *testing.T) { if !known || math.Abs(command.power-tc.commandW) > .01 || command.phaseMode != tc.commandMode { t.Fatalf("command=%+v, want %.0f W with phase %q", command, tc.commandW, tc.commandMode) } - if phases := PhaseFor(command.phaseMode, command.power, 3680); command.power > 0 && tc.worstA+command.power/(230*float64(phases)) > 24.001 { + if phases := PhaseFor(command.phaseMode, command.power, 3680); command.power > 0 && tc.worstA+command.power/(230*float64(phases)) > 25.001 { t.Fatalf("resolved %dp command crosses the phase working limit: %+v", phases, command) } demand := c.FuseDemands() diff --git a/go/internal/loadpoint/controller_phase_choice_test.go b/go/internal/loadpoint/controller_phase_choice_test.go index 28d818990..7b772af20 100644 --- a/go/internal/loadpoint/controller_phase_choice_test.go +++ b/go/internal/loadpoint/controller_phase_choice_test.go @@ -13,7 +13,7 @@ var threePhaseSteps = []float64{0, 1380, 1610, 1840, 2070, 2300, 2530, 2760, 299 4140, 4830, 5520, 6210, 6900, 7590, 8280, 8970, 9660, 10350, 11040} // meteredEVCap stands in for control.EVFuseBudget: the plugged cars' last -// offers plus the room the meter shows below the fuse less 1 A, on the +// offers plus the room the meter shows below the fuse, on the // phases FuseConfigs names for this tick. func meteredEVCap(c *Controller, worstA func() float64) func() (float64, bool) { return func() (float64, bool) { @@ -27,7 +27,7 @@ func meteredEVCap(c *Controller, worstA func() float64) func() (float64, bool) { offersW += math.Max(0, st.CommandedW) } } - return math.Max(0, offersW+(site.MaxAmps-1-worstA())*site.Voltage*phases), true + return math.Max(0, offersW+(site.MaxAmps-worstA())*site.Voltage*phases), true } } From 3860ee19b9cc0d2403bec6d59331557b8fb374be Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 18:25:24 +0100 Subject: [PATCH 13/68] fix(control): keep covered offers whole and leave battery relief out of EV room Two review findings on the fuse-line change: - A cut rounds to whole charger amps only when a new cut is needed. When cuts on their way cover the overage, the offer stays as it is. Rounding a kept step-table offer took the car 6200 -> 5500 -> 4800 -> 0 W in 3 s on a 0.6 A overage while a 180 s cut travelled. - Dispatch records the discharge the fuse guard adds to each battery, and an EV rise or start does not count it as room. Before, the car rose into the relief and the battery fed it 650 W at the line for as long as the house load stayed. The noisy-line sim test now pins the slow one-step cycle at an exact fit (at most 5 cuts an hour, never a stop) and no moves with part of a step left, instead of allowing 45 moves an hour. Co-Authored-By: Claude Opus 5.5 --- .changeset/b-ev-fuse-line-at-rating.md | 2 +- docs/safety.md | 4 +- go/internal/control/dispatch.go | 43 +++++++ .../control/ev_battery_sequence_test.go | 43 +++++-- go/internal/control/ev_fuse_budget.go | 35 +++++- .../control/ev_fuse_cut_netting_test.go | 43 ++++++- .../control/fuse_line_property_test.go | 118 ++++++++++++------ 7 files changed, 229 insertions(+), 59 deletions(-) diff --git a/.changeset/b-ev-fuse-line-at-rating.md b/.changeset/b-ev-fuse-line-at-rating.md index 9d8504a29..f28801459 100644 --- a/.changeset/b-ev-fuse-line-at-rating.md +++ b/.changeset/b-ev-fuse-line-at-rating.md @@ -2,4 +2,4 @@ "ftw": patch --- -The car now charges up to the fuse rating less `fuse.safety_margin_a`, not a fixed 1 A below it. A charging car rises one step once that step fits under the line, instead of needing two steps of room and keeping one free; an idle car starts with all the room it has. Home battery charge beside a car uses the same line, with no 1 A floor. On a three-phase site with the default 0.5 A margin, a car near the fuse gets 0.5 A to 1.5 A more on each phase. Cuts above the line still wait for the fuse's heat budget, and the hour's import limit keeps its own margins. +The car now charges up to the fuse rating less `fuse.safety_margin_a`, not a fixed 1 A below it. A charging car rises one step once that step fits under the line, instead of needing two steps of room and keeping one free; an idle car starts with all the room it has. Home battery charge beside a car uses the same line, with no 1 A floor. On a three-phase site with the default 0.5 A margin, a car near the fuse gets 0.5 A to 1.5 A more on each phase. Cuts above the line still wait for the fuse's heat budget, and the hour's import limit keeps its own margins. A car never rises or starts into battery discharge that the fuse guard added. diff --git a/docs/safety.md b/docs/safety.md index 5d6009432..11981bd67 100644 --- a/docs/safety.md +++ b/docs/safety.md @@ -58,7 +58,9 @@ EVs once that filtered current passes the same limit, and at once above only when that step fits under the limit, and not within 20 s of a cut. Its rise reads the higher of the reading and that filtered current. An idle car's start reads each phase as it is, plus its new current; the filtered -current holds it back only while it is over the limit. Where the meter +current holds it back only while it is over the limit. Neither counts +battery discharge that the fuse guard added as room: that relief ends once +the site fits without it. Where the meter reports phase currents, they replace total import as the EVs' fuse check; a tariff import ceiling still applies. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 395e52725..b78eb2093 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -394,6 +394,11 @@ type State struct { // batteryCommands and evLimit.offers are our own recent commands, the // only device input the EV hard limit and the EV/battery split use. batteryCommands map[string]commandLog + // batteryFuseRelief is the discharge the fuse guard added to each + // battery's last dispatched command (forceFuseDischarge). It ends once + // the site fits without it, so an EV rise or start never counts it as + // room (evFuseReliefW). + batteryFuseRelief map[string]float64 // PI controller (outer, site-level) PI *PIController @@ -2382,6 +2387,7 @@ func applyDispatchSafetyPipeline( // forceFuseDischarge runs after the normal policy rails. A fuse overflow can // demand a battery target far beyond what slew would allow in one tick; // slew-limiting that response would leave the fuse violated for multiple ticks. + beforeRelief := append([]DispatchTarget(nil), targets...) targets = forceFuseDischarge(targets, store, state, driverCapacities, fuseMaxW) // Keep the hardware direction contract last. forceFuseDischarge already // allocates within the discharge cap, but this final check also covers any @@ -2395,9 +2401,36 @@ func applyDispatchSafetyPipeline( targets = state.floorFullBatteryCharge(targets) republishFuseEVCapAfterFuseDischarge(targets, store, state, fuseMaxW) recordDispatchTargets(targets, state, opts.updatePrevTargets, opts.recordDispatch) + if opts.recordDispatch { + state.recordFuseRelief(beforeRelief, targets) + } return targets } +// recordFuseRelief keeps, per battery, the discharge in the final command +// that the fuse guard added: below both the command before forceFuseDischarge +// and 0 W. Planner or operator discharge is not relief. +func (s *State) recordFuseRelief(before, after []DispatchTarget) { + if s == nil { + return + } + pre := make(map[string]float64, len(before)) + for _, t := range before { + pre[t.Driver] += t.TargetW + } + post := make(map[string]float64, len(after)) + for _, t := range after { + post[t.Driver] += t.TargetW + } + relief := make(map[string]float64) + for driver, w := range post { + if r := math.Min(pre[driver]-w, -w); r > 0 { + relief[driver] = r + } + } + s.batteryFuseRelief = relief +} + // Unknown battery energy cannot support a discharge command, even during // fuse relief. Check the final targets so slew cannot restore live discharge // and EV headroom reflects only the battery commands we can actually send. @@ -4067,6 +4100,16 @@ func fuseSaverEarlyExit( if out == nil || state == nil { return out } + // The early path starts from live power, so relief is discharge below + // what each battery reads now. Without a command the last one stands, + // and so does its relief. + live := make([]DispatchTarget, 0, len(out)) + for _, t := range out { + if r := store.Get(t.Driver, telemetry.DerBattery); r != nil { + live = append(live, DispatchTarget{Driver: t.Driver, TargetW: r.SmoothedW}) + } + } + state.recordFuseRelief(live, out) state.LastTargets = out now := state.now() state.LastDispatch = &now diff --git a/go/internal/control/ev_battery_sequence_test.go b/go/internal/control/ev_battery_sequence_test.go index b60f0d2e5..cb65b46e6 100644 --- a/go/internal/control/ev_battery_sequence_test.go +++ b/go/internal/control/ev_battery_sequence_test.go @@ -518,15 +518,40 @@ func TestFuseOverageGetsBatteryReliefUntilEVCutShows(t *testing.T) { t.Fatalf("%v: meter %.0f W, want within the 25 A breaker and no export", m.at.Sub(stepAt), m.w) } } - // The car rises one step once that step fits under the 24 A line, and - // the reading it rises on still holds part of the battery's relief. - // Ending a discharge needs room after the car's raise (EV first), so - // the battery keeps less than that step and the phase sits at the line. - if s.offer() >= 10350 || s.batteryW < -690 || s.batteryW > 0 { - t.Fatalf("after the cut: offer %.0f W battery %.0f W, want a cut car and at most one car step of battery relief", s.offer(), s.batteryW) - } - if a := s.gridW() / 690; a > 24+1e-6 { - t.Fatalf("after the cut: %.2f A on each phase, over the 24 A line", a) + if s.offer() >= 10350 || s.batteryW != 0 { + t.Fatalf("after the cut: offer %.0f W battery %.0f W, want a cut car and an idle battery", s.offer(), s.batteryW) + } + // The car's rise never counts the battery's relief as room. A car that + // rose into it kept the battery feeding it 650 W at the 24 A line for + // as long as the house load stayed. + for range 10 { + s.run(time.Minute) + if s.batteryW != 0 || s.gridW()/690 > 24+1e-6 { + t.Fatalf("%v: offer %.0f W battery %.0f W, %.2f A on each phase; want an idle battery under the 24 A line", + s.now.Sub(stepAt), s.offer(), s.batteryW, s.gridW()/690) + } + } + if s.offer() != 5520 { + t.Fatalf("offer %.0f W, want 5,520 W: 8 A beside 16 A of house under the 24 A line", s.offer()) + } +} + +// Relief is only the discharge the fuse guard added: a cancelled charge or +// the planner's own discharge stays room for the car. +func TestFuseReliefIsOnlyAddedDischarge(t *testing.T) { + s := &State{} + s.recordFuseRelief( + []DispatchTarget{{Driver: "idle", TargetW: 0}, {Driver: "planned", TargetW: -1000}, {Driver: "charge", TargetW: 2000}, {Driver: "flip", TargetW: 300}}, + []DispatchTarget{{Driver: "idle", TargetW: -650}, {Driver: "planned", TargetW: -1650}, {Driver: "charge", TargetW: 500}, {Driver: "flip", TargetW: -200}}, + ) + want := map[string]float64{"idle": 650, "planned": 650, "flip": 200} + if len(s.batteryFuseRelief) != len(want) { + t.Fatalf("relief %v, want %v", s.batteryFuseRelief, want) + } + for d, w := range want { + if got := s.batteryFuseRelief[d]; math.Abs(got-w) > 1e-9 { + t.Fatalf("relief %v, want %v", s.batteryFuseRelief, want) + } } } diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index 21408151c..4150ceb0a 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -475,11 +475,18 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea } over, capW, byImport := r.fuseOverW > 0, math.Inf(1), false if over { - capW = latestW - math.Max(0, fuseCutW) - if r.perPhase { - // A charger rounds to the nearest amp, so a cut that leaves - // half an amp would round back up and stay over the line. - capW = wholeStepsW(capW, step) + capW = latestW + if fuseCutW > 0 { + capW -= fuseCutW + if r.perPhase { + // A charger rounds to the nearest amp, so a cut that leaves + // half an amp would round back up and stay over the line. + // Only a new cut rounds. When cuts on their way cover the + // overage, the offer stays as it is, whole amps or not (a + // step table, a PV surplus); rounding it would lower it + // again on every reading. + capW = wholeStepsW(capW, step) + } } } if r.limitW >= 0 { @@ -520,6 +527,12 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea // An increase needs a fresh reading and room below the level increases // may reach, left after our own battery commands that the meter may not // 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 { + r = s.evMeterRoom(meter, gridW, pool.phases, fuseMaxW, s.withBatteryOrders(s.pendingLoad(at), pending+reliefW)) + } fuseRoom, importRoom := 0.0, 0.0 if fresh { fuseRoom, importRoom = math.Max(0, r.fuseW), math.Max(0, r.riseW) @@ -558,6 +571,18 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea } } +// evFuseReliefW is the fuse guard's battery relief the meter may show now: +// each battery's recorded relief, at most the discharge it reads. +func (s *State) evFuseReliefW(store *telemetry.Store) float64 { + var w float64 + for driver, relief := range s.batteryFuseRelief { + if r := store.Get(driver, telemetry.DerBattery); r != nil && finiteFuseValue(r.RawW) { + w += math.Min(relief, math.Max(0, -r.RawW)) + } + } + return w +} + // wholeStepsW rounds w down to whole charger amps on the pool's phases, one // step each. Chargers round an offer to the nearest amp, so a cap at the // line's exact room could land half an amp over it. This is step diff --git a/go/internal/control/ev_fuse_cut_netting_test.go b/go/internal/control/ev_fuse_cut_netting_test.go index c1eb1ac2f..88dfb337b 100644 --- a/go/internal/control/ev_fuse_cut_netting_test.go +++ b/go/internal/control/ev_fuse_cut_netting_test.go @@ -60,14 +60,16 @@ func TestEVFuseSlowChargerCutCoversItsOverage(t *testing.T) { } // cutRig feeds EVFuseBudget site readings one second apart and applies its -// cap to the charger's offer, in 1 A steps, as the controller does. +// cap to the charger's offer, in 1 A steps, as the controller does, or on +// the charger's step table when snap is set. type cutRig struct { t *testing.T store *telemetry.Store state *State now time.Time offerW float64 - phases int // the phases the offer lands on + phases int // the phases the offer lands on + snap func(w float64) float64 // nil: whole amps on three phases } func newCutRig(t *testing.T, offerW, declaredS float64) *cutRig { @@ -103,6 +105,9 @@ func (r *cutRig) deliver(gridW float64, data []byte) float64 { capW, _ := EVFuseBudget(r.store, r.state, points, configs, 17250) if capW < r.offerW { r.offerW = math.Floor(capW/690) * 690 + if r.snap != nil { + r.offerW = r.snap(capW) + } } return capW } @@ -279,6 +284,40 @@ func TestEVFuseWithoutPhaseCurrentsCoversForSettle(t *testing.T) { } } +// The 22 Oct field site's Easee offers on a step table that is not whole +// amps (fieldNightLoadpoint). With L1 0.6 A over a hot 25 A line, the first +// cut takes 6,200 W to the 5,500 W step. While that cut travels to a slow +// charger it covers the overage, so the offer it left stays: rounding to +// whole amps applies to a new cut, not to an offer kept. Rounding the kept +// offer down took the car 6,200 -> 5,500 -> 4,800 -> 0 W in 3 s. +func TestEVFuseCoveredCutKeepsAStepTableOffer(t *testing.T) { + table := []float64{4800, 5500, 6200, 6900, 7600, 8300, 9000, 9700, 10400, 11100} + r := newCutRig(t, 6200, 180) + r.state.SiteFuseSafetyA = 0 + r.snap = func(w float64) float64 { + best := 0.0 + for _, step := range table { + if step <= w+1e-9 { + best = step + } + } + return best + } + for range 300 { + r.read([3]float64{25, 20, 20}) // heat at the line + } + var offers []float64 + for range 90 { + r.read([3]float64{25.6, 20, 20}) + if len(offers) == 0 || offers[len(offers)-1] != r.offerW { + offers = append(offers, r.offerW) + } + } + if len(offers) != 2 || offers[1] != 5500 { + t.Fatalf("offers %v, want one cut to 5,500 W held while it travels", offers) + } +} + // A change of phases is no cut. A 15 A single-phase order replaced by a 6 A // three-phase one lowers the current on the order's phase but adds 6 A to // the other two, so it covers nothing: with L2 at 32 A on the 25 A fuse the diff --git a/go/internal/control/fuse_line_property_test.go b/go/internal/control/fuse_line_property_test.go index d375d9e7a..1cc28fe92 100644 --- a/go/internal/control/fuse_line_property_test.go +++ b/go/internal/control/fuse_line_property_test.go @@ -225,14 +225,14 @@ func testFuseLineIdleStart(t *testing.T, inA float64, phases int, marginA, lineA } } -// fitScenario runs a 3 × 16 A site, safety margin 0.5 A, with 3.5 A of -// house on each phase: twelve steps of the car fit exactly under the 15.5 A -// line. The car asks for 16 A. -func fitScenario(noise func() float64) *simSite { - sc := simScenario{name: "exact fit", run: 30 * time.Minute, +// fitScenario runs a 3 × 16 A site, safety margin 0.5 A, with houseLoadA of +// house on each phase. At 3.5 A twelve steps of the car fit exactly under +// the 15.5 A line. The car asks for 16 A. +func fitScenario(houseLoadA float64, run time.Duration, noise func() float64) *simSite { + sc := simScenario{name: "exact fit", run: run, plant: func(p *sitesim.Plant) { p.Fuse.RatingA = 16 - p.HouseW = houseA(3.5, 3.5, 3.5) + p.HouseW = houseA(houseLoadA, houseLoadA, houseLoadA) }, setup: func(s *simSite) { s.meterNoise = noise }} return runSimScenario(sc, simStart) @@ -240,7 +240,7 @@ func fitScenario(noise func() float64) *simSite { // Closed loop: the car climbs to the line and stays there for 30 min. func TestSiteSimCarEndsAtTheLine(t *testing.T) { - s := fitScenario(nil) + s := fitScenario(3.5, 30*time.Minute, nil) if s.failure != "" { t.Fatal(s.failure) } @@ -259,41 +259,77 @@ func TestSiteSimCarEndsAtTheLine(t *testing.T) { } } -// Closed loop with 0.1 A of meter noise on each phase: the car steps at -// most once per settle time plus the heat's cooling, no phase passes -// 1.2 × In, and the plant's gG fuse holds. -func TestSiteSimNoisyLineDoesNotHunt(t *testing.T) { - rng := rand.New(rand.NewPCG(1, 0)) - s := fitScenario(func() float64 { return .1 * rng.NormFloat64() }) - if s.failure != "" { - t.Fatal(s.failure) - } - if s.peakA > fuseInstantFactor*s.p.Fuse.RatingA || s.p.Fuse.AnyBlown() { - t.Fatalf("peak phase %.2f A, fuse %+v", s.peakA, s.p.Fuse) - } - var moves []simCommand - last := 0.0 - for _, c := range s.commands { - if c.device == "evse" && c.w != last { - moves, last = append(moves, c), c.w - } - } - // The start, then the climb to the line: one step per reading. - climb := 0 - for climb+1 < len(moves) && moves[climb+1].w > moves[climb].w { - climb++ - } - after := moves[climb+1:] - perHour := float64(len(after)) / s.p.Now.Sub(moves[climb].at).Hours() - if limit := time.Hour.Seconds() / (evSettle + fuseHeatTau).Seconds(); perHour > limit { - t.Fatalf("%d moves after the climb (%.0f an hour, limit %.0f): %v", len(after), perHour, limit, after) - } - for i := 1; i < len(after); i++ { - if after[i].w > after[i-1].w && after[i].at.Sub(after[i-1].at) < evSettle { - t.Fatalf("rose %v after a cut: %v then %v", after[i].at.Sub(after[i-1].at), after[i-1], after[i]) - } +// Closed loop with meter noise, two hours a case, house load constant. +// Every case: no phase passes the line or 1.2 × In, the plant's gG fuse +// holds, the car never stops, every rise is one step at least evSettle +// after a cut, and the car stays within dropSteps of the top it climbed to. +// +// With part of a step left under the line, the car holds still. With +// exactly whole steps left, the car sits at the line and zero-mean noise +// reads over it about half the time. The heat over the line then cuts a +// step, and the car rises back once the heat has cooled to a step of room: +// a slow cycle, three to five cuts an hour. A reading 1 A over the line, +// as 0.2 A of noise gives now and then, cuts two steps. That cycle is the +// cost of holding no amps back below the line (owner rule of 27 Oct); +// timers and the heat model set its pace. This test pins that pace, so a +// faster hunt fails. +func TestSiteSimNoisyLineCyclesSlowly(t *testing.T) { + for _, tc := range []struct { + houseA, sigma float64 + cutsPerHour float64 // the most allowed after the climb + dropSteps float64 // the furthest below the top + }{ + {3.25, .1, 0, 0}, {3.75, .2, 0, 0}, // part of a step left + {3.5, .03, 5, 1}, {3.5, .1, 5, 1}, {3.5, .2, 5, 2}, // exact fit + } { + t.Run(fmt.Sprintf("house_%.2fA/noise_%.2fA", tc.houseA, tc.sigma), func(t *testing.T) { + rng := rand.New(rand.NewPCG(1, 0)) + s := fitScenario(tc.houseA, 2*time.Hour, func() float64 { return tc.sigma * rng.NormFloat64() }) + if s.failure != "" { + t.Fatal(s.failure) + } + lineA := s.state.fuseLineA() + if s.peakA > lineA+1e-6 || s.peakA > fuseInstantFactor*s.p.Fuse.RatingA || s.p.Fuse.AnyBlown() { + t.Fatalf("peak phase %.2f A on the %.1f A line, fuse %+v", s.peakA, lineA, s.p.Fuse) + } + var moves []simCommand + last := 0.0 + for _, c := range s.commands { + if c.device == "evse" && c.w != last { + moves, last = append(moves, c), c.w + } + } + // The start, then the climb to the line: one step per reading. + climb := 0 + for climb+1 < len(moves) && moves[climb+1].w > moves[climb].w { + climb++ + } + top, after := moves[climb].w, moves[climb+1:] + cuts := 0 + for i, c := range after { + prev := moves[climb] + if i > 0 { + prev = after[i-1] + } + switch { + case c.w < top-tc.dropSteps*690: + t.Fatalf("cut to %.0f W, more than %.0f steps below %.0f W: %v", c.w, tc.dropSteps, top, after) + case c.w < prev.w: + cuts++ + case c.w-prev.w != 690: + t.Fatalf("rose from %.0f W to %.0f W, want one step: %v", prev.w, c.w, after) + case c.at.Sub(prev.at) < evSettle: + t.Fatalf("rose %v after a cut: %v then %v", c.at.Sub(prev.at), prev, c) + } + } + perHour := float64(cuts) / s.p.Now.Sub(moves[climb].at).Hours() + if perHour > tc.cutsPerHour { + t.Fatalf("%d cuts after the climb (%.1f an hour, limit %.0f): %v", cuts, perHour, tc.cutsPerHour, after) + } + t.Logf("car %.0f W, peak phase %.2f A, %d cuts in %v after the climb", + s.p.EVSE.DrawW, s.peakA, cuts, s.p.Now.Sub(moves[climb].at).Round(time.Minute)) + }) } - t.Logf("car %.0f W, peak phase %.2f A, %d moves after the climb", s.p.EVSE.DrawW, s.peakA, len(after)) } // With no safety margin, battery charge may fill a phase to exactly the From 784d0ba48e92717c7b687cfde5777f5778c15a77 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 14:26:19 +0100 Subject: [PATCH 14/68] fix(control): battery fuse guard reads each phase with its direction Delete perPhaseOverageW, perPhaseOverageReadingW and perPhaseReliefW. The battery fuse guard, the fuse saver and the forced discharge read the signed phase currents (phaseCurrentsA, with #1849's sum check and dead zone), count the batteries' own move on each phase, and relieve to the car's working limit, the fuse less max(1 A, safety_margin_a). Item A5 of the stable plan. Co-Authored-By: Claude Opus 5.5 --- .changeset/a5-battery-fuse-signed-phases.md | 5 + go/internal/control/dispatch.go | 231 +++++----------- .../control/ev_battery_sequence_test.go | 6 +- .../fuse_battery_phase_direction_test.go | 146 ++++++++++ go/internal/control/fuse_phase.go | 2 +- go/internal/control/fuse_saver_test.go | 126 ++++----- go/internal/control/golden_dump_test.go | 7 +- go/internal/control/peak_limit_test.go | 2 +- .../golden/early_exit_protections.json | 66 ++--- .../control/testdata/golden/seeded_fuse.json | 261 +++++++++--------- .../control/testdata/golden/slew_limiter.json | 10 +- .../testdata/golden/targeted_invariants.json | 24 +- 12 files changed, 473 insertions(+), 413 deletions(-) create mode 100644 .changeset/a5-battery-fuse-signed-phases.md create mode 100644 go/internal/control/fuse_battery_phase_direction_test.go diff --git a/.changeset/a5-battery-fuse-signed-phases.md b/.changeset/a5-battery-fuse-signed-phases.md new file mode 100644 index 000000000..9d5f66132 --- /dev/null +++ b/.changeset/a5-battery-fuse-signed-phases.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +The home battery now protects each fuse phase in the direction its current flows. It no longer discharges into a phase that already exports past the fuse, and no longer cuts a discharge that keeps an importing phase under it. It counts its own share of each phase, so it holds a steady relief instead of switching between full relief and none on every dispatch. It now relieves to the same limit the car uses: the fuse less 1 A, or less the safety margin when that is larger. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index b78eb2093..e3c3b2d1f 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -3623,7 +3623,7 @@ func applyFuseGuard(targets []DispatchTarget, store *telemetry.Store, state *Sta // replacement target would double-remove their contribution and miss // fuse overages. seenBat := make(map[string]struct{}, len(targets)) - var currentBat float64 + var currentBat, rawBat float64 for _, t := range targets { if _, seen := seenBat[t.Driver]; seen { continue @@ -3631,12 +3631,14 @@ func applyFuseGuard(targets []DispatchTarget, store *telemetry.Store, state *Sta seenBat[t.Driver] = struct{}{} if r := store.Get(t.Driver, telemetry.DerBattery); r != nil { currentBat += r.SmoothedW + rawBat += r.RawW } } var currentGrid float64 + var meter *telemetry.DerReading if siteMeter != "" { - if r := store.Get(siteMeter, telemetry.DerMeter); r != nil { - currentGrid = r.SmoothedW + if meter = store.Get(siteMeter, telemetry.DerMeter); meter != nil { + currentGrid = meter.SmoothedW } } var sumTarget float64 @@ -3645,22 +3647,9 @@ func applyFuseGuard(targets []DispatchTarget, store *telemetry.Store, state *Sta } predicted := currentGrid - currentBat + sumTarget - // Per-phase relief: the worst single-phase amperage above the fuse - // trip threshold (less the safety margin), converted by - // perPhaseReliefW into the AGGREGATE battery action needed to bring - // it back — the site's configured phase count does that conversion. - // - // This guard uses relief in BOTH directions. `perPhaseOverageW` is - // direction-agnostic — phase amps from the meter are absolute - // magnitudes. Attribute to whichever side the AGGREGATE METER is - // currently flowing (currentGrid), not to the post-target - // `predicted`. Per-phase amps and currentGrid are read from the - // same DerMeter sample, so they're internally consistent; - // `predicted` mixes in `sumTarget` (a hypothetical future state) - // and can swing across 0 on a large planner request, attributing - // a current-export overage to the import path (or vice versa) and - // pushing the grid further into the violating direction. - perPhase := perPhaseReliefW(store, state) + // Per phase, each way, once the targets replace the batteries' power + // in the same raw reading. + phaseImportW, phaseExportW := phaseFuseReliefW(meter, state, sumTarget-rawBat) // Aggregate budget honours the safety margin too — keep dispatch // commands strictly inside the breaker envelope so the inverter's // own per-phase limiter doesn't fire first and cause a flap. @@ -3672,19 +3661,8 @@ func applyFuseGuard(targets []DispatchTarget, store *telemetry.Store, state *Sta // (recurring Ferroamp 0x8030 fault). Both share one enforcement surface. effImportW := state.effectiveImportCeilingW(fuseMaxW) effExportW := state.effectiveExportCeilingW(fuseMaxW) - importOverage := predicted - effImportW - exportOverage := -effExportW - predicted - if perPhase > 0 { - if currentGrid >= 0 { - if perPhase > importOverage { - importOverage = perPhase - } - } else { - if perPhase > exportOverage { - exportOverage = perPhase - } - } - } + importOverage := math.Max(predicted-effImportW, phaseImportW) + exportOverage := math.Max(-effExportW-predicted, phaseExportW) out := make([]DispatchTarget, len(targets)) copy(out, targets) @@ -3875,106 +3853,55 @@ func (s *State) effectiveExportCeilingW(fuseMaxW float64) float64 { return eff } -// perPhaseOverageW returns the wattage by which the worst single phase -// exceeds the per-phase fuse amperage (less the safety margin). 0 when -// within limits, when per-phase data isn't available, or when the -// per-phase clamp is disabled (state.SiteFuseAmps == 0). The meter -// driver must emit l1_a / l2_a / l3_a in DerReading.Data — Pixii, -// Ferroamp, and Sungrow all do this today. -// -// Only the configured phases are read, in L1/L2/L3 order, matching -// sitePhaseCurrentsAt in cmd/ftw: a 1Φ site has no L2, so a stray -// l2_a in the meter payload is not a breaker this site owns. -// -// Same law as fuseSafetyMarginW: amps become watts only through the -// configured per-phase voltage. No hardcoded 230 V here — a site whose -// fuse description is incomplete gets no per-phase clamp rather than an -// invented one. Config fills both fields (fuse.voltage defaults to 230, -// fuse.phases to 3, and validation rejects <= 0), so this only affects -// harnesses that wire SiteFuseAmps alone. -// -// Direction-agnostic: phase amps from the meter are absolute magnitudes, -// so this function reports overage regardless of whether the breaker is -// being approached on the import or export side. The caller attributes -// the overage to whichever direction the aggregate grid is flowing. -func perPhaseOverageW(store *telemetry.Store, state *State) float64 { - if state == nil || state.SiteFuseAmps <= 0 || state.SiteMeterDriver == "" { - return 0 - } - r := store.Get(state.SiteMeterDriver, telemetry.DerMeter) - return perPhaseOverageReadingW(r, state) -} - -// perPhaseOverageReadingW is the snapshot form used when one control decision -// must keep the aggregate reading and its phase data from the same meter sample. -func perPhaseOverageReadingW(r *telemetry.DerReading, state *State) float64 { - if state == nil || state.SiteFuseAmps <= 0 || state.SiteFuseVoltage <= 0 || state.SiteFusePhases <= 0 { - return 0 - } - if r == nil || len(r.Data) == 0 { - return 0 - } - var d struct { - L1A *float64 `json:"l1_a"` - L2A *float64 `json:"l2_a"` - L3A *float64 `json:"l3_a"` - } - if err := json.Unmarshal(r.Data, &d); err != nil { - return 0 - } - // Use absolute magnitude — drivers like Pixii decode per-phase amps - // as signed i16, so export shows up as negative numbers and a naive - // `*p > maxA` walk starting from 0 leaves maxA = 0 (no fire) even - // when a phase is at -17 A. The fuse trips on current magnitude - // regardless of direction, and the caller attributes the overage - // to the active aggregate-grid direction. - phaseAmps := [...]*float64{d.L1A, d.L2A, d.L3A} - phases := state.SiteFusePhases - if phases > len(phaseAmps) { - phases = len(phaseAmps) - } - maxA := 0.0 - for i := 0; i < phases; i++ { - p := phaseAmps[i] - if p == nil { - continue - } - a := math.Abs(*p) - if a > maxA { - maxA = a - } - } - threshold := state.SiteFuseAmps - state.SiteFuseSafetyA - if threshold < 0 { - threshold = 0 - } - if maxA <= threshold { - return 0 - } - return (maxA - threshold) * state.SiteFuseVoltage -} - -// perPhaseReliefW converts a worst-phase overage into the AGGREGATE -// battery action needed to clear it. One conversion, one law: a battery -// spreads its action evenly across the site's phases, so each watt of -// aggregate action relieves 1/SiteFusePhases watts on the worst phase, -// and an overage of N watts needs N × SiteFusePhases watts of action. -// -// The phase count is the site's, from config — not the constant 3 the -// two call sites used to carry separately. On a 1Φ site the aggregate -// meter and the single phase are the same wire, so demanding 3 × N -// there overshoots by 2 × N and can push the grid through zero into a -// violation on the opposite side. +// phaseFuseReliefW is the aggregate battery move that brings every phase +// inside the working limit: the fuse less the car's 1 A margin, or less +// safety_margin_a when that is larger. importW asks for less charge or more +// discharge, exportW for the reverse. moveW is the batteries' change from +// the power this reading already holds; like the relief, it spreads evenly +// over the site's phases. // -// Conservative for a 1Φ battery on a 3Φ site (Pixii Home etc.): it -// over-corrects on the phases it does not sit on — less import/export -// there, still safe. -func perPhaseReliefW(store *telemetry.Store, state *State) float64 { - overage := perPhaseOverageW(store, state) - if overage <= 0 { - return 0 - } - return overage * float64(state.SiteFusePhases) +// The phases are the meter's signed currents (phaseCurrentsA). When no +// phase reads as export while the total does, the meter gives no direction +// per phase, and the phases take the total's. When no move fits every +// phase, the move leaves the worst phase least over, so a move never +// raises the current on the phase it protects. 0, 0 without usable phase +// currents. +func phaseFuseReliefW(meter *telemetry.DerReading, state *State, moveW float64) (importW, exportW float64) { + if meter == nil || state == nil { + return 0, 0 + } + amps, _, valid := phaseCurrentsA(meter, state, meter.RawW) + if !valid || len(amps) == 0 { + return 0, 0 + } + perA := state.SiteFuseVoltage * float64(state.SiteFusePhases) // aggregate W per phase ampere + limitA := math.Max(0, state.SiteFuseAmps-math.Max(evPhaseMarginA, state.SiteFuseSafetyA)) + exports := meter.RawW < 0 + for _, a := range amps { + exports = exports && a >= 0 + } + hi, lo := math.Inf(-1), math.Inf(1) + for _, a := range amps { + if exports { + a = -a + } + a += moveW / perA + hi, lo = math.Max(hi, a), math.Min(lo, a) + } + // The smallest shift that keeps every phase inside, or the middle one. + shiftA := math.Max(-limitA-lo, math.Min(0, limitA-hi)) + if -limitA-lo > limitA-hi { + shiftA = -(hi + lo) / 2 + } + importW, exportW = math.Max(0, -shiftA)*perA, math.Max(0, shiftA)*perA + // A target that fills the limit exactly can land a rounding error past it. + if importW < 1 { + importW = 0 + } + if exportW < 1 { + exportW = 0 + } + return importW, exportW } // applyPlanSignFloor enforces "executed battery total must agree in sign @@ -4472,7 +4399,7 @@ func fuseSaverFromLivePower( // site is safe. Preserve the deadband in that case: this early-return path // exists to answer a fuse condition, not to take control of an externally // moved battery merely because its reading sits outside a command cap. - requiredRelief := fuseReliefFromSnapshot(rawLive, batteryReadings, meter, state, fuseMaxW, false) + requiredRelief := fuseReliefFromSnapshot(rawLive, batteryReadings, meter, state, fuseMaxW) if requiredRelief <= 0 { return nil } @@ -4490,7 +4417,7 @@ func fuseSaverFromLivePower( if len(safeBaseline) == 0 { return nil } - out := forceFuseDischargeWithSnapshot(safeBaseline, batteryReadings, meter, state, driverCapacities, fuseMaxW, true) + out := forceFuseDischargeWithSnapshot(safeBaseline, batteryReadings, meter, state, driverCapacities, fuseMaxW) rawByDriver := make(map[string]DispatchTarget, len(rawLive)) for _, t := range rawLive { rawByDriver[t.Driver] = t @@ -4515,45 +4442,34 @@ func fuseReliefFromSnapshot( meter *telemetry.DerReading, state *State, fuseMaxW float64, - accountPhaseTargetDelta bool, ) float64 { if fuseMaxW <= 0 || len(targets) == 0 || state == nil { return 0 } - currentBat, sumTarget, predicted := predictedGridFromSnapshot(targets, batteryReadings, meter) - currentGrid := 0.0 - if meter != nil { - currentGrid = meter.SmoothedW - } + _, sumTarget, predicted := predictedGridFromSnapshot(targets, batteryReadings, meter) // The fuse acts on every reading. The hour's import limit is a budget: // the part of its overage that an EV cut we sent will remove waits for // that cut while the meter may not show it yet. Relief for the same watts // would discharge the battery into export once the cut lands (#1674). - // Per-phase relief remains fuse-only and may act only while the matching - // aggregate meter sample is on the import side. + // Per-phase relief is fuse-only. fuseW := math.Max(0, fuseMaxW-state.fuseSafetyMarginW()) overage := predicted - fuseW if ceilingW := state.effectiveImportCeilingW(fuseMaxW); ceilingW < fuseW { overage = math.Max(overage, predicted-ceilingW-state.pendingEVCutW()) } - if currentGrid >= 0 { - relief := perPhaseOverageReadingW(meter, state) * float64(state.SiteFusePhases) - if relief > 0 && accountPhaseTargetDelta { - // The early fuse baseline can only hold or reduce each included - // target. Count that import reduction against the raw phase relief so - // a command-cap clamp is not followed by the same correction twice. - relief += sumTarget - currentBat - if relief < 0 { - relief = 0 - } - } - if relief > overage { - overage = relief + // The phases are raw, so the batteries' move is from their raw power. + moveW := sumTarget + seen := make(map[string]bool, len(targets)) + for _, t := range targets { + if r := batteryReadings[t.Driver]; r != nil && !seen[t.Driver] { + moveW -= r.RawW } + seen[t.Driver] = true } - return overage + phaseW, _ := phaseFuseReliefW(meter, state, moveW) + return math.Max(overage, phaseW) } // predictedGridFromSnapshot holds non-targeted site power constant and replaces @@ -4605,7 +4521,7 @@ func forceFuseDischarge( readings[target.Driver] = store.Get(target.Driver, telemetry.DerBattery) } meter := store.Get(state.SiteMeterDriver, telemetry.DerMeter) - return forceFuseDischargeWithSnapshot(targets, readings, meter, state, driverCapacities, fuseMaxW, false) + return forceFuseDischargeWithSnapshot(targets, readings, meter, state, driverCapacities, fuseMaxW) } // forceFuseDischargeWithSnapshot keeps all math for one decision on the same @@ -4618,12 +4534,11 @@ func forceFuseDischargeWithSnapshot( state *State, driverCapacities map[string]float64, fuseMaxW float64, - accountPhaseTargetDelta bool, ) []DispatchTarget { if fuseMaxW <= 0 || len(targets) == 0 || state == nil { return targets } - overage := fuseReliefFromSnapshot(targets, batteryReadings, meter, state, fuseMaxW, accountPhaseTargetDelta) + overage := fuseReliefFromSnapshot(targets, batteryReadings, meter, state, fuseMaxW) if overage <= 0 { return targets } diff --git a/go/internal/control/ev_battery_sequence_test.go b/go/internal/control/ev_battery_sequence_test.go index cb65b46e6..58665b6e1 100644 --- a/go/internal/control/ev_battery_sequence_test.go +++ b/go/internal/control/ev_battery_sequence_test.go @@ -588,7 +588,7 @@ func TestFuseReliefLeavesOnlyCeilingWattsToCommandedEVCut(t *testing.T) { targets := []DispatchTarget{{Driver: "pixii"}} batteries := map[string]*telemetry.DerReading{"pixii": {}} meter := &telemetry.DerReading{SmoothedW: tc.gridW, Data: tc.data} - got := fuseReliefFromSnapshot(targets, batteries, meter, st, 17250, false) + got := fuseReliefFromSnapshot(targets, batteries, meter, st, 17250) if math.Abs(math.Max(0, got)-tc.wantW) > 1e-6 { t.Errorf("%s: relief %.0f W, want %.0f W", tc.name, got, tc.wantW) } @@ -629,7 +629,7 @@ func TestUnpluggedCarIsNoCutTheBatteryWaitsFor(t *testing.T) { st.SetEVCommanded(points) targets := []DispatchTarget{{Driver: "pixii"}} batteries := map[string]*telemetry.DerReading{"pixii": {}} - return math.Max(0, fuseReliefFromSnapshot(targets, batteries, &telemetry.DerReading{SmoothedW: gridW}, st, 17250, false)) + return math.Max(0, fuseReliefFromSnapshot(targets, batteries, &telemetry.DerReading{SmoothedW: gridW}, st, 17250)) } // 400 W over the ceiling, less than a step: the guard waits. if got := tick(7900, true, 5520); math.Abs(got-400) > 1e-6 { @@ -693,7 +693,7 @@ func TestCutOnStayingCarStillWaitsWhenAnotherLeaves(t *testing.T) { st.SetEVCommanded(points) targets := []DispatchTarget{{Driver: "pixii"}} batteries := map[string]*telemetry.DerReading{"pixii": {SmoothedW: batteryW}} - relief := fuseReliefFromSnapshot(targets, batteries, &telemetry.DerReading{SmoothedW: gridW}, st, 17250, false) + relief := fuseReliefFromSnapshot(targets, batteries, &telemetry.DerReading{SmoothedW: gridW}, st, 17250) batteryW = -math.Max(0, relief) // The battery follows within a tick. if batteryW < 0 && tick < 10 { t.Fatalf("%ds: battery %.0f W for watts a's stop removes; pending cut %.0f W", tick, batteryW, st.pendingEVCutW()) diff --git a/go/internal/control/fuse_battery_phase_direction_test.go b/go/internal/control/fuse_battery_phase_direction_test.go new file mode 100644 index 000000000..111c03ee3 --- /dev/null +++ b/go/internal/control/fuse_battery_phase_direction_test.go @@ -0,0 +1,146 @@ +package control + +import ( + "encoding/json" + "math" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// The battery fuse paths read each phase with its direction and count the +// batteries' own move. 16 A fuse, 230 V, 3 phases; the working limit is +// 15 A. + +func phaseDirectionStore(t *testing.T, gridW, batW float64, data map[string]any) *telemetry.Store { + t.Helper() + s := telemetry.NewStore() + raw, err := json.Marshal(data) + if err != nil { + t.Fatal(err) + } + s.Update("meter", telemetry.DerMeter, gridW, nil, raw) + s.DriverHealthMut("meter").RecordSuccess() + soc := 0.6 + s.Update("bat", telemetry.DerBattery, batW, &soc, nil) + s.DriverHealthMut("bat").RecordSuccess() + return s +} + +func phaseDirectionState(safetyA float64) *State { + st := NewState(0, 50, "meter") + st.SiteFuseAmps, st.SiteFuseVoltage, st.SiteFusePhases, st.SiteFuseSafetyA = 16, 230, 3, safetyA + st.DriverLimits = map[string]PowerLimits{"bat": {MaxChargeW: 10000, MaxDischargeW: 10000}} + return st +} + +// L1 exports 20 A, L2/L3 import 12 A, the total imports 920 W. No phase +// imports over the limit, and a discharge adds export on L1. +var exportingL1 = map[string]any{"l1_a": 20.0, "l2_a": 12.0, "l3_a": 12.0, + "l1_w": -4600.0, "l2_w": 2760.0, "l3_w": 2760.0} + +func TestFuseSaverDoesNotDischargeIntoExportingPhase(t *testing.T) { + store := phaseDirectionStore(t, 920, 0, exportingL1) + out := fuseSaverFromLivePower(store, phaseDirectionState(0.5), map[string]float64{"bat": 15200}, 16*230*3) + for _, o := range out { + if o.TargetW < 0 { + t.Fatalf("fuse saver ordered %.0f W discharge; L1 export 20.0 A -> %.1f A on a 16 A fuse", o.TargetW, 20+(-o.TargetW)/690) + } + } +} + +func TestIdleDispatchDoesNotDischargeIntoExportingPhase(t *testing.T) { + store := phaseDirectionStore(t, 920, 0, exportingL1) + st := phaseDirectionState(0.5) + st.Mode = ModeIdle + out := ComputeDispatch(store, st, map[string]float64{"bat": 15200}, 16*230*3) + for _, o := range out { + if o.TargetW < 0 { + t.Fatalf("Idle ComputeDispatch ordered %.0f W discharge; L1 export 20.0 A -> %.1f A", o.TargetW, 20+(-o.TargetW)/690) + } + } +} + +// L1 imports 22 A, L2/L3 export 15 A, the battery discharges 3 kW and the +// total exports. Cutting the discharge raises L1's import. +func TestFuseGuardKeepsDischargeThatRelievesImportingPhase(t *testing.T) { + store := phaseDirectionStore(t, (22-30)*230, -3000, map[string]any{ + "l1_a": 22.0, "l2_a": 15.0, "l3_a": 15.0, + "l1_w": 5060.0, "l2_w": -3450.0, "l3_w": -3450.0}) + st := phaseDirectionState(0.5) + out := applyFuseGuard([]DispatchTarget{{Driver: "bat", TargetW: -3000}}, store, st, 16*230*3) + if out[0].TargetW > -3000+1 { + t.Fatalf("fuse guard cut discharge -3000 -> %.0f W; L1 import 22.0 -> %.1f A; hold max discharge %.0f W until +%v", + out[0].TargetW, 22+(out[0].TargetW+3000)/690, st.FuseHoldMaxDischargeW, st.FuseHoldUntil.Sub(st.now())) + } +} + +// L1 exports 18 A (one-phase PV), L2/L3 import 14 A, the total imports +// 2300 W. Charging relieves L1 and loads L2/L3. +var exportingL1Charge = map[string]any{"l1_a": 18.0, "l2_a": 14.0, "l3_a": 14.0, + "l1_w": -4140.0, "l2_w": 3220.0, "l3_w": 3220.0} + +func TestFuseSaverIgnoresExportingPhaseUnderImportTotal(t *testing.T) { + store := phaseDirectionStore(t, 2300, 0, exportingL1Charge) + if out := fuseSaverFromLivePower(store, phaseDirectionState(0), map[string]float64{"bat": 15200}, 11040); out != nil { + t.Errorf("fuseSaverFromLivePower = %.0f W; discharging pushes exporting L1 further past the fuse", out[0].TargetW) + } +} + +// No charge fits both sides: 3000 W takes L2/L3 to 18.3 A, none leaves L1 +// at 18 A of export. The guard leaves the charge where the worst phase is +// least over: 1380 W, with every phase at 16 A. +func TestFuseGuardChargeBalancesExportingAndImportingPhases(t *testing.T) { + store := phaseDirectionStore(t, 2300, 0, exportingL1Charge) + got := applyFuseGuard([]DispatchTarget{{Driver: "bat", TargetW: 3000}}, store, phaseDirectionState(0), 11040) + l1, l2 := -18+got[0].TargetW/690, 14+got[0].TargetW/690 + if worst := math.Max(math.Abs(l1), math.Abs(l2)); worst > 16.01 { + t.Errorf("applyFuseGuard charge 3000 -> %.0f W leaves L1 %.2f A, L2/L3 %.2f A; want every phase at or below 16 A", got[0].TargetW, l1, l2) + } +} + +// The relief counts the battery's own share of the phase it reads. A +// battery that follows its order keeps L1 at the working limit on every +// tick instead of returning to 0 W when the overage stops showing. +func TestPerPhaseFuseReliefHoldsWhileOverloadPersists(t *testing.T) { + st := phaseDirectionState(0.5) + st.Mode = ModeIdle + now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) + st.clock = func() time.Time { return now } + + store := telemetry.NewStore() + house := [3]float64{20, 5, 5} // A per phase, import + batW := 0.0 // battery follows its last order within a tick + caps := map[string]float64{"bat": 15200} + var targets, l1 []float64 + for tick := 0; tick < 10; tick++ { + a := house + for i := range a { + a[i] += batW / (230 * 3) // a three-phase battery spreads evenly + } + raw, _ := json.Marshal(map[string]any{"l1_a": a[0], "l2_a": a[1], "l3_a": a[2]}) + store.Update("meter", telemetry.DerMeter, (a[0]+a[1]+a[2])*230, nil, raw) + store.DriverHealthMut("meter").RecordSuccess() + soc := 0.6 + store.Update("bat", telemetry.DerBattery, batW, &soc, nil) + store.DriverHealthMut("bat").RecordSuccess() + + out := ComputeDispatch(store, st, caps, 16*230*3) + w := 0.0 + for _, o := range out { + if o.Driver == "bat" { + w = o.TargetW + } + } + targets = append(targets, math.Round(w)) + l1 = append(l1, math.Round(a[0]*10)/10) + batW = w + now = now.Add(5 * time.Second) + } + for i := 1; i < len(l1); i++ { + if l1[i] > 15 { + t.Fatalf("tick %d: L1 %.1f A over the 15 A working limit while the overload persists; targets %v, L1 %v", i, l1[i], targets, l1) + } + } +} diff --git a/go/internal/control/fuse_phase.go b/go/internal/control/fuse_phase.go index 05541c5d5..0375ea16c 100644 --- a/go/internal/control/fuse_phase.go +++ b/go/internal/control/fuse_phase.go @@ -25,7 +25,7 @@ func (s *State) fuseLineA() float64 { // Meters report phase magnitudes, so the mean uses |aggregate|. Phases // flowing in opposite directions make the gap look smaller than it is; the // per-phase fuse guards still act on a real overage. A single-phase battery -// or charger is outside this model, as it is for perPhaseReliefW. +// or charger is outside this model, as it is for phaseFuseReliefW. func phaseImbalanceA(r *telemetry.DerReading, state *State) (float64, bool) { if state == nil || state.SiteFuseAmps <= 0 || state.SiteFuseVoltage <= 0 || state.SiteFusePhases <= 1 { return 0, false diff --git a/go/internal/control/fuse_saver_test.go b/go/internal/control/fuse_saver_test.go index 0e2f48476..205e25505 100644 --- a/go/internal/control/fuse_saver_test.go +++ b/go/internal/control/fuse_saver_test.go @@ -300,19 +300,19 @@ func setupPerPhaseSite(phases int, voltage float64, aggGridW float64, l1A, l2A, func TestPerPhaseClampScalesChargingOnImbalance(t *testing.T) { // Isolate the per-phase case: aggregate predicted (7000 + 4000 = // 11000 W) is under the 11040 W fuse, so the legacy aggregate - // branch wouldn't fire. But L1 alone is at 18 A × 230 V = 4140 W - // (over the 16 A fuse on that phase) — only the per-phase clamp - // can catch it. - store, state, _ := setupPerPhase(7000, 18, 12, 8, 0.6, 10000) + // branch wouldn't fire. But the 4000 W charge adds 4000 / 690 = + // 5.8 A to each phase, which takes L1 from 13 A to 18.8 A, over the + // 15 A working limit (16 A fuse less 1 A) — only the per-phase + // clamp can catch it. + store, state, _ := setupPerPhase(7000, 13, 12, 8, 0.6, 10000) targets := []DispatchTarget{{Driver: "bat", TargetW: 4000}} guarded := applyFuseGuard(targets, store, state, 11040) if !guarded[0].Clamped { t.Errorf("Clamped flag must mark per-phase response") } - // Per-phase overage = (18 − 16) × 230 = 460 W on the worst phase. - // Balanced-3Φ assumption ⇒ 460 × 3 = 1380 W of total battery - // reduction needed. Charge 4000 → 4000 − 1380 = 2620 W. - expected := 2620.0 + // L1 has (15 − 13) × 690 = 1380 W of room for a balanced-3Φ + // charge. Charge 4000 → 1380 W. + expected := 1380.0 if math.Abs(guarded[0].TargetW-expected) > 1 { t.Errorf("charge after per-phase clamp = %.0f W, want %.0f W", guarded[0].TargetW, expected) @@ -333,9 +333,9 @@ func TestPerPhaseClampFiresFuseSaverFromIdle(t *testing.T) { if out[0].TargetW >= 0 { t.Errorf("expected discharge target, got %.0f W", out[0].TargetW) } - // Same math as the charging test: 460 W × 3 = 1380 W. From idle - // (target 0), full discharge of 1380 W. - expected := -1380.0 + // L1 is (18 − 15) A over the working limit: 3 × 690 = 2070 W of + // discharge from idle. + expected := -2070.0 if math.Abs(out[0].TargetW-expected) > 1 { t.Errorf("forced discharge = %.0f W, want %.0f W", out[0].TargetW, expected) } @@ -365,13 +365,14 @@ func TestPerPhaseClampDisabledWhenSiteFuseAmpsZero(t *testing.T) { // huge imbalance, per-phase × 3 dominates. func TestPerPhaseClampDominatesAggregateWhenLarger(t *testing.T) { // Aggregate over by 500 W (predicted = 11540 vs 11040). But L1 is - // at 22 A → over by 6 A × 230 = 1380 W per-phase × 3 = 4140 W. + // at 22 A → over the 15 A working limit by 7 A × 230 = 1610 W + // per-phase × 3 = 4830 W. store, state, caps := setupPerPhase(11540, 22, 14, 8, 0.6, 10000) out := fuseSaverFromLivePower(store, state, caps, 11040) if out == nil { t.Fatalf("expected discharge, got nil") } - expected := -4140.0 + expected := -4830.0 if math.Abs(out[0].TargetW-expected) > 1 { t.Errorf("forced discharge = %.0f W, want %.0f W (per-phase × 3)", out[0].TargetW, expected) @@ -384,11 +385,12 @@ func TestPerPhaseClampDominatesAggregateWhenLarger(t *testing.T) { // trigger forceFuseDischarge, which would push more power out and // worsen the over-current phase. Regression for PR #219 review S1. func TestPerPhaseClampFiresOnExportImbalance(t *testing.T) { - // Aggregate gridW = -7000 W (heavy export). Phases (magnitude): - // L2 = 18 A (over the 16 A fuse), L1 = 12, L3 = 8. Per-phase - // overage = (18 − 16) × 230 × 3 = 1380 W of discharge to shrink. - // Battery is currently discharging −5000 W; the target reduces - // magnitude to bring L2 back under fuse. + // Aggregate gridW = -7000 W (heavy export). Phases (magnitude, no + // phase power, so they take the total's direction): L2 = 18 A (over + // the 15 A working limit), L1 = 12, L3 = 8. Per-phase overage = + // (18 − 15) × 230 × 3 = 2070 W of discharge to shrink. Battery is + // currently discharging −5000 W; the target reduces magnitude to + // bring L2 back under the limit. store, state, _ := setupPerPhase(-7000, 12, 18, 8, 0.6, 10000) // Set the live battery reading so applyFuseGuard's "predicted" // reflects the current discharge state. @@ -401,8 +403,8 @@ func TestPerPhaseClampFiresOnExportImbalance(t *testing.T) { if !guarded[0].Clamped { t.Errorf("export-side per-phase overage must clamp the discharge target") } - // New discharge magnitude: 5000 − 1380 = 3620 W → target = −3620 W. - expected := -3620.0 + // New discharge magnitude: 5000 − 2070 = 2930 W → target = −2930 W. + expected := -2930.0 if math.Abs(guarded[0].TargetW-expected) > 1 { t.Errorf("discharge after export-side per-phase clamp = %.0f W, want %.0f W", guarded[0].TargetW, expected) @@ -460,43 +462,42 @@ func TestForceFuseDischargeIgnoresExportSidePerPhase(t *testing.T) { // inverter's own per-phase limiter trips first and causes a flap). // Regression for PR #219 — the bug class motivating the safety margin. func TestPerPhaseClampHonorsSafetyMargin(t *testing.T) { - // Phases (15.5, 12, 8). MaxAmps = 16, SafetyA = 1.0 → effective - // threshold = 15 A. L1 at 15.5 A is OVER the effective threshold - // (under the raw 16 A). Per-phase overage = (15.5 − 15) × 230 × 3 - // = 345 W of charge to shrink. - store, state, _ := setupPerPhase(7000, 15.5, 12, 8, 0.6, 10000) - state.SiteFuseSafetyA = 1.0 + // Phases (10, 7, 5). MaxAmps = 16, SafetyA = 2.0 → effective + // threshold = 14 A, below the 1 A working margin's 15 A. The + // 4000 W charge adds 5.8 A per phase, so L1 reaches 15.8 A: over + // 14 A by 1.8 A, 1240 W of charge to shrink. Without the margin it + // would be 550 W. + store, state, _ := setupPerPhase(5000, 10, 7, 5, 0.6, 10000) + state.SiteFuseSafetyA = 2.0 state.SiteFusePhases = 3 targets := []DispatchTarget{{Driver: "bat", TargetW: 4000}} guarded := applyFuseGuard(targets, store, state, 11040) if !guarded[0].Clamped { - t.Errorf("safety margin should pull the threshold under L1 = 15.5 A") - } - // Aggregate effFuseW = 11040 − 1.0×230×3 = 10350. Predicted = - // 7000 + 4000 − 0 = 11000 → aggregate overage = 11000 − 10350 = 650. - // Per-phase overage × 3 = 345. Aggregate wins (650 > 345). - // Buffer = half-margin = 0.5×1×230×3 = 345 W (post-fix headroom). - // Charge 4000 − 650 − 345 = 3005. - expected := 3005.0 + t.Errorf("safety margin should pull the threshold under L1") + } + // Aggregate effFuseW = 11040 − 2×230×3 = 9660. Predicted = + // 5000 + 4000 − 0 = 9000 → no aggregate overage. Per-phase wins. + // Buffer = half-margin = 0.5×2×230×3 = 690 W (post-fix headroom). + // Charge 4000 − 1240 − 690 = 2070. + expected := 2070.0 if math.Abs(guarded[0].TargetW-expected) > 1 { t.Errorf("charge after safety-margin clamp = %.0f W, want %.0f W", guarded[0].TargetW, expected) } } -// SafetyMarginA = 0 must produce identical output to the pre-PR -// behaviour (locks the back-compat contract every existing per-phase -// test relies on by leaving the field unset). +// SafetyMarginA = 0 keeps the 1 A working margin the car uses (every +// existing per-phase test relies on it by leaving the field unset). func TestPerPhaseClampSafetyMarginZeroIsBackCompat(t *testing.T) { - store, state, _ := setupPerPhase(7000, 18, 12, 8, 0.6, 10000) + store, state, _ := setupPerPhase(7000, 13, 12, 8, 0.6, 10000) state.SiteFuseSafetyA = 0 state.SiteFusePhases = 3 targets := []DispatchTarget{{Driver: "bat", TargetW: 4000}} guarded := applyFuseGuard(targets, store, state, 11040) // Same math as TestPerPhaseClampScalesChargingOnImbalance. - expected := 2620.0 + expected := 1380.0 if math.Abs(guarded[0].TargetW-expected) > 1 { - t.Errorf("safety_margin_a=0 must match pre-PR behaviour: got %.0f W, want %.0f W", + t.Errorf("safety_margin_a=0 must keep the 1 A working margin: got %.0f W, want %.0f W", guarded[0].TargetW, expected) } } @@ -508,9 +509,9 @@ func TestPerPhaseClampSafetyMarginZeroIsBackCompat(t *testing.T) { // phase count, and on a 1Φ site the aggregate meter and the single // phase are the same wire — relief there is 1 × the overage, not 3 ×. // -// A 1Φ site at 24 A on a 16 A fuse (0.5 A margin ⇒ 15.5 A threshold, -// 230 V): fuse budget 3680 W, aggregate ceiling 3565 W, meter at -// 5520 W. Worst-phase overage = (24 − 15.5) × 230 = 1955 W, which on +// A 1Φ site at 24 A on a 16 A fuse (1 A margin ⇒ 15 A threshold, +// 230 V): fuse budget 3680 W, aggregate ceiling 3450 W, meter at +// 5520 W. Worst-phase overage = (24 − 15) × 230 = 2070 W, which on // this site is also exactly the aggregate overage — the two numbers // must agree when there is only one phase. @@ -518,21 +519,21 @@ func TestPerPhaseClampSafetyMarginZeroIsBackCompat(t *testing.T) { // once, and leaves the meter on the import side of zero. func TestPerPhaseReliefMatchesSinglePhaseSiteOnImport(t *testing.T) { store, state, caps := setupPerPhaseSite(1, 230, 5520, 24, 0, 0, 0.6, 10000) - state.SiteFuseSafetyA = 0.5 + state.SiteFuseSafetyA = 1 fuseMaxW := 16 * 230.0 * 1 out := fuseSaverFromLivePower(store, state, caps, fuseMaxW) if out == nil { t.Fatalf("1Φ site at 24 A on a 16 A fuse: expected a forced discharge") } - expected := -1955.0 + expected := -2070.0 if math.Abs(out[0].TargetW-expected) > 1 { t.Fatalf("forced discharge = %.0f W, want %.0f W (overage × 1 phase, "+ "not × 3)", out[0].TargetW, expected) } // The site has one phase, so the post-dispatch meter is that - // phase. Demanding 3 × 1955 W would have driven 5520 W of import - // to 345 W of export: relief the site never needed, pushing the + // phase. Demanding 3 × 2070 W would have driven 5520 W of import + // to 690 W of export: relief the site never needed, pushing the // same breaker up the other way. if postGridW := 5520 + out[0].TargetW; postGridW < 0 { t.Errorf("post-dispatch grid = %.0f W: relief overshot through zero "+ @@ -547,7 +548,7 @@ func TestPerPhaseReliefMatchesSinglePhaseSiteOnExport(t *testing.T) { // Meter magnitudes mirror the import case: 5520 W out, 24 A on the // one phase. Pixii-style signed per-phase amps, so L1 reads −24. store, state, _ := setupPerPhaseSite(1, 230, -5520, -24, 0, 0, 0.6, 10000) - state.SiteFuseSafetyA = 0.5 + state.SiteFuseSafetyA = 1 fuseMaxW := 16 * 230.0 * 1 // The battery is already discharging what the meter shows, and the @@ -560,10 +561,10 @@ func TestPerPhaseReliefMatchesSinglePhaseSiteOnExport(t *testing.T) { if !guarded[0].Clamped { t.Fatalf("export-side per-phase overage must clamp the discharge target") } - // Discharge 5000 − overage 1955 − buffer (half the 115 W margin) - // = 2987.5 W. Demanding 1955 × 3 leaves nothing: the discharge is + // Discharge 5000 − overage 2070 − buffer (half the 230 W margin) + // = 2815 W. Demanding 2070 × 3 leaves nothing: the discharge is // zeroed and the site swings to 520 W of import. - expected := -2987.5 + expected := -2815.0 if math.Abs(guarded[0].TargetW-expected) > 1 { t.Errorf("discharge after 1Φ export clamp = %.1f W, want %.1f W", guarded[0].TargetW, expected) @@ -599,15 +600,15 @@ func TestPerPhaseClampReadsConfiguredPhasesOnly(t *testing.T) { // Per-phase watts come from the configured voltage, the same source // fuseSafetyMarginW uses. A 240 V site converts its amps at 240 V. func TestPerPhaseClampUsesConfiguredVoltage(t *testing.T) { - store, state, _ := setupPerPhaseSite(3, 240, 7000, 18, 12, 8, 0.6, 10000) + store, state, _ := setupPerPhaseSite(3, 240, 7000, 13, 12, 8, 0.6, 10000) targets := []DispatchTarget{{Driver: "bat", TargetW: 4000}} guarded := applyFuseGuard(targets, store, state, 16*240.0*3) if !guarded[0].Clamped { - t.Fatalf("L1 at 18 A on a 16 A fuse must clamp") + t.Fatalf("a 4000 W charge on L1 at 13 A on a 16 A fuse must clamp") } - // (18 − 16) × 240 = 480 W per phase × 3 = 1440 W of relief. - // Charge 4000 → 2560. At the old hardcoded 230 V it would be 2620. - expected := 2560.0 + // L1 has (15 − 13) A of room below the working limit: 2 × 240 × 3 + // = 1440 W of charge. At the old hardcoded 230 V it would be 1380. + expected := 1440.0 if math.Abs(guarded[0].TargetW-expected) > 1 { t.Errorf("charge after per-phase clamp on a 240 V site = %.0f W, "+ "want %.0f W", guarded[0].TargetW, expected) @@ -914,9 +915,10 @@ func TestDeadbandExitDefendsPerPhaseBreaker(t *testing.T) { t.Fatalf("L1 at 18 A on a 16 A fuse inside the aggregate deadband: " + "expected a forced discharge, got no targets") } - // Per-phase overage = (18 − 16) × 230 = 460 W on the worst phase, - // × 3 under the balanced-3Φ assumption = 1380 W from idle. - expected := -1380.0 + // Per-phase overage = (18 − 15) × 230 = 690 W over the working + // limit on the worst phase, × 3 under the balanced-3Φ assumption + // = 2070 W from idle. + expected := -2070.0 if math.Abs(out[0].TargetW-expected) > 1 { t.Errorf("forced discharge = %.0f W, want %.0f W", out[0].TargetW, expected) } @@ -932,7 +934,7 @@ func TestDeadbandExitPerPhaseReliefPreservesLiveDischarge(t *testing.T) { const ( liveBatteryW = -5000.0 liveWorstA = 18.0 - fuseA = 16.0 + fuseA = 15.0 // 16 A fuse less the 1 A working margin phases = 3.0 voltage = 230.0 ) @@ -969,7 +971,7 @@ func TestDeadbandExitPerPhaseReliefStartsFromLiveCharge(t *testing.T) { const ( liveBatteryW = 5000.0 liveWorstA = 18.0 - fuseA = 16.0 + fuseA = 15.0 // 16 A fuse less the 1 A working margin phases = 3.0 voltage = 230.0 ) @@ -1380,7 +1382,7 @@ func TestDeadbandExitUsesOnlyRemainingPerPhaseReliefAfterChargeCap(t *testing.T) liveBatteryW = 5000.0 maxChargeW = 4500.0 liveWorstA = 18.0 - fuseA = 16.0 + fuseA = 15.0 // 16 A fuse less the 1 A working margin phaseReliefW = (liveWorstA - fuseA) * 230 * 3 ) store, state, caps := setupPerPhase(0, liveWorstA, 4, 4, 0.6, 10000) diff --git a/go/internal/control/golden_dump_test.go b/go/internal/control/golden_dump_test.go index ae96c9960..32636555b 100644 --- a/go/internal/control/golden_dump_test.go +++ b/go/internal/control/golden_dump_test.go @@ -331,7 +331,12 @@ func runGoldenScenarioAt(sc goldenScenario, scenarioNow time.Time, slotDirective // Pre-dispatch attribution reads (pure). intent := planSignIntent(st) - perPhase := perPhaseOverageW(store, st) + // The worst phase's overage either way, in watts on that phase. + var perPhase float64 + importW, exportW := phaseFuseReliefW(store.Get(st.SiteMeterDriver, telemetry.DerMeter), st, 0) + if st.SiteFusePhases > 0 { + perPhase = math.Max(importW, exportW) / float64(st.SiteFusePhases) + } effImp := st.effectiveImportCeilingW(sc.Inputs.FuseMaxW) effExp := st.effectiveExportCeilingW(sc.Inputs.FuseMaxW) diff --git a/go/internal/control/peak_limit_test.go b/go/internal/control/peak_limit_test.go index 596212a4e..d8a7be220 100644 --- a/go/internal/control/peak_limit_test.go +++ b/go/internal/control/peak_limit_test.go @@ -122,7 +122,7 @@ func TestSetPeakLimitRejectsNonFinite(t *testing.T) { } // An undescribed fuse yields no ceiling rather than an invented one — -// the same back-compat rule fuseSafetyMarginW and perPhaseOverageW keep +// the same back-compat rule fuseSafetyMarginW and phaseFuseReliefW keep // for harnesses that wire only some of the fuse fields. func TestSetPeakLimitWithoutFuseChecksOnlyTheSign(t *testing.T) { st := NewState(0, 50, "ferroamp") // no SiteFuse* wired diff --git a/go/internal/control/testdata/golden/early_exit_protections.json b/go/internal/control/testdata/golden/early_exit_protections.json index e1147757e..6344bac47 100644 --- a/go/internal/control/testdata/golden/early_exit_protections.json +++ b/go/internal/control/testdata/golden/early_exit_protections.json @@ -1,7 +1,7 @@ { "family": "early_exit_protections", "generated_by": "FTW_GOLDEN_DUMP=1 go test ./internal/control/ -run TestGoldenDump", - "ftw_commit": "68c5b6125898bb9da70728b8921259c87e96171d", + "ftw_commit": "83c2b24ccdb730278a9c4e6ef778bab5f9499167", "record_count": 21, "records": [ { @@ -519,7 +519,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1380, + "target_w": -2070, "clamped": true } ], @@ -536,7 +536,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 460, + "per_phase_overage_w": 690, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -544,9 +544,9 @@ }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -1380, + "battery_target_sum_w": -2070, "raw_grid_w": 0, - "projected_grid_w": -1380 + "projected_grid_w": -2070 } }, { @@ -775,7 +775,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 2300, + "per_phase_overage_w": 2530, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -841,7 +841,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1610, + "target_w": -1840, "clamped": true } ], @@ -858,17 +858,17 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1610, + "per_phase_overage_w": 1840, "effective_import_ceiling_w": 5750, "effective_export_ceiling_w": 5750, - "import_ceiling_binding": true, + "import_ceiling_binding": false, "export_ceiling_binding": false }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -1610, + "battery_target_sum_w": -1840, "raw_grid_w": 7360, - "projected_grid_w": 5750 + "projected_grid_w": 5520 } }, { @@ -1009,7 +1009,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -2070, + "target_w": -2760, "clamped": true } ], @@ -1026,7 +1026,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 690, + "per_phase_overage_w": 920, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -1034,9 +1034,9 @@ }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -2070, + "battery_target_sum_w": -2760, "raw_grid_w": 20, - "projected_grid_w": -2050 + "projected_grid_w": -2740 } }, { @@ -1170,7 +1170,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -2760, + "target_w": -3450, "clamped": true } ], @@ -1187,7 +1187,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 920, + "per_phase_overage_w": 1150, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -1195,9 +1195,9 @@ }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -2760, + "battery_target_sum_w": -3450, "raw_grid_w": 1000, - "projected_grid_w": -1760 + "projected_grid_w": -2450 } }, { @@ -1253,7 +1253,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1150, + "target_w": -1380, "clamped": true } ], @@ -1270,17 +1270,17 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1150, + "per_phase_overage_w": 1380, "effective_import_ceiling_w": 5750, "effective_export_ceiling_w": 5750, - "import_ceiling_binding": true, + "import_ceiling_binding": false, "export_ceiling_binding": false }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -1150, + "battery_target_sum_w": -1380, "raw_grid_w": 6900, - "projected_grid_w": 5750 + "projected_grid_w": 5520 } }, { @@ -1495,7 +1495,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -3450, + "target_w": -4140, "clamped": true } ], @@ -1512,7 +1512,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1150, + "per_phase_overage_w": 1380, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -1520,9 +1520,9 @@ }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -3450, + "battery_target_sum_w": -4140, "raw_grid_w": 2000, - "projected_grid_w": -1450 + "projected_grid_w": -2140 } }, { @@ -1578,7 +1578,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1610, + "target_w": -1840, "clamped": true } ], @@ -1595,17 +1595,17 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1610, + "per_phase_overage_w": 1840, "effective_import_ceiling_w": 5750, "effective_export_ceiling_w": 5750, - "import_ceiling_binding": true, + "import_ceiling_binding": false, "export_ceiling_binding": false }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -1610, + "battery_target_sum_w": -1840, "raw_grid_w": 7360, - "projected_grid_w": 5750 + "projected_grid_w": 5520 } }, { diff --git a/go/internal/control/testdata/golden/seeded_fuse.json b/go/internal/control/testdata/golden/seeded_fuse.json index 0100f4d67..9862640e4 100644 --- a/go/internal/control/testdata/golden/seeded_fuse.json +++ b/go/internal/control/testdata/golden/seeded_fuse.json @@ -1,7 +1,7 @@ { "family": "seeded_fuse", "generated_by": "FTW_GOLDEN_DUMP=1 go test ./internal/control/ -run TestGoldenDump", - "ftw_commit": "303f86818a95f056f68e0b652db131a33074a421", + "ftw_commit": "83c2b24ccdb730278a9c4e6ef778bab5f9499167", "record_count": 80, "records": [ { @@ -69,20 +69,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -3245.228082551051, - "clamped": true + "target_w": -1530.5555555555554, + "clamped": false }, { "driver": "sungrow", - "target_w": -3647.771917448948, - "clamped": true + "target_w": -2326.4444444444443, + "clamped": false } ], "clamp_attributions": { - "clamped_drivers": [ - "ferroamp", - "sungrow" - ], + "clamped_drivers": [], "all_targets_zero_clamped": false, "plan_sign_intent": 0, "plan_sign_floor_zeroed": false, @@ -100,9 +97,9 @@ }, "site_totals": { "battery_current_w": 1432, - "battery_target_sum_w": -6892.999999999999, + "battery_target_sum_w": -3857, "raw_grid_w": 8815, - "projected_grid_w": 490.0000000000009 + "projected_grid_w": 3526 } }, { @@ -213,7 +210,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1195.9999999999998, + "per_phase_overage_w": 1425.9999999999998, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -580,7 +577,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 253.00000000000034, + "per_phase_overage_w": 483.0000000000003, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -663,7 +660,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1035, + "per_phase_overage_w": 1265, "effective_import_ceiling_w": 4300, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -757,12 +754,12 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": 0, + "target_w": -0, "clamped": true }, { "driver": "sungrow", - "target_w": 0, + "target_w": -0, "clamped": true } ], @@ -780,7 +777,7 @@ "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 184.00000000000017, + "per_phase_overage_w": 414.00000000000017, "effective_import_ceiling_w": 17250, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -870,13 +867,13 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -2534.523809523809, - "clamped": true + "target_w": -2017.0238095238092, + "clamped": false }, { "driver": "pixii", - "target_w": -2534.523809523809, - "clamped": true + "target_w": -2017.0238095238092, + "clamped": false }, { "driver": "sungrow", @@ -886,8 +883,6 @@ ], "clamp_attributions": { "clamped_drivers": [ - "ferroamp", - "pixii", "sungrow" ], "all_targets_zero_clamped": false, @@ -899,7 +894,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 345, + "per_phase_overage_w": 460, "effective_import_ceiling_w": 10695, "effective_export_ceiling_w": 10695, "import_ceiling_binding": false, @@ -907,9 +902,9 @@ }, "site_totals": { "battery_current_w": -3018, - "battery_target_sum_w": -10069.047619047618, + "battery_target_sum_w": -9034.047619047618, "raw_grid_w": 11913, - "projected_grid_w": 4861.952380952382 + "projected_grid_w": 5896.952380952382 } }, { @@ -1081,7 +1076,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 598.0000000000003, + "per_phase_overage_w": 713.0000000000003, "effective_import_ceiling_w": 16905, "effective_export_ceiling_w": 16905, "import_ceiling_binding": true, @@ -1688,20 +1683,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -3402.6442494330904, - "clamped": true + "target_w": -1518.5290322580647, + "clamped": false }, { "driver": "sungrow", - "target_w": -3145.9557505669086, - "clamped": true + "target_w": -959.0709677419356, + "clamped": false } ], "clamp_attributions": { - "clamped_drivers": [ - "ferroamp", - "sungrow" - ], + "clamped_drivers": [], "all_targets_zero_clamped": false, "plan_sign_intent": 0, "plan_sign_floor_zeroed": false, @@ -1711,7 +1703,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1356.9999999999998, + "per_phase_overage_w": 1586.9999999999998, "effective_import_ceiling_w": 5311, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -1719,9 +1711,9 @@ }, "site_totals": { "battery_current_w": 2317, - "battery_target_sum_w": -6548.5999999999985, + "battery_target_sum_w": -2477.6000000000004, "raw_grid_w": 7991, - "projected_grid_w": -874.5999999999985 + "projected_grid_w": 3196.3999999999996 } }, { @@ -1883,17 +1875,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -644.0000000000001, + "target_w": -323.0000000000004, "clamped": true }, { "driver": "pixii", - "target_w": -644.0000000000001, + "target_w": -323.0000000000004, "clamped": true }, { "driver": "sungrow", - "target_w": -644.0000000000001, + "target_w": -323.0000000000004, "clamped": true } ], @@ -1912,7 +1904,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 644.0000000000001, + "per_phase_overage_w": 759.0000000000001, "effective_import_ceiling_w": 16905, "effective_export_ceiling_w": 16905, "import_ceiling_binding": false, @@ -1920,9 +1912,9 @@ }, "site_totals": { "battery_current_w": 1308, - "battery_target_sum_w": -1932.0000000000005, + "battery_target_sum_w": -969.0000000000011, "raw_grid_w": 13971, - "projected_grid_w": 10731 + "projected_grid_w": 11693.999999999998 } }, { @@ -2290,7 +2282,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 505.99999999999983, + "per_phase_overage_w": 735.9999999999999, "effective_import_ceiling_w": 6067, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -2480,20 +2472,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -2820.0999999999995, - "clamped": true + "target_w": -1026.1, + "clamped": false }, { "driver": "sungrow", - "target_w": -2820.0999999999995, - "clamped": true + "target_w": -1026.1, + "clamped": false } ], "clamp_attributions": { - "clamped_drivers": [ - "ferroamp", - "sungrow" - ], + "clamped_drivers": [], "all_targets_zero_clamped": false, "plan_sign_intent": 0, "plan_sign_floor_zeroed": false, @@ -2503,7 +2492,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1195.9999999999998, + "per_phase_overage_w": 1310.9999999999998, "effective_import_ceiling_w": 10695, "effective_export_ceiling_w": 10695, "import_ceiling_binding": false, @@ -2511,9 +2500,9 @@ }, "site_totals": { "battery_current_w": 4591, - "battery_target_sum_w": -5640.199999999999, + "battery_target_sum_w": -2052.2, "raw_grid_w": 11072, - "projected_grid_w": 840.8000000000011 + "projected_grid_w": 4428.8 } }, { @@ -3365,7 +3354,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 206.99999999999966, + "per_phase_overage_w": 436.9999999999997, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -3564,17 +3553,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": 0, + "target_w": -0, "clamped": true }, { "driver": "pixii", - "target_w": 0, + "target_w": -0, "clamped": true }, { "driver": "sungrow", - "target_w": 0, + "target_w": -0, "clamped": true } ], @@ -3593,7 +3582,7 @@ "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 275.99999999999983, + "per_phase_overage_w": 505.99999999999983, "effective_import_ceiling_w": 5718, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -3812,7 +3801,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1334.0000000000002, + "per_phase_overage_w": 1449.0000000000002, "effective_import_ceiling_w": 10695, "effective_export_ceiling_w": 10695, "import_ceiling_binding": false, @@ -4800,7 +4789,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1550, + "target_w": -0, "clamped": true } ], @@ -4808,16 +4797,16 @@ "clamped_drivers": [ "ferroamp" ], - "all_targets_zero_clamped": false, + "all_targets_zero_clamped": true, "plan_sign_intent": -1, - "plan_sign_floor_zeroed": false, + "plan_sign_floor_zeroed": true, "plan_stale": false, "fuse_saturated": false, "fuse_ev_max_w": 0, "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, - "fuse_hold_max_discharge_w": 1550, - "per_phase_overage_w": 1150, + "fuse_hold_max_discharge_w": 0, + "per_phase_overage_w": 1380, "effective_import_ceiling_w": 4886, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -4825,9 +4814,9 @@ }, "site_totals": { "battery_current_w": -3716, - "battery_target_sum_w": -1550, + "battery_target_sum_w": 0, "raw_grid_w": -15970, - "projected_grid_w": -13804 + "projected_grid_w": -12254 } }, { @@ -4895,20 +4884,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -5000, - "clamped": true + "target_w": -3102.7, + "clamped": false }, { "driver": "sungrow", - "target_w": -5000, - "clamped": true + "target_w": -3102.7, + "clamped": false } ], "clamp_attributions": { - "clamped_drivers": [ - "ferroamp", - "sungrow" - ], + "clamped_drivers": [], "all_targets_zero_clamped": false, "plan_sign_intent": 0, "plan_sign_floor_zeroed": false, @@ -4918,7 +4904,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1288.0000000000002, + "per_phase_overage_w": 1518.0000000000002, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -4926,9 +4912,9 @@ }, "site_totals": { "battery_current_w": 2407, - "battery_target_sum_w": -10000, + "battery_target_sum_w": -6205.4, "raw_grid_w": 14354, - "projected_grid_w": 1947 + "projected_grid_w": 5741.6 } }, { @@ -5313,20 +5299,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1645.1999999999998, - "clamped": true + "target_w": -782.6999999999998, + "clamped": false }, { "driver": "sungrow", - "target_w": -1645.1999999999998, - "clamped": true + "target_w": -782.6999999999998, + "clamped": false } ], "clamp_attributions": { - "clamped_drivers": [ - "ferroamp", - "sungrow" - ], + "clamped_drivers": [], "all_targets_zero_clamped": false, "plan_sign_intent": 0, "plan_sign_floor_zeroed": false, @@ -5344,9 +5327,9 @@ }, "site_totals": { "battery_current_w": 3297, - "battery_target_sum_w": -3290.3999999999996, + "battery_target_sum_w": -1565.3999999999996, "raw_grid_w": 8104, - "projected_grid_w": 1516.6000000000004 + "projected_grid_w": 3241.6000000000004 } }, { @@ -6292,7 +6275,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 184.00000000000017, + "per_phase_overage_w": 414.00000000000017, "effective_import_ceiling_w": 7497, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -6513,17 +6496,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -2088.5, + "target_w": -1335.8333333333328, "clamped": true }, { "driver": "pixii", - "target_w": -2088.5, + "target_w": -1335.8333333333328, "clamped": true }, { "driver": "sungrow", - "target_w": -2088.5, + "target_w": -1335.8333333333328, "clamped": true } ], @@ -6541,8 +6524,8 @@ "fuse_ev_max_w": 0, "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, - "fuse_hold_max_discharge_w": 6265.5, - "per_phase_overage_w": 0, + "fuse_hold_max_discharge_w": 4007.499999999998, + "per_phase_overage_w": 23.000000000000327, "effective_import_ceiling_w": 16905, "effective_export_ceiling_w": 16905, "import_ceiling_binding": false, @@ -6550,9 +6533,9 @@ }, "site_totals": { "battery_current_w": -4249, - "battery_target_sum_w": -6265.5, + "battery_target_sum_w": -4007.499999999998, "raw_grid_w": -14716, - "projected_grid_w": -16732.5 + "projected_grid_w": -14474.499999999998 } }, { @@ -6625,7 +6608,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1150, + "per_phase_overage_w": 1380, "effective_import_ceiling_w": 6574, "effective_export_ceiling_w": 7458, "import_ceiling_binding": false, @@ -6896,12 +6879,12 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1720.5, + "target_w": -1592, "clamped": true }, { "driver": "sungrow", - "target_w": -1720.5, + "target_w": -1592, "clamped": true } ], @@ -6918,18 +6901,18 @@ "fuse_ev_max_w": 0, "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, - "fuse_hold_max_discharge_w": 3441, - "per_phase_overage_w": 0, + "fuse_hold_max_discharge_w": 3184, + "per_phase_overage_w": 45.99999999999984, "effective_import_ceiling_w": 17250, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, - "export_ceiling_binding": true + "export_ceiling_binding": false }, "site_totals": { "battery_current_w": -3322, - "battery_target_sum_w": -3441, + "battery_target_sum_w": -3184, "raw_grid_w": -17131, - "projected_grid_w": -17250 + "projected_grid_w": -16993 } }, { @@ -7099,7 +7082,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1080.9999999999998, + "per_phase_overage_w": 1195.9999999999998, "effective_import_ceiling_w": 10695, "effective_export_ceiling_w": 10695, "import_ceiling_binding": false, @@ -7165,7 +7148,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -3174.000000000001, + "target_w": -1139.0000000000014, "clamped": true } ], @@ -7182,7 +7165,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1058.0000000000002, + "per_phase_overage_w": 1288.0000000000002, "effective_import_ceiling_w": 17250, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -7190,9 +7173,9 @@ }, "site_totals": { "battery_current_w": 2725, - "battery_target_sum_w": -3174.000000000001, + "battery_target_sum_w": -1139.0000000000014, "raw_grid_w": 14295, - "projected_grid_w": 8396 + "projected_grid_w": 10430.999999999998 } }, { @@ -7475,7 +7458,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 184.00000000000017, + "per_phase_overage_w": 414.00000000000017, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -7683,12 +7666,12 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": 0, + "target_w": -0, "clamped": true }, { "driver": "sungrow", - "target_w": 0, + "target_w": -0, "clamped": true } ], @@ -7706,7 +7689,7 @@ "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 345, + "per_phase_overage_w": 460, "effective_import_ceiling_w": 16905, "effective_export_ceiling_w": 16905, "import_ceiling_binding": false, @@ -7917,30 +7900,34 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": 5000, - "clamped": false + "target_w": 4493.333333333333, + "clamped": true }, { "driver": "pixii", - "target_w": 5000, - "clamped": false + "target_w": 4493.333333333333, + "clamped": true }, { "driver": "sungrow", - "target_w": 5000, - "clamped": false + "target_w": 4493.333333333333, + "clamped": true } ], "clamp_attributions": { - "clamped_drivers": [], + "clamped_drivers": [ + "ferroamp", + "pixii", + "sungrow" + ], "all_targets_zero_clamped": false, "plan_sign_intent": 0, "plan_sign_floor_zeroed": false, "plan_stale": false, "fuse_saturated": false, "fuse_ev_max_w": 0, - "fuse_hold_latched": false, - "fuse_hold_max_charge_w": 0, + "fuse_hold_latched": true, + "fuse_hold_max_charge_w": 13480, "fuse_hold_max_discharge_w": 0, "per_phase_overage_w": 0, "effective_import_ceiling_w": 10350, @@ -7950,9 +7937,9 @@ }, "site_totals": { "battery_current_w": 853, - "battery_target_sum_w": 15000, + "battery_target_sum_w": 13480, "raw_grid_w": -7899, - "projected_grid_w": 6248 + "projected_grid_w": 4728 } }, { @@ -8025,7 +8012,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 0, + "per_phase_overage_w": 206.99999999999966, "effective_import_ceiling_w": 4624, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -8131,17 +8118,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -716.6666666666667, + "target_w": -0, "clamped": true }, { "driver": "pixii", - "target_w": -716.6666666666667, + "target_w": -0, "clamped": true }, { "driver": "sungrow", - "target_w": -716.6666666666667, + "target_w": -0, "clamped": true } ], @@ -8151,26 +8138,26 @@ "pixii", "sungrow" ], - "all_targets_zero_clamped": false, + "all_targets_zero_clamped": true, "plan_sign_intent": -1, - "plan_sign_floor_zeroed": false, + "plan_sign_floor_zeroed": true, "plan_stale": false, "fuse_saturated": false, "fuse_ev_max_w": 0, "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, - "fuse_hold_max_discharge_w": 2150, - "per_phase_overage_w": 1173.0000000000002, + "fuse_hold_max_discharge_w": 0, + "per_phase_overage_w": 1403.0000000000002, "effective_import_ceiling_w": 17250, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, - "export_ceiling_binding": true + "export_ceiling_binding": false }, "site_totals": { "battery_current_w": 1653, - "battery_target_sum_w": -2150, + "battery_target_sum_w": 0, "raw_grid_w": -13447, - "projected_grid_w": -17250 + "projected_grid_w": -15100 } } ] diff --git a/go/internal/control/testdata/golden/slew_limiter.json b/go/internal/control/testdata/golden/slew_limiter.json index 896d7f298..0c5efa302 100644 --- a/go/internal/control/testdata/golden/slew_limiter.json +++ b/go/internal/control/testdata/golden/slew_limiter.json @@ -1,7 +1,7 @@ { "family": "slew_limiter", "generated_by": "FTW_GOLDEN_DUMP=1 go test ./internal/control/ -run TestGoldenDump", - "ftw_commit": "15f9edc3b973d7b9151e88d63575a9b7d615a0b3", + "ftw_commit": "83c2b24ccdb730278a9c4e6ef778bab5f9499167", "record_count": 127, "records": [ { @@ -3225,7 +3225,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -2760, + "target_w": -1949.9999999999995, "clamped": true } ], @@ -3242,7 +3242,7 @@ "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 920, + "per_phase_overage_w": 1150, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -3250,9 +3250,9 @@ }, "site_totals": { "battery_current_w": 1500, - "battery_target_sum_w": -2760, + "battery_target_sum_w": -1949.9999999999995, "raw_grid_w": 1000, - "projected_grid_w": -3260 + "projected_grid_w": -2449.9999999999995 } }, { diff --git a/go/internal/control/testdata/golden/targeted_invariants.json b/go/internal/control/testdata/golden/targeted_invariants.json index 467ca3418..b44f92069 100644 --- a/go/internal/control/testdata/golden/targeted_invariants.json +++ b/go/internal/control/testdata/golden/targeted_invariants.json @@ -1,7 +1,7 @@ { "family": "targeted_invariants", "generated_by": "FTW_GOLDEN_DUMP=1 go test ./internal/control/ -run TestGoldenDump", - "ftw_commit": "68c5b6125898bb9da70728b8921259c87e96171d", + "ftw_commit": "83c2b24ccdb730278a9c4e6ef778bab5f9499167", "record_count": 18, "records": [ { @@ -683,7 +683,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -3360, + "target_w": -3450, "clamped": true } ], @@ -700,7 +700,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 920, + "per_phase_overage_w": 1150, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -708,9 +708,9 @@ }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -3360, + "battery_target_sum_w": -3450, "raw_grid_w": 1000, - "projected_grid_w": -2360 + "projected_grid_w": -2450 } }, { @@ -782,7 +782,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -2240, + "target_w": -0, "clamped": true } ], @@ -790,16 +790,16 @@ "clamped_drivers": [ "ferroamp" ], - "all_targets_zero_clamped": false, + "all_targets_zero_clamped": true, "plan_sign_intent": -1, - "plan_sign_floor_zeroed": false, + "plan_sign_floor_zeroed": true, "plan_stale": false, "fuse_saturated": false, "fuse_ev_max_w": 0, "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, - "fuse_hold_max_discharge_w": 2240, - "per_phase_overage_w": 920, + "fuse_hold_max_discharge_w": 0, + "per_phase_overage_w": 1150, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -807,9 +807,9 @@ }, "site_totals": { "battery_current_w": -2000, - "battery_target_sum_w": -2240, + "battery_target_sum_w": 0, "raw_grid_w": -6000, - "projected_grid_w": -6240 + "projected_grid_w": -4000 } }, { From 7e453c05f0c23708aa8fd1ad3e4c7802a47bb49b Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 15:57:50 +0100 Subject: [PATCH 15/68] fix(control): fuse guard reads phases after the hold caps the targets The guard took the phase relief from the original request, then the 30 s fuse hold capped that request and the relief came off again. A charge limited by one phase switched between 1380 W and 0 W on every dispatch. Predict the aggregate and the phases from the held targets instead. The phase reader now takes the meter's raw total from OnlineMeterW, the same reading as its currents, so an offline meter's cached phases drive no relief. The batteries' raw power is read in one helper. dispatch.go keeps its 41 cached telemetry reads. Co-Authored-By: Claude Opus 5.5 --- go/internal/control/dispatch.go | 148 +++++++++++------- .../control/ev_battery_sequence_test.go | 6 +- .../fuse_battery_phase_direction_test.go | 75 +++++++++ go/internal/control/golden_dump_test.go | 2 +- 4 files changed, 172 insertions(+), 59 deletions(-) diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index e3c3b2d1f..6ac7c1078 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -3622,48 +3622,26 @@ func applyFuseGuard(targets []DispatchTarget, store *telemetry.Store, state *Sta // reflected in currentGrid; subtracting them here without adding a // replacement target would double-remove their contribution and miss // fuse overages. - seenBat := make(map[string]struct{}, len(targets)) - var currentBat, rawBat float64 + batteries := make(map[string]*telemetry.DerReading, len(targets)) + var currentBat float64 for _, t := range targets { - if _, seen := seenBat[t.Driver]; seen { + if _, seen := batteries[t.Driver]; seen { continue } - seenBat[t.Driver] = struct{}{} - if r := store.Get(t.Driver, telemetry.DerBattery); r != nil { + r := store.Get(t.Driver, telemetry.DerBattery) + batteries[t.Driver] = r + if r != nil { currentBat += r.SmoothedW - rawBat += r.RawW } } var currentGrid float64 - var meter *telemetry.DerReading + var phases phaseSample if siteMeter != "" { - if meter = store.Get(siteMeter, telemetry.DerMeter); meter != nil { + if meter := store.Get(siteMeter, telemetry.DerMeter); meter != nil { currentGrid = meter.SmoothedW + phases = livePhaseSample(store, siteMeter, meter) } } - var sumTarget float64 - for _, t := range targets { - sumTarget += t.TargetW - } - predicted := currentGrid - currentBat + sumTarget - - // Per phase, each way, once the targets replace the batteries' power - // in the same raw reading. - phaseImportW, phaseExportW := phaseFuseReliefW(meter, state, sumTarget-rawBat) - // Aggregate budget honours the safety margin too — keep dispatch - // commands strictly inside the breaker envelope so the inverter's - // own per-phase limiter doesn't fire first and cause a flap. - // - // Import ceiling is the tighter of (fuse − safety margin) and the - // clock hour's import limit; export ceiling is the tighter of (fuse − - // safety margin) and the operator's max_export_w protection limit — - // set when an inverter trips on sustained export below the breaker - // (recurring Ferroamp 0x8030 fault). Both share one enforcement surface. - effImportW := state.effectiveImportCeilingW(fuseMaxW) - effExportW := state.effectiveExportCeilingW(fuseMaxW) - importOverage := math.Max(predicted-effImportW, phaseImportW) - exportOverage := math.Max(-effExportW-predicted, phaseExportW) - out := make([]DispatchTarget, len(targets)) copy(out, targets) @@ -3716,6 +3694,32 @@ func applyFuseGuard(targets []DispatchTarget, store *telemetry.Store, state *Sta state.FuseHoldUntil = time.Time{} } + // Predict from the held targets. Relief taken from the request would + // count the hold's cut a second time, and a charge limited by one phase + // would switch between the cap and 0 on every dispatch. + var sumTarget float64 + for _, t := range out { + sumTarget += t.TargetW + } + predicted := currentGrid - currentBat + sumTarget + + // Per phase, each way, once the targets replace the batteries' power + // in the same raw reading. + phaseImportW, phaseExportW := phaseFuseReliefW(phases, state, phaseMoveW(out, batteries)) + // Aggregate budget honours the safety margin too — keep dispatch + // commands strictly inside the breaker envelope so the inverter's + // own per-phase limiter doesn't fire first and cause a flap. + // + // Import ceiling is the tighter of (fuse − safety margin) and the + // clock hour's import limit; export ceiling is the tighter of (fuse − + // safety margin) and the operator's max_export_w protection limit — + // set when an inverter trips on sustained export below the breaker + // (recurring Ferroamp 0x8030 fault). Both share one enforcement surface. + effImportW := state.effectiveImportCeilingW(fuseMaxW) + effExportW := state.effectiveExportCeilingW(fuseMaxW) + importOverage := math.Max(predicted-effImportW, phaseImportW) + exportOverage := math.Max(-effExportW-predicted, phaseExportW) + if importOverage <= 0 && exportOverage <= 0 { return out } @@ -3853,30 +3857,70 @@ func (s *State) effectiveExportCeilingW(fuseMaxW float64) float64 { return eff } +// phaseSample is one meter reading's phase currents with the raw total of +// the same reading. The zero value has no phases. +type phaseSample struct { + meter *telemetry.DerReading + totalW float64 +} + +// livePhaseSample pairs meter with its raw total while the meter still +// reports. A watchdog-offline meter gives no phases, since its cached +// currents are no longer the site. So does a store that has moved on to a +// newer reading, since its total no longer matches meter's currents. +func livePhaseSample(store *telemetry.Store, driver string, meter *telemetry.DerReading) phaseSample { + if store == nil || meter == nil { + return phaseSample{} + } + totalW, at, ok := store.OnlineMeterW(driver) + if !ok || !at.Equal(meter.UpdatedAt) { + return phaseSample{} + } + return phaseSample{meter: meter, totalW: totalW} +} + +// phaseMoveW is the batteries' change from the raw power their readings hold +// to the targets. The phase currents are raw, so the move is too. +func phaseMoveW(targets []DispatchTarget, batteries map[string]*telemetry.DerReading) float64 { + var moveW float64 + seen := make(map[string]bool, len(targets)) + for _, t := range targets { + moveW += t.TargetW + if r := batteries[t.Driver]; r != nil && !seen[t.Driver] { + moveW -= r.RawW + } + seen[t.Driver] = true + } + return moveW +} + // phaseFuseReliefW is the aggregate battery move that brings every phase // inside the working limit: the fuse less the car's 1 A margin, or less // safety_margin_a when that is larger. importW asks for less charge or more // discharge, exportW for the reverse. moveW is the batteries' change from -// the power this reading already holds; like the relief, it spreads evenly -// over the site's phases. +// the power this reading already holds (phaseMoveW); like the relief, it +// spreads evenly over the site's phases. // // The phases are the meter's signed currents (phaseCurrentsA). When no // phase reads as export while the total does, the meter gives no direction // per phase, and the phases take the total's. When no move fits every -// phase, the move leaves the worst phase least over, so a move never -// raises the current on the phase it protects. 0, 0 without usable phase -// currents. -func phaseFuseReliefW(meter *telemetry.DerReading, state *State, moveW float64) (importW, exportW float64) { - if meter == nil || state == nil { +// phase, the move leaves the worst phase least over, so on a meter that +// gives each phase's direction a move never raises the current on the phase +// it protects. Two limits remain: a meter without phase power that mixes +// directions under an exporting total, where an importing phase is read as +// export, and a battery on one phase, which is read as balanced. 0, 0 +// without usable phase currents. +func phaseFuseReliefW(p phaseSample, state *State, moveW float64) (importW, exportW float64) { + if p.meter == nil || state == nil { return 0, 0 } - amps, _, valid := phaseCurrentsA(meter, state, meter.RawW) + amps, _, valid := phaseCurrentsA(p.meter, state, p.totalW) if !valid || len(amps) == 0 { return 0, 0 } perA := state.SiteFuseVoltage * float64(state.SiteFusePhases) // aggregate W per phase ampere limitA := math.Max(0, state.SiteFuseAmps-math.Max(evPhaseMarginA, state.SiteFuseSafetyA)) - exports := meter.RawW < 0 + exports := p.totalW < 0 for _, a := range amps { exports = exports && a >= 0 } @@ -4399,7 +4443,8 @@ func fuseSaverFromLivePower( // site is safe. Preserve the deadband in that case: this early-return path // exists to answer a fuse condition, not to take control of an externally // moved battery merely because its reading sits outside a command cap. - requiredRelief := fuseReliefFromSnapshot(rawLive, batteryReadings, meter, state, fuseMaxW) + phases := livePhaseSample(store, state.SiteMeterDriver, meter) + requiredRelief := fuseReliefFromSnapshot(rawLive, batteryReadings, meter, phases, state, fuseMaxW) if requiredRelief <= 0 { return nil } @@ -4417,7 +4462,7 @@ func fuseSaverFromLivePower( if len(safeBaseline) == 0 { return nil } - out := forceFuseDischargeWithSnapshot(safeBaseline, batteryReadings, meter, state, driverCapacities, fuseMaxW) + out := forceFuseDischargeWithSnapshot(safeBaseline, batteryReadings, meter, phases, state, driverCapacities, fuseMaxW) rawByDriver := make(map[string]DispatchTarget, len(rawLive)) for _, t := range rawLive { rawByDriver[t.Driver] = t @@ -4440,6 +4485,7 @@ func fuseReliefFromSnapshot( targets []DispatchTarget, batteryReadings map[string]*telemetry.DerReading, meter *telemetry.DerReading, + phases phaseSample, state *State, fuseMaxW float64, ) float64 { @@ -4447,7 +4493,7 @@ func fuseReliefFromSnapshot( return 0 } - _, sumTarget, predicted := predictedGridFromSnapshot(targets, batteryReadings, meter) + _, _, predicted := predictedGridFromSnapshot(targets, batteryReadings, meter) // The fuse acts on every reading. The hour's import limit is a budget: // the part of its overage that an EV cut we sent will remove waits for @@ -4459,16 +4505,7 @@ func fuseReliefFromSnapshot( if ceilingW := state.effectiveImportCeilingW(fuseMaxW); ceilingW < fuseW { overage = math.Max(overage, predicted-ceilingW-state.pendingEVCutW()) } - // The phases are raw, so the batteries' move is from their raw power. - moveW := sumTarget - seen := make(map[string]bool, len(targets)) - for _, t := range targets { - if r := batteryReadings[t.Driver]; r != nil && !seen[t.Driver] { - moveW -= r.RawW - } - seen[t.Driver] = true - } - phaseW, _ := phaseFuseReliefW(meter, state, moveW) + phaseW, _ := phaseFuseReliefW(phases, state, phaseMoveW(targets, batteryReadings)) return math.Max(overage, phaseW) } @@ -4521,7 +4558,7 @@ func forceFuseDischarge( readings[target.Driver] = store.Get(target.Driver, telemetry.DerBattery) } meter := store.Get(state.SiteMeterDriver, telemetry.DerMeter) - return forceFuseDischargeWithSnapshot(targets, readings, meter, state, driverCapacities, fuseMaxW) + return forceFuseDischargeWithSnapshot(targets, readings, meter, livePhaseSample(store, state.SiteMeterDriver, meter), state, driverCapacities, fuseMaxW) } // forceFuseDischargeWithSnapshot keeps all math for one decision on the same @@ -4531,6 +4568,7 @@ func forceFuseDischargeWithSnapshot( targets []DispatchTarget, batteryReadings map[string]*telemetry.DerReading, meter *telemetry.DerReading, + phases phaseSample, state *State, driverCapacities map[string]float64, fuseMaxW float64, @@ -4538,7 +4576,7 @@ func forceFuseDischargeWithSnapshot( if fuseMaxW <= 0 || len(targets) == 0 || state == nil { return targets } - overage := fuseReliefFromSnapshot(targets, batteryReadings, meter, state, fuseMaxW) + overage := fuseReliefFromSnapshot(targets, batteryReadings, meter, phases, state, fuseMaxW) if overage <= 0 { return targets } diff --git a/go/internal/control/ev_battery_sequence_test.go b/go/internal/control/ev_battery_sequence_test.go index 58665b6e1..8a8c22db7 100644 --- a/go/internal/control/ev_battery_sequence_test.go +++ b/go/internal/control/ev_battery_sequence_test.go @@ -588,7 +588,7 @@ func TestFuseReliefLeavesOnlyCeilingWattsToCommandedEVCut(t *testing.T) { targets := []DispatchTarget{{Driver: "pixii"}} batteries := map[string]*telemetry.DerReading{"pixii": {}} meter := &telemetry.DerReading{SmoothedW: tc.gridW, Data: tc.data} - got := fuseReliefFromSnapshot(targets, batteries, meter, st, 17250) + got := fuseReliefFromSnapshot(targets, batteries, meter, phaseSample{meter: meter, totalW: meter.RawW}, st, 17250) if math.Abs(math.Max(0, got)-tc.wantW) > 1e-6 { t.Errorf("%s: relief %.0f W, want %.0f W", tc.name, got, tc.wantW) } @@ -629,7 +629,7 @@ func TestUnpluggedCarIsNoCutTheBatteryWaitsFor(t *testing.T) { st.SetEVCommanded(points) targets := []DispatchTarget{{Driver: "pixii"}} batteries := map[string]*telemetry.DerReading{"pixii": {}} - return math.Max(0, fuseReliefFromSnapshot(targets, batteries, &telemetry.DerReading{SmoothedW: gridW}, st, 17250)) + return math.Max(0, fuseReliefFromSnapshot(targets, batteries, &telemetry.DerReading{SmoothedW: gridW}, phaseSample{}, st, 17250)) } // 400 W over the ceiling, less than a step: the guard waits. if got := tick(7900, true, 5520); math.Abs(got-400) > 1e-6 { @@ -693,7 +693,7 @@ func TestCutOnStayingCarStillWaitsWhenAnotherLeaves(t *testing.T) { st.SetEVCommanded(points) targets := []DispatchTarget{{Driver: "pixii"}} batteries := map[string]*telemetry.DerReading{"pixii": {SmoothedW: batteryW}} - relief := fuseReliefFromSnapshot(targets, batteries, &telemetry.DerReading{SmoothedW: gridW}, st, 17250) + relief := fuseReliefFromSnapshot(targets, batteries, &telemetry.DerReading{SmoothedW: gridW}, phaseSample{}, st, 17250) batteryW = -math.Max(0, relief) // The battery follows within a tick. if batteryW < 0 && tick < 10 { t.Fatalf("%ds: battery %.0f W for watts a's stop removes; pending cut %.0f W", tick, batteryW, st.pendingEVCutW()) diff --git a/go/internal/control/fuse_battery_phase_direction_test.go b/go/internal/control/fuse_battery_phase_direction_test.go index 111c03ee3..2e740b1f8 100644 --- a/go/internal/control/fuse_battery_phase_direction_test.go +++ b/go/internal/control/fuse_battery_phase_direction_test.go @@ -144,3 +144,78 @@ func TestPerPhaseFuseReliefHoldsWhileOverloadPersists(t *testing.T) { } } } + +// chargeLoop repeats a 4000 W charge request against house loads of +// 13/7/5 A on a 0 A margin, with a three-phase battery that follows each +// order. dispatch returns the battery's next target. +func chargeLoop(t *testing.T, ticks int, dispatch func(*telemetry.Store, *State) float64) (targets, l1 []float64) { + t.Helper() + st := phaseDirectionState(0) + now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) + st.clock = func() time.Time { return now } + store := telemetry.NewStore() + batW := 0.0 + for tick := 0; tick < ticks; tick++ { + a := [3]float64{13, 7, 5} + for i := range a { + a[i] += batW / 690 + } + raw, _ := json.Marshal(map[string]any{"l1_a": a[0], "l2_a": a[1], "l3_a": a[2], + "l1_w": a[0] * 230, "l2_w": a[1] * 230, "l3_w": a[2] * 230}) + store.Update("meter", telemetry.DerMeter, (a[0]+a[1]+a[2])*230, nil, raw) + store.DriverHealthMut("meter").RecordSuccess() + soc := 0.5 + store.Update("bat", telemetry.DerBattery, batW, &soc, nil) + store.DriverHealthMut("bat").RecordSuccess() + batW = dispatch(store, st) + targets = append(targets, math.Round(batW)) + l1 = append(l1, math.Round(a[0]*100)/100) + now = now.Add(5 * time.Second) + } + return targets, l1 +} + +// The fuse hold caps the request before the guard reads the phases, so the +// hold's cut is not taken off again. The charge settles at 1380 W with L1 +// at 15 A instead of switching between 1380 W and 0 W. +func TestFuseGuardHeldChargeHoldsSteady(t *testing.T) { + assertSteady := func(name string, targets, l1 []float64) { + t.Helper() + for i := 1; i < len(targets); i++ { + if math.Abs(targets[i]-targets[i-1]) > 50 || l1[i] > 15.01 { + t.Fatalf("%s: tick %d charge %v -> %v W; targets %v, L1 %v", name, i, targets[i-1], targets[i], targets, l1) + } + } + } + targets, l1 := chargeLoop(t, 10, func(store *telemetry.Store, st *State) float64 { + return applyFuseGuard([]DispatchTarget{{Driver: "bat", TargetW: 4000}}, store, st, 16*230*3)[0].TargetW + }) + assertSteady("applyFuseGuard", targets, l1) + + targets, l1 = chargeLoop(t, 12, func(store *telemetry.Store, st *State) float64 { + st.Mode = ModeCharge + st.DriverLimits = map[string]PowerLimits{"bat": {MaxChargeW: 4000, MaxDischargeW: 4000}} + for _, o := range ComputeDispatch(store, st, map[string]float64{"bat": 15200}, 16*230*3) { + if o.Driver == "bat" { + return o.TargetW + } + } + return 0 + }) + assertSteady("Charge mode", targets, l1) +} + +// A watchdog-offline meter's cached phases are not the site: they drive no +// phase relief. +func TestPhaseReliefSkipsOfflineMeter(t *testing.T) { + store := phaseDirectionStore(t, 20*230, 0, map[string]any{"l1_a": 20.0, "l2_a": 0.0, "l3_a": 0.0, + "l1_w": 4600.0, "l2_w": 0.0, "l3_w": 0.0}) + meter := store.Get("meter", telemetry.DerMeter) + if imp, _ := phaseFuseReliefW(livePhaseSample(store, "meter", meter), phaseDirectionState(0), 0); imp <= 0 { + t.Fatalf("online meter: import relief %.0f W, want > 0 for L1 at 20 A", imp) + } + store.DriverHealthMut("meter").SetOffline() + if imp, exp := phaseFuseReliefW(livePhaseSample(store, "meter", meter), phaseDirectionState(0), 0); imp != 0 || exp != 0 { + t.Fatalf("offline meter: relief %.0f/%.0f W, want none", imp, exp) + } +} diff --git a/go/internal/control/golden_dump_test.go b/go/internal/control/golden_dump_test.go index 32636555b..07a6f8f4d 100644 --- a/go/internal/control/golden_dump_test.go +++ b/go/internal/control/golden_dump_test.go @@ -333,7 +333,7 @@ func runGoldenScenarioAt(sc goldenScenario, scenarioNow time.Time, slotDirective intent := planSignIntent(st) // The worst phase's overage either way, in watts on that phase. var perPhase float64 - importW, exportW := phaseFuseReliefW(store.Get(st.SiteMeterDriver, telemetry.DerMeter), st, 0) + importW, exportW := phaseFuseReliefW(livePhaseSample(store, st.SiteMeterDriver, store.Get(st.SiteMeterDriver, telemetry.DerMeter)), st, 0) if st.SiteFusePhases > 0 { perPhase = math.Max(importW, exportW) / float64(st.SiteFusePhases) } From a11706b4810e946a4ebb5c3fbc428fbaf2e831a7 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 18:31:21 +0100 Subject: [PATCH 16/68] fix(control): battery relieves to the fuse less safety_margin_a phaseFuseReliefW now reads fuseLineA(), the line the car uses since the EV change, instead of max(1 A, safety_margin_a). There is no floor under the margin: at margin 0 the battery works to the fuse rating. Tests return to the rating where they had moved to the 1 A limit, and a new property test covers In x phases x margin in both directions. Co-Authored-By: Claude Opus 5.5 --- .changeset/a5-battery-fuse-signed-phases.md | 2 +- go/internal/control/dispatch.go | 6 +- .../control/ev_battery_priority_test.go | 8 +- .../fuse_battery_phase_direction_test.go | 90 ++++++++++++++-- go/internal/control/fuse_saver_test.go | 100 +++++++++--------- 5 files changed, 138 insertions(+), 68 deletions(-) diff --git a/.changeset/a5-battery-fuse-signed-phases.md b/.changeset/a5-battery-fuse-signed-phases.md index 9d5f66132..a8ac1435f 100644 --- a/.changeset/a5-battery-fuse-signed-phases.md +++ b/.changeset/a5-battery-fuse-signed-phases.md @@ -2,4 +2,4 @@ "ftw": patch --- -The home battery now protects each fuse phase in the direction its current flows. It no longer discharges into a phase that already exports past the fuse, and no longer cuts a discharge that keeps an importing phase under it. It counts its own share of each phase, so it holds a steady relief instead of switching between full relief and none on every dispatch. It now relieves to the same limit the car uses: the fuse less 1 A, or less the safety margin when that is larger. +The home battery now protects each fuse phase in the direction its current flows. It no longer discharges into a phase that already exports past the fuse, and no longer cuts a discharge that keeps an importing phase under it. It counts its own share of each phase, so it holds a steady relief instead of switching between full relief and none on every dispatch. It relieves to the fuse less `safety_margin_a`, the same line the car uses. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 6ac7c1078..17a14d15d 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -3895,8 +3895,8 @@ func phaseMoveW(targets []DispatchTarget, batteries map[string]*telemetry.DerRea } // phaseFuseReliefW is the aggregate battery move that brings every phase -// inside the working limit: the fuse less the car's 1 A margin, or less -// safety_margin_a when that is larger. importW asks for less charge or more +// inside the working limit, fuseLineA: the fuse less safety_margin_a, the +// same line the car uses. importW asks for less charge or more // discharge, exportW for the reverse. moveW is the batteries' change from // the power this reading already holds (phaseMoveW); like the relief, it // spreads evenly over the site's phases. @@ -3919,7 +3919,7 @@ func phaseFuseReliefW(p phaseSample, state *State, moveW float64) (importW, expo return 0, 0 } perA := state.SiteFuseVoltage * float64(state.SiteFusePhases) // aggregate W per phase ampere - limitA := math.Max(0, state.SiteFuseAmps-math.Max(evPhaseMarginA, state.SiteFuseSafetyA)) + limitA := state.fuseLineA() exports := p.totalW < 0 for _, a := range amps { exports = exports && a >= 0 diff --git a/go/internal/control/ev_battery_priority_test.go b/go/internal/control/ev_battery_priority_test.go index 18474dba7..d1ca72bc0 100644 --- a/go/internal/control/ev_battery_priority_test.go +++ b/go/internal/control/ev_battery_priority_test.go @@ -58,8 +58,12 @@ func TestIssue1868BatteryChargeYieldsBeforeTheCar(t *testing.T) { if target.TargetW > 3931.001 { t.Fatalf("%s left the car's relief in the battery: %+v", mode, target) } - // The import guard trims its own buffer as well (dispatch.go). - if mode == ModeCharge && target.TargetW < 3600 { + // Charge mode asks for a raise. No phase reaches the 15.5 A + // line, so only the hour's limit binds: the guard cuts the + // 69 W overage and half the margin (172.5 W) to 3758.5 W, + // and the car's headroom then takes the same 69 W again + // (3689.5 W). + if mode == ModeCharge && target.TargetW < 3689 { t.Fatalf("small overage needlessly stopped battery charging: %+v", target) } } diff --git a/go/internal/control/fuse_battery_phase_direction_test.go b/go/internal/control/fuse_battery_phase_direction_test.go index 2e740b1f8..ac217b759 100644 --- a/go/internal/control/fuse_battery_phase_direction_test.go +++ b/go/internal/control/fuse_battery_phase_direction_test.go @@ -2,6 +2,7 @@ package control import ( "encoding/json" + "fmt" "math" "testing" "time" @@ -11,7 +12,7 @@ import ( // The battery fuse paths read each phase with its direction and count the // batteries' own move. 16 A fuse, 230 V, 3 phases; the working limit is -// 15 A. +// the fuse less safety_margin_a (fuseLineA). func phaseDirectionStore(t *testing.T, gridW, batW float64, data map[string]any) *telemetry.Store { t.Helper() @@ -101,8 +102,9 @@ func TestFuseGuardChargeBalancesExportingAndImportingPhases(t *testing.T) { } // The relief counts the battery's own share of the phase it reads. A -// battery that follows its order keeps L1 at the working limit on every -// tick instead of returning to 0 W when the overage stops showing. +// battery that follows its order keeps L1 at the working limit, 15.5 A on +// a 0.5 A margin, on every tick instead of returning to 0 W when the +// overage stops showing. func TestPerPhaseFuseReliefHoldsWhileOverloadPersists(t *testing.T) { st := phaseDirectionState(0.5) st.Mode = ModeIdle @@ -138,9 +140,10 @@ func TestPerPhaseFuseReliefHoldsWhileOverloadPersists(t *testing.T) { batW = w now = now.Add(5 * time.Second) } + line := st.fuseLineA() for i := 1; i < len(l1); i++ { - if l1[i] > 15 { - t.Fatalf("tick %d: L1 %.1f A over the 15 A working limit while the overload persists; targets %v, L1 %v", i, l1[i], targets, l1) + if l1[i] > line || l1[i] < line-0.05 { + t.Fatalf("tick %d: L1 %.1f A, want the %.1f A working limit while the overload persists; targets %v, L1 %v", i, l1[i], line, targets, l1) } } } @@ -176,14 +179,15 @@ func chargeLoop(t *testing.T, ticks int, dispatch func(*telemetry.Store, *State) } // The fuse hold caps the request before the guard reads the phases, so the -// hold's cut is not taken off again. The charge settles at 1380 W with L1 -// at 15 A instead of switching between 1380 W and 0 W. +// hold's cut is not taken off again. On a 0 A margin the charge holds +// 2070 W with L1 at the 16 A rating on every repeat, instead of switching +// between 2070 W and 0 W. func TestFuseGuardHeldChargeHoldsSteady(t *testing.T) { assertSteady := func(name string, targets, l1 []float64) { t.Helper() - for i := 1; i < len(targets); i++ { - if math.Abs(targets[i]-targets[i-1]) > 50 || l1[i] > 15.01 { - t.Fatalf("%s: tick %d charge %v -> %v W; targets %v, L1 %v", name, i, targets[i-1], targets[i], targets, l1) + for i := range targets { + if math.Abs(targets[i]-2070) > 1 || (i > 0 && math.Abs(l1[i]-16) > 0.01) { + t.Fatalf("%s: tick %d charge %v W, L1 %v A; want 2070 W and 16 A; targets %v, L1 %v", name, i, targets[i], l1[i], targets, l1) } } } @@ -219,3 +223,69 @@ func TestPhaseReliefSkipsOfflineMeter(t *testing.T) { t.Fatalf("offline meter: relief %.0f/%.0f W, want none", imp, exp) } } + +// The battery's working limit on each phase is L = In − safety_margin_a, +// in both directions, with no floor under the margin. A phase at L needs no +// relief, 0.1 A past it needs exactly 0.1 A, and a target that lands a +// phase exactly at L passes the guard unchanged. +func TestBatteryFuseLineProperty(t *testing.T) { + const v = 230.0 + for _, in := range []float64{16, 20, 25, 35} { + for _, phases := range []int{1, 3} { + for _, margin := range []float64{0, 0.5, 1.2} { + for _, dir := range []float64{1, -1} { // 1 import, -1 export + name := fmt.Sprintf("%gA/%dp/margin%g/dir%+g", in, phases, margin, dir) + st := NewState(0, 50, "meter") + st.SiteFuseAmps, st.SiteFuseVoltage, st.SiteFusePhases, st.SiteFuseSafetyA = in, v, phases, margin + st.DriverLimits = map[string]PowerLimits{"bat": {MaxChargeW: 50000, MaxDischargeW: 50000}} + line := in - margin + if got := st.fuseLineA(); got != line { + t.Fatalf("%s: fuseLineA %.2f A, want %.2f A", name, got, line) + } + perA := v * float64(phases) + fuseMaxW := in * perA + // store reads the worst phase at worstA and 2 A on the + // others, all flowing in dir, with phase power. + store := func(worstA float64) *telemetry.Store { + amps := []float64{worstA, 2, 2}[:phases] + data := map[string]any{} + var totalW float64 + for i, a := range amps { + w := dir * a * v + data[fmt.Sprintf("l%d_a", i+1)] = a + data[fmt.Sprintf("l%d_w", i+1)] = w + totalW += w + } + return phaseDirectionStore(t, totalW, 0, data) + } + relief := func(worstA float64) (float64, float64) { + s := store(worstA) + meter := s.Get("meter", telemetry.DerMeter) + return phaseFuseReliefW(livePhaseSample(s, "meter", meter), st, 0) + } + + if imp, exp := relief(line); imp != 0 || exp != 0 { + t.Errorf("%s: phase at the %.1f A line: relief %.1f/%.1f W, want none", name, line, imp, exp) + } + + imp, exp := relief(line + 0.1) + want := 0.1 * perA + gotW, otherW := imp, exp + if dir < 0 { + gotW, otherW = exp, imp + } + if math.Abs(gotW-want) > 1 || otherW != 0 { + t.Errorf("%s: 0.1 A past the line: relief %.1f/%.1f W, want %.1f W on the flowing side", name, imp, exp, want) + } + + // The battery moves the phase from line − 2 A to the line. + targetW := dir * 2 * perA + out := applyFuseGuard([]DispatchTarget{{Driver: "bat", TargetW: targetW}}, store(line-2), st, fuseMaxW) + if out[0].Clamped || math.Abs(out[0].TargetW-targetW) > 1e-6 || !st.FuseHoldUntil.IsZero() { + t.Errorf("%s: target %.0f W that lands at the %.1f A line: guard gave %+v, hold until %v", name, targetW, line, out[0], st.FuseHoldUntil) + } + } + } + } + } +} diff --git a/go/internal/control/fuse_saver_test.go b/go/internal/control/fuse_saver_test.go index 205e25505..006bc35e7 100644 --- a/go/internal/control/fuse_saver_test.go +++ b/go/internal/control/fuse_saver_test.go @@ -302,17 +302,16 @@ func TestPerPhaseClampScalesChargingOnImbalance(t *testing.T) { // 11000 W) is under the 11040 W fuse, so the legacy aggregate // branch wouldn't fire. But the 4000 W charge adds 4000 / 690 = // 5.8 A to each phase, which takes L1 from 13 A to 18.8 A, over the - // 15 A working limit (16 A fuse less 1 A) — only the per-phase - // clamp can catch it. + // 16 A fuse (margin 0) — only the per-phase clamp can catch it. store, state, _ := setupPerPhase(7000, 13, 12, 8, 0.6, 10000) targets := []DispatchTarget{{Driver: "bat", TargetW: 4000}} guarded := applyFuseGuard(targets, store, state, 11040) if !guarded[0].Clamped { t.Errorf("Clamped flag must mark per-phase response") } - // L1 has (15 − 13) × 690 = 1380 W of room for a balanced-3Φ - // charge. Charge 4000 → 1380 W. - expected := 1380.0 + // L1 has (16 − 13) × 690 = 2070 W of room for a balanced-3Φ + // charge. Charge 4000 → 2070 W. + expected := 2070.0 if math.Abs(guarded[0].TargetW-expected) > 1 { t.Errorf("charge after per-phase clamp = %.0f W, want %.0f W", guarded[0].TargetW, expected) @@ -333,9 +332,9 @@ func TestPerPhaseClampFiresFuseSaverFromIdle(t *testing.T) { if out[0].TargetW >= 0 { t.Errorf("expected discharge target, got %.0f W", out[0].TargetW) } - // L1 is (18 − 15) A over the working limit: 3 × 690 = 2070 W of - // discharge from idle. - expected := -2070.0 + // Same math as the charging test: 460 W × 3 = 1380 W. From idle + // (target 0), full discharge of 1380 W. + expected := -1380.0 if math.Abs(out[0].TargetW-expected) > 1 { t.Errorf("forced discharge = %.0f W, want %.0f W", out[0].TargetW, expected) } @@ -365,14 +364,13 @@ func TestPerPhaseClampDisabledWhenSiteFuseAmpsZero(t *testing.T) { // huge imbalance, per-phase × 3 dominates. func TestPerPhaseClampDominatesAggregateWhenLarger(t *testing.T) { // Aggregate over by 500 W (predicted = 11540 vs 11040). But L1 is - // at 22 A → over the 15 A working limit by 7 A × 230 = 1610 W - // per-phase × 3 = 4830 W. + // at 22 A → over by 6 A × 230 = 1380 W per-phase × 3 = 4140 W. store, state, caps := setupPerPhase(11540, 22, 14, 8, 0.6, 10000) out := fuseSaverFromLivePower(store, state, caps, 11040) if out == nil { t.Fatalf("expected discharge, got nil") } - expected := -4830.0 + expected := -4140.0 if math.Abs(out[0].TargetW-expected) > 1 { t.Errorf("forced discharge = %.0f W, want %.0f W (per-phase × 3)", out[0].TargetW, expected) @@ -387,10 +385,10 @@ func TestPerPhaseClampDominatesAggregateWhenLarger(t *testing.T) { func TestPerPhaseClampFiresOnExportImbalance(t *testing.T) { // Aggregate gridW = -7000 W (heavy export). Phases (magnitude, no // phase power, so they take the total's direction): L2 = 18 A (over - // the 15 A working limit), L1 = 12, L3 = 8. Per-phase overage = - // (18 − 15) × 230 × 3 = 2070 W of discharge to shrink. Battery is - // currently discharging −5000 W; the target reduces magnitude to - // bring L2 back under the limit. + // the 16 A fuse), L1 = 12, L3 = 8. Per-phase + // overage = (18 − 16) × 230 × 3 = 1380 W of discharge to shrink. + // Battery is currently discharging −5000 W; the target reduces + // magnitude to bring L2 back under fuse. store, state, _ := setupPerPhase(-7000, 12, 18, 8, 0.6, 10000) // Set the live battery reading so applyFuseGuard's "predicted" // reflects the current discharge state. @@ -403,8 +401,8 @@ func TestPerPhaseClampFiresOnExportImbalance(t *testing.T) { if !guarded[0].Clamped { t.Errorf("export-side per-phase overage must clamp the discharge target") } - // New discharge magnitude: 5000 − 2070 = 2930 W → target = −2930 W. - expected := -2930.0 + // New discharge magnitude: 5000 − 1380 = 3620 W → target = −3620 W. + expected := -3620.0 if math.Abs(guarded[0].TargetW-expected) > 1 { t.Errorf("discharge after export-side per-phase clamp = %.0f W, want %.0f W", guarded[0].TargetW, expected) @@ -462,32 +460,31 @@ func TestForceFuseDischargeIgnoresExportSidePerPhase(t *testing.T) { // inverter's own per-phase limiter trips first and causes a flap). // Regression for PR #219 — the bug class motivating the safety margin. func TestPerPhaseClampHonorsSafetyMargin(t *testing.T) { - // Phases (10, 7, 5). MaxAmps = 16, SafetyA = 2.0 → effective - // threshold = 14 A, below the 1 A working margin's 15 A. The - // 4000 W charge adds 5.8 A per phase, so L1 reaches 15.8 A: over - // 14 A by 1.8 A, 1240 W of charge to shrink. Without the margin it - // would be 550 W. + // Phases (10, 7, 5). MaxAmps = 16, SafetyA = 1.0 → effective + // threshold = 15 A. The 4000 W charge adds 5.8 A per phase, so L1 + // reaches 15.8 A: over 15 A by 0.8 A, 550 W of charge to shrink. + // Without the margin it is under the 16 A fuse and nothing clamps. store, state, _ := setupPerPhase(5000, 10, 7, 5, 0.6, 10000) - state.SiteFuseSafetyA = 2.0 + state.SiteFuseSafetyA = 1.0 state.SiteFusePhases = 3 targets := []DispatchTarget{{Driver: "bat", TargetW: 4000}} guarded := applyFuseGuard(targets, store, state, 11040) if !guarded[0].Clamped { t.Errorf("safety margin should pull the threshold under L1") } - // Aggregate effFuseW = 11040 − 2×230×3 = 9660. Predicted = + // Aggregate effFuseW = 11040 − 1.0×230×3 = 10350. Predicted = // 5000 + 4000 − 0 = 9000 → no aggregate overage. Per-phase wins. - // Buffer = half-margin = 0.5×2×230×3 = 690 W (post-fix headroom). - // Charge 4000 − 1240 − 690 = 2070. - expected := 2070.0 + // Buffer = half-margin = 0.5×1×230×3 = 345 W (post-fix headroom). + // Charge 4000 − 550 − 345 = 3105. + expected := 3105.0 if math.Abs(guarded[0].TargetW-expected) > 1 { t.Errorf("charge after safety-margin clamp = %.0f W, want %.0f W", guarded[0].TargetW, expected) } } -// SafetyMarginA = 0 keeps the 1 A working margin the car uses (every -// existing per-phase test relies on it by leaving the field unset). +// SafetyMarginA = 0 works to the fuse rating (every existing per-phase +// test relies on it by leaving the field unset). func TestPerPhaseClampSafetyMarginZeroIsBackCompat(t *testing.T) { store, state, _ := setupPerPhase(7000, 13, 12, 8, 0.6, 10000) state.SiteFuseSafetyA = 0 @@ -495,9 +492,9 @@ func TestPerPhaseClampSafetyMarginZeroIsBackCompat(t *testing.T) { targets := []DispatchTarget{{Driver: "bat", TargetW: 4000}} guarded := applyFuseGuard(targets, store, state, 11040) // Same math as TestPerPhaseClampScalesChargingOnImbalance. - expected := 1380.0 + expected := 2070.0 if math.Abs(guarded[0].TargetW-expected) > 1 { - t.Errorf("safety_margin_a=0 must keep the 1 A working margin: got %.0f W, want %.0f W", + t.Errorf("safety_margin_a=0 must work to the 16 A rating: got %.0f W, want %.0f W", guarded[0].TargetW, expected) } } @@ -509,9 +506,9 @@ func TestPerPhaseClampSafetyMarginZeroIsBackCompat(t *testing.T) { // phase count, and on a 1Φ site the aggregate meter and the single // phase are the same wire — relief there is 1 × the overage, not 3 ×. // -// A 1Φ site at 24 A on a 16 A fuse (1 A margin ⇒ 15 A threshold, -// 230 V): fuse budget 3680 W, aggregate ceiling 3450 W, meter at -// 5520 W. Worst-phase overage = (24 − 15) × 230 = 2070 W, which on +// A 1Φ site at 24 A on a 16 A fuse (0.5 A margin ⇒ 15.5 A threshold, +// 230 V): fuse budget 3680 W, aggregate ceiling 3565 W, meter at +// 5520 W. Worst-phase overage = (24 − 15.5) × 230 = 1955 W, which on // this site is also exactly the aggregate overage — the two numbers // must agree when there is only one phase. @@ -519,21 +516,21 @@ func TestPerPhaseClampSafetyMarginZeroIsBackCompat(t *testing.T) { // once, and leaves the meter on the import side of zero. func TestPerPhaseReliefMatchesSinglePhaseSiteOnImport(t *testing.T) { store, state, caps := setupPerPhaseSite(1, 230, 5520, 24, 0, 0, 0.6, 10000) - state.SiteFuseSafetyA = 1 + state.SiteFuseSafetyA = 0.5 fuseMaxW := 16 * 230.0 * 1 out := fuseSaverFromLivePower(store, state, caps, fuseMaxW) if out == nil { t.Fatalf("1Φ site at 24 A on a 16 A fuse: expected a forced discharge") } - expected := -2070.0 + expected := -1955.0 if math.Abs(out[0].TargetW-expected) > 1 { t.Fatalf("forced discharge = %.0f W, want %.0f W (overage × 1 phase, "+ "not × 3)", out[0].TargetW, expected) } // The site has one phase, so the post-dispatch meter is that - // phase. Demanding 3 × 2070 W would have driven 5520 W of import - // to 690 W of export: relief the site never needed, pushing the + // phase. Demanding 3 × 1955 W would have driven 5520 W of import + // to 345 W of export: relief the site never needed, pushing the // same breaker up the other way. if postGridW := 5520 + out[0].TargetW; postGridW < 0 { t.Errorf("post-dispatch grid = %.0f W: relief overshot through zero "+ @@ -548,7 +545,7 @@ func TestPerPhaseReliefMatchesSinglePhaseSiteOnExport(t *testing.T) { // Meter magnitudes mirror the import case: 5520 W out, 24 A on the // one phase. Pixii-style signed per-phase amps, so L1 reads −24. store, state, _ := setupPerPhaseSite(1, 230, -5520, -24, 0, 0, 0.6, 10000) - state.SiteFuseSafetyA = 1 + state.SiteFuseSafetyA = 0.5 fuseMaxW := 16 * 230.0 * 1 // The battery is already discharging what the meter shows, and the @@ -561,10 +558,10 @@ func TestPerPhaseReliefMatchesSinglePhaseSiteOnExport(t *testing.T) { if !guarded[0].Clamped { t.Fatalf("export-side per-phase overage must clamp the discharge target") } - // Discharge 5000 − overage 2070 − buffer (half the 230 W margin) - // = 2815 W. Demanding 2070 × 3 leaves nothing: the discharge is + // Discharge 5000 − overage 1955 − buffer (half the 115 W margin) + // = 2987.5 W. Demanding 1955 × 3 leaves nothing: the discharge is // zeroed and the site swings to 520 W of import. - expected := -2815.0 + expected := -2987.5 if math.Abs(guarded[0].TargetW-expected) > 1 { t.Errorf("discharge after 1Φ export clamp = %.1f W, want %.1f W", guarded[0].TargetW, expected) @@ -606,9 +603,9 @@ func TestPerPhaseClampUsesConfiguredVoltage(t *testing.T) { if !guarded[0].Clamped { t.Fatalf("a 4000 W charge on L1 at 13 A on a 16 A fuse must clamp") } - // L1 has (15 − 13) A of room below the working limit: 2 × 240 × 3 - // = 1440 W of charge. At the old hardcoded 230 V it would be 1380. - expected := 1440.0 + // L1 has (16 − 13) A of room below the fuse: 3 × 240 × 3 = 2160 W + // of charge. At the old hardcoded 230 V it would be 2070. + expected := 2160.0 if math.Abs(guarded[0].TargetW-expected) > 1 { t.Errorf("charge after per-phase clamp on a 240 V site = %.0f W, "+ "want %.0f W", guarded[0].TargetW, expected) @@ -915,10 +912,9 @@ func TestDeadbandExitDefendsPerPhaseBreaker(t *testing.T) { t.Fatalf("L1 at 18 A on a 16 A fuse inside the aggregate deadband: " + "expected a forced discharge, got no targets") } - // Per-phase overage = (18 − 15) × 230 = 690 W over the working - // limit on the worst phase, × 3 under the balanced-3Φ assumption - // = 2070 W from idle. - expected := -2070.0 + // Per-phase overage = (18 − 16) × 230 = 460 W on the worst phase, + // × 3 under the balanced-3Φ assumption = 1380 W from idle. + expected := -1380.0 if math.Abs(out[0].TargetW-expected) > 1 { t.Errorf("forced discharge = %.0f W, want %.0f W", out[0].TargetW, expected) } @@ -934,7 +930,7 @@ func TestDeadbandExitPerPhaseReliefPreservesLiveDischarge(t *testing.T) { const ( liveBatteryW = -5000.0 liveWorstA = 18.0 - fuseA = 15.0 // 16 A fuse less the 1 A working margin + fuseA = 16.0 phases = 3.0 voltage = 230.0 ) @@ -971,7 +967,7 @@ func TestDeadbandExitPerPhaseReliefStartsFromLiveCharge(t *testing.T) { const ( liveBatteryW = 5000.0 liveWorstA = 18.0 - fuseA = 15.0 // 16 A fuse less the 1 A working margin + fuseA = 16.0 phases = 3.0 voltage = 230.0 ) @@ -1382,7 +1378,7 @@ func TestDeadbandExitUsesOnlyRemainingPerPhaseReliefAfterChargeCap(t *testing.T) liveBatteryW = 5000.0 maxChargeW = 4500.0 liveWorstA = 18.0 - fuseA = 15.0 // 16 A fuse less the 1 A working margin + fuseA = 16.0 phaseReliefW = (liveWorstA - fuseA) * 230 * 3 ) store, state, caps := setupPerPhase(0, liveWorstA, 4, 4, 0.6, 10000) From c31176020022c7d6cd0bae000b7cba8363cca0f8 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 18:32:51 +0100 Subject: [PATCH 17/68] test(control): re-record golden records at the fuse less safety_margin_a Replayed from stored inputs; only records whose dispatch changed against the parent branch were replaced. Co-Authored-By: Claude Opus 5.5 --- .../golden/early_exit_protections.json | 66 +++++----- .../control/testdata/golden/seeded_fuse.json | 118 +++++++++--------- .../control/testdata/golden/slew_limiter.json | 10 +- .../testdata/golden/targeted_invariants.json | 12 +- 4 files changed, 103 insertions(+), 103 deletions(-) diff --git a/go/internal/control/testdata/golden/early_exit_protections.json b/go/internal/control/testdata/golden/early_exit_protections.json index 6344bac47..e1147757e 100644 --- a/go/internal/control/testdata/golden/early_exit_protections.json +++ b/go/internal/control/testdata/golden/early_exit_protections.json @@ -1,7 +1,7 @@ { "family": "early_exit_protections", "generated_by": "FTW_GOLDEN_DUMP=1 go test ./internal/control/ -run TestGoldenDump", - "ftw_commit": "83c2b24ccdb730278a9c4e6ef778bab5f9499167", + "ftw_commit": "68c5b6125898bb9da70728b8921259c87e96171d", "record_count": 21, "records": [ { @@ -519,7 +519,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -2070, + "target_w": -1380, "clamped": true } ], @@ -536,7 +536,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 690, + "per_phase_overage_w": 460, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -544,9 +544,9 @@ }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -2070, + "battery_target_sum_w": -1380, "raw_grid_w": 0, - "projected_grid_w": -2070 + "projected_grid_w": -1380 } }, { @@ -775,7 +775,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 2530, + "per_phase_overage_w": 2300, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -841,7 +841,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1840, + "target_w": -1610, "clamped": true } ], @@ -858,17 +858,17 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1840, + "per_phase_overage_w": 1610, "effective_import_ceiling_w": 5750, "effective_export_ceiling_w": 5750, - "import_ceiling_binding": false, + "import_ceiling_binding": true, "export_ceiling_binding": false }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -1840, + "battery_target_sum_w": -1610, "raw_grid_w": 7360, - "projected_grid_w": 5520 + "projected_grid_w": 5750 } }, { @@ -1009,7 +1009,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -2760, + "target_w": -2070, "clamped": true } ], @@ -1026,7 +1026,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 920, + "per_phase_overage_w": 690, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -1034,9 +1034,9 @@ }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -2760, + "battery_target_sum_w": -2070, "raw_grid_w": 20, - "projected_grid_w": -2740 + "projected_grid_w": -2050 } }, { @@ -1170,7 +1170,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -3450, + "target_w": -2760, "clamped": true } ], @@ -1187,7 +1187,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1150, + "per_phase_overage_w": 920, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -1195,9 +1195,9 @@ }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -3450, + "battery_target_sum_w": -2760, "raw_grid_w": 1000, - "projected_grid_w": -2450 + "projected_grid_w": -1760 } }, { @@ -1253,7 +1253,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1380, + "target_w": -1150, "clamped": true } ], @@ -1270,17 +1270,17 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1380, + "per_phase_overage_w": 1150, "effective_import_ceiling_w": 5750, "effective_export_ceiling_w": 5750, - "import_ceiling_binding": false, + "import_ceiling_binding": true, "export_ceiling_binding": false }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -1380, + "battery_target_sum_w": -1150, "raw_grid_w": 6900, - "projected_grid_w": 5520 + "projected_grid_w": 5750 } }, { @@ -1495,7 +1495,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -4140, + "target_w": -3450, "clamped": true } ], @@ -1512,7 +1512,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1380, + "per_phase_overage_w": 1150, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -1520,9 +1520,9 @@ }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -4140, + "battery_target_sum_w": -3450, "raw_grid_w": 2000, - "projected_grid_w": -2140 + "projected_grid_w": -1450 } }, { @@ -1578,7 +1578,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1840, + "target_w": -1610, "clamped": true } ], @@ -1595,17 +1595,17 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1840, + "per_phase_overage_w": 1610, "effective_import_ceiling_w": 5750, "effective_export_ceiling_w": 5750, - "import_ceiling_binding": false, + "import_ceiling_binding": true, "export_ceiling_binding": false }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -1840, + "battery_target_sum_w": -1610, "raw_grid_w": 7360, - "projected_grid_w": 5520 + "projected_grid_w": 5750 } }, { diff --git a/go/internal/control/testdata/golden/seeded_fuse.json b/go/internal/control/testdata/golden/seeded_fuse.json index 9862640e4..41ca9a8c4 100644 --- a/go/internal/control/testdata/golden/seeded_fuse.json +++ b/go/internal/control/testdata/golden/seeded_fuse.json @@ -1,7 +1,7 @@ { "family": "seeded_fuse", "generated_by": "FTW_GOLDEN_DUMP=1 go test ./internal/control/ -run TestGoldenDump", - "ftw_commit": "83c2b24ccdb730278a9c4e6ef778bab5f9499167", + "ftw_commit": "a11706b4", "record_count": 80, "records": [ { @@ -210,7 +210,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1425.9999999999998, + "per_phase_overage_w": 1195.9999999999998, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -577,7 +577,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 483.0000000000003, + "per_phase_overage_w": 253.00000000000034, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -660,7 +660,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1265, + "per_phase_overage_w": 1035, "effective_import_ceiling_w": 4300, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -754,12 +754,12 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -0, + "target_w": 0, "clamped": true }, { "driver": "sungrow", - "target_w": -0, + "target_w": 0, "clamped": true } ], @@ -777,7 +777,7 @@ "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 414.00000000000017, + "per_phase_overage_w": 184.00000000000017, "effective_import_ceiling_w": 17250, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -894,7 +894,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 460, + "per_phase_overage_w": 345, "effective_import_ceiling_w": 10695, "effective_export_ceiling_w": 10695, "import_ceiling_binding": false, @@ -1076,7 +1076,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 713.0000000000003, + "per_phase_overage_w": 598.0000000000003, "effective_import_ceiling_w": 16905, "effective_export_ceiling_w": 16905, "import_ceiling_binding": true, @@ -1703,7 +1703,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1586.9999999999998, + "per_phase_overage_w": 1356.9999999999998, "effective_import_ceiling_w": 5311, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -1875,17 +1875,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -323.0000000000004, + "target_w": -208.0000000000004, "clamped": true }, { "driver": "pixii", - "target_w": -323.0000000000004, + "target_w": -208.0000000000004, "clamped": true }, { "driver": "sungrow", - "target_w": -323.0000000000004, + "target_w": -208.0000000000004, "clamped": true } ], @@ -1904,7 +1904,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 759.0000000000001, + "per_phase_overage_w": 644.0000000000001, "effective_import_ceiling_w": 16905, "effective_export_ceiling_w": 16905, "import_ceiling_binding": false, @@ -1912,9 +1912,9 @@ }, "site_totals": { "battery_current_w": 1308, - "battery_target_sum_w": -969.0000000000011, + "battery_target_sum_w": -624.0000000000011, "raw_grid_w": 13971, - "projected_grid_w": 11693.999999999998 + "projected_grid_w": 12038.999999999998 } }, { @@ -2282,7 +2282,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 735.9999999999999, + "per_phase_overage_w": 505.99999999999983, "effective_import_ceiling_w": 6067, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -2492,7 +2492,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1310.9999999999998, + "per_phase_overage_w": 1195.9999999999998, "effective_import_ceiling_w": 10695, "effective_export_ceiling_w": 10695, "import_ceiling_binding": false, @@ -3354,7 +3354,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 436.9999999999997, + "per_phase_overage_w": 206.99999999999966, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -3553,17 +3553,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -0, + "target_w": 0, "clamped": true }, { "driver": "pixii", - "target_w": -0, + "target_w": 0, "clamped": true }, { "driver": "sungrow", - "target_w": -0, + "target_w": 0, "clamped": true } ], @@ -3582,7 +3582,7 @@ "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 505.99999999999983, + "per_phase_overage_w": 275.99999999999983, "effective_import_ceiling_w": 5718, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -3801,7 +3801,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1449.0000000000002, + "per_phase_overage_w": 1334.0000000000002, "effective_import_ceiling_w": 10695, "effective_export_ceiling_w": 10695, "import_ceiling_binding": false, @@ -4789,7 +4789,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -0, + "target_w": -265.9999999999991, "clamped": true } ], @@ -4797,16 +4797,16 @@ "clamped_drivers": [ "ferroamp" ], - "all_targets_zero_clamped": true, + "all_targets_zero_clamped": false, "plan_sign_intent": -1, - "plan_sign_floor_zeroed": true, + "plan_sign_floor_zeroed": false, "plan_stale": false, "fuse_saturated": false, "fuse_ev_max_w": 0, "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, - "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1380, + "fuse_hold_max_discharge_w": 265.9999999999991, + "per_phase_overage_w": 1150, "effective_import_ceiling_w": 4886, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -4814,9 +4814,9 @@ }, "site_totals": { "battery_current_w": -3716, - "battery_target_sum_w": 0, + "battery_target_sum_w": -265.9999999999991, "raw_grid_w": -15970, - "projected_grid_w": -12254 + "projected_grid_w": -12520 } }, { @@ -4904,7 +4904,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1518.0000000000002, + "per_phase_overage_w": 1288.0000000000002, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -6275,7 +6275,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 414.00000000000017, + "per_phase_overage_w": 184.00000000000017, "effective_import_ceiling_w": 7497, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -6496,17 +6496,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1335.8333333333328, + "target_w": -1450.8333333333328, "clamped": true }, { "driver": "pixii", - "target_w": -1335.8333333333328, + "target_w": -1450.8333333333328, "clamped": true }, { "driver": "sungrow", - "target_w": -1335.8333333333328, + "target_w": -1450.8333333333328, "clamped": true } ], @@ -6524,8 +6524,8 @@ "fuse_ev_max_w": 0, "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, - "fuse_hold_max_discharge_w": 4007.499999999998, - "per_phase_overage_w": 23.000000000000327, + "fuse_hold_max_discharge_w": 4352.499999999998, + "per_phase_overage_w": 0, "effective_import_ceiling_w": 16905, "effective_export_ceiling_w": 16905, "import_ceiling_binding": false, @@ -6533,9 +6533,9 @@ }, "site_totals": { "battery_current_w": -4249, - "battery_target_sum_w": -4007.499999999998, + "battery_target_sum_w": -4352.499999999998, "raw_grid_w": -14716, - "projected_grid_w": -14474.499999999998 + "projected_grid_w": -14819.499999999998 } }, { @@ -6608,7 +6608,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1380, + "per_phase_overage_w": 1150, "effective_import_ceiling_w": 6574, "effective_export_ceiling_w": 7458, "import_ceiling_binding": false, @@ -6879,12 +6879,12 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1592, + "target_w": -1720.5, "clamped": true }, { "driver": "sungrow", - "target_w": -1592, + "target_w": -1720.5, "clamped": true } ], @@ -6901,18 +6901,18 @@ "fuse_ev_max_w": 0, "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, - "fuse_hold_max_discharge_w": 3184, - "per_phase_overage_w": 45.99999999999984, + "fuse_hold_max_discharge_w": 3441, + "per_phase_overage_w": 0, "effective_import_ceiling_w": 17250, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, - "export_ceiling_binding": false + "export_ceiling_binding": true }, "site_totals": { "battery_current_w": -3322, - "battery_target_sum_w": -3184, + "battery_target_sum_w": -3441, "raw_grid_w": -17131, - "projected_grid_w": -16993 + "projected_grid_w": -17250 } }, { @@ -7082,7 +7082,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1195.9999999999998, + "per_phase_overage_w": 1080.9999999999998, "effective_import_ceiling_w": 10695, "effective_export_ceiling_w": 10695, "import_ceiling_binding": false, @@ -7148,7 +7148,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1139.0000000000014, + "target_w": -449.0000000000014, "clamped": true } ], @@ -7165,7 +7165,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1288.0000000000002, + "per_phase_overage_w": 1058.0000000000002, "effective_import_ceiling_w": 17250, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -7173,9 +7173,9 @@ }, "site_totals": { "battery_current_w": 2725, - "battery_target_sum_w": -1139.0000000000014, + "battery_target_sum_w": -449.0000000000014, "raw_grid_w": 14295, - "projected_grid_w": 10430.999999999998 + "projected_grid_w": 11120.999999999998 } }, { @@ -7458,7 +7458,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 414.00000000000017, + "per_phase_overage_w": 184.00000000000017, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -7666,12 +7666,12 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -0, + "target_w": 0, "clamped": true }, { "driver": "sungrow", - "target_w": -0, + "target_w": 0, "clamped": true } ], @@ -7689,7 +7689,7 @@ "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 460, + "per_phase_overage_w": 345, "effective_import_ceiling_w": 16905, "effective_export_ceiling_w": 16905, "import_ceiling_binding": false, @@ -8012,7 +8012,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 206.99999999999966, + "per_phase_overage_w": 0, "effective_import_ceiling_w": 4624, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, @@ -8147,7 +8147,7 @@ "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1403.0000000000002, + "per_phase_overage_w": 1173.0000000000002, "effective_import_ceiling_w": 17250, "effective_export_ceiling_w": 17250, "import_ceiling_binding": false, diff --git a/go/internal/control/testdata/golden/slew_limiter.json b/go/internal/control/testdata/golden/slew_limiter.json index 0c5efa302..21eec3639 100644 --- a/go/internal/control/testdata/golden/slew_limiter.json +++ b/go/internal/control/testdata/golden/slew_limiter.json @@ -1,7 +1,7 @@ { "family": "slew_limiter", "generated_by": "FTW_GOLDEN_DUMP=1 go test ./internal/control/ -run TestGoldenDump", - "ftw_commit": "83c2b24ccdb730278a9c4e6ef778bab5f9499167", + "ftw_commit": "a11706b4", "record_count": 127, "records": [ { @@ -3225,7 +3225,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1949.9999999999995, + "target_w": -1259.9999999999995, "clamped": true } ], @@ -3242,7 +3242,7 @@ "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1150, + "per_phase_overage_w": 920, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -3250,9 +3250,9 @@ }, "site_totals": { "battery_current_w": 1500, - "battery_target_sum_w": -1949.9999999999995, + "battery_target_sum_w": -1259.9999999999995, "raw_grid_w": 1000, - "projected_grid_w": -2449.9999999999995 + "projected_grid_w": -1759.9999999999995 } }, { diff --git a/go/internal/control/testdata/golden/targeted_invariants.json b/go/internal/control/testdata/golden/targeted_invariants.json index b44f92069..a96ef8fc6 100644 --- a/go/internal/control/testdata/golden/targeted_invariants.json +++ b/go/internal/control/testdata/golden/targeted_invariants.json @@ -1,7 +1,7 @@ { "family": "targeted_invariants", "generated_by": "FTW_GOLDEN_DUMP=1 go test ./internal/control/ -run TestGoldenDump", - "ftw_commit": "83c2b24ccdb730278a9c4e6ef778bab5f9499167", + "ftw_commit": "a11706b4", "record_count": 18, "records": [ { @@ -683,7 +683,7 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -3450, + "target_w": -2760, "clamped": true } ], @@ -700,7 +700,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1150, + "per_phase_overage_w": 920, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, @@ -708,9 +708,9 @@ }, "site_totals": { "battery_current_w": 0, - "battery_target_sum_w": -3450, + "battery_target_sum_w": -2760, "raw_grid_w": 1000, - "projected_grid_w": -2450 + "projected_grid_w": -1760 } }, { @@ -799,7 +799,7 @@ "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 1150, + "per_phase_overage_w": 920, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, From 3efb3ed708af8dcd0ddcbd1f06119052ee05039a Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 18:43:57 +0100 Subject: [PATCH 18/68] fix(control): battery fuse cut lands on the line, not half a margin below applyFuseGuard cut a battery charge or discharge by the overage plus half of safety_margin_a. The guard now predicts from the held targets and keeps its 30 s hold, so the extra cut only parked the phase below the line the user set. Cut by the overage only. Co-Authored-By: Claude Opus 5.5 --- .changeset/c-battery-fuse-no-buffer.md | 5 + go/internal/control/dispatch.go | 23 ++--- .../control/ev_battery_priority_test.go | 4 +- go/internal/control/fuse_saver_test.go | 95 ++++++++++++------- .../control/testdata/golden/seeded_fuse.json | 24 ++--- 5 files changed, 88 insertions(+), 63 deletions(-) create mode 100644 .changeset/c-battery-fuse-no-buffer.md diff --git a/.changeset/c-battery-fuse-no-buffer.md b/.changeset/c-battery-fuse-no-buffer.md new file mode 100644 index 000000000..aab7466e0 --- /dev/null +++ b/.changeset/c-battery-fuse-no-buffer.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +When the home battery cuts its charge or discharge to protect a fuse phase, it now cuts only by the overage, so the phase lands on the fuse less `safety_margin_a`. It used to cut half the safety margin more on top. Sites without a safety margin see no change. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 9089ffe5f..3c41fd910 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -3693,20 +3693,11 @@ func applyFuseGuard(targets []DispatchTarget, store *telemetry.Store, state *Sta return out } - // Headroom buffer: shrink targets by `overage + half the configured - // safety margin` so post-clamp the grid sits *below* the threshold - // instead of riding right at it. Without this, the next dispatch - // tick lets the planner re-ramp into the threshold and the system - // oscillates at the boundary — the operator's "safety margin" - // becomes the active steady-state instead of a buffer below it. - // - // Half-margin chosen so the post-clamp phase amps still cluster - // near the threshold (operator wants the fuse used efficiently) - // but with enough buffer to absorb load fluctuations and per-phase - // imbalance on the next tick. Operators wanting tighter or looser - // buffer just adjust safety_margin_a. - buffer := state.fuseSafetyMarginW() * 0.5 - + // Cut by the overage only, so the grid lands on the line, not below it. + // The prediction from the held targets above keeps the next dispatch + // from re-ramping through the line, and the 30 s hold below keeps the + // planner at the clamped total. A site that wants headroom sets + // safety_margin_a, which lowers the line itself. switch { case importOverage > 0: // Too much import (aggregate or per-phase) → shrink charging. @@ -3723,7 +3714,7 @@ func applyFuseGuard(targets []DispatchTarget, store *telemetry.Store, state *Sta // still flip idle batteries to discharge. return out } - newTotal := totalCharge - importOverage - buffer + newTotal := totalCharge - importOverage if newTotal < 0 { newTotal = 0 } @@ -3751,7 +3742,7 @@ func applyFuseGuard(targets []DispatchTarget, store *telemetry.Store, state *Sta // is the lever in that scenario (annotateCurtailment). return out } - newTotal := totalDischarge - exportOverage - buffer + newTotal := totalDischarge - exportOverage if newTotal < 0 { newTotal = 0 } diff --git a/go/internal/control/ev_battery_priority_test.go b/go/internal/control/ev_battery_priority_test.go index 582a67eee..bb9fa5947 100644 --- a/go/internal/control/ev_battery_priority_test.go +++ b/go/internal/control/ev_battery_priority_test.go @@ -48,8 +48,8 @@ func TestIssue1868BatteryChargeYieldsBeforeTheCar(t *testing.T) { t.Fatalf("%s left the car's relief in the battery: %+v", mode, target) } // Charge mode asks for a raise. The fuse guard caps it at L1's - // working limit less half the margin (3758.5 W), and the car's - // headroom then takes the same 69 W again. + // working limit (3931 W), and the car's headroom then takes the + // same 69 W again. if mode == ModeCharge && target.TargetW < 3600 { t.Fatalf("small overage needlessly stopped battery charging: %+v", target) } diff --git a/go/internal/control/fuse_saver_test.go b/go/internal/control/fuse_saver_test.go index 205e25505..c1475845a 100644 --- a/go/internal/control/fuse_saver_test.go +++ b/go/internal/control/fuse_saver_test.go @@ -477,9 +477,8 @@ func TestPerPhaseClampHonorsSafetyMargin(t *testing.T) { } // Aggregate effFuseW = 11040 − 2×230×3 = 9660. Predicted = // 5000 + 4000 − 0 = 9000 → no aggregate overage. Per-phase wins. - // Buffer = half-margin = 0.5×2×230×3 = 690 W (post-fix headroom). - // Charge 4000 − 1240 − 690 = 2070. - expected := 2070.0 + // Charge 4000 − 1240 = 2760, which puts L1 on 14 A. + expected := 2760.0 if math.Abs(guarded[0].TargetW-expected) > 1 { t.Errorf("charge after safety-margin clamp = %.0f W, want %.0f W", guarded[0].TargetW, expected) @@ -561,10 +560,10 @@ func TestPerPhaseReliefMatchesSinglePhaseSiteOnExport(t *testing.T) { if !guarded[0].Clamped { t.Fatalf("export-side per-phase overage must clamp the discharge target") } - // Discharge 5000 − overage 2070 − buffer (half the 230 W margin) - // = 2815 W. Demanding 2070 × 3 leaves nothing: the discharge is - // zeroed and the site swings to 520 W of import. - expected := -2815.0 + // Discharge 5000 − overage 2070 = 2930 W. Demanding 2070 × 3 leaves + // nothing: the discharge is zeroed and the site swings to 520 W of + // import. + expected := -2930.0 if math.Abs(guarded[0].TargetW-expected) > 1 { t.Errorf("discharge after 1Φ export clamp = %.1f W, want %.1f W", guarded[0].TargetW, expected) @@ -656,33 +655,63 @@ func TestFuseSaverFiresInIdleMode(t *testing.T) { } } -// Operator-report 2026-04-30: with safety_margin_a=1 (threshold = 15 A) -// the system stabilised with phase amps oscillating between 15.0 and -// 15.8 A — fuse guard reactively scaled targets just enough to clear -// the trip, then the planner re-ramped, then it re-tripped. Half-margin -// buffer keeps post-clamp aggregate below the threshold by an explicit -// margin so the next tick has room before re-tripping. -func TestFuseGuardLeavesHeadroomBelowThreshold(t *testing.T) { - store, state, _ := setupPerPhase(-7000, 12, 18, 8, 0.6, 10000) - state.SiteFuseSafetyA = 1.0 - state.SiteFusePhases = 3 - soc := 0.6 - store.Update("bat", telemetry.DerBattery, -5000, &soc, nil) - store.DriverHealthMut("bat").RecordSuccess() +// A guard cut lands the worst phase on the line, In − safety_margin_a, and +// stays there. It takes no extra headroom below the line: the prediction +// from held targets and the 30 s hold keep the next dispatch from +// re-ramping through it. 16 A fuse, margin 1.2 A, so the line is 14.8 A. +// The battery follows each order; the loop runs 60 ticks of 5 s, so the +// hold expires and fires again several times. +func TestFuseGuardCutLandsOnTheLine(t *testing.T) { + const marginA, lineA = 1.2, 14.8 + for _, tc := range []struct { + name string + houseA [3]float64 // signed: + import, − export + requestW float64 + roomA float64 // worst phase's room to the line before the battery moves + }{ + {"charge on import", [3]float64{13, 7, 5}, 4000, lineA - 13}, + {"discharge on export", [3]float64{-8, -12, -5}, -5000, lineA - 12}, + } { + t.Run(tc.name, func(t *testing.T) { + st := NewState(0, 50, "meter") + st.SiteFuseAmps, st.SiteFuseVoltage, st.SiteFusePhases, st.SiteFuseSafetyA = 16, 230, 3, marginA + st.DriverLimits = map[string]PowerLimits{"bat": {MaxChargeW: 10000, MaxDischargeW: 10000}} + now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) + st.clock = func() time.Time { return now } + store := telemetry.NewStore() + wantW := math.Copysign(tc.roomA*690, tc.requestW) + batW := 0.0 + for tick := 0; tick < 60; tick++ { + a := tc.houseA + data := map[string]any{} + for i := range a { + a[i] += batW / 690 + data[fmt.Sprintf("l%d_a", i+1)] = a[i] + data[fmt.Sprintf("l%d_w", i+1)] = a[i] * 230 + } + raw, _ := json.Marshal(data) + store.Update("meter", telemetry.DerMeter, (a[0]+a[1]+a[2])*230, nil, raw) + store.DriverHealthMut("meter").RecordSuccess() + soc := 0.5 + store.Update("bat", telemetry.DerBattery, batW, &soc, nil) + store.DriverHealthMut("bat").RecordSuccess() + + worstA := 0.0 + for _, x := range a { + worstA = math.Max(worstA, math.Abs(x)) + } + if tick > 0 && math.Abs(worstA-lineA) > 0.01 { + t.Fatalf("tick %d: worst phase %.3f A, want %.1f A (the line, not below it)", tick, worstA, lineA) + } - out := applyFuseGuard( - []DispatchTarget{{Driver: "bat", TargetW: -5000}}, - store, state, 11040) - if !out[0].Clamped { - t.Fatalf("expected per-phase export clamp") - } - // perPhase = (18−15) × 230 × 3 = 2070 W - // half-margin buffer = 0.5 × 1A × 230V × 3p = 345 W - // totalDischarge = 5000 → newTotal = 5000 − 2070 − 345 = 2585 - expected := -2585.0 - if math.Abs(out[0].TargetW-expected) > 1 { - t.Errorf("post-clamp target = %.0f W, want %.0f W (overage + half-margin)", - out[0].TargetW, expected) + out := applyFuseGuard([]DispatchTarget{{Driver: "bat", TargetW: tc.requestW}}, store, st, 16*230*3) + if math.Abs(out[0].TargetW-wantW) > 1 { + t.Fatalf("tick %d: target %.1f W, want %.1f W (cut by the overage only)", tick, out[0].TargetW, wantW) + } + batW = out[0].TargetW + now = now.Add(5 * time.Second) + } + }) } } diff --git a/go/internal/control/testdata/golden/seeded_fuse.json b/go/internal/control/testdata/golden/seeded_fuse.json index 9862640e4..0464f7cbb 100644 --- a/go/internal/control/testdata/golden/seeded_fuse.json +++ b/go/internal/control/testdata/golden/seeded_fuse.json @@ -6496,17 +6496,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": -1335.8333333333328, + "target_w": -1393.3333333333328, "clamped": true }, { "driver": "pixii", - "target_w": -1335.8333333333328, + "target_w": -1393.3333333333328, "clamped": true }, { "driver": "sungrow", - "target_w": -1335.8333333333328, + "target_w": -1393.3333333333328, "clamped": true } ], @@ -6524,7 +6524,7 @@ "fuse_ev_max_w": 0, "fuse_hold_latched": true, "fuse_hold_max_charge_w": 0, - "fuse_hold_max_discharge_w": 4007.499999999998, + "fuse_hold_max_discharge_w": 4179.999999999998, "per_phase_overage_w": 23.000000000000327, "effective_import_ceiling_w": 16905, "effective_export_ceiling_w": 16905, @@ -6533,9 +6533,9 @@ }, "site_totals": { "battery_current_w": -4249, - "battery_target_sum_w": -4007.499999999998, + "battery_target_sum_w": -4179.999999999998, "raw_grid_w": -14716, - "projected_grid_w": -14474.499999999998 + "projected_grid_w": -14646.999999999998 } }, { @@ -7900,17 +7900,17 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": 4493.333333333333, + "target_w": 4608.333333333333, "clamped": true }, { "driver": "pixii", - "target_w": 4493.333333333333, + "target_w": 4608.333333333333, "clamped": true }, { "driver": "sungrow", - "target_w": 4493.333333333333, + "target_w": 4608.333333333333, "clamped": true } ], @@ -7927,7 +7927,7 @@ "fuse_saturated": false, "fuse_ev_max_w": 0, "fuse_hold_latched": true, - "fuse_hold_max_charge_w": 13480, + "fuse_hold_max_charge_w": 13825, "fuse_hold_max_discharge_w": 0, "per_phase_overage_w": 0, "effective_import_ceiling_w": 10350, @@ -7937,9 +7937,9 @@ }, "site_totals": { "battery_current_w": 853, - "battery_target_sum_w": 13480, + "battery_target_sum_w": 13825, "raw_grid_w": -7899, - "projected_grid_w": 4728 + "projected_grid_w": 5073 } }, { From f93b81fd0698c51d4b75f487ef57178409dd67c5 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 18:53:43 +0100 Subject: [PATCH 19/68] docs(changeset): name the limit the battery cut lands on The changeset said the phase lands on the fuse less safety_margin_a. On #1891 as it stands, the phase line is the fuse less max(1 A, safety_margin_a), so at the 0.5 A default a 16 A phase settles at 15 A, not 15.5 A. Say what this PR changes, cutting only by the overage, without naming a line that depends on step 4. Co-Authored-By: Claude Opus 5.5 --- .changeset/c-battery-fuse-no-buffer.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/c-battery-fuse-no-buffer.md b/.changeset/c-battery-fuse-no-buffer.md index aab7466e0..de59208a1 100644 --- a/.changeset/c-battery-fuse-no-buffer.md +++ b/.changeset/c-battery-fuse-no-buffer.md @@ -2,4 +2,4 @@ "ftw": patch --- -When the home battery cuts its charge or discharge to protect a fuse phase, it now cuts only by the overage, so the phase lands on the fuse less `safety_margin_a`. It used to cut half the safety margin more on top. Sites without a safety margin see no change. +When the home battery cuts its charge or discharge to protect the fuse, it now cuts only by the overage, so the grid settles on the limit instead of below it. It used to cut half of `safety_margin_a` more on top. Sites without a safety margin see no change. From fab8f6f030a232a032ac1ae53aaeae94f49cbfb3 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 19:05:16 +0100 Subject: [PATCH 20/68] fix(config): fuse safety_margin_a defaults to 0 Core now works to the fuse rating unless a site sets a margin. Every explicit safety_margin_a is kept. A stored value of exactly 0.5 A, the old default, adds one load-time notice and changes nothing. The peak-limit error names the margin only when it is above 0, and the settings field shows 0 with help that says the margin is opt-in. Co-Authored-By: Claude Opus 5.5 --- .changeset/d-fuse-margin-default-0.md | 5 ++ go/cmd/ftw/control_state.go | 5 +- go/cmd/ftw/main.go | 4 +- go/internal/config/config.go | 55 +++++++++++++--------- go/internal/config/config_test.go | 39 +++++++++++++-- go/internal/config/retired_control_test.go | 48 +++++++++++++++++++ go/internal/config/storage.go | 1 + go/internal/control/dispatch.go | 8 +++- go/internal/control/peak_limit_test.go | 21 ++++++++- go/internal/control/sitesim_test.go | 54 +++++++++++++-------- web/settings-shell.test.mjs | 17 ++++++- web/settings/tabs/control.js | 4 +- 12 files changed, 205 insertions(+), 56 deletions(-) create mode 100644 .changeset/d-fuse-margin-default-0.md diff --git a/.changeset/d-fuse-margin-default-0.md b/.changeset/d-fuse-margin-default-0.md new file mode 100644 index 000000000..e0e5fcd4a --- /dev/null +++ b/.changeset/d-fuse-margin-default-0.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +`fuse.safety_margin_a` now defaults to 0, so FTW works to the fuse rating unless you set a margin. A margin is opt-in, for an inverter whose own phase limiter trips at the rating. FTW keeps any margin you have saved. If yours is exactly 0.5 A, FTW's old default, the log says so once at startup; set 0 to work to the rating. diff --git a/go/cmd/ftw/control_state.go b/go/cmd/ftw/control_state.go index 89c03dad9..ff90c439d 100644 --- a/go/cmd/ftw/control_state.go +++ b/go/cmd/ftw/control_state.go @@ -31,9 +31,8 @@ func newControlStateFromConfig(cfg *config.Config) *control.State { ctrl.SiteFuseAmps = cfg.Fuse.MaxAmps ctrl.SiteFuseVoltage = cfg.Fuse.Voltage ctrl.SiteFusePhases = cfg.Fuse.Phases - // EffectiveSafetyMarginA distinguishes nil ("unset, use default") - // from explicit 0 ("operator chose to disable"). The earlier - // `<= 0 -> default` shortcut clobbered the disable case. + // EffectiveSafetyMarginA resolves nil to the default (0: work to the + // fuse rating) and keeps any explicit value, 0 included. ctrl.SiteFuseSafetyA = cfg.Fuse.EffectiveSafetyMarginA() // PV surplus absorber underlay (opt-in). cap == 0 keeps it off. ctrl.PVSurplusAbsorbSoCCap = cfg.Site.PVSurplusAbsorbSoCCap diff --git a/go/cmd/ftw/main.go b/go/cmd/ftw/main.go index 57e59b4df..f54b28457 100644 --- a/go/cmd/ftw/main.go +++ b/go/cmd/ftw/main.go @@ -1164,8 +1164,8 @@ func main() { ctrl.SiteFuseAmps = newCfg.Fuse.MaxAmps ctrl.SiteFuseVoltage = newCfg.Fuse.Voltage ctrl.SiteFusePhases = newCfg.Fuse.Phases - // Mirror the startup-path default semantics — nil → 0.5, - // explicit 0 → disabled. See EffectiveSafetyMarginA. + // Mirror the startup path: nil → 0 (work to the fuse rating), an + // explicit value wins. See EffectiveSafetyMarginA. ctrl.SiteFuseSafetyA = newCfg.Fuse.EffectiveSafetyMarginA() ctrl.MaxExportW = newCfg.Site.MaxExportW // Lowering the fuse can strand a peak limit that was legal when it diff --git a/go/internal/config/config.go b/go/internal/config/config.go index 731455fdc..75580b720 100644 --- a/go/internal/config/config.go +++ b/go/internal/config/config.go @@ -54,8 +54,9 @@ type Config struct { LoadWarnings []string `yaml:"-" json:"-"` LoadpointWarnings []string `yaml:"-" json:"-"` // Retired names settings of removed features that loading dropped so - // they cannot steer the site. Startup warns once for each; - // DropRetiredSettings deletes them from stored settings. + // they cannot steer the site, and stored values that match an old + // default. Startup warns once for each; DropRetiredSettings deletes the + // removed settings from stored settings and leaves the values alone. Retired []string `yaml:"-" json:"-"` // Used once at startup to end an old calendar's persisted away selection. RetiredCalendarEnabled bool `yaml:"-" json:"-"` @@ -868,11 +869,16 @@ type Site struct { MaxExportW float64 `yaml:"max_export_w,omitempty" json:"max_export_w,omitempty"` } -// DefaultFuseSafetyMarginA is the fall-back per-phase amp headroom -// applied when fuse.safety_margin_a is unset (nil) in the YAML. -// Single source of truth — main.go routes through Fuse.Effective- -// SafetyMarginA() rather than re-declaring it. -const DefaultFuseSafetyMarginA = 0.5 +// DefaultFuseSafetyMarginA is the per-phase margin applied when +// fuse.safety_margin_a is unset (nil). Core works to the fuse rating by +// default; a margin is opt-in. Single source of truth: main.go routes +// through Fuse.EffectiveSafetyMarginA() rather than re-declaring it. +const DefaultFuseSafetyMarginA = 0.0 + +// oldDefaultFuseSafetyMarginA was the default until FTW worked to the fuse +// rating. A stored value equal to it may be the settings form's old prefill +// rather than a choice, so loading names it once and keeps it. +const oldDefaultFuseSafetyMarginA = 0.5 // Fuse describes the shared breaker limit used by the fuse guard. type Fuse struct { @@ -880,15 +886,11 @@ type Fuse struct { Phases int `yaml:"phases" json:"phases"` Voltage float64 `yaml:"voltage" json:"voltage"` - // SafetyMarginA reserves headroom (per-phase amps) below MaxAmps - // inside the dispatch fuse guard. Pointer so we can distinguish - // "unset" (nil → DefaultFuseSafetyMarginA) from "explicitly - // disabled" (non-nil 0.0). Inverters often have their own per- - // phase current protection that trips before the breaker; without - // a margin the dispatch can ride right up to MaxAmps and the - // inverter cuts to 0 W in one tick, then dispatch ramps back up — - // visible as a flap. 0.5 A × 230 V × 3 phases ≈ 345 W of aggregate - // headroom. + // SafetyMarginA is an opt-in per-phase margin below MaxAmps: each + // phase's working limit is MaxAmps − SafetyMarginA. Pointer so an + // explicit value, 0 included, always wins over the default (nil → + // DefaultFuseSafetyMarginA, which is 0). Set it for an inverter whose + // own per-phase limiter trips at the rating and cuts to 0 W. SafetyMarginA *float64 `yaml:"safety_margin_a,omitempty" json:"safety_margin_a,omitempty"` } @@ -897,10 +899,9 @@ func (f Fuse) MaxPowerW() float64 { return f.MaxAmps * f.Voltage * float64(f.Phases) } -// EffectiveSafetyMarginA returns the per-phase amp headroom to apply, -// resolving nil ("unset → use default") vs an explicit value (including -// 0.0 to disable the margin entirely). Single read site so the default -// can never drift across consumers. +// EffectiveSafetyMarginA returns the per-phase margin to apply: the +// explicit value when set, otherwise DefaultFuseSafetyMarginA. Single read +// site so the default can never drift across consumers. func (f Fuse) EffectiveSafetyMarginA() float64 { if f.SafetyMarginA == nil { return DefaultFuseSafetyMarginA @@ -908,6 +909,17 @@ func (f Fuse) EffectiveSafetyMarginA() float64 { return *f.SafetyMarginA } +// noteOldFuseMargin adds one notice when fuse.safety_margin_a holds FTW's +// old default. The value stays: from April to September 2026 the settings +// form saved its 0.5 A prefill on any save, but a value saved later is the +// user's choice, and the stored document cannot tell the two apart. +func (c *Config) noteOldFuseMargin() { + if m := c.Fuse.SafetyMarginA; m != nil && *m == oldDefaultFuseSafetyMarginA { + c.Retired = append(c.Retired, + "fuse.safety_margin_a is 0.5 A, FTW's old default. FTW now works to the fuse rating. Set 0 to use it.") + } +} + // Driver is one driver entry. Each driver is a Lua script loaded by // the driver host at startup (or on hot-reload via the file watcher). type Driver struct { @@ -1491,6 +1503,7 @@ func Parse(data []byte, baseDir string) (*Config, error) { var retiredControl retiredControlSettings _ = doc.Decode(&retiredControl) c.applyRetiredControl(retiredControl) + c.noteOldFuseMargin() // An omitted app_link section follows the new default. An explicit YAML // null was a valid opt-out before that default changed, so retain it as an // explicit disabled section instead of letting applyDefaults turn it on. @@ -2060,7 +2073,7 @@ func (c *Config) Validate() error { } // safety_margin_a must be in [0, max_amps) when explicitly set. // Negative would *raise* the per-phase threshold above the breaker - // rating (defeating the guard); >= max_amps zeroes the headroom + // rating (defeating the guard); >= max_amps leaves no working limit // and silently disables the per-phase clamp — both are real safety // holes if reached through a typo'd config. nil (unset) is OK and // resolves to DefaultFuseSafetyMarginA at the consumer. diff --git a/go/internal/config/config_test.go b/go/internal/config/config_test.go index 86bb85cb9..d628ee75a 100644 --- a/go/internal/config/config_test.go +++ b/go/internal/config/config_test.go @@ -1260,12 +1260,43 @@ func TestNotificationsMaskSecrets(t *testing.T) { } } +// An unset margin works to the fuse rating: the default is 0 and a margin +// is opt-in (owner rule, 27 Oct 2026). func TestFuseSafetyMarginNilUsesDefault(t *testing.T) { - // Field omitted in YAML → nil pointer → default 0.5 A. f := Fuse{MaxAmps: 16, Voltage: 230, Phases: 3} - if got := f.EffectiveSafetyMarginA(); got != DefaultFuseSafetyMarginA { - t.Errorf("nil margin: got %v, want %v (DefaultFuseSafetyMarginA)", - got, DefaultFuseSafetyMarginA) + if got := f.EffectiveSafetyMarginA(); got != 0 || DefaultFuseSafetyMarginA != 0 { + t.Errorf("nil margin: got %v (default %v), want 0", got, DefaultFuseSafetyMarginA) + } +} + +// Every explicit margin is kept. Exactly 0.5 A was the old default, which +// the settings form once saved on any save, so loading adds one notice for +// it and changes nothing. +func TestFuseSafetyMarginLoadKeepsExplicitValues(t *testing.T) { + for _, tc := range []struct { + line string + want float64 + wantNotice bool + }{ + {"", 0, false}, + {" safety_margin_a: 0\n", 0, false}, + {" safety_margin_a: 0.5\n", 0.5, true}, + {" safety_margin_a: 0.4\n", 0.4, false}, + {" safety_margin_a: 1.2\n", 1.2, false}, + } { + yaml := strings.Replace(minimalYAML, " max_amps: 16\n", " max_amps: 16\n"+tc.line, 1) + c, err := Parse([]byte(yaml), "/tmp") + if err != nil { + t.Fatalf("%q: %v", tc.line, err) + } + if got := c.Fuse.EffectiveSafetyMarginA(); got != tc.want { + t.Errorf("%q: margin %v, want %v", tc.line, got, tc.want) + } + notice := len(c.Retired) == 1 && strings.Contains(c.Retired[0], "old default") && + strings.Contains(c.Retired[0], "Set 0") + if notice != tc.wantNotice || (!tc.wantNotice && len(c.Retired) != 0) { + t.Errorf("%q: notices %q, want the old-default notice: %v", tc.line, c.Retired, tc.wantNotice) + } } } diff --git a/go/internal/config/retired_control_test.go b/go/internal/config/retired_control_test.go index 0eb9f03f8..ca0897e03 100644 --- a/go/internal/config/retired_control_test.go +++ b/go/internal/config/retired_control_test.go @@ -132,3 +132,51 @@ func TestStoredRetiredControlSettingsMigrateAndAreDeleted(t *testing.T) { t.Fatalf("second DropRetiredSettings = %v, %v; want nothing", removed, err) } } + +// A stored 0.5 A margin keeps steering the site and stays in state.db; the +// notice comes from loading it, so dropping retired settings leaves it alone. +func TestStoredOldDefaultFuseMarginIsKeptWithANotice(t *testing.T) { + dir := t.TempDir() + path, database := filepath.Join(dir, "config.yaml"), filepath.Join(dir, "state.db") + yaml := strings.Replace(minimalYAML, " max_amps: 16\n", " max_amps: 16\n safety_margin_a: 0.5\n", 1) + if err := os.WriteFile(path, []byte(yaml), 0600); err != nil { + t.Fatal(err) + } + cfg, err := Load(path) + if err != nil { + t.Fatal(err) + } + st, err := state.Open(database) + if err != nil { + t.Fatal(err) + } + defer st.Close() + if _, err := InitializeStorage(path, database, cfg, st); err != nil { + t.Fatal(err) + } + for range 2 { + loaded, err := Load(path) + if err != nil { + t.Fatal(err) + } + if loaded.ConfigDatabase == "" { + t.Fatal("loaded from the YAML file, not from stored settings") + } + if got := loaded.Fuse.EffectiveSafetyMarginA(); got != 0.5 { + t.Fatalf("stored margin = %v, want 0.5", got) + } + if len(loaded.Retired) != 1 || !strings.Contains(loaded.Retired[0], "safety_margin_a is 0.5 A") { + t.Fatalf("notices = %q, want one naming the old 0.5 A default", loaded.Retired) + } + if removed, err := DropRetiredSettings(st, path, loaded); err != nil || len(removed) != 0 { + t.Fatalf("DropRetiredSettings = %v, %v; the margin is a setting, not a retired one", removed, err) + } + } + after, _, err := st.Configuration() + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(after.Document), `"safety_margin_a":0.5`) { + t.Fatalf("stored settings lost the margin: %s", after.Document) + } +} diff --git a/go/internal/config/storage.go b/go/internal/config/storage.go index 501b03310..58a7655d5 100644 --- a/go/internal/config/storage.go +++ b/go/internal/config/storage.go @@ -64,6 +64,7 @@ func decodeStored(c state.Configuration, database, baseDir string) (*Config, err } _ = json.Unmarshal(c.Document, &legacyControl) cfg.applyRetiredControl(legacyControl.Config) + cfg.noteOldFuseMargin() // This is the same typed config that was validated on save. Do not apply new // defaults during a storage-only reload: nil, false and zero stay distinct. if err := cfg.Validate(); err != nil { diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 3c41fd910..7f23fc497 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -1083,11 +1083,15 @@ func (s *State) SetPeakLimit(w float64) error { return fmt.Errorf("peak_limit_w must be ≥ 0, got %.0f W", w) } if ceiling := s.peakLimitCeilingW(); ceiling > 0 && w > ceiling { + margin := "" + if s.SiteFuseSafetyA > 0 { + margin = fmt.Sprintf(", less a %.1f A safety margin", s.SiteFuseSafetyA) + } return fmt.Errorf( "peak_limit_w %.0f W is above the site's import ceiling %.0f W "+ - "(fuse %.0f A × %.0f V × %d phases, less a %.1f A safety margin) "+ + "(fuse %.0f A × %.0f V × %d phases%s) "+ "— a peak limit above the fuse can never bind", - w, ceiling, s.SiteFuseAmps, s.SiteFuseVoltage, s.SiteFusePhases, s.SiteFuseSafetyA) + w, ceiling, s.SiteFuseAmps, s.SiteFuseVoltage, s.SiteFusePhases, margin) } s.PeakLimitW = w return nil diff --git a/go/internal/control/peak_limit_test.go b/go/internal/control/peak_limit_test.go index d8a7be220..b1c7f7861 100644 --- a/go/internal/control/peak_limit_test.go +++ b/go/internal/control/peak_limit_test.go @@ -7,8 +7,8 @@ import ( ) // SetPeakLimit is the one place the peak-shaving threshold is validated -// against the site's fuse. A 16 A / 230 V / 3-phase site is 11040 W; the -// default 0.5 A safety margin costs 345 W, so the highest limit that can +// against the site's fuse. A 16 A / 230 V / 3-phase site is 11040 W; an +// opt-in 0.5 A safety margin costs 345 W, so the highest limit that can // still be the first thing to bind is 10695 W. func fusedState() *State { st := NewState(0, 50, "ferroamp") @@ -63,6 +63,23 @@ func TestSetPeakLimitRejectsValueInsideTheSafetyMargin(t *testing.T) { } } +// The message names the margin only when the site has one. With the +// default 0 the ceiling is the fuse itself. +func TestSetPeakLimitMessageNamesOnlyARealMargin(t *testing.T) { + st := fusedState() + if err := st.SetPeakLimit(20000); err == nil || !strings.Contains(err.Error(), "less a 0.5 A safety margin") { + t.Fatalf("with a 0.5 A margin the message must name it, got %v", err) + } + st.SiteFuseSafetyA = 0 + err := st.SetPeakLimit(20000) + if err == nil || strings.Contains(err.Error(), "margin") || !strings.Contains(err.Error(), "11040 W") { + t.Fatalf("with no margin the message must give the fuse as the ceiling and no margin, got %v", err) + } + if err := st.SetPeakLimit(11040); err != nil { + t.Fatalf("with no margin the fuse itself is the ceiling, got %v", err) + } +} + // Zero is a real threshold in peak shaving — "correct everything above // 0 W of import" — not the zero-means-disabled convention that // PeakImportCeilingW and MaxExportW use. Dispatch has always read it that diff --git a/go/internal/control/sitesim_test.go b/go/internal/control/sitesim_test.go index 6022cd157..b37c46a1e 100644 --- a/go/internal/control/sitesim_test.go +++ b/go/internal/control/sitesim_test.go @@ -83,7 +83,7 @@ func (s *simSite) boot() { s.state = NewState(0, 42, "meter") s.state.clock = func() time.Time { return s.p.Now } s.state.SlewRateW, s.state.MinDispatchIntervalS = 3000, 2 - s.state.SiteFuseAmps, s.state.SiteFuseVoltage, s.state.SiteFusePhases, s.state.SiteFuseSafetyA = s.p.Fuse.RatingA, s.p.Voltage, 3, .5 + s.state.SiteFuseAmps, s.state.SiteFuseVoltage, s.state.SiteFusePhases, s.state.SiteFuseSafetyA = s.p.Fuse.RatingA, s.p.Voltage, 3, 0 if b := s.p.Battery; b != nil { s.state.DriverLimits = map[string]PowerLimits{"battery": {MaxChargeW: b.MaxChargeW, MaxDischargeW: b.MaxDischargeW}} } @@ -604,6 +604,24 @@ func simScenarios() []simScenario { c.AllowedStepsW = append(steps, c.AllowedStepsW[1:]...) } } + replay1761 := simScenario{name: "#1761 replay", run: 20 * time.Minute, + plant: func(p *sitesim.Plant) { + p.HouseW, p.Car.MaxW = houseA(1, 1, 1), 4200 + p.Battery = &sitesim.Battery{Phases: 3, MaxChargeW: 9400, MaxDischargeW: 9400, CapacityWh: 20000, SoC: .3, Latency: 3 * time.Second} + p.Events = []sitesim.Event{{At: 10 * time.Minute, Do: func(p *sitesim.Plant) { p.Car.MaxW = 11040 }}} + }, + lp: func(c *loadpoint.Config) { + c.MaxChargeW, c.AllowedStepsW = 10350, c.AllowedStepsW[:len(c.AllowedStepsW)-1] + }, + setup: planBatteryCharge(9400), + expect: []simExpect{{9*time.Minute + 50*time.Second, func(s *simSite) error { + p := s.p + offerW := p.EVSE.OfferA * p.Voltage * float64(p.EVSE.OfferPhases) + if offerW != 10350 || math.Abs(p.EVSE.DrawW-4200) > 50 || math.Abs(p.Battery.W-9400) > 200 { + return fmt.Errorf("not the #1761 state before the car takes its offer: offer %.0f W, car %.0f W, battery %.0f W", offerW, p.EVSE.DrawW, p.Battery.W) + } + return nil + }}}} return []simScenario{ {name: "export start", run: 5 * time.Minute, plant: func(p *sitesim.Plant) { p.HouseW, p.PVW = houseA(2, 2, 2), -22*690 }}, @@ -622,24 +640,8 @@ func simScenarios() []simScenario { plant: slowCharger(time.Minute)}, {name: "slow cloud charger 120 s", run: 15 * time.Minute, plant: slowCharger(2 * time.Minute)}, - {name: "#1761 replay", run: 20 * time.Minute, - plant: func(p *sitesim.Plant) { - p.HouseW, p.Car.MaxW = houseA(1, 1, 1), 4200 - p.Battery = &sitesim.Battery{Phases: 3, MaxChargeW: 9400, MaxDischargeW: 9400, CapacityWh: 20000, SoC: .3, Latency: 3 * time.Second} - p.Events = []sitesim.Event{{At: 10 * time.Minute, Do: func(p *sitesim.Plant) { p.Car.MaxW = 11040 }}} - }, - lp: func(c *loadpoint.Config) { - c.MaxChargeW, c.AllowedStepsW = 10350, c.AllowedStepsW[:len(c.AllowedStepsW)-1] - }, - setup: planBatteryCharge(9400), - expect: []simExpect{{9*time.Minute + 50*time.Second, func(s *simSite) error { - p := s.p - offerW := p.EVSE.OfferA * p.Voltage * float64(p.EVSE.OfferPhases) - if offerW != 10350 || math.Abs(p.EVSE.DrawW-4200) > 50 || math.Abs(p.Battery.W-9400) > 200 { - return fmt.Errorf("not the #1761 state before the car takes its offer: offer %.0f W, car %.0f W, battery %.0f W", offerW, p.EVSE.DrawW, p.Battery.W) - } - return nil - }}}}, + replay1761, + withSafetyMarginA(replay1761, .5), {name: "meter every 30 s after a cut", known: "a meter slower than evSettle makes every reading a gap, ev_fuse_budget.go:141", run: 10 * time.Minute, plant: func(p *sitesim.Plant) { p.HouseW = houseA(3, 3, 3) @@ -761,6 +763,20 @@ func simScenarios() []simScenario { } } +// withSafetyMarginA runs sc with an opt-in fuse.safety_margin_a. The +// default is 0; a site that keeps the old 0.5 A must still pass. +func withSafetyMarginA(sc simScenario, a float64) simScenario { + setup := sc.setup + sc.name = fmt.Sprintf("%s, safety_margin_a %.1f A", sc.name, a) + sc.setup = func(s *simSite) { + if setup != nil { + setup(s) + } + s.state.SiteFuseSafetyA = a + } + return sc +} + // runSimScenario runs sc from start and returns the site, with the first // broken invariant or expectation in failure. func runSimScenario(sc simScenario, start time.Time) *simSite { diff --git a/web/settings-shell.test.mjs b/web/settings-shell.test.mjs index 6f940efbc..5c625044b 100644 --- a/web/settings-shell.test.mjs +++ b/web/settings-shell.test.mjs @@ -522,7 +522,7 @@ async function electricalShell(fuse) { const rig = loadShell(structuredClone(original)); rig.loadTab('./settings/tabs/control.js'); const fields = {}; - for (const [key, fallback] of Object.entries({ phases: 3, voltage: 230, max_amps: 16, safety_margin_a: 0.5 })) { + for (const [key, fallback] of Object.entries({ phases: 3, voltage: 230, max_amps: 16, safety_margin_a: 0 })) { fields[key] = Object.assign(stubElement(), { dataset: { path: 'fuse.' + key }, type: 'number', value: String(fuse[key] ?? fallback), }); @@ -563,6 +563,21 @@ describe('electricity connection settings', () => { }); } + it('shows an unset safety margin as 0 and offers a margin as opt-in', () => { + const rig = loadShell({}); + rig.loadTab('./settings/tabs/control.js'); + const config = { site: {}, fuse: { max_amps: 16 } }; + const getByPath = (obj, path, dflt) => path.split('.').reduce((node, key) => node?.[key], obj) ?? dflt; + const html = rig.tabs.control.render({ + config, getByPath, escHtml: s => String(s ?? ''), + help: text => '?', + field: (label, path, type, dflt) => '', + }); + assert.match(html, /data-path="fuse\.safety_margin_a" value="0"/); + assert.match(html, /Optional\. Amps to keep below the fuse rating[^"]*0 works to the rating\./); + assert.doesNotMatch(html, /Defaults to 0\.5 A/); + }); + it('only replaces custom voltage when the user picks a standard connection', async () => { const rig = await electricalShell({ phases: 2, voltage: 240, max_amps: 20, safety_margin_a: 0 }); rig.connection.value = '3'; diff --git a/web/settings/tabs/control.js b/web/settings/tabs/control.js index e5611b15d..40d9a7f4b 100644 --- a/web/settings/tabs/control.js +++ b/web/settings/tabs/control.js @@ -96,8 +96,8 @@ '
' + field("Phase-to-neutral voltage (V)", "fuse.voltage", "number", 230) + '
' + - decimalField("Safety margin (A)", "fuse.safety_margin_a", 0.5, - "Headroom below max amps so the inverter's own per-phase limiter doesn't trip first. Defaults to 0.5 A.", + decimalField("Safety margin (A)", "fuse.safety_margin_a", 0, + "Optional. Amps to keep below the fuse rating, for an inverter whose own phase limiter trips at the rating. 0 works to the rating.", "0.1") + ''; }, From 94f19b3edf2617981e699464f697fe1426145b16 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 19:22:17 +0100 Subject: [PATCH 21/68] docs(changeset): say what the default change moves on its own The changeset said FTW works to the fuse rating unless a site sets a margin. On this PR's base every per-phase line still sits 1 A under the rating; that holds only once #1910 and the step-4 amendment of #1891 land. The changeset now names what this PR changes: the default, and the whole-site import and export limits. Co-Authored-By: Claude Opus 5.5 --- .changeset/d-fuse-margin-default-0.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/d-fuse-margin-default-0.md b/.changeset/d-fuse-margin-default-0.md index e0e5fcd4a..3a82a6eb7 100644 --- a/.changeset/d-fuse-margin-default-0.md +++ b/.changeset/d-fuse-margin-default-0.md @@ -2,4 +2,4 @@ "ftw": patch --- -`fuse.safety_margin_a` now defaults to 0, so FTW works to the fuse rating unless you set a margin. A margin is opt-in, for an inverter whose own phase limiter trips at the rating. FTW keeps any margin you have saved. If yours is exactly 0.5 A, FTW's old default, the log says so once at startup; set 0 to work to the rating. +`fuse.safety_margin_a` now defaults to 0. On a site with no saved margin, the limits FTW puts on the site's total import and export rise to the fuse rating, 0.5 A per phase higher than before. A margin is opt-in, for an inverter whose own phase limiter trips at the rating. FTW keeps any margin you have saved. If yours is exactly 0.5 A, FTW's old default, the log says so once at startup; set 0 to drop it. From 8a7c2bed2100904b4717875ed95d28b0b3cda99a Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 19:45:24 +0100 Subject: [PATCH 22/68] test(control): relief stays at the line after a PV drop (C3, seed 207533) On a 16 A fuse with no margin the battery holds 3 kW of discharge with L1 at 14.4 A; PV drops 1280 W and L1 reads 16.3 A. The relief must bring L1 to 16 A and keep it there while the reading sits at the line with the battery at its relief power. Without phaseFuseReliefW's own-move count the relief flips between -3214 W and -3005 W on every tick and L1 crosses the rating 13 times; with it, L1 crosses once. Co-Authored-By: Claude Opus 5.5 --- .../fuse_battery_phase_direction_test.go | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/go/internal/control/fuse_battery_phase_direction_test.go b/go/internal/control/fuse_battery_phase_direction_test.go index ac217b759..5845c7acf 100644 --- a/go/internal/control/fuse_battery_phase_direction_test.go +++ b/go/internal/control/fuse_battery_phase_direction_test.go @@ -289,3 +289,71 @@ func TestBatteryFuseLineProperty(t *testing.T) { } } } + +// C3, rig seed 207533, on a 16 A fuse with no margin: the battery holds a +// 3 kW discharge with L1 at 14.4 A, then PV drops 1280 W and L1 reads +// 16.3 A. The relief brings L1 to the line. On the next ticks the reading +// sits at the line with the battery at its relief power, and the relief +// stays: L1 crosses the rating once, on the PV step, and never again while +// PV is low. Each tick the battery reaches the order it was sent the tick +// before, and the meter reads it there. +func TestFuseReliefStaysAtTheLineAfterPVDrop(t *testing.T) { + st := phaseDirectionState(0) + now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) + st.clock = func() time.Time { return now } + st.SetBatteryManualHold(BatteryManualHold{PowerW: -3005, ExpiresAt: now.Add(time.Hour)}) + + store := telemetry.NewStore() + load := [3]float64{23.44, 11.04, 11.54} // house and car, A import per phase + pvW, batW := -3200.0, -3005.0 + line := st.fuseLineA() + var targets, l1 []float64 + for tick := 0; tick < 40; tick++ { + switch tick { + case 5: + pvW = -1920 + case 30: + pvW = -3200 + } + var a [3]float64 + data := map[string]any{} + var totalW float64 + for i := range a { + a[i] = load[i] + (pvW+batW)/690 + data[fmt.Sprintf("l%d_a", i+1)] = math.Abs(a[i]) + data[fmt.Sprintf("l%d_w", i+1)] = a[i] * 230 + totalW += a[i] * 230 + } + raw, _ := json.Marshal(data) + store.Update("meter", telemetry.DerMeter, totalW, nil, raw) + store.DriverHealthMut("meter").RecordSuccess() + soc := 0.6 + store.Update("bat", telemetry.DerBattery, batW, &soc, nil) + store.DriverHealthMut("bat").RecordSuccess() + + for _, o := range ComputeDispatch(store, st, map[string]float64{"bat": 15200}, 16*230*3) { + if o.Driver == "bat" { + batW = o.TargetW + } + } + targets = append(targets, math.Round(batW)) + l1 = append(l1, math.Round(a[0]*100)/100) + now = now.Add(5 * time.Second) + } + crossings := 0 + for i := range l1 { + if l1[i] > line+0.01 && (i == 0 || l1[i-1] <= line+0.01) { + crossings++ + } + if i > 5 && i < 30 && (l1[i] > line+0.01 || l1[i] < line-0.05) { + t.Errorf("tick %d: L1 %.2f A, want the %.1f A line while PV is low", i, l1[i], line) + } + } + if crossings != 1 { + t.Errorf("L1 crossed the %.1f A line %d times, want once (the PV step)", line, crossings) + } + if t.Failed() { + t.Logf("targets %v", targets) + t.Logf("L1 %v", l1) + } +} From 66e1caf50fe59408a239e5758a2f221d0ec56862 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 19:47:13 +0100 Subject: [PATCH 23/68] test(site): judge random runs by rig items R2-R7 of the 27 Oct triage The random judge called eight nightly seeds on master 83c2b24c wrong in ways the triage traced to the judge, not to Core: - R2: a stretch over the fuse took only the windows open at its first sample. Every window that opens inside it while it is still allowed now extends it, a Core restart included (207530, 207539). - R3: the battery counted as the 2 s lever while its inverter was offline or had no spare power. It is the lever only while it runs, is above its floor and its spare power covers the overage; otherwise the charger, at max(2, command_response_s) (207530, 207534, 207539). - R4: a car that starts on the charger's own default, or on an order still on its way, is a step FTW did not take, answered by the charger from draw start + max(2, command_response_s) + 5 s. A stretch is FTW's own only after FTW's last change to the car's order was a rise, or its battery order moved toward import (207532, 207534, 207537). - R5 (owner rule): between the fuse and 1.2 x the fuse a phase counts only once Core's 60 s I2 heat is over the fuse too; above 1.2 x at once (207536). r3 and r5a take the same heat budget (#1888 review). - R6: idle seconds with room under Charge now are counted from when the room appears and may last evRestartDwell + command + startup + a tick (+ 2 s meter and tick + 3 s). The count starts again on a Charge now that changes the request, on each FTW cut and when Core answers after a restart. Only meter and charger faults excuse the car. - R7: the floor judges FTW's own orders (status.dispatch), not the inverter register, against max(inverter floor, planner soc_min) with no +0.5 %. TestJudge now also judges the random seeds a results directory holds, from each run's plan.json, so a nightly run can be judged again. Co-Authored-By: Claude Opus 5.5 --- go/test/site/README.md | 6 +- go/test/site/evaluate_test.go | 74 ++++- go/test/site/random_test.go | 398 +++++++++++++++++++++---- go/test/site/random_unit_test.go | 276 +++++++++++++++++ go/test/site/rig_test.go | 21 +- go/test/site/rig_unit_test.go | 46 ++- go/test/site/scenarios_p0_unit_test.go | 40 +++ go/test/site/verdicts_test.go | 14 +- 8 files changed, 787 insertions(+), 88 deletions(-) create mode 100644 go/test/site/random_unit_test.go diff --git a/go/test/site/README.md b/go/test/site/README.md index b1a75ca3c..57f763c31 100644 --- a/go/test/site/README.md +++ b/go/test/site/README.md @@ -37,7 +37,7 @@ make siterig-judge DIR=/tmp/ftw-site-123 # judge a recorded run again | `FTW_SITE_DEVSIM_SRC` | a device-simulator checkout at the pinned commit; without it the test clones the pin into the user cache | | `FTW_SITE_FTW_BIN`, `FTW_SITE_DEVSIM_BIN` | prebuilt binaries | | `FTW_SITE_CATALOG` | the fault catalog, for `TestCatalogCoverage` | -| `FTW_SITE_JUDGE` | a results directory: `TestJudge` judges its runs again with the criteria as they are now, and rewrites their `result.json` and the summary | +| `FTW_SITE_JUDGE` | a results directory: `TestJudge` judges its runs again with the criteria as they are now, random seeds included (from each run's `plan.json`), and rewrites their `result.json` and the summary | Each run directory keeps `house/plant.jsonl` (the house once a second, with every event and mark), `house/ocpp-.jsonl` (every OCPP frame the @@ -79,7 +79,9 @@ its sources (`provenance` in [catalog_test.go](catalog_test.go)). "Over the limit" is the worst phase above the fuse rating, measured through the fuse. A device's response time counts as 2 s, the meter and control -tick as 2 s more. +tick as 2 s more. The random cases, `r3` and `r5a` judge a phase between +the fuse and 1.2 × the fuse as Core does: it counts only once its 60 s heat +(I² filter) is above the fuse too. | Scenario | House and steps | Criteria | Short | |---|---|---|---| diff --git a/go/test/site/evaluate_test.go b/go/test/site/evaluate_test.go index 0ab41b730..70a65fb06 100644 --- a/go/test/site/evaluate_test.go +++ b/go/test/site/evaluate_test.go @@ -46,10 +46,12 @@ type plantDevice struct { EMSCmd float64 `json:"ems_cmd"` // 170 charge, 187 discharge, 204 stop EMSSetW float64 `json:"ems_setpoint_w"` Connected bool `json:"connected"` + Running *bool `json:"running"` // an inverter that answers; nil when not recorded } type ftwStatus struct { Drivers map[string]ftwDriver `json:"drivers"` + Dispatch []ftwDispatch `json:"dispatch"` // Core's battery orders this tick LoadQuality *string `json:"load_quality"` LoadReason *string `json:"load_reason"` LoadW *float64 `json:"load_w"` @@ -61,6 +63,12 @@ type ftwStatus struct { } `json:"energy"` } +// ftwDispatch is one battery order Core sent: + charge, - discharge. +type ftwDispatch struct { + Driver string `json:"driver"` + TargetW float64 `json:"target_w"` +} + type ftwDriver struct { Status string `json:"status"` EVSessionWh *float64 `json:"ev_session_wh"` // a charger's session energy @@ -107,6 +115,7 @@ type sample struct { Bat2 plantDevice // the second, if any Status *ftwStatus LPs []ftwLoadpoint + HeatA [3]float64 // each phase's 60 s heat, filled in by warm } type frame struct { @@ -130,6 +139,7 @@ type runData struct { events []houseEventLine frames []frame // garage's charger meta map[string]any + warmed bool // every sample's HeatA is filled in } type markLine struct { @@ -390,10 +400,72 @@ func (d *runData) runsOver(t0, t1, limit float64) (longest, total float64) { return round(longest, 1), round(total, 1) } +// fuseHeatTauS is the time constant of Core's fuse heat model +// (control/fuse_heat.go). +const fuseHeatTauS = 60.0 + +// warm fills in each sample's HeatA: per phase, the 60 s I² filter of Core's +// fuse heat model, on the current through the fuse in either direction, +// from the record's first sample on. +func (d *runData) warm() { + if d.warmed { + return + } + d.warmed = true + var sq [3]float64 + for i, r := range d.samples { + for k, a := range r.PhaseA { + if i == 0 { + sq[k] = a * a + } else { + sq[k] += (1 - math.Exp(-(r.T-d.samples[i-1].T)/fuseHeatTauS)) * (a*a - sq[k]) + } + r.HeatA[k] = math.Sqrt(sq[k]) + } + } +} + +// heatOver is whether a phase is over the fuse as Core's heat model judges +// it (owner rule, 27 Oct 2026): above the fuse while its 60 s heat is above +// the fuse too, or above fuseInstantFactor x the fuse. Between the fuse and +// that factor the heat is the budget. Call warm first. +func heatOver(r *sample, fuse float64) bool { + for k, a := range r.PhaseA { + a = math.Abs(a) + if a > fuse && (r.HeatA[k] > fuse || a > fuseInstantFactor*fuse) { + return true + } + } + return false +} + +// heatRunsOver is the longest stretch in [t0, t1] that heatOver holds, +// timed like runsOver. +func (d *runData) heatRunsOver(t0, t1, fuse float64) float64 { + d.warm() + longest := 0.0 + var from *float64 + var last float64 + for _, r := range d.window(t0, t1) { + t := r.T + switch { + case heatOver(r, fuse) && from == nil: + from = &t + case !heatOver(r, fuse) && from != nil: + longest, from = math.Max(longest, t-*from), nil + } + last = t + } + if from != nil { + longest = math.Max(longest, last-*from) + } + return round(longest, 1) +} + // i2Over is the seconds the worst phase's I² filter (tau 60 s) is above // limit, and the filter's peak. func (d *runData) i2Over(t0, t1, limit float64) (over, peak float64) { - const tau = 60.0 + const tau = fuseHeatTauS var y, prev float64 started := false for _, r := range d.window(t0, t1) { diff --git a/go/test/site/random_test.go b/go/test/site/random_test.go index 537ac7cca..14cfa38c6 100644 --- a/go/test/site/random_test.go +++ b/go/test/site/random_test.go @@ -212,96 +212,306 @@ func (d *runData) timing() houseTiming { return h } -// eventWindow is when the house changed on its own, and how long FTW may -// take to answer it. +// eventWindow is a stretch of time: a fault, or a Charge now hold. type eventWindow struct{ from, to float64 } +// within is whether t falls in one of ws, or up to afterS after its end. +func within(ws []eventWindow, t, afterS float64) bool { + for _, w := range ws { + if t >= w.from && t <= w.to+afterS { + return true + } + } + return false +} + +// stepWindow is a change FTW did not make, and how long FTW may take to +// answer it: until from + extraS + its lever's time + 2 s for the meter and +// the tick + 3 s. +type stepWindow struct { + from, extraS float64 + leverS float64 // > 0: the only lever that can answer (the charger, for a car FTW did not start) + untilT float64 // > 0: the window ends here, whatever the lever (a Core restart) + noBattery bool // the step took the inverter away +} + +// What the random judge takes from the rig and from Core. +const ( + rigBatteryMaxW = 5000.0 // the simulated Sungrow's largest charge or discharge + evRestartDwellS = 35.0 // control/ev_fuse_budget.go evRestartDwell + tickS = 2.0 // the rig's site.control_interval_s + plannerFloorPct = 10.0 // Core's planner.soc_min when the config leaves it out (cmd/ftw/main.go) +) + +// dispatchW is Core's battery order on r, + charge; false when Core +// dispatched no battery. +func dispatchW(r *sample) (float64, bool) { + if r == nil || r.Status == nil || len(r.Status.Dispatch) == 0 { + return 0, false + } + w := 0.0 + for _, x := range r.Status.Dispatch { + w += x.TargetW + } + return w, true +} + +// worstSignedA is the phase current furthest from 0, with its direction. +func worstSignedA(r *sample) float64 { + w := 0.0 + for _, a := range r.PhaseA { + if math.Abs(a) > math.Abs(w) { + w = a + } + } + return w +} + +// chargeNowChanges says, for each Charge now in the run's plan, whether it +// asked for a power or phase mode other than the Charge now before it. +// Without a plan every Charge now counts as a change. +func (d *runData) chargeNowChanges() []bool { + b, err := os.ReadFile(filepath.Join(d.dir, "plan.json")) + if d.dir == "" || err != nil { + return nil + } + var p randomPlan + if json.Unmarshal(b, &p) != nil { + return nil + } + var out []bool + var last *ftwAction + for i, a := range p.Actions { + if a.Do != "charge_now" { + continue + } + out = append(out, last == nil || last.W != a.W || last.PhaseMode != a.PhaseMode) + last = &p.Actions[i] + } + return out +} + func judgeInvariants(d *runData) (metrics, []criterion) { fuse := d.metaF("fuse") h := d.timing() t0, t1 := d.marks["start"], d.marks["end"] run := d.window(t0, t1) + d.warm() m := metrics{"charger_command_s": h.commandS, "charger_startup_s": h.startupS, "events": len(d.events)} + charger := math.Max(2, h.commandS) // the charger answers in its own time, never under 2 s + orders := d.offers() // Windows in which an over-limit second is the house's doing. - var windows []eventWindow - faultUntil := map[float64]float64{} // a fault's start and end + var windows []stepWindow + var faults, chargerFaults, inverterOut []eventWindow for _, ev := range d.events { - batteryUsable := true - if r := d.at(ev.T); r != nil && r.Bat.SoCPct <= h.floorPct+1 { - batteryUsable = false - } - // The fastest lever: the battery answers in 2 s, the charger in its - // own time, never under 2 s; then the meter and tick, 2 s, and 3 s. - lever := math.Max(2, h.commandS) - if batteryUsable { - lever = 2 - } - allow := lever + 2 + 3 + w := stepWindow{from: ev.T} + until := 0.0 switch ev.Event.Do { case "meter_late", "silence", "offline", "reconnect": - allow += ev.Event.ForS - faultUntil[ev.T] = ev.T + ev.Event.ForS + w.extraS, until = ev.Event.ForS, ev.T+ev.Event.ForS case "meter_glitch": - faultUntil[ev.T] = ev.T + 5 + until = ev.T + 5 } - windows = append(windows, eventWindow{ev.T, ev.T + allow}) + if until > 0 { + f := eventWindow{ev.T, until} + faults = append(faults, f) + switch ev.Event.Device { + case "", "meter", "garage": + chargerFaults = append(chargerFaults, f) + case "inverter": + inverterOut = append(inverterOut, f) + w.noBattery = true + } + } + windows = append(windows, w) } for _, mk := range d.allMarks { if mk.Label == "ftw:restart" { - windows = append(windows, eventWindow{mk.T, mk.T + 60}) + windows = append(windows, stepWindow{from: mk.T, untilT: mk.T + 60}) } } - explained := func(t float64) (float64, bool) { - best, ok := 0.0, false - for _, w := range windows { - if t >= w.from && t <= w.to { - best, ok = math.Max(best, w.to), true + // A car that starts to draw more than FTW's last order lets it (the + // charger's own default, or a lower order still on its way) is a step + // FTW did not take, and only the charger can answer it. + orderW := func(t float64) (float64, bool) { + w, ok := 0.0, false + for _, p := range orders { + if p.T > t { + break + } + w, ok = p.offerW(), true + } + return w, ok + } + carStarts := 0 + for i := 1; i < len(d.samples); i++ { + r := d.samples[i] + if r.T < t0 || r.T > t1 || carW(r, 0)-carW(d.samples[i-1], 0) <= 1000 { + continue + } + if w, ok := orderW(r.T); !ok || carW(r, 0) > w+3*volt { + windows = append(windows, stepWindow{from: r.T, leverS: charger}) + carStarts++ + } + } + m["car_starts_ftw_did_not_order"] = carStarts + + // lever is how long FTW's fastest lever takes, from t, to take overA off + // the worst phase: the battery, in 2 s, while its inverter runs, it is + // above its floor and its spare power covers the overage; otherwise the + // charger. + lever := func(t, overA float64, export bool) float64 { + r := d.at(t) + if r == nil || within(inverterOut, t, 0) || (r.Bat.Running != nil && !*r.Bat.Running) || r.Bat.SoCPct <= h.floorPct+1 { + return charger + } + spare := rigBatteryMaxW + r.BatW // discharge more, or charge less + if export { + spare = rigBatteryMaxW - r.BatW + } + if spare < overA*3*volt { + return charger + } + return 2 + } + until := func(w stepWindow, at, overA float64, export bool) float64 { + if w.untilT > 0 { + return w.untilT + } + lv := w.leverS + if lv == 0 { + lv = charger + if !w.noBattery { + lv = lever(math.Max(w.from, at), overA, export) + } + } + return w.from + w.extraS + lv + 2 + 3 + } + // ownRise is whether FTW raised what a stretch from s can come from: its + // last change to the car's order was a rise, sent within the time the + // charger takes to apply it, or a battery order moved toward import in + // the last 10 s. + ownRise := func(s float64) bool { + changedAt, rose, prev := math.Inf(-1), false, 0.0 + for _, p := range orders { + if p.T > s { + break + } + if w := p.offerW(); math.Abs(w-prev) > 1 { + changedAt, rose, prev = p.T, w > prev, w + } + } + if rose && changedAt >= s-(h.commandS+h.startupS+10) { + return true + } + lo := math.Inf(1) + for _, r := range d.window(s-10, s) { + if w, ok := dispatchW(r); ok { + lo = math.Min(lo, w) } } - return best, ok + w, ok := dispatchW(d.at(s)) + return ok && w > lo+100 } // 1, 2: the fuse holds; over the limit only as long as an outside step - // allows, and at most 3 s after FTW's own raise. + // allows, and at most 3 s after FTW's own raise. Between the fuse and + // 1.2 x the fuse the 60 s heat is the budget (heatOver): the clock + // starts when the heat passes the fuse, as Core's cut does. blownAny := anyBlown(run) unexplained, longestOwn := 0.0, 0.0 var firstBad float64 - var start *sample + bad := func(t float64) { + if firstBad == 0 { + firstBad = t + } + } + // judged lists each stretch the heat or 1.2 x the fuse put on the clock: + // from, end, clock start and allowed until, in seconds from the start, + // and whether it was FTW's own raise or a step. + judged := [][]any{} + judgeStretch := func(stretch []*sample, end float64) { + s := stretch[0].T + var clock *sample + overA, export := 0.0, false + for _, r := range stretch { + if clock == nil && heatOver(r, fuse) { + clock = r + } + if w := worstSignedA(r); math.Abs(w)-fuse > overA { + overA, export = math.Abs(w)-fuse, w < 0 + } + } + if clock == nil { + return // the heat budget covers it + } + c := clock.T + to, explained, own := math.Inf(-1), false, false + for _, w := range windows { + if x := until(w, s, overA, export); w.from <= s && s <= x { + to, explained = math.Max(to, x), true + } + } + switch { + case explained: + case ownRise(s): + own, to = true, c+3 + default: // nothing FTW raised: a change outside it + to = s + lever(s, overA, export) + 2 + 3 + } + if !own && c > s { // Core answers once the heat says so + to = math.Max(to, c+lever(c, overA, export)+2+3) + } + // Every window that opens inside the stretch while it is still + // allowed extends it: a second step, an outage or a Core restart. + for grown := true; grown; { + grown = false + for _, w := range windows { + if x := until(w, w.from, overA, export); w.from >= s && w.from <= math.Min(end, to) && x > to { + to, own, grown = x, false, true + } + } + } + kind := "step" + if own { + kind = "own" + } + judged = append(judged, []any{round(s-t0, 1), round(end-t0, 1), round(c-t0, 1), round(to-t0, 1), kind}) + switch { + case end <= to: + case own: + longestOwn = math.Max(longestOwn, end-c) + bad(to) + default: + unexplained = math.Max(unexplained, end-to) + bad(to) + } + } + from := -1 for i, r := range run { over := maxAbsI(r) > fuse - if over && start == nil { - start = r - } - if (!over || i == len(run)-1) && start != nil { - end := r.T - if to, ok := explained(start.T); ok { - if end > to { - unexplained = math.Max(unexplained, end-to) - if firstBad == 0 { - firstBad = to - } - } - } else if end-start.T > 3 { - longestOwn = math.Max(longestOwn, end-start.T) - if firstBad == 0 { - firstBad = start.T + 3 - } + if over && from < 0 { + from = i + } + if (!over || i == len(run)-1) && from >= 0 { + hi := i + if over { + hi = i + 1 } - start = nil + judgeStretch(run[from:hi], r.T) + from = -1 } } + heatPeak := 0.0 + for _, r := range run { + heatPeak = math.Max(heatPeak, max(r.HeatA[0], r.HeatA[1], r.HeatA[2])) + } m["over_limit_after_steps_s"], m["over_limit_own_s"] = round(unexplained, 1), round(longestOwn, 1) + m["heat_peak_a"], m["over_limit_judged"] = round(heatPeak, 2), judged // 3: with every device reading and no fault, Home use is measured. - inFault := func(t float64) bool { - for from, to := range faultUntil { - if t >= from && t <= to+30 { - return true - } - } - return false - } + inFault := func(t float64) bool { return within(faults, t, 30) } restartAt := []float64{t0} for _, mk := range d.allMarks { if mk.Label == "ftw:up" { @@ -346,12 +556,24 @@ func judgeInvariants(d *runData) (metrics, []criterion) { } m["home_use_estimated_while_reading_s"] = round(dishonest, 1) - // 4: during Charge now the car charges when there is room for it. + // 4: during Charge now the car charges when there is room for it. With + // room, Core waits evRestartDwell before it starts a stopped car, then + // the charger takes its own time, and a tick. The count of idle seconds + // with room starts again on each Charge now that changes the request, + // on each cut FTW sends and when Core answers after a restart. Only a + // fault of the meter or of the charger excuses an idle car. var holds []eventWindow + var graceFrom []float64 var holdFrom float64 + changes, k := d.chargeNowChanges(), 0 for _, mk := range d.allMarks { switch mk.Label { case "ftw:charge_now": + changed := k >= len(changes) || changes[k] + k++ + if holdFrom == 0 || changed { + graceFrom = append(graceFrom, mk.T) + } if holdFrom == 0 { holdFrom = mk.T } @@ -362,19 +584,56 @@ func judgeInvariants(d *runData) (metrics, []criterion) { } } } - grace := 60 + h.commandS + h.startupS + 10 + for i := 1; i < len(orders); i++ { + if orders[i].offerW() < orders[i-1].offerW()-1 { + graceFrom = append(graceFrom, orders[i].T) + } + } + // While Core is down nothing can start the car; it starts the grace + // again when it answers. + var down []eventWindow + for i, mk := range d.allMarks { + if mk.Label != "ftw:restart" { + continue + } + up := t1 + for _, n := range d.allMarks[i:] { + if n.Label == "ftw:up" { + up = n.T + break + } + } + down = append(down, eventWindow{mk.T, up}) + graceFrom = append(graceFrom, up) + } + // The car may stand idle with room for Core's dwell, the charger's + // command and startup time and a tick, plus the 2 s for the meter and + // tick and 3 s the fuse budgets also give. + allowedIdle := evRestartDwellS + h.commandS + h.startupS + tickS + 2 + 3 + regrace := func(from, to float64) bool { + for _, g := range graceFrom { + if g > from && g <= to { + return true + } + } + return false + } idle, run4 := 0.0, 0.0 for _, hw := range holds { run4 = 0 - for i, r := range d.window(hw.from+grace, hw.to) { + ws := d.window(hw.from, hw.to) + for i, r := range ws { + if i > 0 && regrace(ws[i-1].T, r.T) { + run4 = 0 + } // Room below the fuse, the car's line in Core; 6 A is the car's // minimum on three phases. roomA := fuse - (maxAbsI(r) - carW(r, 0)/(3*volt)) - bad := carW(r, 0) < 0.5*1380 && roomA >= 6 && !inFault(r.T) && !nearRestart(r.T) + bad := carW(r, 0) < 0.5*1380 && roomA >= 6 && !within(chargerFaults, r.T, 30) && !within(down, r.T, 0) if bad && i > 0 { - run4++ + run4 += r.T - ws[i-1].T idle = math.Max(idle, run4) - if idle > 30 { + if run4 > allowedIdle { note("charge now", r.T) } } else { @@ -382,7 +641,7 @@ func judgeInvariants(d *runData) (metrics, []criterion) { } } } - m["charge_now_idle_with_room_s"] = idle + m["charge_now_idle_with_room_s"], m["charge_now_idle_allowed_s"] = round(idle, 1), allowedIdle // 5: no order above the charger's 16 A per phase. over := 0 @@ -394,17 +653,26 @@ func judgeInvariants(d *runData) (metrics, []criterion) { } m["offers_over_rating"] = over - // 6: FTW does not ask the battery to discharge at its floor. + // 6: FTW does not ask the battery to discharge at its floor: the higher + // of the inverter's own floor and the planner's soc_min. FTW's orders + // are judged, not the inverter's register, which can hold an order from + // before an outage. + floorPct := h.floorPct + if p := d.metaF("planner_floor_pct"); p > 0 { + floorPct = math.Max(floorPct, p) + } else { + floorPct = math.Max(floorPct, plannerFloorPct) + } floorS := 0.0 for _, r := range run { - if r.Bat.EMSCmd == 187 && r.Bat.EMSSetW > 50 && r.Bat.SoCPct <= h.floorPct+0.5 { + if w, ok := dispatchW(r); ok && w < -50 && r.Bat.SoCPct <= floorPct { floorS++ if floorS > 10 { note("floor", r.T) } } } - m["discharge_at_floor_s"] = floorS + m["discharge_at_floor_s"], m["floor_pct"] = floorS, floorPct // 7: a stale meter means no raise. raises := 0 @@ -434,7 +702,7 @@ func judgeInvariants(d *runData) (metrics, []criterion) { crit("over the limit no longer than an outside step allows", unexplained == 0), crit("over the limit at most 3 s after FTW's own raise", longestOwn == 0), crit("Home use measured while every device reads", dishonest <= 10), - crit("Charge now charges when there is room", idle <= 30), + crit("Charge now charges when there is room", idle <= allowedIdle), crit("no offer above the charger's rating", over == 0), crit("no discharge asked at the battery's floor", floorS <= 10), crit("no raise on a stale meter", raises == 0), diff --git a/go/test/site/random_unit_test.go b/go/test/site/random_unit_test.go new file mode 100644 index 000000000..9ec5b1097 --- /dev/null +++ b/go/test/site/random_unit_test.go @@ -0,0 +1,276 @@ +//go:build unix + +package site + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "testing" +) + +// Unit tests for the random judge (judgeInvariants), each on the shape of +// a nightly seed that the judge called wrong (triage of 27 Oct 2026, rig +// items R2-R7). They run in every go test, without a simulator. + +const ( + limitStep = "over the limit no longer than an outside step allows" + limitOwn = "over the limit at most 3 s after FTW's own raise" + chargeNow = "Charge now charges when there is room" + atFloor = "no discharge asked at the battery's floor" +) + +// randomRun is n one-second samples on a fuse, from start at 0 to end at +// n-1: house current base per phase, the car idle, the battery at 50 % +// with its inverter running. set changes sample i. +func randomRun(n int, fuse, base float64, set func(i int, r *sample)) *runData { + d := &runData{marks: map[string]float64{"start": 0, "end": float64(n - 1)}, meta: map[string]any{"fuse": fuse}} + running := true + for i := 0; i < n; i++ { + r := &sample{T: float64(i), PhaseA: [3]float64{base, base, base}, CarW: []float64{0}, + Bat: plantDevice{SoCPct: 50, Running: &running}} + if set != nil { + set(i, r) + } + d.samples = append(d.samples, r) + } + return d +} + +// withCharger records the charger's command and startup times as the house +// wrote them, so the judge reads them as from a real run. +func withCharger(t *testing.T, d *runData, commandS, startupS float64) { + t.Helper() + dir := t.TempDir() + spec := houseSpec{Devices: []houseDevice{{ID: "garage", CommandResponseS: &commandS, StartupDelayS: &startupS}}} + b, _ := json.Marshal(spec) + if err := os.MkdirAll(filepath.Join(dir, "house"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "house", "timeline.json"), b, 0o644); err != nil { + t.Fatal(err) + } + d.dir = dir +} + +func judged(d *runData) map[string]bool { + _, cs := judgeInvariants(d) + return verdictsOf(cs) +} + +// R2, seed 207539's shape: a step the battery answers opens the stretch, +// and a Core restart 1 s into it extends what the stretch may take. A +// restart that comes after the step's time ran out excuses nothing. +func TestInvariantsExtendAStretchByEveryWindowInsideIt(t *testing.T) { + for _, c := range []struct { + name string + restartAt float64 // 0: no restart + want bool + }{ + {"restart 1 s into the stretch", 120, true}, + {"no restart", 0, false}, + {"restart after the step's time", 130, false}, + } { + // 20 A fuse; 26 A (1.3 x) from 119 to 143 s, after a load step + // at 114.7 s. The battery's 5 kW (7.2 A) covers the 6 A overage, + // so the step alone allows 2 + 2 + 3 s. + d := randomRun(301, 20, 10, func(i int, r *sample) { + if i >= 119 && i < 144 { + r.PhaseA = [3]float64{26, 13, 12} + } + }) + withCharger(t, d, 40, 0) + d.events = []houseEventLine{{T: 114.7, Event: houseEvent{Do: "loads"}}} + if c.restartAt > 0 { + d.allMarks = []markLine{{T: c.restartAt, Label: "ftw:restart"}, {T: c.restartAt + 9, Label: "ftw:up"}} + } + if got := judged(d)[limitStep]; got != c.want { + t.Errorf("%s: %q = %v, want %v", c.name, limitStep, got, c.want) + } + } +} + +// R3, seeds 207534, 207530 and 207539: the battery answers in 2 s only +// while its inverter runs and its spare power covers the overage; otherwise +// the charger is the lever, in its own time (5 s here). +func TestInvariantsBatteryIsTheLeverOnlyWhenItCanAnswer(t *testing.T) { + for _, c := range []struct { + name string + batW float64 + running bool + want bool + }{ + {"battery idle, 7.2 A spare for a 4 A overage", 0, true, false}, + {"battery already discharging 3266 W, 2.5 A spare", -3266, true, true}, + {"inverter offline", 0, false, true}, + } { + // 16 A fuse; 20 A (1.25 x) from 50 to 59 s after a step at 49.5 s: + // 9.5 s, past the battery's 7 s and inside the charger's 10 s. + d := randomRun(101, 16, 8, func(i int, r *sample) { + r.BatW, r.Bat.Running = c.batW, &c.running + if i >= 50 && i < 59 { + r.PhaseA = [3]float64{20, 12, 12} + } + }) + withCharger(t, d, 5, 0) + d.events = []houseEventLine{{T: 49.5, Event: houseEvent{Do: "loads"}}} + if got := judged(d)[limitStep]; got != c.want { + t.Errorf("%s: %q = %v, want %v", c.name, limitStep, got, c.want) + } + } +} + +// R4, seeds 207532 and 207537: a car that starts on the charger's own +// 16 A while FTW's order is 0 A is a step FTW did not take, answered by the +// 40 s charger. The same start right after FTW raised the order to 16 A is +// FTW's own. +func TestInvariantsCarStartingOnItsOwnIsAStep(t *testing.T) { + for _, c := range []struct { + name string + frames []frame + wantStep bool + wantOwn bool + }{ + {"FTW ordered 0 A", []frame{profileAt(0, 0), profileAt(20, 0)}, true, true}, + {"FTW raised to 16 A", []frame{profileAt(0, 0), profileAt(25, 16)}, true, false}, + } { + // 16 A fuse; the car draws 11 040 W from 30 s; the meter shows + // 20 A (1.25 x) from 31 to 39 s. + d := randomRun(121, 16, 4, func(i int, r *sample) { + if i >= 30 && i < 40 { + r.CarW[0] = 11040 + } + if i >= 31 && i < 39 { + r.PhaseA = [3]float64{20, 18, 19} + } + }) + withCharger(t, d, 40, 30) + d.frames = c.frames + v := judged(d) + if v[limitStep] != c.wantStep || v[limitOwn] != c.wantOwn { + t.Errorf("%s: step %v, own %v; want %v, %v", c.name, v[limitStep], v[limitOwn], c.wantStep, c.wantOwn) + } + } +} + +// R5, seed 207536: between the fuse and 1.2 x the fuse the 60 s heat is the +// budget (owner rule, 27 Oct 2026). 27.84 A on 25 A for 15 s from 15 A +// passes; above 1.2 x it fails once the step's time is up; so does the same +// 27.84 A held until the heat passes the fuse, and 25.5 A on a fuse already +// warm at its rating. +func TestInvariantsJudgeBetweenFuseAndInstantByHeat(t *testing.T) { + for _, c := range []struct { + name string + base, a float64 + from, to int + want bool + }{ + {"27.84 A for 15 s", 15, 27.84, 50, 65, true}, + {"30.1 A for 15 s", 15, 30.1, 50, 65, false}, + {"27.84 A for 200 s", 15, 27.84, 50, 250, false}, + {"25.5 A for 15 s on a warm fuse", 25, 25.5, 50, 65, false}, + } { + d := randomRun(301, 25, c.base, func(i int, r *sample) { + if i >= c.from && i < c.to { + r.PhaseA[0] = c.a + } + }) + d.events = []houseEventLine{{T: 49.5, Event: houseEvent{Do: "loads"}}} + if got := judged(d)[limitStep]; got != c.want { + t.Errorf("%s: %q = %v, want %v", c.name, limitStep, got, c.want) + } + } +} + +// R6, seeds 207533, 207536 and 207539: during Charge now an idle car with +// room is allowed Core's 35 s dwell, the charger's command and startup time +// and a tick, plus 5 s (72 s here, with a 30 s startup). The grace starts +// again on each Charge now that changes the request, on each cut FTW sends +// and when Core answers after a restart. A fault of the meter or the +// charger excuses the car; an inverter outage does not. +func TestInvariantsChargeNowGrace(t *testing.T) { + for _, c := range []struct { + name string + startS int // the car draws from here; 0: never + marks []markLine + frames []frame + events []houseEventLine + want bool + }{ + {"starts after 70 s", 71, nil, nil, nil, true}, + {"starts after 80 s", 81, nil, nil, nil, false}, + {"a changed Charge now at 60 s", 121, []markLine{{T: 60, Label: "ftw:charge_now"}}, nil, nil, true}, + {"FTW cuts at 60 s", 121, nil, []frame{profileAt(0, 16), profileAt(60, 0)}, nil, true}, + {"Core restarts at 50 s and answers at 60 s", 121, + []markLine{{T: 50, Label: "ftw:restart"}, {T: 60, Label: "ftw:up"}}, nil, nil, true}, + {"the meter late for 40 s from 10 s", 140, nil, nil, + []houseEventLine{{T: 10, Event: houseEvent{Do: "meter_late", ForS: 40}}}, true}, + {"the inverter offline for 40 s from 10 s", 140, nil, nil, + []houseEventLine{{T: 10, Event: houseEvent{Do: "offline", Device: "inverter", ForS: 40}}}, false}, + } { + // 16 A fuse, a 5 A house: 11 A of room. Charge now at 1 s. + d := randomRun(201, 16, 5, func(i int, r *sample) { + if c.startS > 0 && i >= c.startS { + r.CarW[0] = 6900 + r.PhaseA = [3]float64{15, 15, 15} + } + }) + withCharger(t, d, 0, 30) + d.allMarks = append([]markLine{{T: 1, Label: "ftw:charge_now"}}, c.marks...) + d.allMarks = append(d.allMarks, markLine{T: 200, Label: "end"}) + d.frames, d.events = c.frames, c.events + if got := judged(d)[chargeNow]; got != c.want { + t.Errorf("%s: %q = %v, want %v", c.name, chargeNow, got, c.want) + } + } +} + +// R7, seeds 207534 and 207536: the floor judges FTW's own discharge orders +// (status.dispatch) against the higher of the inverter's 5 % and the +// planner's 10 %, with no extra 0.5 %. A forced discharge the inverter +// still holds while FTW dispatches nothing is not FTW's order. +func TestInvariantsFloorJudgesFTWsOrders(t *testing.T) { + for _, c := range []struct { + name string + socPct float64 + orderW float64 // FTW's dispatch; 0: none + forcedW float64 // the inverter's register + want bool + }{ + {"FTW orders 3 kW at 5.0 %", 5, -3000, 3000, false}, + {"FTW orders 3 kW at 9 %, under the planner's 10 %", 9, -3000, 3000, false}, + {"FTW orders 3 kW at 10.5 %", 10.5, -3000, 3000, true}, + {"the register holds 3 kW at 5.0 %, FTW orders nothing", 5, 0, 3000, true}, + } { + d := randomRun(61, 16, 5, func(i int, r *sample) { + r.Bat.SoCPct = c.socPct + r.Bat.EMSMode, r.Bat.EMSCmd, r.Bat.EMSSetW = 2, 187, c.forcedW + r.Status = &ftwStatus{} + if c.orderW != 0 { + r.Status.Dispatch = []ftwDispatch{{Driver: "sungrow", TargetW: c.orderW}} + } + }) + if got := judged(d)[atFloor]; got != c.want { + t.Errorf("%s: %q = %v, want %v", c.name, atFloor, got, c.want) + } + } +} + +// TestJudge also judges the random seeds a results directory holds, from +// the plan each run wrote. +func TestRecordedRandomFindsSeedRuns(t *testing.T) { + dir := t.TempDir() + for _, seed := range []int64{7, 9} { + b, _ := json.Marshal(drawPlan(seed)) + os.MkdirAll(filepath.Join(dir, fmt.Sprintf("random-%d", seed)), 0o755) + os.WriteFile(filepath.Join(dir, fmt.Sprintf("random-%d", seed), "plan.json"), b, 0o644) + } + var got []string + for _, sc := range recordedRandom(dir) { + got = append(got, sc.name+"@"+sc.dir) + } + if len(got) != 2 || got[0] != "r7@random-7" || got[1] != "r9@random-9" { + t.Fatalf("recordedRandom = %v", got) + } +} diff --git a/go/test/site/rig_test.go b/go/test/site/rig_test.go index a2730cf71..f507fc33d 100644 --- a/go/test/site/rig_test.go +++ b/go/test/site/rig_test.go @@ -375,7 +375,7 @@ func TestJudge(t *testing.T) { t.Skip("set FTW_SITE_JUDGE to a results directory of an earlier run") } var outs []outcome - for _, sc := range selected(t, "full") { + for _, sc := range append(selected(t, "full"), recordedRandom(dir)...) { rundir := filepath.Join(dir, sc.dir) b, err := os.ReadFile(filepath.Join(rundir, "meta.json")) if err != nil { @@ -403,6 +403,25 @@ func TestJudge(t *testing.T) { writeSummary(t, dir, outs) } +// recordedRandom is each random seed recorded in dir, from the plan.json +// its run wrote, so TestJudge judges a nightly random run again. +func recordedRandom(dir string) []scenario { + files, _ := filepath.Glob(filepath.Join(dir, "random-*", "plan.json")) + sort.Strings(files) + var out []scenario + for _, f := range files { + b, err := os.ReadFile(f) + if err != nil { + continue + } + var p randomPlan + if json.Unmarshal(b, &p) == nil && p.Found == nil { + out = append(out, randomScenario(p)) + } + } + return out +} + func writeSummary(t *testing.T, out string, outs []outcome) { if len(outs) == 0 { return diff --git a/go/test/site/rig_unit_test.go b/go/test/site/rig_unit_test.go index 6ceab9e1c..d4ae8e810 100644 --- a/go/test/site/rig_unit_test.go +++ b/go/test/site/rig_unit_test.go @@ -107,20 +107,26 @@ func TestRandomPlansAreSeeded(t *testing.T) { } // An over-limit stretch right after an outside step is the house's; the -// same stretch with no step before it is FTW's own and fails after 3 s. +// same stretch right after FTW raised the car's order is FTW's own and +// fails after 3 s. With neither before it, it counts as a step FTW did not +// take (R4) and gets the step's time. 31 A is over 1.2 x the 25 A fuse, so +// the heat gives no budget. func TestInvariantsTellStepsFromOwnRaises(t *testing.T) { - mk := func(withStep bool) *runData { + mk := func(withStep, withRise bool) *runData { d := &runData{marks: map[string]float64{"start": 0, "end": 100}, meta: map[string]any{"fuse": 25.0}} for i := 0; i <= 100; i++ { a := 10.0 if i >= 50 && i < 56 { - a = 26 // 6 s over the 25 A fuse + a = 31 // 6 s over the 25 A fuse } d.samples = append(d.samples, &sample{T: float64(i), PhaseA: [3]float64{a, a, a}, Bat: plantDevice{SoCPct: 50}}) } if withStep { d.events = append(d.events, houseEventLine{T: 49.5, Event: houseEvent{Do: "loads"}}) } + if withRise { + d.frames = []frame{profileAt(40, 0), profileAt(45, 16)} + } return d } failed := func(cs []criterion) []string { @@ -132,38 +138,50 @@ func TestInvariantsTellStepsFromOwnRaises(t *testing.T) { } return out } - if _, cs := judgeInvariants(mk(true)); len(failed(cs)) != 0 { + if _, cs := judgeInvariants(mk(true, false)); len(failed(cs)) != 0 { t.Fatalf("after a step: %v", failed(cs)) } - _, cs := judgeInvariants(mk(false)) + if _, cs := judgeInvariants(mk(false, false)); len(failed(cs)) != 0 { + t.Fatalf("after nothing FTW raised: %v", failed(cs)) + } + _, cs := judgeInvariants(mk(false, true)) if f := failed(cs); len(f) != 1 || f[0] != "over the limit at most 3 s after FTW's own raise" { - t.Fatalf("without a step: %v", f) + t.Fatalf("after FTW's raise: %v", f) } } // The limit is the fuse rating: a phase may sit at exactly the fuse until -// the end of the run, and 0.1 A above it fails once the time budget is up. +// the end of the run, and 0.1 A above it fails once the time budget is up +// while the fuse is already warm (heat at the fuse). From a cool fuse the +// same 20 s stays inside the heat budget. func TestInvariantsJudgeAtTheFuse(t *testing.T) { const fuse = 25.0 const own = "over the limit at most 3 s after FTW's own raise" const step = "over the limit no longer than an outside step allows" for _, c := range []struct { name string - a float64 - to int // the level holds from 50 s until this second + base, a float64 // the level before 50 s, and from 50 s + to int // the level holds from 50 s until this second withStep bool want []string }{ - {"at the fuse", fuse, 101, false, nil}, - {"at the fuse after a step", fuse, 101, true, nil}, + {"at the fuse", fuse, fuse, 101, false, nil}, + {"at the fuse after a step", fuse, fuse, 101, true, nil}, // 20 s is past the 3 s for FTW's own raise, and past the // 2 + 2 + 3 s a step allows while the battery can answer. - {"0.1 A over", fuse + 0.1, 70, false, []string{own}}, - {"0.1 A over after a step", fuse + 0.1, 70, true, []string{step}}, + {"0.1 A over", fuse, fuse + 0.1, 70, false, []string{own}}, + {"0.1 A over after a step", fuse, fuse + 0.1, 70, true, []string{step}}, + {"0.1 A over a cool fuse", 10, fuse + 0.1, 70, false, nil}, + {"0.1 A over a cool fuse after a step", 10, fuse + 0.1, 70, true, nil}, } { d := &runData{marks: map[string]float64{"start": 0, "end": 100}, meta: map[string]any{"fuse": fuse}} + // FTW raised the car's order at 45 s. + d.frames = []frame{profileAt(40, 0), profileAt(45, 16)} + if c.withStep { + d.frames = nil + } for i := 0; i <= 100; i++ { - a := 10.0 + a := c.base if i >= 50 && i < c.to { a = c.a } diff --git a/go/test/site/scenarios_p0_unit_test.go b/go/test/site/scenarios_p0_unit_test.go index be1d59704..dfdb6624c 100644 --- a/go/test/site/scenarios_p0_unit_test.go +++ b/go/test/site/scenarios_p0_unit_test.go @@ -407,3 +407,43 @@ func TestJudgeR3JudgesAtTheFuse(t *testing.T) { t.Error("25.1 A for 80 s passes") } } + +// Between the fuse and 1.2 x the fuse R3 and R5a allow what Core's 60 s +// heat allows (the #1888 review): a cool site may sit at 1.08 x the fuse +// past the budget while the heat stays under the fuse; above 1.2 x the +// budget holds. +func TestJudgeR3AndR5aAllowTheHeatBudget(t *testing.T) { + const r3over = "over the fuse no longer than the charger's delay + 7 s" + const r5over = "over the fuse at most 3 s once under it" + r3 := func(a float64) bool { + d := synth(400, map[string]float64{"plug": 0, "charge_now": 20, "end": 400}, + map[string]any{"fuse": 25.0, "charger_delay_s": 60.0, "planner_floor_pct": 10.0}, func(i int, r *sample) { + if i >= 100 && i < 180 { // 80 s, past the 67 s budget + r.PhaseA = [3]float64{a, a, a} + } + }) + _, cs := judgeR3(d) + return verdictsOf(cs)[r3over] + } + if !r3(27) { + t.Error("R3: 27 A for 80 s from a cool fuse fails; its heat stays under 25 A") + } + if r3(30.5) { + t.Error("R3: 30.5 A, over 1.2 x the fuse, for 80 s passes") + } + r5 := func(a float64) bool { + _, cs := judgeR5a(r5aRun(30, func(i int) float64 { + if i >= 200 && i < 215 { // 15 s, past the 3 s budget + return a + } + return 20 + })) + return verdictsOf(cs)[r5over] + } + if !r5(27) { + t.Error("R5a: 27 A for 15 s after 2 min at 20 A fails; its heat stays under 25 A") + } + if r5(30.5) { + t.Error("R5a: 30.5 A, over 1.2 x the fuse, for 15 s passes") + } +} diff --git a/go/test/site/verdicts_test.go b/go/test/site/verdicts_test.go index 428f985c8..64d3fbb99 100644 --- a/go/test/site/verdicts_test.go +++ b/go/test/site/verdicts_test.go @@ -670,11 +670,13 @@ func judgeR3(d *runData) (metrics, []criterion) { } minSoC := minOf(run, func(r *sample) float64 { return r.Bat.SoCPct }) // Core may work up to the fuse rating; safety_margin_a is a site's - // opt-in, so the overage that counts is above the fuse. - over, _ := d.runsOver(tCN, t1, fuse) + // opt-in, so the overage that counts is above the fuse. Between the + // fuse and 1.2 x the fuse Core's 60 s heat is the budget (heatOver). + overInstant, _ := d.runsOver(tCN, t1, fuse) + over := d.heatRunsOver(tCN, t1, fuse) allowed := delay + 7 m := metrics{"discharge_below_floor_samples": below, "battery_order_swing_last5min_w": math.Round(swing), - "soc_min_pct": round(minSoC, 2), "over_fuse_longest_s": over, + "soc_min_pct": round(minSoC, 2), "over_fuse_longest_s": overInstant, "over_fuse_heat_longest_s": over, "allowed_over_s": allowed, "max_i": round(maxOf(run, maxAbsI), 2)} return m, []criterion{ crit("the battery reached the planner floor", len(run) > 0 && minSoC <= floor+0.5), // the setup @@ -739,7 +741,9 @@ func (d *runData) homeUseBack(t0 float64) *float64 { // judgeR5a: Core starting beside a car that already draws its maximum, with // the site over the fuse, brings the site under the limit within 30 s and // keeps it there. The limit is the fuse: Core may work up to the rating, -// and safety_margin_a is a site's opt-in. +// and safety_margin_a is a site's opt-in. Once under it, a reading between +// the fuse and 1.2 x the fuse counts only while the 60 s heat is over the +// fuse too (heatOver), as Core's cut does. func judgeR5a(d *runData) (metrics, []criterion) { fuse := d.metaF("fuse") tS, tUp, t1 := d.marks["ftw_start"], d.marks["ftw_up"], d.marks["end"] @@ -748,7 +752,7 @@ func judgeR5a(d *runData) (metrics, []criterion) { fit := d.firstT(tUp, func(r *sample) bool { return maxAbsI(r) <= fuse }) overAfter := 0.0 if fit != nil { - overAfter, _ = d.runsOver(tUp+*fit, t1, fuse) + overAfter = d.heatRunsOver(tUp+*fit, t1, fuse) } shown := d.homeUseBack(tUp) m := metrics{"car_w_before_start": math.Round(pre), "under_limit_s": roundp(fit, 1), "over_after_that_longest_s": overAfter, From 44e74f307bc621b81126eb2c8c023f5011bc21b6 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 20:14:24 +0100 Subject: [PATCH 24/68] test(site): tighten the random judge after review of #1920 - A stretch over the fuse that no outside change explains is FTW's own again (3 s after the heat clock), in either direction. The guess that it was a step let export raises and warm fuses split by short dips pass. ownRise is gone: with that rule it decided nothing. - A window that opens inside FTW's own raise no longer turns it into a step; only a step's stretch grows. - Charge now: a cut no longer restarts the idle count. A cut FTW had to make stops the car, and the count starts when the car stops; a cut with room is FTW's doing. The restart on Core's return was dead (the down mask already resets the count). - The battery lever uses the floor the floor check uses (max of the inverter floor and the planner soc_min). At the floor it can only charge less. - Only a meter fault adds its length to a step's time. An inverter outage takes the battery lever away; a charger outage delays the charger lever by what is left of it. - New check (R8, C1): a forced battery mode FTW does not dispatch lasts at most 10 s once the inverter and Core are back. Co-Authored-By: Claude Opus 5.5 --- go/test/site/random_test.go | 165 +++++++++++++++++-------------- go/test/site/random_unit_test.go | 161 +++++++++++++++++++++++++++--- go/test/site/rig_unit_test.go | 18 ++-- 3 files changed, 248 insertions(+), 96 deletions(-) diff --git a/go/test/site/random_test.go b/go/test/site/random_test.go index 14cfa38c6..beab667e1 100644 --- a/go/test/site/random_test.go +++ b/go/test/site/random_test.go @@ -301,15 +301,18 @@ func judgeInvariants(d *runData) (metrics, []criterion) { charger := math.Max(2, h.commandS) // the charger answers in its own time, never under 2 s orders := d.offers() - // Windows in which an over-limit second is the house's doing. + // Windows in which an over-limit second is the house's doing. Only a + // meter fault adds its length to the time FTW may take: it blinds FTW. + // An inverter outage takes the battery lever away; a charger outage + // delays the charger lever (chargerLever). var windows []stepWindow - var faults, chargerFaults, inverterOut []eventWindow + var faults, chargerFaults, inverterOut, chargerOut []eventWindow for _, ev := range d.events { w := stepWindow{from: ev.T} until := 0.0 switch ev.Event.Do { case "meter_late", "silence", "offline", "reconnect": - w.extraS, until = ev.Event.ForS, ev.T+ev.Event.ForS + until = ev.T + ev.Event.ForS case "meter_glitch": until = ev.T + 5 } @@ -317,8 +320,12 @@ func judgeInvariants(d *runData) (metrics, []criterion) { f := eventWindow{ev.T, until} faults = append(faults, f) switch ev.Event.Device { - case "", "meter", "garage": + case "", "meter": chargerFaults = append(chargerFaults, f) + w.extraS = ev.Event.ForS + case "garage": + chargerFaults = append(chargerFaults, f) + chargerOut = append(chargerOut, f) case "inverter": inverterOut = append(inverterOut, f) w.noBattery = true @@ -326,6 +333,15 @@ func judgeInvariants(d *runData) (metrics, []criterion) { } windows = append(windows, w) } + // The battery's floor: the higher of the inverter's own floor and the + // planner's soc_min. FTW may not discharge it there (check 6), so there + // it is no lever for import either. + floorPct := h.floorPct + if p := d.metaF("planner_floor_pct"); p > 0 { + floorPct = math.Max(floorPct, p) + } else { + floorPct = math.Max(floorPct, plannerFloorPct) + } for _, mk := range d.allMarks { if mk.Label == "ftw:restart" { windows = append(windows, stepWindow{from: mk.T, untilT: mk.T + 60}) @@ -357,21 +373,35 @@ func judgeInvariants(d *runData) (metrics, []criterion) { } m["car_starts_ftw_did_not_order"] = carStarts + // chargerLever is how long the charger takes to answer from t: its own + // time, after the rest of any outage it is in. + chargerLever := func(t float64) float64 { + left := 0.0 + for _, w := range chargerOut { + if t >= w.from && t <= w.to { + left = math.Max(left, w.to-t) + } + } + return charger + left + } // lever is how long FTW's fastest lever takes, from t, to take overA off - // the worst phase: the battery, in 2 s, while its inverter runs, it is - // above its floor and its spare power covers the overage; otherwise the - // charger. + // the worst phase: the battery, in 2 s, while its inverter runs and its + // spare power covers the overage; otherwise the charger. At its floor + // the battery may only charge less, never discharge more. lever := func(t, overA float64, export bool) float64 { r := d.at(t) - if r == nil || within(inverterOut, t, 0) || (r.Bat.Running != nil && !*r.Bat.Running) || r.Bat.SoCPct <= h.floorPct+1 { - return charger + if r == nil || within(inverterOut, t, 0) || (r.Bat.Running != nil && !*r.Bat.Running) { + return chargerLever(t) } spare := rigBatteryMaxW + r.BatW // discharge more, or charge less - if export { + switch { + case export: spare = rigBatteryMaxW - r.BatW + case r.Bat.SoCPct <= floorPct: + spare = math.Max(0, r.BatW) } if spare < overA*3*volt { - return charger + return chargerLever(t) } return 2 } @@ -380,40 +410,16 @@ func judgeInvariants(d *runData) (metrics, []criterion) { return w.untilT } lv := w.leverS - if lv == 0 { - lv = charger - if !w.noBattery { - lv = lever(math.Max(w.from, at), overA, export) - } + switch { + case lv > 0: + lv += chargerLever(w.from) - charger + case w.noBattery: + lv = chargerLever(w.from) + default: + lv = lever(math.Max(w.from, at), overA, export) } return w.from + w.extraS + lv + 2 + 3 } - // ownRise is whether FTW raised what a stretch from s can come from: its - // last change to the car's order was a rise, sent within the time the - // charger takes to apply it, or a battery order moved toward import in - // the last 10 s. - ownRise := func(s float64) bool { - changedAt, rose, prev := math.Inf(-1), false, 0.0 - for _, p := range orders { - if p.T > s { - break - } - if w := p.offerW(); math.Abs(w-prev) > 1 { - changedAt, rose, prev = p.T, w > prev, w - } - } - if rose && changedAt >= s-(h.commandS+h.startupS+10) { - return true - } - lo := math.Inf(1) - for _, r := range d.window(s-10, s) { - if w, ok := dispatchW(r); ok { - lo = math.Min(lo, w) - } - } - w, ok := dispatchW(d.at(s)) - return ok && w > lo+100 - } // 1, 2: the fuse holds; over the limit only as long as an outside step // allows, and at most 3 s after FTW's own raise. Between the fuse and @@ -453,23 +459,20 @@ func judgeInvariants(d *runData) (metrics, []criterion) { to, explained = math.Max(to, x), true } } - switch { - case explained: - case ownRise(s): + if !explained { // no change outside FTW: its own, import or export own, to = true, c+3 - default: // nothing FTW raised: a change outside it - to = s + lever(s, overA, export) + 2 + 3 } if !own && c > s { // Core answers once the heat says so to = math.Max(to, c+lever(c, overA, export)+2+3) } - // Every window that opens inside the stretch while it is still + // Every window that opens inside a step's stretch while it is still // allowed extends it: a second step, an outage or a Core restart. - for grown := true; grown; { + // FTW's own raise stays its own. + for grown := !own; grown; { grown = false for _, w := range windows { if x := until(w, w.from, overA, export); w.from >= s && w.from <= math.Min(end, to) && x > to { - to, own, grown = x, false, true + to, grown = x, true } } } @@ -559,9 +562,12 @@ func judgeInvariants(d *runData) (metrics, []criterion) { // 4: during Charge now the car charges when there is room for it. With // room, Core waits evRestartDwell before it starts a stopped car, then // the charger takes its own time, and a tick. The count of idle seconds - // with room starts again on each Charge now that changes the request, - // on each cut FTW sends and when Core answers after a restart. Only a - // fault of the meter or of the charger excuses an idle car. + // with room starts again on each Charge now that changes the request. + // A cut FTW had to send needs no new start: the count runs only while + // the car is idle with room, so it starts when the cut car stops. A + // cut with room is FTW's doing and starts nothing. While Core is down + // the count stops. Only a fault of the meter or of the charger excuses + // an idle car. var holds []eventWindow var graceFrom []float64 var holdFrom float64 @@ -584,13 +590,10 @@ func judgeInvariants(d *runData) (metrics, []criterion) { } } } - for i := 1; i < len(orders); i++ { - if orders[i].offerW() < orders[i-1].offerW()-1 { - graceFrom = append(graceFrom, orders[i].T) - } - } - // While Core is down nothing can start the car; it starts the grace - // again when it answers. + // roomA is the room below the fuse for the car, Core's line; 6 A is + // the car's minimum on three phases. + roomA := func(r *sample) float64 { return fuse - (maxAbsI(r) - carW(r, 0)/(3*volt)) } + // While Core is down nothing can start the car. var down []eventWindow for i, mk := range d.allMarks { if mk.Label != "ftw:restart" { @@ -604,7 +607,6 @@ func judgeInvariants(d *runData) (metrics, []criterion) { } } down = append(down, eventWindow{mk.T, up}) - graceFrom = append(graceFrom, up) } // The car may stand idle with room for Core's dwell, the charger's // command and startup time and a tick, plus the 2 s for the meter and @@ -626,10 +628,7 @@ func judgeInvariants(d *runData) (metrics, []criterion) { if i > 0 && regrace(ws[i-1].T, r.T) { run4 = 0 } - // Room below the fuse, the car's line in Core; 6 A is the car's - // minimum on three phases. - roomA := fuse - (maxAbsI(r) - carW(r, 0)/(3*volt)) - bad := carW(r, 0) < 0.5*1380 && roomA >= 6 && !within(chargerFaults, r.T, 30) && !within(down, r.T, 0) + bad := carW(r, 0) < 0.5*1380 && roomA(r) >= 6 && !within(chargerFaults, r.T, 30) && !within(down, r.T, 0) if bad && i > 0 { run4 += r.T - ws[i-1].T idle = math.Max(idle, run4) @@ -653,16 +652,9 @@ func judgeInvariants(d *runData) (metrics, []criterion) { } m["offers_over_rating"] = over - // 6: FTW does not ask the battery to discharge at its floor: the higher - // of the inverter's own floor and the planner's soc_min. FTW's orders - // are judged, not the inverter's register, which can hold an order from - // before an outage. - floorPct := h.floorPct - if p := d.metaF("planner_floor_pct"); p > 0 { - floorPct = math.Max(floorPct, p) - } else { - floorPct = math.Max(floorPct, plannerFloorPct) - } + // 6: FTW does not ask the battery to discharge at its floor (floorPct). + // FTW's orders are judged, not the inverter's register, which can hold + // an order from before an outage; check 8 judges that. floorS := 0.0 for _, r := range run { if w, ok := dispatchW(r); ok && w < -50 && r.Bat.SoCPct <= floorPct { @@ -690,6 +682,27 @@ func judgeInvariants(d *runData) (metrics, []criterion) { } } m["raises_on_a_stale_meter"] = raises + + // 8: a battery FTW does not dispatch is back in its own mode within + // 10 s: no forced charge or discharge left in the inverter's register + // once the inverter and Core are both up again (R8, C1). The 10 s + // count starts when both are back. + forcedS, run8 := 0.0, 0.0 + for i, r := range run { + w, ok := dispatchW(r) + stray := r.Status != nil && (!ok || math.Abs(w) <= 50) && math.Abs(batOrder(r)) > 50 && + !within(inverterOut, r.T, 0) && !within(down, r.T, 0) + if stray && i > 0 { + run8 += r.T - run[i-1].T + forcedS = math.Max(forcedS, run8) + if run8 > 10 { + note("forced battery", r.T) + } + } else { + run8 = 0 + } + } + m["battery_forced_without_dispatch_s"] = round(forcedS, 1) // The first second an invariant broke, from the start, per invariant: // a kept seed is cut a minute after the one it failed on. firsts := map[string]float64{} @@ -706,6 +719,7 @@ func judgeInvariants(d *runData) (metrics, []criterion) { crit("no offer above the charger's rating", over == 0), crit("no discharge asked at the battery's floor", floorS <= 10), crit("no raise on a stale meter", raises == 0), + crit("no forced battery mode FTW does not dispatch", forcedS <= 10), } } @@ -758,6 +772,7 @@ var invariantKey = map[string]string{ "no offer above the charger's rating": "rating", "no discharge asked at the battery's floor": "floor", "no raise on a stale meter": "stale meter", + "no forced battery mode FTW does not dispatch": "forced battery", } // keepFailure writes a failing random run as a case to keep: its plan with diff --git a/go/test/site/random_unit_test.go b/go/test/site/random_unit_test.go index 9ec5b1097..ea502de39 100644 --- a/go/test/site/random_unit_test.go +++ b/go/test/site/random_unit_test.go @@ -186,27 +186,37 @@ func TestInvariantsJudgeBetweenFuseAndInstantByHeat(t *testing.T) { // R6, seeds 207533, 207536 and 207539: during Charge now an idle car with // room is allowed Core's 35 s dwell, the charger's command and startup time // and a tick, plus 5 s (72 s here, with a 30 s startup). The grace starts -// again on each Charge now that changes the request, on each cut FTW sends -// and when Core answers after a restart. A fault of the meter or the -// charger excuses the car; an inverter outage does not. +// again on each Charge now that changes the request and on each cut FTW +// had to send, over the fuse or with no room; a cut with room does not. +// While Core is down the count stops. A fault of the meter or the charger +// excuses the car; an inverter outage does not. func TestInvariantsChargeNowGrace(t *testing.T) { for _, c := range []struct { name string - startS int // the car draws from here; 0: never + startS int // the car draws from here; 0: never + overS [2]int // the car draws 16 A, 21 A on the 16 A fuse, in [from, to) marks []markLine frames []frame events []houseEventLine want bool }{ - {"starts after 70 s", 71, nil, nil, nil, true}, - {"starts after 80 s", 81, nil, nil, nil, false}, - {"a changed Charge now at 60 s", 121, []markLine{{T: 60, Label: "ftw:charge_now"}}, nil, nil, true}, - {"FTW cuts at 60 s", 121, nil, []frame{profileAt(0, 16), profileAt(60, 0)}, nil, true}, - {"Core restarts at 50 s and answers at 60 s", 121, + {"starts after 70 s", 71, [2]int{}, nil, nil, nil, true}, + {"starts after 80 s", 81, [2]int{}, nil, nil, nil, false}, + {"a changed Charge now at 60 s", 121, [2]int{}, []markLine{{T: 60, Label: "ftw:charge_now"}}, nil, nil, true}, + {"FTW cuts the car over the fuse at 60 s", 121, [2]int{10, 61}, nil, + []frame{profileAt(0, 16), profileAt(60, 0)}, nil, true}, + {"FTW cuts an idle car with room at 60 s", 121, [2]int{}, nil, + []frame{profileAt(0, 16), profileAt(60, 0)}, nil, false}, + {"FTW hunts 6 A, 0 A, 6 A with room", 0, [2]int{}, nil, + []frame{profileAt(0, 6), profileAt(15, 0), profileAt(30, 6), profileAt(45, 0), + profileAt(60, 6), profileAt(75, 0), profileAt(90, 6), profileAt(105, 0), + profileAt(120, 6), profileAt(135, 0), profileAt(150, 6), profileAt(165, 0), + profileAt(180, 6), profileAt(195, 0)}, nil, false}, + {"Core restarts at 50 s and answers at 60 s", 121, [2]int{}, []markLine{{T: 50, Label: "ftw:restart"}, {T: 60, Label: "ftw:up"}}, nil, nil, true}, - {"the meter late for 40 s from 10 s", 140, nil, nil, + {"the meter late for 40 s from 10 s", 140, [2]int{}, nil, nil, []houseEventLine{{T: 10, Event: houseEvent{Do: "meter_late", ForS: 40}}}, true}, - {"the inverter offline for 40 s from 10 s", 140, nil, nil, + {"the inverter offline for 40 s from 10 s", 140, [2]int{}, nil, nil, []houseEventLine{{T: 10, Event: houseEvent{Do: "offline", Device: "inverter", ForS: 40}}}, false}, } { // 16 A fuse, a 5 A house: 11 A of room. Charge now at 1 s. @@ -215,6 +225,10 @@ func TestInvariantsChargeNowGrace(t *testing.T) { r.CarW[0] = 6900 r.PhaseA = [3]float64{15, 15, 15} } + if i >= c.overS[0] && i < c.overS[1] { + r.CarW[0] = 11040 + r.PhaseA = [3]float64{21, 21, 21} + } }) withCharger(t, d, 0, 30) d.allMarks = append([]markLine{{T: 1, Label: "ftw:charge_now"}}, c.marks...) @@ -257,6 +271,131 @@ func TestInvariantsFloorJudgesFTWsOrders(t *testing.T) { } } +// An over-limit stretch no outside change explains is FTW's own, whichever +// way the current flows and however it is cut up: FTW's discharge pushing +// export over the fuse, and a warm fuse held over its rating with a 1 s dip +// every 7 s. Both fail after 3 s. +func TestInvariantsAStretchWithNoStepIsFTWsOwn(t *testing.T) { + export := randomRun(121, 16, -10, func(i int, r *sample) { + w := 0.0 + if i >= 47 { + w, r.BatW = -5000, -5000 + } + r.Status = &ftwStatus{Dispatch: []ftwDispatch{{Driver: "sungrow", TargetW: w}}} + if i >= 50 && i < 56 { + r.PhaseA = [3]float64{-21, -21, -21} + } + }) + dips := randomRun(601, 25, 25.5, func(i int, r *sample) { + if i%7 == 6 { + r.PhaseA = [3]float64{24.9, 24.9, 24.9} + } + }) + for name, d := range map[string]*runData{"export 6 s at 1.31 x In": export, "600 s on a warm fuse, with dips": dips} { + withCharger(t, d, 5, 0) + if v := judged(d); v[limitOwn] { + t.Errorf("%s: %q passed", name, limitOwn) + } + } +} + +// A window that opens inside FTW's own raise does not turn it into a step: +// FTW raises the car at 45 s and the phases sit at 31 A (1.24 x 25 A) from +// 50 to 60 s; PV rising at 51 s changes nothing. The battery is at its +// floor, so the 40 s charger would be a step's lever. +func TestInvariantsAnEventInsideFTWsRaiseLeavesItOwn(t *testing.T) { + for _, withEvent := range []bool{false, true} { + d := randomRun(121, 25, 10, func(i int, r *sample) { + r.Bat.SoCPct = 6 + if i >= 50 && i < 60 { + r.PhaseA = [3]float64{31, 31, 31} + } + }) + withCharger(t, d, 40, 0) + d.frames = []frame{profileAt(40, 0), profileAt(45, 16)} + if withEvent { + d.events = []houseEventLine{{T: 51, Event: houseEvent{Do: "pv", Device: "inverter"}}} + } + if v := judged(d); v[limitOwn] { + t.Errorf("event %v: FTW's raise held 10 s at 1.24 x In and passed", withEvent) + } + } +} + +// The battery is the 2 s lever for import only above the floor the floor +// check uses (the planner's 10 % here), and never while its inverter is +// out; a charger outage delays the charger. Only a meter fault adds its +// length to a step's time. 16 A fuse, a 5 s charger, 20 A on L1 (1.25 x). +func TestInvariantsLeverAndFaults(t *testing.T) { + for _, c := range []struct { + name string + socPct float64 + from, to int // 20 A on L1 in [from, to) + events []houseEventLine + want bool + }{ + {"a step at 8 %: the charger answers", 8, 50, 59, nil, true}, + {"a step at 11 %: the battery answers", 11, 50, 59, nil, false}, + {"a step while the inverter is offline", 50, 50, 59, + []houseEventLine{{T: 30, Event: houseEvent{Do: "offline", Device: "inverter", ForS: 40}}}, true}, + {"the inverter offline 40 s, 15 s over", 50, 50, 65, + []houseEventLine{{T: 45, Event: houseEvent{Do: "offline", Device: "inverter", ForS: 40}}}, false}, + {"the meter late 40 s, 15 s over", 50, 50, 65, + []houseEventLine{{T: 45, Event: houseEvent{Do: "meter_late", ForS: 40}}}, true}, + {"the charger away 20 s, 18 s over", 8, 50, 68, + []houseEventLine{{T: 45, Event: houseEvent{Do: "reconnect", Device: "garage", ForS: 20}}}, true}, + } { + d := randomRun(121, 16, 8, func(i int, r *sample) { + r.Bat.SoCPct = c.socPct + if i >= c.from && i < c.to { + r.PhaseA = [3]float64{20, 12, 12} + } + }) + withCharger(t, d, 5, 0) + d.events = append([]houseEventLine{{T: 49.5, Event: houseEvent{Do: "loads"}}}, c.events...) + if got := judged(d)[limitStep]; got != c.want { + t.Errorf("%s: %q = %v, want %v", c.name, limitStep, got, c.want) + } + } +} + +// R8, C1: once the inverter and Core are back, a battery FTW does not +// dispatch leaves its forced mode within 10 s. +func TestInvariantsNoForcedBatteryWithoutDispatch(t *testing.T) { + const forced = "no forced battery mode FTW does not dispatch" + for _, c := range []struct { + name string + forcedS int // the register holds 187 / 3 kW until here + orderW float64 // FTW's dispatch; 0: none + down bool // Core, not the inverter, is away from 10 to 40 s + want bool + }{ + {"8 s after the inverter is back", 48, 0, false, true}, + {"30 s after the inverter is back", 70, 0, false, false}, + {"FTW dispatches the discharge", 120, -3000, false, true}, + {"8 s after Core is back", 48, 0, true, true}, + {"30 s after Core is back", 70, 0, true, false}, + } { + d := randomRun(121, 16, 5, func(i int, r *sample) { + r.Status = &ftwStatus{} + if c.orderW != 0 { + r.Status.Dispatch = []ftwDispatch{{Driver: "sungrow", TargetW: c.orderW}} + } + if i < c.forcedS { + r.Bat.EMSMode, r.Bat.EMSCmd, r.Bat.EMSSetW = 2, 187, 3000 + } + }) + if c.down { + d.allMarks = []markLine{{T: 10, Label: "ftw:restart"}, {T: 40, Label: "ftw:up"}} + } else { + d.events = []houseEventLine{{T: 10, Event: houseEvent{Do: "offline", Device: "inverter", ForS: 30}}} + } + if got := judged(d)[forced]; got != c.want { + t.Errorf("%s: %q = %v, want %v", c.name, forced, got, c.want) + } + } +} + // TestJudge also judges the random seeds a results directory holds, from // the plan each run wrote. func TestRecordedRandomFindsSeedRuns(t *testing.T) { diff --git a/go/test/site/rig_unit_test.go b/go/test/site/rig_unit_test.go index d4ae8e810..fff3d3251 100644 --- a/go/test/site/rig_unit_test.go +++ b/go/test/site/rig_unit_test.go @@ -107,10 +107,9 @@ func TestRandomPlansAreSeeded(t *testing.T) { } // An over-limit stretch right after an outside step is the house's; the -// same stretch right after FTW raised the car's order is FTW's own and -// fails after 3 s. With neither before it, it counts as a step FTW did not -// take (R4) and gets the step's time. 31 A is over 1.2 x the 25 A fuse, so -// the heat gives no budget. +// same stretch with no step before it is FTW's own and fails after 3 s, +// whether or not the record shows FTW raising anything. 31 A is over +// 1.2 x the 25 A fuse, so the heat gives no budget. func TestInvariantsTellStepsFromOwnRaises(t *testing.T) { mk := func(withStep, withRise bool) *runData { d := &runData{marks: map[string]float64{"start": 0, "end": 100}, meta: map[string]any{"fuse": 25.0}} @@ -141,12 +140,11 @@ func TestInvariantsTellStepsFromOwnRaises(t *testing.T) { if _, cs := judgeInvariants(mk(true, false)); len(failed(cs)) != 0 { t.Fatalf("after a step: %v", failed(cs)) } - if _, cs := judgeInvariants(mk(false, false)); len(failed(cs)) != 0 { - t.Fatalf("after nothing FTW raised: %v", failed(cs)) - } - _, cs := judgeInvariants(mk(false, true)) - if f := failed(cs); len(f) != 1 || f[0] != "over the limit at most 3 s after FTW's own raise" { - t.Fatalf("after FTW's raise: %v", f) + for _, withRise := range []bool{false, true} { + _, cs := judgeInvariants(mk(false, withRise)) + if f := failed(cs); len(f) != 1 || f[0] != "over the limit at most 3 s after FTW's own raise" { + t.Fatalf("with no step, FTW's raise %v: %v", withRise, f) + } } } From b19d30df80d8b393cd5958aa21647d9be5b40024 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 20:31:02 +0100 Subject: [PATCH 25/68] test(control): phase relief reads each battery live, in the decision's reading The merge of #1876 moved stopPhaseReliefW's live reads into phaseSample.moveW. Pin it: a battery that went offline, moved on to a newer reading or has no reading gives no phase relief. With the cached RawW read #1891 had, the offline and newer-reading cases relieve 2310 W and the no-reading case counts a 2000 W charge from 0 W. Co-Authored-By: Claude Opus 5.5 --- .../fuse_battery_phase_direction_test.go | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/go/internal/control/fuse_battery_phase_direction_test.go b/go/internal/control/fuse_battery_phase_direction_test.go index 5845c7acf..99a38a4e9 100644 --- a/go/internal/control/fuse_battery_phase_direction_test.go +++ b/go/internal/control/fuse_battery_phase_direction_test.go @@ -224,6 +224,49 @@ func TestPhaseReliefSkipsOfflineMeter(t *testing.T) { } } +// The batteries' move counts only power read live from the store, in the +// same reading the rest of the decision used. A battery that went offline, +// moved on to a newer reading or has no reading leaves its power in the +// phases unknown: no phase relief, as #1876's stop relief did. Before, +// the cached reading's RawW drove the relief. +func TestPhaseReliefNeedsTheBatteryReadingItUses(t *testing.T) { + data := map[string]any{"l1_a": 15.0, "l2_a": 6.0, "l3_a": 5.1, "l1_w": 3450.0, "l2_w": 1380.0, "l3_w": 1173.0} + st := phaseDirectionState(0) + stop := []DispatchTarget{{Driver: "bat", TargetW: 0}} + seed := func() (*telemetry.Store, map[string]*telemetry.DerReading, phaseSample) { + store := phaseDirectionStore(t, 6003, -3000, data) + meter := store.Get("meter", telemetry.DerMeter) + return store, map[string]*telemetry.DerReading{"bat": store.Get("bat", telemetry.DerBattery)}, livePhaseSample(store, "meter", meter) + } + + _, readings, phases := seed() + // Stopping 3000 W puts L1 at 15 + 4.35 A; 3.35 A over 16 A is 2310 W. + if imp, _ := phaseReliefForTargets(phases, st, stop, readings); math.Abs(imp-2310) > 1 { + t.Fatalf("live readings: relief %.0f W, want 2310 W", imp) + } + + store, readings, phases := seed() + store.DriverHealthMut("bat").SetOffline() + if imp, exp := phaseReliefForTargets(phases, st, stop, readings); imp != 0 || exp != 0 { + t.Errorf("offline battery: relief %.0f/%.0f W, want none", imp, exp) + } + + store, readings, phases = seed() + time.Sleep(time.Millisecond) + soc := 0.6 + store.Update("bat", telemetry.DerBattery, -3000, &soc, nil) + if imp, exp := phaseReliefForTargets(phases, st, stop, readings); imp != 0 || exp != 0 { + t.Errorf("newer battery reading: relief %.0f/%.0f W, want none", imp, exp) + } + + // Counted from 0 W, a 2000 W charge would read as L1 at 17.9 A. + _, _, phases = seed() + charge := []DispatchTarget{{Driver: "bat", TargetW: 2000}} + if imp, exp := phaseReliefForTargets(phases, st, charge, map[string]*telemetry.DerReading{}); imp != 0 || exp != 0 { + t.Errorf("no battery reading: relief %.0f/%.0f W, want none", imp, exp) + } +} + // The battery's working limit on each phase is L = In − safety_margin_a, // in both directions, with no floor under the margin. A phase at L needs no // relief, 0.1 A past it needs exactly 0.1 A, and a target that lands a From fd07863ba02063b5a6f11b495f596b5462c77e9b Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 20:31:32 +0100 Subject: [PATCH 26/68] fix(control): battery relief holds when the battery's reading lags the meter The phase relief counts the battery's move from its own reading. When that reading lags the meter by a tick, the meter already shows the relief while the reading does not, so the relief came off; on the next tick it went back on top of the reading's catch-up. In the 207533 shape (16 A, margin 0) with a one-tick lag the order ran -3214, -3005, -3422, -3005, ... -5717 W and L1 went back to 16.3 A on every other tick: 13 crossings. A move from the battery's last command (the one it got in the last dispatch) may now not pass the room the meter shows either. That bound only tightens, and a phase already over the line gives it no room, so it never asks for more than to stay at the last command: a battery that falls short of its order does not wind it up. With lag 1 or 2 the order holds -3214 W with L1 at 16.0 A and one crossing, on the PV step. Co-Authored-By: Claude Opus 5.5 --- .changeset/a5-battery-fuse-signed-phases.md | 2 +- go/internal/control/dispatch.go | 122 ++++++++++++++---- .../fuse_battery_phase_direction_test.go | 76 ++++++++++- 3 files changed, 169 insertions(+), 31 deletions(-) diff --git a/.changeset/a5-battery-fuse-signed-phases.md b/.changeset/a5-battery-fuse-signed-phases.md index a8ac1435f..cfe5e70bb 100644 --- a/.changeset/a5-battery-fuse-signed-phases.md +++ b/.changeset/a5-battery-fuse-signed-phases.md @@ -2,4 +2,4 @@ "ftw": patch --- -The home battery now protects each fuse phase in the direction its current flows. It no longer discharges into a phase that already exports past the fuse, and no longer cuts a discharge that keeps an importing phase under it. It counts its own share of each phase, so it holds a steady relief instead of switching between full relief and none on every dispatch. It relieves to the fuse less `safety_margin_a`, the same line the car uses. +The home battery now protects each fuse phase in the direction its current flows. It no longer discharges into a phase that already exports past the fuse, and no longer cuts a discharge that keeps an importing phase under it. It counts its own share of each phase, so it holds a steady relief instead of switching between full relief and none on every dispatch, also when its own power reading lags the meter. It relieves to the fuse less `safety_margin_a`, the same line the car uses. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 79a4aa924..6353d9cea 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -4008,47 +4008,131 @@ func livePhaseSample(store *telemetry.Store, driver string, meter *telemetry.Der // batteries. false when a targeted battery has no reading, has gone // offline or has moved on to a newer reading: its power in the phases is // then unknown. -func (p phaseSample) moveW(targets []DispatchTarget, batteries map[string]*telemetry.DerReading) (float64, bool) { +// +// sentW is the same change from the command each battery got in the last +// dispatch, for a battery that got one, and from its reading otherwise. +func (p phaseSample) moveW(state *State, targets []DispatchTarget, batteries map[string]*telemetry.DerReading) (moveW, sentW float64, ok bool) { if p.store == nil { - return 0, false + return 0, 0, false } - var moveW float64 seen := make(map[string]bool, len(targets)) for _, t := range targets { moveW += t.TargetW + sentW += t.TargetW if seen[t.Driver] { continue } seen[t.Driver] = true r := batteries[t.Driver] if r == nil { - return 0, false + return 0, 0, false } rawW, at, ok := p.store.OnlineRawW(t.Driver, telemetry.DerBattery) if !ok || !at.Equal(r.UpdatedAt) { - return 0, false + return 0, 0, false } moveW -= rawW + if w, sent := state.lastDispatchedW(t.Driver); sent { + sentW -= w + } else { + sentW -= rawW + } + } + return moveW, sentW, true +} + +// lastDispatchedW is the command driver got in the last dispatch, if it +// got one. +func (s *State) lastDispatchedW(driver string) (float64, bool) { + if s == nil { + return 0, false + } + log := s.batteryCommands[driver] + if len(log) == 0 || s.LastDispatch == nil || !log[len(log)-1].at.Equal(*s.LastDispatch) { + return 0, false } - return moveW, true + return log[len(log)-1].w, true } -// phaseReliefForTargets is phaseFuseReliefW for targets replacing the -// batteries' power in the phases. 0, 0 when that power is unknown. +// phaseReliefForTargets is the relief that keeps every phase inside +// fuseLineA once the targets replace the batteries' power. 0, 0 when that +// power is unknown. +// +// The relief counts the batteries' move from their readings +// (phaseFuseReliefW). A reading can lag the meter: the meter already shows +// the battery at its last command while the reading still holds the power +// before it. The phase then sits at the line, the reading shows no relief +// in force, and the relief is taken back; on the next tick the reading +// shows it and the relief goes on top of it. The order runs further out +// each time. So a move from the last command may not pass the room the +// meter shows either (phaseSentReliefW). func phaseReliefForTargets(p phaseSample, state *State, targets []DispatchTarget, batteries map[string]*telemetry.DerReading) (importW, exportW float64) { - moveW, ok := p.moveW(targets, batteries) + moveW, sentW, ok := p.moveW(state, targets, batteries) + if !ok { + return 0, 0 + } + importW, exportW = phaseFuseReliefW(p, state, moveW) + sentImportW, sentExportW := phaseSentReliefW(p, state, sentW) + return math.Max(importW, sentImportW), math.Max(exportW, sentExportW) +} + +// phaseSentReliefW is the relief that keeps sentW, the batteries' move from +// their last commands, inside the room the meter shows on each phase. A +// phase already over the line has no room; its overage is +// phaseFuseReliefW's. So this relief never asks for more than to stay at +// the last command, and a battery that cannot reach its command does not +// wind the relief up. +func phaseSentReliefW(p phaseSample, state *State, sentW float64) (importW, exportW float64) { + amps, ok := p.signedA(state) if !ok { return 0, 0 } - return phaseFuseReliefW(p, state, moveW) + perA := state.SiteFuseVoltage * float64(state.SiteFusePhases) + limitA := state.fuseLineA() + hi, lo := math.Inf(-1), math.Inf(1) + for _, a := range amps { + a = math.Max(-limitA, math.Min(limitA, a)) + sentW/perA + hi, lo = math.Max(hi, a), math.Min(lo, a) + } + importW, exportW = math.Max(0, hi-limitA)*perA, math.Max(0, -limitA-lo)*perA + if importW < 1 { + importW = 0 + } + if exportW < 1 { + exportW = 0 + } + return importW, exportW +} + +// signedA is the phase currents, + import, from phaseCurrentsA. When no +// phase reads as export while the total does, the meter gives no direction +// per phase, and the phases take the total's. +func (p phaseSample) signedA(state *State) ([]float64, bool) { + if p.meter == nil || state == nil { + return nil, false + } + amps, _, valid := phaseCurrentsA(p.meter, state, p.totalW) + if !valid || len(amps) == 0 { + return nil, false + } + exports := p.totalW < 0 + for _, a := range amps { + exports = exports && a >= 0 + } + if exports { + for i := range amps { + amps[i] = -amps[i] + } + } + return amps, true } // phaseFuseReliefW is the aggregate battery move that brings every phase // inside the working limit, fuseLineA: the fuse less safety_margin_a, the // same line the car uses. importW asks for less charge or more // discharge, exportW for the reverse. moveW is the batteries' change from -// the power this reading already holds (phaseMoveW); like the relief, it -// spreads evenly over the site's phases. +// the power this reading already holds (phaseSample.moveW); like the +// relief, it spreads evenly over the site's phases. // // The phases are the meter's signed currents (phaseCurrentsA). When no // phase reads as export while the total does, the meter gives no direction @@ -4060,24 +4144,14 @@ func phaseReliefForTargets(p phaseSample, state *State, targets []DispatchTarget // export, and a battery on one phase, which is read as balanced. 0, 0 // without usable phase currents. func phaseFuseReliefW(p phaseSample, state *State, moveW float64) (importW, exportW float64) { - if p.meter == nil || state == nil { - return 0, 0 - } - amps, _, valid := phaseCurrentsA(p.meter, state, p.totalW) - if !valid || len(amps) == 0 { + amps, ok := p.signedA(state) + if !ok { return 0, 0 } perA := state.SiteFuseVoltage * float64(state.SiteFusePhases) // aggregate W per phase ampere limitA := state.fuseLineA() - exports := p.totalW < 0 - for _, a := range amps { - exports = exports && a >= 0 - } hi, lo := math.Inf(-1), math.Inf(1) for _, a := range amps { - if exports { - a = -a - } a += moveW / perA hi, lo = math.Max(hi, a), math.Min(lo, a) } diff --git a/go/internal/control/fuse_battery_phase_direction_test.go b/go/internal/control/fuse_battery_phase_direction_test.go index 99a38a4e9..9e48abe66 100644 --- a/go/internal/control/fuse_battery_phase_direction_test.go +++ b/go/internal/control/fuse_battery_phase_direction_test.go @@ -341,6 +341,16 @@ func TestBatteryFuseLineProperty(t *testing.T) { // PV is low. Each tick the battery reaches the order it was sent the tick // before, and the meter reads it there. func TestFuseReliefStaysAtTheLineAfterPVDrop(t *testing.T) { + targets, l1, line := pvDropLoop(0, 0) + assertHeldAtTheLine(t, targets, l1, line) +} + +// pvDropLoop runs the 207533 shape: a -3005 W hold, L1 at 14.45 A, and PV +// down 1280 W from tick 5 to tick 29, with 5 s ticks. The meter sees the +// battery's actual power. The battery's own reading reports the power of +// readLag ticks earlier. maxDischargeW > 0 caps what the battery delivers +// without Core knowing it. +func pvDropLoop(readLag int, maxDischargeW float64) (targets, l1 []float64, line float64) { st := phaseDirectionState(0) now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) st.clock = func() time.Time { return now } @@ -348,9 +358,9 @@ func TestFuseReliefStaysAtTheLineAfterPVDrop(t *testing.T) { store := telemetry.NewStore() load := [3]float64{23.44, 11.04, 11.54} // house and car, A import per phase - pvW, batW := -3200.0, -3005.0 - line := st.fuseLineA() - var targets, l1 []float64 + pvW := -3200.0 + actual := []float64{-3005} + line = st.fuseLineA() for tick := 0; tick < 40; tick++ { switch tick { case 5: @@ -358,6 +368,7 @@ func TestFuseReliefStaysAtTheLineAfterPVDrop(t *testing.T) { case 30: pvW = -3200 } + batW := actual[len(actual)-1] var a [3]float64 data := map[string]any{} var totalW float64 @@ -371,18 +382,31 @@ func TestFuseReliefStaysAtTheLineAfterPVDrop(t *testing.T) { store.Update("meter", telemetry.DerMeter, totalW, nil, raw) store.DriverHealthMut("meter").RecordSuccess() soc := 0.6 - store.Update("bat", telemetry.DerBattery, batW, &soc, nil) + store.Update("bat", telemetry.DerBattery, actual[max(0, len(actual)-1-readLag)], &soc, nil) store.DriverHealthMut("bat").RecordSuccess() + order := batW for _, o := range ComputeDispatch(store, st, map[string]float64{"bat": 15200}, 16*230*3) { if o.Driver == "bat" { - batW = o.TargetW + order = o.TargetW } } - targets = append(targets, math.Round(batW)) + batW = order + if maxDischargeW > 0 { + batW = math.Max(order, -maxDischargeW) + } + actual = append(actual, batW) + targets = append(targets, math.Round(order)) l1 = append(l1, math.Round(a[0]*100)/100) now = now.Add(5 * time.Second) } + return targets, l1, line +} + +// assertHeldAtTheLine wants L1 at the line while PV is low, and one crossing +// of it, on the PV step. +func assertHeldAtTheLine(t *testing.T, targets, l1 []float64, line float64) { + t.Helper() crossings := 0 for i := range l1 { if l1[i] > line+0.01 && (i == 0 || l1[i-1] <= line+0.01) { @@ -400,3 +424,43 @@ func TestFuseReliefStaysAtTheLineAfterPVDrop(t *testing.T) { t.Logf("L1 %v", l1) } } + +// The battery's reading lags the meter by one or two ticks: the meter +// already shows the battery at its relief while the reading still holds +// the power before it. Counted from that reading, the relief looked like a +// move still to make, so every other tick took it back, and the order ran +// out further each time (-3214, -3005, -3422, -3005, ... -5717 W) with L1 +// back at 16.3 A on every other tick. The last command bounds the move, so +// the relief holds -3214 W with L1 at the line. +func TestFuseReliefHoldsWhenTheBatteryReadingLags(t *testing.T) { + for _, lag := range []int{1, 2} { + t.Run(fmt.Sprintf("lag %d", lag), func(t *testing.T) { + targets, l1, line := pvDropLoop(lag, 0) + assertHeldAtTheLine(t, targets, l1, line) + for i := 6; i < 30; i++ { + if targets[i] != targets[5] { + t.Errorf("tick %d: order %.0f W, want the %.0f W relief held", i, targets[i], targets[5]) + } + } + }) + } +} + +// A battery that cannot reach its order, with no limit Core knows, must +// not wind the relief up through the last-command bound: the order settles, +// and it returns to the hold once PV comes back. +func TestFuseReliefSettlesWhenTheBatteryFallsShort(t *testing.T) { + targets, l1, _ := pvDropLoop(0, 3100) + for i := 8; i < 30; i++ { + if targets[i] != targets[i-1] || targets[i] < -3300 { + t.Errorf("tick %d: order %.0f W after %.0f W, want it settled near -3214 W", i, targets[i], targets[i-1]) + } + } + if targets[31] != -3005 { + t.Errorf("tick 31: order %.0f W, want the -3005 W hold back once PV returns", targets[31]) + } + if t.Failed() { + t.Logf("targets %v", targets) + t.Logf("L1 %v", l1) + } +} From 4c48376fcb9696e56d932903ea4335c5b70fb13e Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 20:39:49 +0100 Subject: [PATCH 27/68] test(site): R8 counts a forced battery from when Core has the inverter back The random judge's R8 check counted 10 s from the inverter's return. The Modbus reconnect backoff (up to 60 s) holds Core's first good read back, so the check could not pass even with C1 fixed (207539: 55.7 s). The count now starts at Core's first good read of the inverter after an outage or a restart, at the latest 60 s after the return. After an outage it allows the registry's 30 s default retry (defaultRetryMax) until #1915 (C11) lands. While Core is stopped with SIGTERM, a running inverter must leave its forced mode within 10 s of the stop: the driver cleanup writes the default (triage item 10). Co-Authored-By: Claude Opus 5.5 --- go/test/site/evaluate_test.go | 5 +- go/test/site/random_test.go | 102 ++++++++++++++++++---- go/test/site/random_unit_test.go | 143 ++++++++++++++++++++++++------- 3 files changed, 204 insertions(+), 46 deletions(-) diff --git a/go/test/site/evaluate_test.go b/go/test/site/evaluate_test.go index 70a65fb06..7a2f93145 100644 --- a/go/test/site/evaluate_test.go +++ b/go/test/site/evaluate_test.go @@ -70,8 +70,9 @@ type ftwDispatch struct { } type ftwDriver struct { - Status string `json:"status"` - EVSessionWh *float64 `json:"ev_session_wh"` // a charger's session energy + Status string `json:"status"` + EVSessionWh *float64 `json:"ev_session_wh"` // a charger's session energy + ConsecutiveErrors *int `json:"consecutive_errors"` // failed polls in a row; 0 once a poll reads } type ftwLoadpoint struct { diff --git a/go/test/site/random_test.go b/go/test/site/random_test.go index beab667e1..1f07cfa98 100644 --- a/go/test/site/random_test.go +++ b/go/test/site/random_test.go @@ -225,6 +225,60 @@ func within(ws []eventWindow, t, afterS float64) bool { return false } +// inverterBackFrom gives, for a time t, when the R8 count may start after +// the latest return before t: the inverter's from an outage (inverterOut) +// or Core's from a restart (down). Core has the inverter back at its first +// good read of it (no consecutive errors), which the Modbus reconnect +// backoff may hold back up to reconnectBackoffMaxS. After an outage, a +// default that failed while the inverter was away waits on the registry's +// retry timer, up to defaultRetryMaxS more, until #1915 (C11) sends it on +// the first good poll. A Core that starts fresh has no such wait. +func (d *runData) inverterBackFrom(inverterOut, down []eventWindow) func(t float64) float64 { + type back struct { + at, from float64 + } + var backs []back + add := func(at float64, outage bool) { + from := at + reconnectBackoffMaxS + for _, r := range d.samples { + if r.T >= at && r.T < from && readsInverter(r) { + from = r.T + break + } + } + if outage { + from += defaultRetryMaxS + } + backs = append(backs, back{at, from}) + } + for _, w := range inverterOut { + add(w.to, true) + } + for _, w := range down { + add(w.to, false) + } + return func(t float64) float64 { + at, from := math.Inf(-1), math.Inf(-1) + for _, b := range backs { + if b.at <= t && b.at >= at { + at, from = b.at, b.from + } + } + return from + } +} + +// readsInverter is whether Core's last poll of the inverter succeeded. A +// status without the driver's error count says nothing, and counts as a +// read. +func readsInverter(r *sample) bool { + if r.Status == nil { + return false + } + dr, ok := r.Status.Drivers[inverterDriver] + return !ok || dr.ConsecutiveErrors == nil || *dr.ConsecutiveErrors == 0 +} + // stepWindow is a change FTW did not make, and how long FTW may take to // answer it: until from + extraS + its lever's time + 2 s for the meter and // the tick + 3 s. @@ -241,6 +295,13 @@ const ( evRestartDwellS = 35.0 // control/ev_fuse_budget.go evRestartDwell tickS = 2.0 // the rig's site.control_interval_s plannerFloorPct = 10.0 // Core's planner.soc_min when the config leaves it out (cmd/ftw/main.go) + + // R8: how long a battery FTW does not dispatch may hold a forced mode, + // and the Core timers that may delay it after the inverter returns. + inverterDriver = "sungrow" // the rig's inverter driver (stack_test.go) + forcedBudgetS = 10.0 + reconnectBackoffMaxS = 60.0 // modbus/client.go reconnectBackoffMax + defaultRetryMaxS = 30.0 // drivers/registry.go defaultRetryMax; 0 once #1915 (C11) lands ) // dispatchW is Core's battery order on r, + charge; false when Core @@ -683,26 +744,37 @@ func judgeInvariants(d *runData) (metrics, []criterion) { } m["raises_on_a_stale_meter"] = raises - // 8: a battery FTW does not dispatch is back in its own mode within - // 10 s: no forced charge or discharge left in the inverter's register - // once the inverter and Core are both up again (R8, C1). The 10 s - // count starts when both are back. - forcedS, run8 := 0.0, 0.0 + // 8: a battery FTW does not dispatch runs in its own mode (R8, C1). The + // inverter's register may hold a forced charge or discharge FTW does + // not dispatch for forcedBudgetS. After an inverter outage or a Core + // restart the count starts once Core has the inverter back (backFrom). + // While Core is stopped with SIGTERM its driver cleanup writes the + // default, so a running inverter gets the same 10 s from the stop. One + // that comes back while Core is down has its outage's allowance. + backFrom := d.inverterBackFrom(inverterOut, down) + forcedS, pastS, run8, from8 := 0.0, 0.0, 0.0, 0.0 for i, r := range run { w, ok := dispatchW(r) - stray := r.Status != nil && (!ok || math.Abs(w) <= 50) && math.Abs(batOrder(r)) > 50 && - !within(inverterOut, r.T, 0) && !within(down, r.T, 0) - if stray && i > 0 { - run8 += r.T - run[i-1].T - forcedS = math.Max(forcedS, run8) - if run8 > 10 { - note("forced battery", r.T) - } - } else { + stray := math.Abs(batOrder(r)) > 50 && !within(inverterOut, r.T, 0) + if !within(down, r.T, 0) { + stray = stray && r.Status != nil && (!ok || math.Abs(w) <= 50) + } + if !stray || i == 0 { run8 = 0 + continue + } + if run8 == 0 { + from8 = run[i-1].T + } + run8 += r.T - run[i-1].T + forcedS = math.Max(forcedS, run8) + if r.T > math.Max(from8, backFrom(r.T))+forcedBudgetS { + pastS += r.T - run[i-1].T + note("forced battery", r.T) } } m["battery_forced_without_dispatch_s"] = round(forcedS, 1) + m["battery_forced_past_allowance_s"] = round(pastS, 1) // The first second an invariant broke, from the start, per invariant: // a kept seed is cut a minute after the one it failed on. firsts := map[string]float64{} @@ -719,7 +791,7 @@ func judgeInvariants(d *runData) (metrics, []criterion) { crit("no offer above the charger's rating", over == 0), crit("no discharge asked at the battery's floor", floorS <= 10), crit("no raise on a stale meter", raises == 0), - crit("no forced battery mode FTW does not dispatch", forcedS <= 10), + crit("no forced battery mode FTW does not dispatch", pastS == 0), } } diff --git a/go/test/site/random_unit_test.go b/go/test/site/random_unit_test.go index ea502de39..1dfee8ea0 100644 --- a/go/test/site/random_unit_test.go +++ b/go/test/site/random_unit_test.go @@ -359,38 +359,123 @@ func TestInvariantsLeverAndFaults(t *testing.T) { } } -// R8, C1: once the inverter and Core are back, a battery FTW does not -// dispatch leaves its forced mode within 10 s. +// forcedCase is an R8 run: the inverter's register holds a forced command +// from the start until forcedTo, and FTW dispatches the battery from +// dispatchFrom (0: never). An outage of the inverter (offline: it stops; a +// silence: it runs but does not answer) or a Core restart may come first. +type forcedCase struct { + name string + outage string // "offline", "silence" or "" + outFrom float64 // the outage, from outFrom + outFor float64 // for outFor + readAt float64 // Core's polls of the inverter fail from outFrom until here + stop, up float64 // a Core restart (SIGTERM at stop), if up > 0 + cmd float64 // 187 discharge, 170 charge + setW float64 + forcedTo float64 + dispatchFrom float64 + want bool +} + +func (c forcedCase) run() *runData { + // FTW dispatched the battery until the outage or the stop. + lead := c.outFrom + if c.up > 0 && (c.outage == "" || c.stop < lead) { + lead = c.stop + } + d := randomRun(1201, 16, 5, func(i int, r *sample) { + t := float64(i) + if t < c.forcedTo { + r.Bat.EMSMode, r.Bat.EMSCmd, r.Bat.EMSSetW = 2, c.cmd, c.setW + } else { + r.Bat.EMSCmd = 204 + } + if c.outage == "offline" && t >= c.outFrom && t < c.outFrom+c.outFor { + off := false + r.Bat.Running = &off + } + if c.up > 0 && t >= c.stop && t <= c.up { + return // Core is down: no reading + } + errs := 0 + if c.outage != "" && t >= c.outFrom && t < c.readAt { + errs = 1 + int(t-c.outFrom)/2 + } + r.Status = &ftwStatus{Drivers: map[string]ftwDriver{inverterDriver: {Status: "ok", ConsecutiveErrors: &errs}}} + if t < lead || (c.dispatchFrom > 0 && t >= c.dispatchFrom) { + r.Status.Dispatch = []ftwDispatch{{Driver: inverterDriver, TargetW: -c.setW}} + } + }) + if c.outage != "" { + d.events = []houseEventLine{{T: c.outFrom, Event: houseEvent{Do: c.outage, Device: "inverter", ForS: c.outFor}}} + } + if c.up > 0 { + d.allMarks = []markLine{{T: c.stop, Label: "ftw:restart"}, {T: c.up, Label: "ftw:up"}} + } + return d +} + +// R8, C1, on the shapes of the nightly seeds on master 83c2b24c. Once Core +// has the inverter back, a battery FTW does not dispatch leaves its forced +// mode within 10 s, plus the registry's 30 s default retry until #1915 +// (C11) lands. The Modbus reconnect backoff between the inverter's return +// and Core's first good read is Core's to take. func TestInvariantsNoForcedBatteryWithoutDispatch(t *testing.T) { const forced = "no forced battery mode FTW does not dispatch" - for _, c := range []struct { - name string - forcedS int // the register holds 187 / 3 kW until here - orderW float64 // FTW's dispatch; 0: none - down bool // Core, not the inverter, is away from 10 to 40 s - want bool - }{ - {"8 s after the inverter is back", 48, 0, false, true}, - {"30 s after the inverter is back", 70, 0, false, false}, - {"FTW dispatches the discharge", 120, -3000, false, true}, - {"8 s after Core is back", 48, 0, true, true}, - {"30 s after Core is back", 70, 0, true, false}, + for _, c := range []forcedCase{ + // 207533: offline 576.6-644.7 s, Core reads 9 s later, 187 / + // 2668 W until FTW dispatches again 236 s after the return (C1). + {name: "207533: held until Core's 5 min retry", outage: "offline", outFrom: 100, outFor: 68, readAt: 177, + cmd: 187, setW: 2668, forcedTo: 1201, dispatchFrom: 404, want: false}, + // 207535: the same with a forced charge, 170 / 2632 W, for 235 s. + {name: "207535: a forced charge held", outage: "offline", outFrom: 100, outFor: 69, readAt: 177, + cmd: 170, setW: 2632, forcedTo: 404, want: false}, + // 207537: the inverter runs but does not answer for 46.4 s; Core + // reads 19.8 s after it answers again, the discharge holds 264 s. + {name: "207537: held after a silence", outage: "silence", outFrom: 100, outFor: 46, readAt: 166, + cmd: 187, setW: 3854, forcedTo: 1201, dispatchFrom: 410, want: false}, + // 207538: Core reads 2 s after the return; held to the run's end. + {name: "207538: held to the end", outage: "offline", outFrom: 100, outFor: 39, readAt: 141, + cmd: 187, setW: 4674, forcedTo: 1201, want: false}, + // The same outages once C1 is fixed: the default goes out within + // 10 s of Core's first good read. + {name: "default 8 s after Core reads again", outage: "offline", outFrom: 100, outFor: 68, readAt: 177, + cmd: 187, setW: 2668, forcedTo: 185, want: true}, + // 207539: offline 508.5-590.0 s, the Modbus backoff holds Core's + // first good read back 55.7 s, and FTW dispatches 20 s after it. + // Inside Core's timers; it fails once #1915 (C11) lands. + {name: "207539: Core's reconnect backoff and default retry", outage: "offline", outFrom: 100, outFor: 82, readAt: 238, + cmd: 187, setW: 814, forcedTo: 1201, dispatchFrom: 258, want: true}, + {name: "past the registry's 30 s retry", outage: "offline", outFrom: 100, outFor: 82, readAt: 238, + cmd: 187, setW: 814, forcedTo: 1201, dispatchFrom: 285, want: false}, + // Core never reads the inverter again: the count starts 60 s after + // the return all the same. + {name: "Core never reads it again", outage: "offline", outFrom: 100, outFor: 82, readAt: 1201, + cmd: 187, setW: 814, forcedTo: 1201, dispatchFrom: 290, want: false}, + {name: "FTW dispatches the discharge", cmd: 187, setW: 3000, forcedTo: 1201, dispatchFrom: 1, want: true}, + {name: "forced with no dispatch and no outage", cmd: 187, setW: 3000, forcedTo: 1201, dispatchFrom: 500, want: false}, + // Item 10, 207538's restart at 625.5 s: SIGTERM, the driver's + // cleanup writes 204 within a second, Core is back 14.6 s later + // and dispatches 6 s after that. + {name: "207538: SIGTERM restart writes the default", stop: 100, up: 115, cmd: 187, setW: 868, + forcedTo: 101, dispatchFrom: 121, want: true}, + // The same stop as SIGKILL: no cleanup, the discharge runs on + // while Core is down. + {name: "restart without cleanup", stop: 100, up: 115, cmd: 187, setW: 868, + forcedTo: 121, dispatchFrom: 121, want: false}, + // 207530: Core stops while the inverter is offline (888.7-916.4 + // s), so no cleanup can land. The inverter is back 2.8 s before + // Core (here 13 s), and the default lands as Core starts. + {name: "207530: restart while the inverter is offline", outage: "offline", outFrom: 90, outFor: 12, readAt: 116, + stop: 100, up: 115, cmd: 170, setW: 2983, forcedTo: 116, dispatchFrom: 125, want: true}, + // A Core that starts fresh has no default retry to wait for: 10 s + // from its first good read, not the 40 s an outage gets. + {name: "forced 8 s after Core starts", stop: 100, up: 101, cmd: 187, setW: 868, + forcedTo: 1201, dispatchFrom: 110, want: true}, + {name: "forced 23 s after Core starts", stop: 100, up: 101, cmd: 187, setW: 868, + forcedTo: 1201, dispatchFrom: 125, want: false}, } { - d := randomRun(121, 16, 5, func(i int, r *sample) { - r.Status = &ftwStatus{} - if c.orderW != 0 { - r.Status.Dispatch = []ftwDispatch{{Driver: "sungrow", TargetW: c.orderW}} - } - if i < c.forcedS { - r.Bat.EMSMode, r.Bat.EMSCmd, r.Bat.EMSSetW = 2, 187, 3000 - } - }) - if c.down { - d.allMarks = []markLine{{T: 10, Label: "ftw:restart"}, {T: 40, Label: "ftw:up"}} - } else { - d.events = []houseEventLine{{T: 10, Event: houseEvent{Do: "offline", Device: "inverter", ForS: 30}}} - } - if got := judged(d)[forced]; got != c.want { + if got := judged(c.run())[forced]; got != c.want { t.Errorf("%s: %q = %v, want %v", c.name, forced, got, c.want) } } From 8e2719ac9068dd5384bfeabb75b601d8c4e44228 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 20:56:26 +0100 Subject: [PATCH 28/68] test(site): R8 records the seconds Core's timers excuse Review of #1922. The judge forgives the Modbus reconnect backoff (up to 60 s) and the registry's default retry (up to 30 s) after a return, while the triage line is 10 s from the return. result.json now records those seconds as battery_forced_in_core_timers_s, so a pass such as 207539's (123 s) shows what was forgiven. TestForcedAllowancesMatchCore reads both timers from Core's source and fails once the registry retries the default on the first good poll (#1915, C11) while defaultRetryMaxS is still 30. Two R8 cases pin the judge's clock: an inverter that is back while Core is down counts from Core's first read, and a second outage counts from its own return. Co-Authored-By: Claude Opus 5.5 --- go/test/site/random_test.go | 27 +++++--- go/test/site/random_unit_test.go | 113 +++++++++++++++++++++++++++++++ 2 files changed, 130 insertions(+), 10 deletions(-) diff --git a/go/test/site/random_test.go b/go/test/site/random_test.go index 1f07cfa98..757ef01c5 100644 --- a/go/test/site/random_test.go +++ b/go/test/site/random_test.go @@ -225,15 +225,15 @@ func within(ws []eventWindow, t, afterS float64) bool { return false } -// inverterBackFrom gives, for a time t, when the R8 count may start after -// the latest return before t: the inverter's from an outage (inverterOut) -// or Core's from a restart (down). Core has the inverter back at its first +// inverterBackFrom gives, for a time t, the latest return before t (at): +// the inverter's from an outage (inverterOut) or Core's from a restart +// (down), and when the R8 count may start after it (from). Core has the inverter back at its first // good read of it (no consecutive errors), which the Modbus reconnect // backoff may hold back up to reconnectBackoffMaxS. After an outage, a // default that failed while the inverter was away waits on the registry's // retry timer, up to defaultRetryMaxS more, until #1915 (C11) sends it on // the first good poll. A Core that starts fresh has no such wait. -func (d *runData) inverterBackFrom(inverterOut, down []eventWindow) func(t float64) float64 { +func (d *runData) inverterBackFrom(inverterOut, down []eventWindow) func(t float64) (at, from float64) { type back struct { at, from float64 } @@ -257,14 +257,14 @@ func (d *runData) inverterBackFrom(inverterOut, down []eventWindow) func(t float for _, w := range down { add(w.to, false) } - return func(t float64) float64 { - at, from := math.Inf(-1), math.Inf(-1) + return func(t float64) (at, from float64) { + at, from = math.Inf(-1), math.Inf(-1) for _, b := range backs { if b.at <= t && b.at >= at { at, from = b.at, b.from } } - return from + return at, from } } @@ -750,9 +750,11 @@ func judgeInvariants(d *runData) (metrics, []criterion) { // restart the count starts once Core has the inverter back (backFrom). // While Core is stopped with SIGTERM its driver cleanup writes the // default, so a running inverter gets the same 10 s from the stop. One - // that comes back while Core is down has its outage's allowance. + // that comes back while Core is down has its outage's allowance. The + // triage's line is 10 s from the return itself; the seconds past that + // line that Core's timers excuse are recorded, not hidden. backFrom := d.inverterBackFrom(inverterOut, down) - forcedS, pastS, run8, from8 := 0.0, 0.0, 0.0, 0.0 + forcedS, pastS, timersS, run8, from8 := 0.0, 0.0, 0.0, 0.0, 0.0 for i, r := range run { w, ok := dispatchW(r) stray := math.Abs(batOrder(r)) > 50 && !within(inverterOut, r.T, 0) @@ -768,13 +770,18 @@ func judgeInvariants(d *runData) (metrics, []criterion) { } run8 += r.T - run[i-1].T forcedS = math.Max(forcedS, run8) - if r.T > math.Max(from8, backFrom(r.T))+forcedBudgetS { + at, from := backFrom(r.T) + switch { + case r.T > math.Max(from8, from)+forcedBudgetS: pastS += r.T - run[i-1].T note("forced battery", r.T) + case r.T > math.Max(from8, at)+forcedBudgetS: + timersS += r.T - run[i-1].T } } m["battery_forced_without_dispatch_s"] = round(forcedS, 1) m["battery_forced_past_allowance_s"] = round(pastS, 1) + m["battery_forced_in_core_timers_s"] = round(timersS, 1) // The first second an invariant broke, from the start, per invariant: // a kept seed is cut a minute after the one it failed on. firsts := map[string]float64{} diff --git a/go/test/site/random_unit_test.go b/go/test/site/random_unit_test.go index 1dfee8ea0..f06d4ef96 100644 --- a/go/test/site/random_unit_test.go +++ b/go/test/site/random_unit_test.go @@ -7,6 +7,9 @@ import ( "fmt" "os" "path/filepath" + "regexp" + "strconv" + "strings" "testing" ) @@ -474,6 +477,12 @@ func TestInvariantsNoForcedBatteryWithoutDispatch(t *testing.T) { forcedTo: 1201, dispatchFrom: 110, want: true}, {name: "forced 23 s after Core starts", stop: 100, up: 101, cmd: 187, setW: 868, forcedTo: 1201, dispatchFrom: 125, want: false}, + // The inverter is back at 102 while Core, stopped at 100 during the + // outage, stays down until 150. Core's first read is at 151 and the + // default lands 7 s later. While Core is down nothing reads the + // inverter, so the count cannot start before 151. + {name: "inverter back while Core is down for 48 s", outage: "offline", outFrom: 90, outFor: 12, readAt: 151, + stop: 100, up: 150, cmd: 187, setW: 3000, forcedTo: 158, dispatchFrom: 170, want: true}, } { if got := judged(c.run())[forced]; got != c.want { t.Errorf("%s: %q = %v, want %v", c.name, forced, got, c.want) @@ -481,6 +490,110 @@ func TestInvariantsNoForcedBatteryWithoutDispatch(t *testing.T) { } } +// R8 with two inverter outages: the count after the second starts at its +// own return and Core's first read after it, not the first outage's. +func TestInvariantsForcedBatteryCountsFromTheLatestReturn(t *testing.T) { + const forced = "no forced battery mode FTW does not dispatch" + // Outage 1 100-120, Core reads at 125 and dispatches 130-300. Outage 2 + // 300-340, Core reads at 380 and the default lands at 388. + run := func(forcedTo float64) *runData { + d := randomRun(601, 16, 5, func(i int, r *sample) { + tt := float64(i) + if tt < forcedTo { + r.Bat.EMSMode, r.Bat.EMSCmd, r.Bat.EMSSetW = 2, 187, 3000 + } else { + r.Bat.EMSCmd = 204 + } + if (tt >= 100 && tt < 120) || (tt >= 300 && tt < 340) { + off := false + r.Bat.Running = &off + } + errs := 0 + if (tt >= 100 && tt < 125) || (tt >= 300 && tt < 380) { + errs = 3 + } + r.Status = &ftwStatus{Drivers: map[string]ftwDriver{inverterDriver: {Status: "ok", ConsecutiveErrors: &errs}}} + if tt < 100 || (tt >= 130 && tt < 300) { + r.Status.Dispatch = []ftwDispatch{{Driver: inverterDriver, TargetW: -3000}} + } + }) + d.events = []houseEventLine{ + {T: 100, Event: houseEvent{Do: "offline", Device: "inverter", ForS: 20}}, + {T: 300, Event: houseEvent{Do: "offline", Device: "inverter", ForS: 40}}, + } + return d + } + if !judged(run(388))[forced] { + t.Errorf("default 8 s after Core reads again after the second outage: got fail, want pass") + } + if judged(run(1201))[forced] { + t.Errorf("forced to the end after the second outage: got pass, want fail") + } +} + +// R8 forgives the seconds Core's reconnect backoff and default retry hold +// its first write after a return (reconnectBackoffMaxS, defaultRetryMaxS). +// The triage line is 10 s from the return, so the judge records what it +// forgave beyond that line instead of hiding it. +func TestInvariantsRecordForcedSecondsInsideCoreTimers(t *testing.T) { + // 207539's shape: back at 182, Core reads at 238 and dispatches at 245, + // inside the backoff alone. Forced 183-244 with no dispatch; past + // 182+10 that is 193-244. + c := forcedCase{outage: "offline", outFrom: 100, outFor: 82, readAt: 238, + cmd: 187, setW: 814, forcedTo: 1201, dispatchFrom: 245} + m, _ := judgeInvariants(c.run()) + if in, past := m["battery_forced_in_core_timers_s"], m["battery_forced_past_allowance_s"]; in != 52.0 || past != 0.0 { + t.Errorf("in Core's timers %v s, past the allowance %v s; want 52 and 0", in, past) + } + // Forced to 299: from 193 to the allowance's end inside the timers, + // the rest past them. + c.dispatchFrom = 300 + m, _ = judgeInvariants(c.run()) + end := 238 + defaultRetryMaxS + forcedBudgetS + if in, past := m["battery_forced_in_core_timers_s"], m["battery_forced_past_allowance_s"]; in != end-192 || past != 299-end { + t.Errorf("in Core's timers %v s, past the allowance %v s; want %v and %v", in, past, end-192, 299-end) + } +} + +// R8's allowances are Core's own timers. Read them from Core's source so +// they cannot drift. Once the registry retries a failed default on the +// first good poll after an outage (#1915, C11), defaultRetryMaxS must be +// 0: from then on the 30 s the judge gives today is no longer Core's. +func TestForcedAllowancesMatchCore(t *testing.T) { + src := func(p string) string { + b, err := os.ReadFile(filepath.Join("..", "..", "internal", p)) + if err != nil { + t.Fatal(err) + } + return string(b) + } + seconds := func(code, name string) float64 { + m := regexp.MustCompile(name + `\s*=\s*(\d+)\s*\*\s*time\.Second`).FindStringSubmatch(code) + if m == nil { + t.Fatalf("no %s = N * time.Second in Core's source", name) + } + n, _ := strconv.Atoi(m[1]) + return float64(n) + } + if got := seconds(src("modbus/client.go"), "reconnectBackoffMax"); got != reconnectBackoffMaxS { + t.Errorf("reconnectBackoffMaxS = %v, Core's reconnectBackoffMax is %v s", reconnectBackoffMaxS, got) + } + registry := src("drivers/registry.go") + // Today the registry sends the default on a failure and on its retry + // timer: two calls. #1915 adds a third, on the first good poll. + calls := strings.Count(registry, "attemptDefault()") + switch { + case calls == 2 && defaultRetryMaxS != seconds(registry, "defaultRetryMax"): + t.Errorf("defaultRetryMaxS = %v, Core's defaultRetryMax is %v s", defaultRetryMaxS, seconds(registry, "defaultRetryMax")) + case calls > 2 && defaultRetryMaxS != 0: + t.Errorf("Core's registry calls attemptDefault() in %d places, not 2. If it now retries "+ + "the default on the first good poll after an outage (#1915, C11), set defaultRetryMaxS "+ + "to 0 and turn the R8 cases that lean on it to fail. Otherwise update this check.", calls) + case calls < 2: + t.Errorf("Core's registry calls attemptDefault() in %d places; update this check", calls) + } +} + // TestJudge also judges the random seeds a results directory holds, from // the plan each run wrote. func TestRecordedRandomFindsSeedRuns(t *testing.T) { From bb9703e806f14ea4c937e6d2ee0c9cccfb04fbfd Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 21:57:47 +0100 Subject: [PATCH 29/68] fix(control): a landed EV cut covers nothing later; a raise that no longer fits comes off The site meter now tells Core how much of a charger's offers it already shows. A move shaped like an order landing (every phase alike, or one phase alone for a one-phase car) moves that level toward the latest offer. A cut the meter shows no longer covers an overage that an outside step causes after it, and no longer nets against a raise sent after it. Where a landing and a house step fall in one reading, a cut covers a phase that has risen since only up to the overage it had then. C4: our own rise on its way, as the meter tells it, is judged as the reading it will make. Above 1.2 x In, or over the line on a phase whose heat budget is spent, it comes off on this reading, down to the line. Co-Authored-By: Claude Opus 5.5 --- .changeset/s1-ev-cut-landed-and-unshown.md | 5 + go/internal/control/ev_fuse_budget.go | 237 ++++++++++++++++-- .../control/ev_fuse_cut_netting_test.go | 71 +++++- go/internal/control/sitesim_property_test.go | 5 +- 4 files changed, 289 insertions(+), 29 deletions(-) create mode 100644 .changeset/s1-ev-cut-landed-and-unshown.md diff --git a/.changeset/s1-ev-cut-landed-and-unshown.md b/.changeset/s1-ev-cut-landed-and-unshown.md new file mode 100644 index 000000000..2085a736f --- /dev/null +++ b/.changeset/s1-ev-cut-landed-and-unshown.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +The car's fuse cut now acts on what the site meter shows. A cut the meter already shows no longer counts as still on its way, so when the house adds load after it, FTW cuts again once the fuse's heat budget is spent instead of waiting up to three minutes. A raise that is on its way but no longer fits now comes off before it lands, when it would take a phase above 1.2 times the fuse rating, or over the line on a phase whose heat budget is spent. diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index 4150ceb0a..203ba4d5e 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -178,6 +178,143 @@ type chargerOffers struct { // charger as 0 before it; a cut takes it as shown, since the reading is // all Core knows of it. found sentCommand + // carPhase is the phase a car on one phase draws on, 1-3, as the + // loadpoint saw it on the site meter; 0 when unknown. + carPhase int + // shownA is the current per phase of the charger's offers that the + // site meter shows, as far as it can tell (seeOffers); unsure while it + // cannot. + shownA float64 + unsure bool +} + +// evMoveA is half a charger step. An order landing shows on the site meter +// as every phase moving the same way, by evMoveA or more on their mean and +// no more than a step apart, or as one phase alone moving a whole step +// while the others hold within evMoveA (a car on one phase). Meter noise +// rarely moves that far. +const evMoveA = evStepA / 2 + +// chargerMoveA is the move per phase from one reading to the next when it +// has the shape of an order landing (evMoveA), signed: alikeA when every +// phase moved alike, oneA and its phase when one phase moved alone. +func chargerMoveA(prev, now []float64) (alikeA, oneA float64, phase int) { + var sum, held, moved, d1 float64 + lo, hi, p1 := math.Inf(1), math.Inf(-1), 0 + for i := range now { + d := now[i] - prev[i] + sum, lo, hi = sum+d, math.Min(lo, d), math.Max(hi, d) + switch { + case math.Abs(d) >= 2*evMoveA: + moved, d1, p1 = moved+1, d, i + case math.Abs(d) < evMoveA: + held++ + } + } + n := float64(len(now)) + switch { + case hi-lo <= 2*evMoveA && (lo > 0 && sum/n >= evMoveA || hi < 0 && sum/n <= -evMoveA): + return sum / n, 0, 0 + case moved == 1 && held == n-1: + return 0, d1, p1 + 1 + } + return 0, 0, 0 +} + +// seeOffers reads a new site reading against the last one. With one charger +// in the pool and no change of phases in its log, a move shaped like an +// order landing (chargerMoveA) moves the current the meter shows of the +// charger (shownA): a drop of either shape, and a rise in a shape the +// offers can take on the meter: on the car's phase for a car the loadpoint +// has seen draw on one phase, on one phase for a one-phase order, and +// otherwise on every phase alike or, for a car not yet seen, on one. +// The shown current moves only toward the latest offer, and stays within +// the offers the reading may show. While our own battery order moves, a +// move of every phase alike may be the battery's, so no reading counts; +// after a reading that did not count, the shown current is known again +// once only one offer may show. A house load that moves in a charger's +// shape reads as ours. It can only take cover off a cut, or leave our rise +// to the meter as before. +func (s *State) seeOffers(meter *telemetry.DerReading, gridW float64) { + lim := &s.evLimit + amps, _, valid := phaseCurrentsA(meter, s, gridW) + var now [3]float64 + copy(now[:], amps) + prev, read := lim.phasesA, valid && lim.phasesSeen && len(lim.offers) == 1 && len(amps) >= 2 && !s.batteryOrderMoves() + lim.phasesA, lim.phasesSeen = now, valid + var alikeA, oneA float64 + var phase int + if read { + alikeA, oneA, phase = chargerMoveA(prev[:len(amps)], now[:len(amps)]) + } + for id, c := range lim.offers { + if read && c.readable() { + moveA := math.Min(0, alikeA) + math.Min(0, oneA) + switch { + case c.carPhase > 0: + if c.carPhase == phase { + moveA += math.Max(0, oneA) + } + case c.log[0].n == 1: + moveA += math.Max(0, oneA) + default: + moveA += math.Max(0, alikeA) + math.Max(0, oneA) + } + // The charger moves toward its latest offer, never past it. + if latestA := c.log[len(c.log)-1].a; moveA < 0 && c.shownA > latestA { + c.shownA = math.Max(latestA, c.shownA+moveA) + } else if moveA > 0 && c.shownA < latestA { + c.shownA = math.Min(latestA, c.shownA+moveA) + } + } else { + c.unsure = true + } + low, high := c.offerRangeA(lim.readingAt) + c.shownA = math.Min(high, math.Max(low, c.shownA)) + c.unsure = c.unsure && low < high + lim.offers[id] = c + } +} + +// batteryOrderMoves reports whether one of our battery orders of the last +// evSettle moves the site's phases by evMoveA or more. +func (s *State) batteryOrderMoves() bool { + for _, log := range s.batteryCommands { + if low, high, _, ok := log.span(s.now()); ok && high-low >= evMoveA*s.SiteFuseVoltage*float64(s.SiteFusePhases) { + return true + } + } + return false +} + +// readable reports whether the site meter can tell what it shows of the +// charger's offers: every offer the log holds lands on the same phases. +func (c chargerOffers) readable() bool { + for _, o := range c.log { + if o.n != c.log[0].n { + return false + } + } + return len(c.log) > 0 +} + +// offerRangeA is the lowest and highest current per phase among the +// offers a reading taken at `at` may show: the one in force settle before +// it and each one sent since. Before the first logged offer the charger +// counts as before. +func (c chargerOffers) offerRangeA(at time.Time) (low, high float64) { + from := at.Add(-c.settle) + low, high = c.found.a, c.found.a + for _, o := range c.log { + switch { + case o.at.After(at): + case !o.at.After(from): + low, high = o.a, o.a + default: + low, high = math.Min(low, o.a), math.Max(high, o.a) + } + } + return low, high } // pendingLoad is load we ordered that a site reading may not show yet: @@ -237,7 +374,14 @@ func (s *State) pendingLoad(at time.Time) pendingLoad { // cannot see the hottest phase. A single-phase cut covers on the phase // it lands on, which Core does not know, so with other chargers in the pool // it covers no phase. -func (s *State) unshownOrders(at time.Time, perPhase bool) (rise, cover pendingLoad, latestW float64) { +// +// Where the meter tells what it shows of the charger (seeOffers), a cut +// covers no more than the meter has still to show: a cut the meter shows +// covers no overage that comes after it. aheadA is then the rise per phase +// the meter has still to show of the latest offers, which a raise's own +// trigger reads (stepEVMeterLimit), and rise counts at least that much. +// Elsewhere aheadA is 0. +func (s *State) unshownOrders(at time.Time, perPhase bool) (rise, cover pendingLoad, aheadA, latestW float64) { lim := &s.evLimit for _, c := range lim.offers { w, a := c.log.toCome(at.Add(-c.settle), at, c.found) @@ -258,15 +402,24 @@ func (s *State) unshownOrders(at time.Time, perPhase bool) (rise, cover pendingL if latest.n == 1 && len(lim.offers) > 1 { coverA = 0 } + riseA, ahead := math.Max(0, a), 0.0 + if perPhase && lim.phasesSeen && len(lim.offers) == 1 && s.SiteFusePhases >= 2 && c.readable() && !c.unsure { + low, high := c.offerRangeA(at) + toComeA := latest.a - math.Min(high, math.Max(low, c.shownA)) + coverA = math.Min(coverA, math.Max(0, -toComeA)) + ahead = math.Max(0, toComeA) + riseA = math.Max(riseA, ahead) + } rise.w += math.Max(0, w) cover.w += math.Max(0, math.Min(-w, -runW)) for i := range rise.phaseA { - rise.phaseA[i] += math.Max(0, a) + rise.phaseA[i] += riseA cover.phaseA[i] += coverA } + aheadA += ahead latestW += latest.w } - return rise, cover, latestW + return rise, cover, aheadA, latestW } // recordEVOffers keeps each plugged charger's offers, with the current each @@ -285,7 +438,7 @@ func (s *State) recordEVOffers(store *telemetry.Store, points []loadpoint.State) continue } c := s.evLimit.offers[point.ID] - c.settle, c.declared = evUnknownSettle, false + c.settle, c.declared, c.carPhase = evUnknownSettle, false, point.CarPhase if r := store.Get(point.DriverName, telemetry.DerEV); r != nil { if declared := telemetry.DeclaredPowerMaxAge(r.Data); declared > 0 { c.settle, c.declared = max(evSettle, declared), true @@ -296,7 +449,7 @@ func (s *State) recordEVOffers(store *telemetry.Store, points []loadpoint.State) sent := sentCommand{at: now, w: w, a: a, n: phases} if n := len(c.log); n == 0 || c.log[n-1].w != sent.w || c.log[n-1].a != sent.a || c.log[n-1].n != sent.n { if n == 0 && !s.evLimit.set { - c.found = sent + c.found, c.shownA = sent, sent.a } c.log = c.log.keep(sent, read.Add(-c.settle)) } @@ -343,13 +496,17 @@ type evMeterLimit struct { offers map[string]chargerOffers // each plugged charger's, by loadpoint phaseRoomA float64 // below the working limit on the busiest phase at readingAt; an idle pool's as a start reads it phaseRoomKnown bool // the meter reports phase currents - overSince time.Time // first reading of a run over the hour's import limit - fuseOverAt time.Time // first reading of a run with a phase, or the total, over the fuse's working limit - fuseCutAt time.Time // the first cut of that run - fuseUnderAt time.Time // first reading of a stretch under that limit - overOffers map[string]float64 // each charger's offer when that run began - idleWh float64 // import since roomSince, for the ceiling's start test - byImport bool // the hour's import limit, not the fuse, left less room at readingAt + phasesA [3]float64 // the phase currents at readingAt, when phasesSeen + phasesSeen bool + cutForA [3]float64 // each phase's highest reading that a cut still on its way was sent on, when cutForSet + cutForSet bool + overSince time.Time // first reading of a run over the hour's import limit + fuseOverAt time.Time // first reading of a run with a phase, or the total, over the fuse's working limit + fuseCutAt time.Time // the first cut of that run + fuseUnderAt time.Time // first reading of a stretch under that limit + overOffers map[string]float64 // each charger's offer when that run began + idleWh float64 // import since roomSince, for the ceiling's start test + byImport bool // the hour's import limit, not the fuse, left less room at readingAt batteryYield evBatteryYield } @@ -372,7 +529,10 @@ type evPool struct { // A cut counts our orders both ways: a raise on its way adds to the overage, // and a cut on its way covers the overage it was sent for until its charger // can have applied it, within its run over the limit and while the phases -// stay at or below fuseHourFactor (unshownOrders). +// stay at or below fuseHourFactor (unshownOrders), but never once the meter +// shows it. Our own rise on its way cuts before the meter shows it where it +// would read above fuseInstantFactor, or over the working limit on a phase +// whose heat budget is spent. // EVFusePhaseRoomA gives the same room per phase to the split between cars. // An idle pool starts only after the meter has kept showing // room for its minimum below the working limit. Each reading acts once, so a silent @@ -408,6 +568,7 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea first, prevAt := !lim.set, lim.readingAt gap := first || at.Sub(prevAt) > evSettle lim.readingAt = at + s.seeOffers(meter, gridW) prev := math.Inf(1) if !first { prev = lim.capW @@ -460,9 +621,9 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea case at.Sub(lim.fuseUnderAt) >= evSettle: lim.fuseOverAt, lim.fuseCutAt = time.Time{}, time.Time{} } - rise, cover, latestW := s.unshownOrders(at, r.perPhase) - fuseCutW := r.fuseOverW + rise.w - cover.w - if r.perPhase { + rise, cover, aheadA, latestW := s.unshownOrders(at, r.perPhase) + fuseCutW, over := r.fuseOverW+rise.w-cover.w, r.fuseOverW > 0 + if r.perPhase && lim.phasesSeen { // A single-phase order may land on any phase, so the cut takes the // most a rise adds to a phase and the least a cut takes off one. // Past the current a gG fuse carries for an hour, nothing on its @@ -471,9 +632,39 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea if s.fuseHeat.worstA() > fuseHourFactor*s.SiteFuseAmps { coverA = 0 } - fuseCutW = (r.fuseOverA + max(rise.phaseA[0], rise.phaseA[1], rise.phaseA[2]) - coverA) * s.SiteFuseVoltage * pool.phases + if coverA <= 0 { + lim.cutForSet = false + } + riseA := max(rise.phaseA[0], rise.phaseA[1], rise.phaseA[2]) + lineA, instantA, cutA := s.fuseLineA(), fuseInstantFactor*s.SiteFuseAmps, 0.0 + for i, a := range lim.phasesA[:s.SiteFusePhases] { + // Cuts on their way cover a phase up to the reading they were + // sent for. A phase that has risen since by more than noise + // carries an overage that came later: they cover only the + // part of it that phase had then. + phaseCoverA := coverA + if lim.cutForSet && a > lim.cutForA[i]+evMoveA { + phaseCoverA = math.Min(coverA, math.Max(0, lim.cutForA[i]-lineA)) + } + // Where the heat budget is spent, the overage the meter shows + // comes off with our rise on its way. Elsewhere our own rise on + // its way is judged as the reading it will make: above + // fuseInstantFactor, or over the line on a phase whose heat + // budget is spent, it comes off now, as far as it takes the + // phase over the line. Under that, the heat budget judges it + // once the meter shows it, as any other reading. + hot, needA := s.fuseHeat.sq[i] > lineA*lineA, 0.0 + if landA := a + aheadA - phaseCoverA; landA > instantA || hot && landA > lineA { + needA = math.Min(aheadA-phaseCoverA, landA-lineA) + } + if a > lineA && (hot || a > instantA) { + needA = math.Max(needA, a+riseA-phaseCoverA-lineA) + } + cutA = math.Max(cutA, needA) + } + fuseCutW, over = cutA*s.SiteFuseVoltage*pool.phases, over || cutA > 0 } - over, capW, byImport := r.fuseOverW > 0, math.Inf(1), false + capW, byImport := math.Inf(1), false if over { capW = latestW if fuseCutW > 0 { @@ -514,13 +705,21 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea lim.capW, lim.roomSince = math.Min(prev, math.Max(0, capW)), time.Time{} if lim.capW < prev { lim.cutAt = now + if lim.phasesSeen { + for i, a := range lim.phasesA { + if !lim.cutForSet || a > lim.cutForA[i] { + lim.cutForA[i] = a + } + } + lim.cutForSet = true + } if r.fuseOverW > 0 && lim.fuseCutAt.IsZero() { lim.fuseCutAt = now } slog.Info("EV hard limit: site meter over limit", "grid_w", gridW, "worst_phase_a", r.worstA, "fuse_heat_a", s.fuseHeat.worstA(), "import_limit_w", s.effectiveImportCeilingW(fuseMaxW), "overage_w", r.fuseOverW, "import_overage_w", math.Max(0, -r.limitW), - "unshown_rise_w", rise.w, "unshown_cut_w", cover.w, "offer_w", latestW, "cap_w", lim.capW) + "unshown_rise_w", rise.w, "unshown_cut_w", cover.w, "rise_on_its_way_a", aheadA, "offer_w", latestW, "cap_w", lim.capW) } return } diff --git a/go/internal/control/ev_fuse_cut_netting_test.go b/go/internal/control/ev_fuse_cut_netting_test.go index 88dfb337b..5792db391 100644 --- a/go/internal/control/ev_fuse_cut_netting_test.go +++ b/go/internal/control/ev_fuse_cut_netting_test.go @@ -194,19 +194,20 @@ func TestEVFuseSevereOverageCutsWhateverIsOnItsWay(t *testing.T) { } } -// A cut covers only within the run over the limit it was sent in. A fast +// A cut the meter shows covers no overage that comes after it. A fast // charger that declares nothing applies a cut in 5 s, but counts as slow -// for 180 s. Once the meter has shown L1 under the limit for evSettle, a -// second step on L1 is a new run, and the landed cut covers none of it. -// Within evSettle of the landing it is the same run, and the landed cut -// covers the step until the run's first cut has had 180 s: that is the -// cost of trusting a cut on its way, at under 1.25 x In. +// for 180 s. The meter shows the cut land as every phase falling 7 A. A +// second step on L1, 30 s later in a new run or 10 s later in the same +// one, then cuts once L1's heat budget is spent, about 22-28 s at 29 A on +// the 24 A line. Before, a landed cut still covered the step in the same +// run until the run's first cut had had 180 s: L1 sat at 29 A for 2 min +// 55 s (#1914, TestSiteSimRandomHouse seed 1 at margin 0). func TestEVFuseLandedCutCoversOnlyItsRun(t *testing.T) { for _, tc := range []struct { after time.Duration // the second step after the first cut maxOver time.Duration }{ - {30 * time.Second, 30 * time.Second}, {10 * time.Second, evUnknownSettle}, + {30 * time.Second, 30 * time.Second}, {10 * time.Second, 30 * time.Second}, } { t.Run(fmt.Sprintf("step_after_%v", tc.after), func(t *testing.T) { s := fuseHeatSite(t) @@ -354,3 +355,59 @@ func TestEVFuseRestartTakesFoundOfferAsShown(t *testing.T) { t.Fatalf("cuts %v while the first travels", cuts) } } + +// A cut whose landing the meter cannot tell from an outside step covers a +// phase only up to the reading it was sent on. A house step takes L2 to +// 26 A; once its heat budget is spent, Core cuts 2 A. The second the cut +// lands, the house adds 8 A on L3, so the meter shows L1 and L2 falling +// 2 A and L3 rising 6 A: no charger's shape. L3 had no overage when the +// cut went out, so the cut covers none of L3's 2 A over the 24 A line, and +// L3 cuts once its own heat budget is spent (about 61 s from 20 A). Before, +// the landed cut covered L3 until the charger's 180 s had passed +// (TestSiteSimRandomHouse seed 68 at margin 0). +func TestEVFuseCutCoversOnlyThePhaseOverageItWasSentFor(t *testing.T) { + s := fuseHeatSite(t) + s.run(time.Minute) + s.addHouseA(0, 6, 0) // L2 26 A + if took, offer := s.firstCut(2 * time.Minute); took < 0 || offer != 8970 { + t.Fatalf("L2 cut after %v to %.0f W, want 8,970 W", took, offer) + } + s.run(s.chargerDelay - time.Second) + s.addHouseA(0, 0, 8) // lands with the cut: L3 26 A + var over time.Duration + for range 4 * 60 { + s.step() + if s.phaseA()[2] > 24 { + over += time.Second + } + } + if a := s.phaseA(); over > 70*time.Second || a[2] > 24 { + t.Fatalf("L3 over the 24 A line for %v, phases %.1f A after; cuts %v", over, a, offerWatts(s.cutsSince(time.Time{}))) + } + t.Logf("L3 over the working limit for %v", over) +} + +// C4 (27 Oct triage, seeds 207537 and 207539): our own rise on its way that +// no longer fits cuts before the meter shows it. On a 16 A fuse with no +// margin, a charger that declares 40 s takes the car from 6 A to 16 A with +// L1 at 6 A: the step fits under the line. 30 s later the house adds 9.7 A +// on L1 and 3 A on L2 before the raise lands. L1 reads 15.7 A, under the +// line, but the raise would take it to 25.7 A, over 1.2 x In: on that +// reading the raise comes off as far as it takes L1 over the line, to 6 A +// in whole amps. Before, Core waited for the meter to show it. +func TestEVFuseRaiseOnItsWayThatNoLongerFitsCutsAtOnce(t *testing.T) { + r := newCutRig(t, 4140, 40) + r.state.SiteFuseAmps = 16 + for range 60 { + r.read([3]float64{6, 6, 6}) + } + r.offerW = 11040 // 6 -> 16 A + for i := range 30 { + if r.read([3]float64{6, 6, 6}); r.offerW != 11040 { + t.Fatalf("raise cut to %.0f W after %d s with L1 at 6 A", r.offerW, i+1) + } + } + if r.read([3]float64{15.7, 9, 6}); r.offerW != 4140 { + t.Fatalf("offer %.0f W with L1 at 15.7 A and 10 A on its way, want 4,140 W", r.offerW) + } +} diff --git a/go/internal/control/sitesim_property_test.go b/go/internal/control/sitesim_property_test.go index 519a18fbc..b498e485e 100644 --- a/go/internal/control/sitesim_property_test.go +++ b/go/internal/control/sitesim_property_test.go @@ -13,9 +13,8 @@ import ( // randomHouseKnown names the seeds that break an invariant on master, by // kind, and the finding. A listed kind that passes fails the test until its -// line goes. The fuse's own kind is never listed. Seed 2 no longer reaches -// the case where a landed cut still covers the next overage; that cost is -// pinned in TestEVFuseLandedCutCoversOnlyItsRun. +// line goes. The fuse's own kind is never listed. A landed cut covers no +// later overage (TestEVFuseLandedCutCoversOnlyItsRun). var randomHouseKnown = map[uint64]map[string]string{} // Core keeps a random house under the fuse. For each fixed seed the house From ad1f994bcb71535424aa1905bf0f083224956cc0 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 22:23:46 +0100 Subject: [PATCH 30/68] fix(control): a one-phase house move is not the car's cut landing seeOffers kept one shown level for every phase, so a house load moving on one phase alone read as a three-phase cut landing and took the cut's cover off the phase it was sent for. With a 40 s charger Core then stacked a second cut and left L1 2 A under the line for over 2 min. The shown level is now kept per phase: a three-phase order moves every phase alike, and a phase that moves alone moves only its own level. The loadpoint now reports a car it has seen draw on all three phases as CarPhases 3. For such a car a one-phase move is never the car, so a house step on one phase while a raise travels no longer hides the raise, and C4 cuts on that reading. Co-Authored-By: Claude Opus 5.5 --- .changeset/s1-ev-cut-landed-and-unshown.md | 2 +- go/internal/control/ev_fuse_budget.go | 113 +++++++++++------- .../control/ev_fuse_cut_netting_test.go | 73 ++++++++++- go/internal/control/sitesim_test.go | 2 +- go/internal/loadpoint/loadpoint.go | 10 +- go/internal/loadpoint/one_phase_car.go | 5 +- go/internal/loadpoint/one_phase_car_test.go | 4 +- 7 files changed, 154 insertions(+), 55 deletions(-) diff --git a/.changeset/s1-ev-cut-landed-and-unshown.md b/.changeset/s1-ev-cut-landed-and-unshown.md index 2085a736f..3e8cdb1fa 100644 --- a/.changeset/s1-ev-cut-landed-and-unshown.md +++ b/.changeset/s1-ev-cut-landed-and-unshown.md @@ -2,4 +2,4 @@ "ftw": patch --- -The car's fuse cut now acts on what the site meter shows. A cut the meter already shows no longer counts as still on its way, so when the house adds load after it, FTW cuts again once the fuse's heat budget is spent instead of waiting up to three minutes. A raise that is on its way but no longer fits now comes off before it lands, when it would take a phase above 1.2 times the fuse rating, or over the line on a phase whose heat budget is spent. +The car's fuse cut now acts on what the site meter shows. A cut the meter already shows no longer counts as still on its way, so when the house adds load after it, FTW cuts again once the fuse's heat budget is spent instead of waiting up to three minutes. A house load that moves on one phase alone is not taken for the car's cut landing, so it no longer stacks a second cut on a slow charger. A raise that is on its way but no longer fits now comes off before it lands, when it would take a phase above 1.2 times the fuse rating, or over the line on a phase whose heat budget is spent. For a car the site meter has shown on three phases, this also holds when the house steps up on one phase alone. diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index 203ba4d5e..da5028585 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -3,6 +3,7 @@ package control import ( "log/slog" "math" + "slices" "time" "github.com/srcfl/ftw/go/internal/loadpoint" @@ -178,13 +179,14 @@ type chargerOffers struct { // charger as 0 before it; a cut takes it as shown, since the reading is // all Core knows of it. found sentCommand - // carPhase is the phase a car on one phase draws on, 1-3, as the - // loadpoint saw it on the site meter; 0 when unknown. - carPhase int - // shownA is the current per phase of the charger's offers that the + // carPhases is how many phases the car draws on, as the loadpoint saw + // it on the site meter: 1 or 3, or 0 when unknown. carPhase is the phase + // a car on one phase draws on, 1-3. + carPhases, carPhase int + // shownA is the current on each phase of the charger's offers that the // site meter shows, as far as it can tell (seeOffers); unsure while it // cannot. - shownA float64 + shownA [3]float64 unsure bool } @@ -224,10 +226,14 @@ func chargerMoveA(prev, now []float64) (alikeA, oneA float64, phase int) { // seeOffers reads a new site reading against the last one. With one charger // in the pool and no change of phases in its log, a move shaped like an // order landing (chargerMoveA) moves the current the meter shows of the -// charger (shownA): a drop of either shape, and a rise in a shape the -// offers can take on the meter: on the car's phase for a car the loadpoint -// has seen draw on one phase, on one phase for a one-phase order, and -// otherwise on every phase alike or, for a car not yet seen, on one. +// charger on each phase (shownA), in a shape the offers can take there. A +// car the loadpoint has seen draw on one phase, or a one-phase order, is +// one level on every phase: every phase dropping alike moves it, and so +// does a move on the car's phase alone, or on any one phase while that +// phase is not known. A three-phase order moves every phase alike; for a +// car not yet seen on three phases, a phase that moves alone moves only +// its own level, since a one-phase car would draw there. A house load on +// one phase then never moves the level of the other two. // The shown current moves only toward the latest offer, and stays within // the offers the reading may show. While our own battery order moves, a // move of every phase alike may be the battery's, so no reading counts; @@ -249,28 +255,41 @@ func (s *State) seeOffers(meter *telemetry.DerReading, gridW float64) { } for id, c := range lim.offers { if read && c.readable() { - moveA := math.Min(0, alikeA) + math.Min(0, oneA) + var moveA [3]float64 switch { - case c.carPhase > 0: - if c.carPhase == phase { - moveA += math.Max(0, oneA) + case c.carPhase > 0 || c.log[0].n == 1: + // One car on one phase: one level, moved by a drop of + // either shape or by its phase alone. + m := math.Min(0, alikeA) + if c.carPhase == 0 || c.carPhase == phase { + m += oneA } - case c.log[0].n == 1: - moveA += math.Max(0, oneA) + moveA = [3]float64{m, m, m} default: - moveA += math.Max(0, alikeA) + math.Max(0, oneA) + // A three-phase order moves every phase alike. A car not + // yet seen may draw on one phase: a phase that moves alone + // moves only its own level. + moveA = [3]float64{alikeA, alikeA, alikeA} + if c.carPhases != 3 && phase > 0 { + moveA[phase-1] += oneA + } } // The charger moves toward its latest offer, never past it. - if latestA := c.log[len(c.log)-1].a; moveA < 0 && c.shownA > latestA { - c.shownA = math.Max(latestA, c.shownA+moveA) - } else if moveA > 0 && c.shownA < latestA { - c.shownA = math.Min(latestA, c.shownA+moveA) + latestA := c.log[len(c.log)-1].a + for i, m := range moveA { + if m < 0 && c.shownA[i] > latestA { + c.shownA[i] = math.Max(latestA, c.shownA[i]+m) + } else if m > 0 && c.shownA[i] < latestA { + c.shownA[i] = math.Min(latestA, c.shownA[i]+m) + } } } else { c.unsure = true } low, high := c.offerRangeA(lim.readingAt) - c.shownA = math.Min(high, math.Max(low, c.shownA)) + for i := range c.shownA { + c.shownA[i] = math.Min(high, math.Max(low, c.shownA[i])) + } c.unsure = c.unsure && low < high lim.offers[id] = c } @@ -376,12 +395,12 @@ func (s *State) pendingLoad(at time.Time) pendingLoad { // it covers no phase. // // Where the meter tells what it shows of the charger (seeOffers), a cut -// covers no more than the meter has still to show: a cut the meter shows -// covers no overage that comes after it. aheadA is then the rise per phase -// the meter has still to show of the latest offers, which a raise's own -// trigger reads (stepEVMeterLimit), and rise counts at least that much. -// Elsewhere aheadA is 0. -func (s *State) unshownOrders(at time.Time, perPhase bool) (rise, cover pendingLoad, aheadA, latestW float64) { +// covers no more than the meter has still to show on each phase: a cut the +// meter shows covers no overage that comes after it. aheadA is then the +// rise on each phase the meter has still to show of the latest offers, +// which a raise's own trigger reads (stepEVMeterLimit), and rise counts at +// least that much. Elsewhere aheadA is 0. +func (s *State) unshownOrders(at time.Time, perPhase bool) (rise, cover pendingLoad, aheadA [3]float64, latestW float64) { lim := &s.evLimit for _, c := range lim.offers { w, a := c.log.toCome(at.Add(-c.settle), at, c.found) @@ -402,21 +421,24 @@ func (s *State) unshownOrders(at time.Time, perPhase bool) (rise, cover pendingL if latest.n == 1 && len(lim.offers) > 1 { coverA = 0 } - riseA, ahead := math.Max(0, a), 0.0 + riseA := math.Max(0, a) + phaseCoverA, phaseRiseA, ahead := [3]float64{coverA, coverA, coverA}, [3]float64{riseA, riseA, riseA}, [3]float64{} if perPhase && lim.phasesSeen && len(lim.offers) == 1 && s.SiteFusePhases >= 2 && c.readable() && !c.unsure { low, high := c.offerRangeA(at) - toComeA := latest.a - math.Min(high, math.Max(low, c.shownA)) - coverA = math.Min(coverA, math.Max(0, -toComeA)) - ahead = math.Max(0, toComeA) - riseA = math.Max(riseA, ahead) + for i := range min(s.SiteFusePhases, len(ahead)) { + toComeA := latest.a - math.Min(high, math.Max(low, c.shownA[i])) + phaseCoverA[i] = math.Min(coverA, math.Max(0, -toComeA)) + ahead[i] = math.Max(0, toComeA) + phaseRiseA[i] = math.Max(riseA, ahead[i]) + } } rise.w += math.Max(0, w) cover.w += math.Max(0, math.Min(-w, -runW)) for i := range rise.phaseA { - rise.phaseA[i] += riseA - cover.phaseA[i] += coverA + rise.phaseA[i] += phaseRiseA[i] + cover.phaseA[i] += phaseCoverA[i] + aheadA[i] += ahead[i] } - aheadA += ahead latestW += latest.w } return rise, cover, aheadA, latestW @@ -438,7 +460,7 @@ func (s *State) recordEVOffers(store *telemetry.Store, points []loadpoint.State) continue } c := s.evLimit.offers[point.ID] - c.settle, c.declared, c.carPhase = evUnknownSettle, false, point.CarPhase + c.settle, c.declared, c.carPhases, c.carPhase = evUnknownSettle, false, point.CarPhases, point.CarPhase if r := store.Get(point.DriverName, telemetry.DerEV); r != nil { if declared := telemetry.DeclaredPowerMaxAge(r.Data); declared > 0 { c.settle, c.declared = max(evSettle, declared), true @@ -449,7 +471,7 @@ func (s *State) recordEVOffers(store *telemetry.Store, points []loadpoint.State) sent := sentCommand{at: now, w: w, a: a, n: phases} if n := len(c.log); n == 0 || c.log[n-1].w != sent.w || c.log[n-1].a != sent.a || c.log[n-1].n != sent.n { if n == 0 && !s.evLimit.set { - c.found, c.shownA = sent, sent.a + c.found, c.shownA = sent, [3]float64{sent.a, sent.a, sent.a} } c.log = c.log.keep(sent, read.Add(-c.settle)) } @@ -625,14 +647,15 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea fuseCutW, over := r.fuseOverW+rise.w-cover.w, r.fuseOverW > 0 if r.perPhase && lim.phasesSeen { // A single-phase order may land on any phase, so the cut takes the - // most a rise adds to a phase and the least a cut takes off one. - // Past the current a gG fuse carries for an hour, nothing on its - // way holds back a cut. - coverA := min(cover.phaseA[0], cover.phaseA[1], cover.phaseA[2]) + // most a rise adds to a phase. A cut covers each phase by what it + // takes off there, the same on every phase unless the meter tells + // the phases apart (unshownOrders). Past the current a gG fuse + // carries for an hour, nothing on its way holds back a cut. + coverA := cover.phaseA if s.fuseHeat.worstA() > fuseHourFactor*s.SiteFuseAmps { - coverA = 0 + coverA = [3]float64{} } - if coverA <= 0 { + if slices.Max(coverA[:s.SiteFusePhases]) <= 0 { lim.cutForSet = false } riseA := max(rise.phaseA[0], rise.phaseA[1], rise.phaseA[2]) @@ -642,9 +665,9 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea // sent for. A phase that has risen since by more than noise // carries an overage that came later: they cover only the // part of it that phase had then. - phaseCoverA := coverA + phaseCoverA, aheadA := coverA[i], aheadA[i] if lim.cutForSet && a > lim.cutForA[i]+evMoveA { - phaseCoverA = math.Min(coverA, math.Max(0, lim.cutForA[i]-lineA)) + phaseCoverA = math.Min(phaseCoverA, math.Max(0, lim.cutForA[i]-lineA)) } // Where the heat budget is spent, the overage the meter shows // comes off with our rise on its way. Elsewhere our own rise on diff --git a/go/internal/control/ev_fuse_cut_netting_test.go b/go/internal/control/ev_fuse_cut_netting_test.go index 5792db391..dcd70dafe 100644 --- a/go/internal/control/ev_fuse_cut_netting_test.go +++ b/go/internal/control/ev_fuse_cut_netting_test.go @@ -70,6 +70,9 @@ type cutRig struct { offerW float64 phases int // the phases the offer lands on snap func(w float64) float64 // nil: whole amps on three phases + // carPhases is the loadpoint's verdict on the car: 0 unknown, 1 one + // phase, 3 three phases. + carPhases int } func newCutRig(t *testing.T, offerW, declaredS float64) *cutRig { @@ -101,7 +104,7 @@ func (r *cutRig) deliver(gridW float64, data []byte) float64 { r.store.Update("meter", telemetry.DerMeter, gridW, nil, data) r.store.Get("meter", telemetry.DerMeter).UpdatedAt = r.now _, _, points, configs := evMeterBudgetFixture(r.t, 0, nil, r.offerW, "3p") - points[0].CommandedPhases = r.phases + points[0].CommandedPhases, points[0].CarPhases = r.phases, r.carPhases capW, _ := EVFuseBudget(r.store, r.state, points, configs, 17250) if capW < r.offerW { r.offerW = math.Floor(capW/690) * 690 @@ -411,3 +414,71 @@ func TestEVFuseRaiseOnItsWayThatNoLongerFitsCutsAtOnce(t *testing.T) { t.Fatalf("offer %.0f W with L1 at 15.7 A and 10 A on its way, want 4,140 W", r.offerW) } } + +// The C4 case as the triage wrote it, with only L1 moving, for a car the +// loadpoint has seen draw on three phases. A house step on L1 alone is then +// not the raise landing: the raise would take L1 to 25.7 A, over 1.2 x In, +// so it comes off on that reading. For a car not yet seen, a step on one +// phase may be a one-phase car taking the raise; the meter judges it then. +func TestEVFuseRaiseOnItsWayCutsForACarSeenOnThreePhases(t *testing.T) { + r := newCutRig(t, 4140, 40) + r.state.SiteFuseAmps, r.carPhases = 16, 3 + for range 60 { + r.read([3]float64{6, 6, 6}) + } + r.offerW = 11040 // 6 -> 16 A + for range 30 { + r.read([3]float64{6, 6, 6}) + } + if r.read([3]float64{15.7, 6, 6}); r.offerW > 4140 { + t.Fatalf("offer %.0f W with L1 at 15.7 A and 10 A on its way, want 4,140 W or less", r.offerW) + } +} + +// A house load that moves on one phase alone is not a three-phase cut +// landing. While a cut travels to a charger that declares 40 s, such a move +// must not take the cut's cover off the phase it was sent for. Before, a +// 3 A load switching off on L2 read as the cut landing: Core cut again to +// 7,590 W and left L1 2 A under the line for over 2 min. A 1.5 A load +// cycling on L2 gave three cuts and two rises; one cut is enough. +func TestEVFuseOnePhaseHouseMoveIsNotTheCutLanding(t *testing.T) { + t.Run("drop_on_L2", func(t *testing.T) { + s := fuseHeatSite(t) + s.chargerDelay, s.chargerMaxAgeS = 40*time.Second, 40 + s.addHouseA(0, 3, 0) // L2 23 A + s.run(2 * time.Minute) + stepAt := s.now + s.addHouseA(6, 0, 0) // L1 26 A + if took, offer := s.firstCut(2 * time.Minute); took < 0 || offer != 8970 { + t.Fatalf("first cut after %v to %.0f W, want 8,970 W", took, offer) + } + s.run(10 * time.Second) + s.addHouseA(0, -3, 0) + s.run(5 * time.Minute) + if cuts := offerWatts(s.cutsSince(stepAt)); len(cuts) != 1 || s.offer() != 8970 { + t.Fatalf("cuts %v, offer %.0f W after; want one cut to 8,970 W", cuts, s.offer()) + } + }) + t.Run("cycling_on_L2", func(t *testing.T) { + s := fuseHeatSite(t) + s.chargerDelay, s.chargerMaxAgeS = 40*time.Second, 40 + s.run(time.Minute) + stepAt := s.now + s.addHouseA(5, 0, 0) // L1 25 A on the 24 A line + for i := range 20 * 60 { + if i%7 == 0 { + s.addHouseA(0, []float64{1.5, -1.5}[i/7%2], 0) + } + s.step() + } + var offers []float64 + for _, o := range s.offersSince(stepAt) { + if n := len(offers); n == 0 || o.w != offers[n-1] { + offers = append(offers, o.w) + } + } + if len(offers) != 2 || offers[1] != 9660 { + t.Fatalf("offers %v, want one cut to 9,660 W and no rise", offers) + } + }) +} diff --git a/go/internal/control/sitesim_test.go b/go/internal/control/sitesim_test.go index caa84aa04..09e8c1a42 100644 --- a/go/internal/control/sitesim_test.go +++ b/go/internal/control/sitesim_test.go @@ -507,7 +507,7 @@ func fieldNightLoadpoint(c *loadpoint.Config) { // carPhasesUnknown checks that the session's car was never marked one-phase. func carPhasesUnknown(s *simSite) error { - if st, _ := s.mgr.State(s.lp.ID); st.CarPhases != 0 { + if st, _ := s.mgr.State(s.lp.ID); st.CarPhases == 1 { return fmt.Errorf("car marked one-phase on L%d; car draws %.0f W on %d phases", st.CarPhase, s.p.EVSE.DrawW, s.p.EVSE.DrawPhases) } return nil diff --git a/go/internal/loadpoint/loadpoint.go b/go/internal/loadpoint/loadpoint.go index e532d9d3a..ef16f9de2 100644 --- a/go/internal/loadpoint/loadpoint.go +++ b/go/internal/loadpoint/loadpoint.go @@ -204,8 +204,9 @@ type State struct { CarMaxW float64 `json:"-"` CarChargeLimit float64 `json:"-"` // CarPhases is 1 when this session's car draws on one phase of a - // three-phase order, seen on the site meter, and 0 when unknown; a car - // profile's phases may set it later. CarPhase is that phase, 1-3. The + // three-phase order, seen on the site meter, 3 when it draws on all + // three, and 0 when unknown; a car profile's phases may set it later. + // CarPhase is the phase of a one-phase car, 1-3. The // plan counts the car's one-phase levels (OnePhaseCarSteps) and the // order names the current per phase it should take. CarPhases int `json:"-"` @@ -1382,8 +1383,11 @@ func (lp *loadpointRuntime) snapshot() State { CommandedPhases: lp.commandedPhases, CarPhase: lp.carPhases.phase, } - if lp.carPhases.phase > 0 { + switch { + case lp.carPhases.phase > 0: st.CarPhases = 1 + case lp.carPhases.three: + st.CarPhases = 3 } if lp.VehicleCapacityWh <= 0 { st.VehicleCapacityWh = 60000 diff --git a/go/internal/loadpoint/one_phase_car.go b/go/internal/loadpoint/one_phase_car.go index 031bbeed3..e91c6463e 100644 --- a/go/internal/loadpoint/one_phase_car.go +++ b/go/internal/loadpoint/one_phase_car.go @@ -51,7 +51,7 @@ type phaseTest struct { } // carPhases is one session's evidence. phase is 1-3 once the car is seen on -// that phase alone. +// that phase alone; three is set once it is seen on all three. type carPhases struct { orderA float64 // per phase, the order the next rise is measured from // rising is set once the order has gone above orderA, and before is the @@ -67,6 +67,7 @@ type carPhases struct { seen bool test *phaseTest phase int + three bool } // phaseVerdict reads one meter reading against the baseline of a rise of @@ -196,7 +197,7 @@ func (m *Manager) observePhases(id string, meter SitePhases, drawA, voltage floa if t.verdict == 0 || now.Sub(t.since) < onePhaseHold { return } - s.phase = max(t.verdict, 0) + s.phase, s.three = max(t.verdict, 0), t.verdict < 0 s.test = nil } diff --git a/go/internal/loadpoint/one_phase_car_test.go b/go/internal/loadpoint/one_phase_car_test.go index ae002be08..4d84b9e07 100644 --- a/go/internal/loadpoint/one_phase_car_test.go +++ b/go/internal/loadpoint/one_phase_car_test.go @@ -83,8 +83,8 @@ func TestOnePhaseCarMarkedFromTheMeter(t *testing.T) { return threePhase(16)(d) } run(125*time.Second, 200*time.Second, allThree, 11040) - if st := state(); st.CarPhases != 0 { - t.Fatalf("a rise on all three phases left the mark on L%d", st.CarPhase) + if st := state(); st.CarPhases != 3 || st.CarPhase != 0 { + t.Fatalf("a rise on all three phases: car phases %d on L%d, want 3", st.CarPhases, st.CarPhase) } order(4830) run(205*time.Second, 210*time.Second, still, 0) From 43d38ff7bebee778574e8c2e02b335ad9beea8fd Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 22:39:31 +0100 Subject: [PATCH 31/68] fix(control): a battery charge rise fits each phase before it is sent The battery fuse guard judged a rise from the battery's own reading and the meter's phases, so it took a rise the meter did not show yet as already shown. With the meter a poll behind the battery, a PV surplus that grew each tick stacked rises past the line, then the relief cut them back: 16.4 A on a 16 A fuse and a charge that rose and fell (C2, seeds 207530, 207535). fitBatteryRisesToFuse caps charge above the battery's latest order to (fuseLineA - worst phase - own unshown rises) x V x phases. The unshown rises are the battery's orders of the last evSettle and the chargers' raises, counted as evShownW counts them, so the car comes first. Holding an order is never a rise and the check never cuts; an overage stays with the relief. No margin and no floor: the order ends at the line. Co-Authored-By: Claude Opus 5.5 --- .changeset/s2-battery-rise-per-phase.md | 5 + .../control/battery_rise_phase_test.go | 172 ++++++++++++++++++ go/internal/control/dispatch.go | 99 +++++++++- go/internal/control/ev_fuse_budget.go | 16 +- 4 files changed, 277 insertions(+), 15 deletions(-) create mode 100644 .changeset/s2-battery-rise-per-phase.md create mode 100644 go/internal/control/battery_rise_phase_test.go diff --git a/.changeset/s2-battery-rise-per-phase.md b/.changeset/s2-battery-rise-per-phase.md new file mode 100644 index 000000000..306154792 --- /dev/null +++ b/.changeset/s2-battery-rise-per-phase.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +A battery charge rise now fits each phase before FTW sends it. The room is the fuse's working limit less the phase's reading and less FTW's own rises the meter does not show yet: the car's raises and the battery's earlier orders. The car's raise comes first. This stops the battery from charging into a phase the meter shows full, and from stacking a second rise on one the meter has not shown yet, which pushed a phase over the fuse and made the charge rise and fall around the limit. Holding a charge is never a rise, so this check never cuts a charge. diff --git a/go/internal/control/battery_rise_phase_test.go b/go/internal/control/battery_rise_phase_test.go new file mode 100644 index 000000000..290f51c5c --- /dev/null +++ b/go/internal/control/battery_rise_phase_test.go @@ -0,0 +1,172 @@ +package control + +import ( + "fmt" + "math" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// C2 of the 27 Oct rig triage: a battery charge rise fits each phase's room, +// (fuseLineA − measured phase − our unshown rises) × V × phases, before it is +// sent. 16 A fuse, 230 V, 3 phases. + +// riseStore holds one meter reading with these phase currents, all import, +// and the battery's reading. +func riseStore(t *testing.T, phaseA [3]float64, batW float64) *telemetry.Store { + t.Helper() + data := map[string]any{} + var totalW float64 + for i, a := range phaseA { + data[fmt.Sprintf("l%d_a", i+1)] = math.Abs(a) + data[fmt.Sprintf("l%d_w", i+1)] = a * 230 + totalW += a * 230 + } + return phaseDirectionStore(t, totalW, batW, data) +} + +// riseState asks the battery for askW of charge (Charge mode at a charge +// limit of askW), so the fuse path alone shapes the order. +func riseState(askW float64) *State { + st := phaseDirectionState(0) + st.Mode = ModeCharge + now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) + st.clock = func() time.Time { return now } + st.batteryCommands = map[string]commandLog{} + ask(st, askW) + return st +} + +func ask(st *State, w float64) { + st.DriverLimits = map[string]PowerLimits{"bat": {MaxChargeW: w, MaxDischargeW: 10000}} +} + +func batteryOrder(t *testing.T, store *telemetry.Store, st *State) float64 { + t.Helper() + for _, o := range ComputeDispatch(store, st, map[string]float64{"bat": 15200}, 16*230*3) { + if o.Driver == "bat" { + return o.TargetW + } + } + t.Fatal("no battery target") + return 0 +} + +// Seed 207530 at 897 s: L3 reads 16.04 A, over the 16 A line, with the +// battery at 491 W after a cut to 491 W. A plan target of 3350 W is no rise +// room: the order stays at or below the battery's reading. +func TestBatteryRiseIntoPhaseOverTheLine(t *testing.T) { + store := riseStore(t, [3]float64{8.5, 10.5, 16.04}, 491) + st := riseState(3350) + sent(st, "bat", 3349, 491) + if got := batteryOrder(t, store, st); got > 491+1e-6 { + t.Fatalf("order %.0f W with L3 at 16.04 A and the battery at 491 W; want <= 491 W", got) + } +} + +// Seed 207535 at 37-41 s, with no margin. L3 reads 14.27 A with the battery +// at 12 W: 871 W fits under the line and goes out whole. Two seconds later +// the battery reads 871 W, but the meter's reading is from before the +// battery moved and still shows L3 at 14.27 A. The 871 W rise is ours and +// not shown, so a further ask may add only what is left above it: the order +// stays at or below 12 W + (16 − 14.27) × 690 W. +func TestBatteryRiseCountsOwnUnshownRise(t *testing.T) { + phases := [3]float64{13.77, 13.97, 14.27} + limitW := 12 + (16-14.27)*690 + + st := riseState(871) + sent(st, "bat", 12) + if got := batteryOrder(t, riseStore(t, phases, 12), st); math.Abs(got-871) > 1e-6 { + t.Fatalf("first ask: order %.1f W, want the whole 871 W (it fits under %.1f W)", got, limitW) + } + + st = riseState(1500) + sent(st, "bat", 12, 871) + got := batteryOrder(t, riseStore(t, phases, 871), st) + if got > limitW+1e-6 { + t.Fatalf("order %.1f W while the meter does not show our 871 W yet: L3 would reach %.2f A; want <= %.1f W", + got, 14.27+(got-12)/690, limitW) + } + if got < 871-1e-6 { + t.Fatalf("order %.1f W cut below our 871 W hold; a rise check never cuts", got) + } +} + +// Closed loop, battery only, no margin: house loads 13.77/13.97/14.27 A and +// a charge ask that grows 300 W a tick from 600 W to 3000 W, as a PV +// surplus does. The battery reaches each order one tick later; the meter +// shows the battery one tick after the battery's own reading does. L3 +// never passes the 16 A line, the order never moves down (no hunting), and +// it ends at the line: 1193.7 W. +func TestBatteryRiseClosedLoopStopsAtTheLine(t *testing.T) { + house := [3]float64{13.77, 13.97, 14.27} + st := riseState(600) + now := st.now() + st.clock = func() time.Time { return now } + var orders, l3 []float64 + batW, meterBatW := 0.0, 0.0 + for tick := 0; tick < 40; tick++ { + ask(st, math.Min(3000, 600+300*float64(tick))) + var a [3]float64 + for i := range a { + a[i] = house[i] + meterBatW/690 + } + order := batteryOrder(t, riseStore(t, a, batW), st) + orders = append(orders, math.Round(order*10)/10) + l3 = append(l3, math.Round(a[2]*1000)/1000) + meterBatW, batW = batW, order + now = now.Add(2 * time.Second) + } + for i := range orders { + if l3[i] > 16+1e-3 { + t.Errorf("tick %d: L3 %.3f A over the 16 A line", i, l3[i]) + } + if i > 0 && orders[i] < orders[i-1]-0.5 { + t.Errorf("tick %d: order fell %.1f -> %.1f W", i, orders[i-1], orders[i]) + } + } + if want := (16 - 14.27) * 690; math.Abs(orders[len(orders)-1]-want) > 1 { + t.Errorf("final order %.1f W, want %.1f W: L3 at the line", orders[len(orders)-1], want) + } + if t.Failed() { + t.Logf("orders %v", orders) + t.Logf("L3 %v", l3) + } +} + +// Car first: the car's raise from 6 A to 10 A per phase went out 2 s ago +// and the meter does not show it yet: L3 reads 11 A with the car at 6 A. +// The raise takes L3 to 15 A, so the battery's 2000 W charge ask gets the +// 1 A left, 690 W. Once the meter shows the car at 10 A and the battery at +// 690 W, L3 sits at the 16 A line and the battery holds. With the car's demand +// and without it (a raise still on its way after the demand left). +func TestBatteryRiseLeavesRoomForUnshownCarRaise(t *testing.T) { + for _, demand := range []bool{true, false} { + t.Run(fmt.Sprintf("demand=%v", demand), func(t *testing.T) { + st := riseState(2000) + now := st.now() + st.clock = func() time.Time { return now } + sent(st, "bat", 0) + var log commandLog + log = log.keep(sentCommand{at: now.Add(-evSettle - time.Second), w: 4140, a: 6, n: 3}, now.Add(-evSettle)) + log = log.keep(sentCommand{at: now.Add(-2 * time.Second), w: 6900, a: 10, n: 3}, now.Add(-evSettle)) + st.evLimit.offers = map[string]chargerOffers{"car": {log: log, settle: evSettle}} + st.EVCommandedW = 6900 + if demand { + st.evFuseDemands = []evFuseDemand{{"car", 6900, "3p"}} + } + got := batteryOrder(t, riseStore(t, [3]float64{9, 9, 11}, 0), st) + if got > 690+1e-6 { + t.Fatalf("battery %.1f W beside the car's unshown 4 A: L3 would reach %.2f A", got, 11+4+got/690) + } + + now = now.Add(evSettle) + got = batteryOrder(t, riseStore(t, [3]float64{13 + got/690, 13 + got/690, 15 + got/690}, got), st) + if math.Abs(got-690) > 1 { + t.Fatalf("battery %.1f W once the meter shows the car, want 690 W: L3 at the 16 A line", got) + } + }) + } +} diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index ff6ffc27b..7c8ba79a6 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -2385,6 +2385,7 @@ func applyDispatchSafetyPipeline( } // ---- Fuse guard (bidirectional, #145) ---- targets = applyFuseGuard(targets, store, state, fuseMaxW) + targets = fitBatteryRisesToFuse(targets, store, state) // ---- Plan/exec sign-mismatch floor (energy planner modes only) ---- // Operator-report 2026-04-28 (08:00-08:15 CEST): planner_arbitrage @@ -3900,6 +3901,91 @@ func livePhaseSample(store *telemetry.Store, driver string, meter *telemetry.Der return phaseSample{meter: meter, totalW: totalW} } +// signedPhasesA is the sample's phase currents, import positive +// (phaseCurrentsA). When no phase reads as export while the total does, the +// meter gives no direction per phase, and every phase takes the total's. +// false without usable phase currents. +func (p phaseSample) signedPhasesA(state *State) ([]float64, bool) { + if p.meter == nil || state == nil { + return nil, false + } + amps, _, valid := phaseCurrentsA(p.meter, state, p.totalW) + if !valid || len(amps) == 0 { + return nil, false + } + exports := p.totalW < 0 + for _, a := range amps { + exports = exports && a >= 0 + } + if exports { + for i := range amps { + amps[i] = -amps[i] + } + } + return amps, true +} + +// fitBatteryRisesToFuse keeps battery charge rises inside the room the site +// meter shows on its busiest phase: the working limit (fuseLineA) less the +// phase's reading and less our own rises that reading may not show yet, the +// chargers' offers (counted as evShownW does) and the batteries' orders +// (pendingBatteryCommandsW). A three-phase battery puts its power evenly on +// every phase. A rise is charge above the battery's latest order, or above +// its reading before our first order. Holding an order is never a rise, and +// a discharge we end uses room first. Nothing here cuts below the hold: an +// overage is the relief's (applyFuseGuard, forceFuseDischarge), which reads +// the battery's own power. Without usable phase currents the aggregate guard +// is the check. +func fitBatteryRisesToFuse(targets []DispatchTarget, store *telemetry.Store, state *State) []DispatchTarget { + if store == nil || state == nil || len(targets) == 0 || state.SiteFuseVoltage <= 0 || state.SiteFusePhases <= 0 { + return targets + } + meter := store.Get(state.SiteMeterDriver, telemetry.DerMeter) + if meter == nil { + return targets + } + amps, ok := livePhaseSample(store, state.SiteMeterDriver, meter).signedPhasesA(state) + if !ok { + return targets + } + now := state.now() + perA := state.SiteFuseVoltage * float64(state.SiteFusePhases) + unshownA := state.pendingBatteryCommandsW(now) / perA + for _, c := range state.evLimit.offers { + _, a := c.log.unshown(now, c.batterySettle()) + unshownA += a // A one-phase offer may land on any phase. + } + worstA := math.Inf(-1) + for _, a := range amps { + worstA = math.Max(worstA, a) + } + roomW := (state.fuseLineA() - worstA - unshownA) * perA + holds := make([]float64, len(targets)) + var riseW float64 + for i, t := range targets { + var base float64 + if _, _, latest, sent := state.batteryCommands[t.Driver].span(now); sent { + base = latest + } else if r := store.Get(t.Driver, telemetry.DerBattery); r != nil { + base = r.RawW + } + roomW -= math.Max(0, math.Min(0, t.TargetW)-math.Min(0, base)) + holds[i] = math.Min(t.TargetW, math.Max(0, base)) + riseW += t.TargetW - holds[i] + } + if riseW <= 0 || roomW >= riseW { + return targets + } + scale := math.Max(0, roomW) / riseW + out := append([]DispatchTarget(nil), targets...) + for i := range out { + if out[i].TargetW > holds[i] { + out[i].TargetW, out[i].Clamped = holds[i]+(out[i].TargetW-holds[i])*scale, true + } + } + return out +} + // phaseMoveW is the batteries' change from the raw power their readings hold // to the targets. The phase currents are raw, so the move is too. func phaseMoveW(targets []DispatchTarget, batteries map[string]*telemetry.DerReading) float64 { @@ -3932,24 +4018,17 @@ func phaseMoveW(targets []DispatchTarget, batteries map[string]*telemetry.DerRea // export, and a battery on one phase, which is read as balanced. 0, 0 // without usable phase currents. func phaseFuseReliefW(p phaseSample, state *State, moveW float64) (importW, exportW float64) { - if p.meter == nil || state == nil { + if state == nil { return 0, 0 } - amps, _, valid := phaseCurrentsA(p.meter, state, p.totalW) - if !valid || len(amps) == 0 { + amps, ok := p.signedPhasesA(state) + if !ok { return 0, 0 } perA := state.SiteFuseVoltage * float64(state.SiteFusePhases) // aggregate W per phase ampere limitA := state.fuseLineA() - exports := p.totalW < 0 - for _, a := range amps { - exports = exports && a >= 0 - } hi, lo := math.Inf(-1), math.Inf(1) for _, a := range amps { - if exports { - a = -a - } a += moveW / perA hi, lo = math.Max(hi, a), math.Min(lo, a) } diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index da5028585..37b108dc8 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -359,17 +359,23 @@ func (s *State) evShownW(at time.Time) float64 { var w float64 for _, c := range s.evLimit.offers { if n := len(c.log); n > 0 { - settle := evSettle - if c.declared { - settle = c.settle - } - unshown, _ := c.log.unshown(at, settle) + unshown, _ := c.log.unshown(at, c.batterySettle()) w += math.Max(0, c.log[n-1].w-unshown) } } return w } +// batterySettle is how long the battery side counts a raise of this +// charger's as unshown: its declared response time, else evSettle +// (evShownW). +func (c chargerOffers) batterySettle() time.Duration { + if c.declared { + return c.settle + } + return evSettle +} + func (s *State) pendingLoad(at time.Time) pendingLoad { var p pendingLoad for _, c := range s.evLimit.offers { From c94fa56c3b945a7f42d4c93e060e79cb98f91d85 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 23:09:07 +0100 Subject: [PATCH 32/68] fix(control): battery rise check counts slow batteries and direction-less phases A battery order now stays unshown until evSettle after the battery's own reading reaches it, so a battery that ramps slower than evSettle no longer gets a second rise on top of an order the meter cannot show yet. On a meter with phase currents but no phase power while the total exports, a phase counts as export only when the other phases cannot carry the export alone; any other phase counts as import. Before, every phase flipped to export, so a three-phase charge could rise into a phase that imports beside two exporting ones. Co-Authored-By: Claude Opus 5.5 --- .changeset/s2-battery-rise-per-phase.md | 2 +- docs/safety.md | 5 +- .../control/battery_rise_phase_test.go | 64 +++++++++++++++++ go/internal/control/dispatch.go | 72 +++++++++++++++++-- .../golden/early_exit_protections.json | 2 +- 5 files changed, 135 insertions(+), 10 deletions(-) diff --git a/.changeset/s2-battery-rise-per-phase.md b/.changeset/s2-battery-rise-per-phase.md index 306154792..f416fc33a 100644 --- a/.changeset/s2-battery-rise-per-phase.md +++ b/.changeset/s2-battery-rise-per-phase.md @@ -2,4 +2,4 @@ "ftw": patch --- -A battery charge rise now fits each phase before FTW sends it. The room is the fuse's working limit less the phase's reading and less FTW's own rises the meter does not show yet: the car's raises and the battery's earlier orders. The car's raise comes first. This stops the battery from charging into a phase the meter shows full, and from stacking a second rise on one the meter has not shown yet, which pushed a phase over the fuse and made the charge rise and fall around the limit. Holding a charge is never a rise, so this check never cuts a charge. +A battery charge rise now fits each phase before FTW sends it. The room is the fuse's working limit less the phase's reading and less FTW's own rises the meter does not show yet: the car's raises and the battery's earlier orders. The car's raise comes first. A battery order stays counted until the meter has had time to show the battery's own reading of it, so a battery that ramps slowly does not get a second rise on top. On a meter that reports phase currents without phase power, a phase counts as export only when the other phases cannot carry the exported total alone; any other phase counts as import. Near the line this keeps the battery from charging into a phase the meter shows full, and from stacking a rise on one the meter has not shown yet, which pushed a phase over the fuse and made the charge rise and fall around the limit. Holding a charge is never a rise, so this check never cuts a charge. A frozen meter is not covered here. diff --git a/docs/safety.md b/docs/safety.md index 11981bd67..6229cb646 100644 --- a/docs/safety.md +++ b/docs/safety.md @@ -66,7 +66,10 @@ tariff import ceiling still applies. A phase's current takes its direction from the same phase's power. It counts as export only when that power shows it clearly and the phases' -powers add up to the meter's total; otherwise it counts as import. An +powers add up to the meter's total; otherwise it counts as import. The +battery's fuse checks make one exception for a meter with no phase power +while the total exports: a phase counts as export when the other phases' +currents cannot carry that export alone. An exporting phase is never cut for: less EV load would raise its export. A rise or start on it reads its current as it is, without its heat. diff --git a/go/internal/control/battery_rise_phase_test.go b/go/internal/control/battery_rise_phase_test.go index 290f51c5c..522880bd9 100644 --- a/go/internal/control/battery_rise_phase_test.go +++ b/go/internal/control/battery_rise_phase_test.go @@ -170,3 +170,67 @@ func TestBatteryRiseLeavesRoomForUnshownCarRaise(t *testing.T) { }) } } + +// A meter that reports current magnitudes and no phase power, as Tibber +// Pulse does (l1_a..l3_a only). L1 reads 15.5 A, L2 and L3 8.7 A, and the +// total exports 1300 W. L2 and L3 alone can carry that export, so L1 may be +// a load importing 15.5 A beside them, and a three-phase charge rise adds to +// it: the order stays at or below (16 − 15.5) × 690 W. When the currents add +// up to the export, every phase must export, and charge may soak it up. +func TestBatteryRiseMagnitudeOnlyMeter(t *testing.T) { + st := riseState(3000) + sent(st, "bat", 0) + store := phaseDirectionStore(t, -1300, 0, map[string]any{"l1_a": 15.5, "l2_a": 8.7, "l3_a": 8.7}) + if got, limit := batteryOrder(t, store, st), (16-15.5)*690; got > limit+1e-6 { + t.Fatalf("order %.0f W: L1 would reach %.2f A if it imports; want <= %.0f W", got, 15.5+got/690, limit) + } + + st = riseState(3000) + sent(st, "bat", 0) + store = phaseDirectionStore(t, -12075, 0, map[string]any{"l1_a": 17.5, "l2_a": 17.5, "l3_a": 17.5}) + if got := batteryOrder(t, store, st); math.Abs(got-3000) > 1e-6 { + t.Fatalf("order %.0f W with every phase exporting 17.5 A; want the whole 3000 W ask", got) + } +} + +// A battery that ramps 50 W a tick toward its order, so it has not reached +// an order older than evSettle, and a meter that shows the battery two ticks +// after the battery reads it. The order counts as unshown until evSettle +// after the battery reads it: L3 never passes the 16 A line and the order +// never falls. +func TestBatteryRiseSlowBatteryLaggingMeter(t *testing.T) { + house := [3]float64{13.77, 13.97, 14.27} + st := riseState(3000) + now := st.now() + st.clock = func() time.Time { return now } + var hist, orders []float64 + batW, maxL3 := 0.0, 0.0 + for tick := 0; tick < 120; tick++ { + meterBatW := 0.0 + if n := len(hist); n >= 2 { + meterBatW = hist[n-2] + } + var a [3]float64 + for i := range a { + a[i] = house[i] + meterBatW/690 + } + order := batteryOrder(t, riseStore(t, a, batW), st) + orders = append(orders, math.Round(order)) + maxL3 = math.Max(maxL3, house[2]+batW/690) + hist = append(hist, batW) + batW = math.Min(order, batW+50) + now = now.Add(2 * time.Second) + } + if maxL3 > 16+1e-3 { + t.Errorf("L3 reached %.3f A, over the 16 A line", maxL3) + } + for i := 1; i < len(orders); i++ { + if orders[i] < orders[i-1]-0.5 { + t.Errorf("tick %d: order fell %.0f -> %.0f W", i, orders[i-1], orders[i]) + break + } + } + if t.Failed() { + t.Logf("orders %v", orders) + } +} diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 7c8ba79a6..593a4fb5f 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -398,6 +398,9 @@ type State struct { // batteryCommands and evLimit.offers are our own recent commands, the // only device input the EV hard limit and the EV/battery split use. batteryCommands map[string]commandLog + // batteryReadings is each battery's own reading at our last commands, + // for the power the site meter may not show yet (unshownBatteryW). + batteryReadings map[string]commandLog // batteryFuseRelief is the discharge the fuse guard added to each // battery's last dispatched command (forceFuseDischarge). It ends once // the site fits without it, so an EV rise or start never counts it as @@ -2434,6 +2437,7 @@ func applyDispatchSafetyPipeline( recordDispatchTargets(targets, state, opts.updatePrevTargets, opts.recordDispatch) if opts.recordDispatch { state.recordFuseRelief(beforeRelief, targets) + state.recordBatteryReadings(targets, store) } return targets } @@ -3903,8 +3907,12 @@ func livePhaseSample(store *telemetry.Store, driver string, meter *telemetry.Der // signedPhasesA is the sample's phase currents, import positive // (phaseCurrentsA). When no phase reads as export while the total does, the -// meter gives no direction per phase, and every phase takes the total's. -// false without usable phase currents. +// meter gives no direction per phase. A phase then counts as export only +// when it must: when the other phases' currents, at most V × A of real power +// each, cannot carry the exported total on their own (tolerance as in +// phasePowersAddUp). A phase that may import counts as import, +// phaseCurrentsA's safe side, since a reactive load can draw its whole +// current beside exporting phases. false without usable phase currents. func (p phaseSample) signedPhasesA(state *State) ([]float64, bool) { if p.meter == nil || state == nil { return nil, false @@ -3914,22 +3922,72 @@ func (p phaseSample) signedPhasesA(state *State) ([]float64, bool) { return nil, false } exports := p.totalW < 0 + var sumW float64 for _, a := range amps { exports = exports && a >= 0 + sumW += a * state.SiteFuseVoltage } - if exports { - for i := range amps { - amps[i] = -amps[i] + if !exports { + return amps, true + } + tolW := math.Max(250, sumW/10) + for i, a := range amps { + if sumW-a*state.SiteFuseVoltage < -p.totalW-tolW { + amps[i] = -a } } return amps, true } +// unshownBatteryW is the batteries' increase the site meter may not show +// yet: each battery's latest order less the least the meter may show of it, +// the lowest order of the last evSettle (as pendingBatteryCommandsW) or the +// lowest of the battery's own readings over that time, the current one +// included. A battery that ramps slower than evSettle has not reached an +// order older than evSettle, so the order stays unshown until evSettle after +// the battery reads it. +func (s *State) unshownBatteryW(now time.Time, store *telemetry.Store) float64 { + var unshown float64 + for driver, log := range s.batteryCommands { + low, _, latest, ok := log.span(now) + if !ok { + continue + } + if read, _, _, seen := s.batteryReadings[driver].span(now); seen { + low = math.Min(low, read) + } + if r := store.Get(driver, telemetry.DerBattery); r != nil { + low = math.Min(low, r.RawW) + } + unshown += math.Max(0, latest-low) + } + return unshown +} + +// recordBatteryReadings logs each dispatched battery's reading for +// unshownBatteryW. +func (s *State) recordBatteryReadings(targets []DispatchTarget, store *telemetry.Store) { + if store == nil { + return + } + now := s.now() + for _, t := range targets { + r := store.Get(t.Driver, telemetry.DerBattery) + if r == nil { + continue + } + if s.batteryReadings == nil { + s.batteryReadings = map[string]commandLog{} + } + s.batteryReadings[t.Driver] = s.batteryReadings[t.Driver].add(now, r.RawW) + } +} + // fitBatteryRisesToFuse keeps battery charge rises inside the room the site // meter shows on its busiest phase: the working limit (fuseLineA) less the // phase's reading and less our own rises that reading may not show yet, the // chargers' offers (counted as evShownW does) and the batteries' orders -// (pendingBatteryCommandsW). A three-phase battery puts its power evenly on +// (unshownBatteryW). A three-phase battery puts its power evenly on // every phase. A rise is charge above the battery's latest order, or above // its reading before our first order. Holding an order is never a rise, and // a discharge we end uses room first. Nothing here cuts below the hold: an @@ -3950,7 +4008,7 @@ func fitBatteryRisesToFuse(targets []DispatchTarget, store *telemetry.Store, sta } now := state.now() perA := state.SiteFuseVoltage * float64(state.SiteFusePhases) - unshownA := state.pendingBatteryCommandsW(now) / perA + unshownA := state.unshownBatteryW(now, store) / perA for _, c := range state.evLimit.offers { _, a := c.log.unshown(now, c.batterySettle()) unshownA += a // A one-phase offer may land on any phase. diff --git a/go/internal/control/testdata/golden/early_exit_protections.json b/go/internal/control/testdata/golden/early_exit_protections.json index e1147757e..c8e9929d2 100644 --- a/go/internal/control/testdata/golden/early_exit_protections.json +++ b/go/internal/control/testdata/golden/early_exit_protections.json @@ -775,7 +775,7 @@ "fuse_hold_latched": false, "fuse_hold_max_charge_w": 0, "fuse_hold_max_discharge_w": 0, - "per_phase_overage_w": 2300, + "per_phase_overage_w": 2070, "effective_import_ceiling_w": 11040, "effective_export_ceiling_w": 11040, "import_ceiling_binding": false, From a6bdd9e5a66dee3886d5e290657f0798b28d28c5 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 23:33:06 +0100 Subject: [PATCH 33/68] fix(control): the car comes before battery charge With battery_covers_ev off, dispatch took the car out of the meter reading before the battery decided. The battery then saw the PV the car was using as export and charged from it while the site imported for the car (rig seeds 207535, 207539, 207530: about 10 kW import). The battery now charges only from the surplus the meter shows after the car. Where the house alone has surplus, the battery sees the meter with the car included, and any discharge stops at once, since it would feed the car. A planned PV charge on the energy path takes only the surplus the car leaves; a planned grid purchase keeps its charge. Cover off still never discharges the battery for the car. Co-Authored-By: Claude Opus 5.5 --- .changeset/p1-car-before-battery-charge.md | 5 + go/internal/control/control_test.go | 48 +++-- go/internal/control/dispatch.go | 47 +++-- .../control/ev_car_before_battery_test.go | 183 ++++++++++++++++++ go/internal/control/ev_site_test.go | 19 +- .../testdata/golden/seeded_ev_boost.json | 20 +- .../control/testdata/golden/slew_limiter.json | 6 +- 7 files changed, 276 insertions(+), 52 deletions(-) create mode 100644 .changeset/p1-car-before-battery-charge.md create mode 100644 go/internal/control/ev_car_before_battery_test.go diff --git a/.changeset/p1-car-before-battery-charge.md b/.changeset/p1-car-before-battery-charge.md new file mode 100644 index 000000000..9895c3b79 --- /dev/null +++ b/.changeset/p1-car-before-battery-charge.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +The car comes before home battery charging, also when the battery does not cover the car. The battery now charges only from the solar surplus the car leaves. Before, with battery cover off, FTW took the car out of the meter reading, so the battery charged from solar the car was using while the site imported up to 10 kW. Battery cover off still means the battery never discharges into the car. A planned grid purchase keeps its charge. diff --git a/go/internal/control/control_test.go b/go/internal/control/control_test.go index dc9a400d5..6a2f97f89 100644 --- a/go/internal/control/control_test.go +++ b/go/internal/control/control_test.go @@ -4063,12 +4063,23 @@ func TestPlannerSelfIdleGateLeavesSurplusOnlyEVReserve(t *testing.T) { st.MinDispatchIntervalS = 0 st.SlotDirective = func(time.Time) (SlotDirective, bool) { return dir, true } - targets := ComputeDispatch(store, st, caps(map[string]float64{"ferroamp": 15200}), 11040) - if len(targets) != 1 { - t.Fatalf("want 1 target, got %d", len(targets)) + // The PI may take a few ticks to get there; it must never pass it. + var last float64 + for i := 0; i < 10; i++ { + targets := ComputeDispatch(store, st, caps(map[string]float64{"ferroamp": 15200}), 11040) + if len(targets) != 1 { + t.Fatalf("tick %d: want 1 target, got %d", i, len(targets)) + } + last = targets[0].TargetW + if last > 1000+1 { + t.Fatalf("tick %d: TargetW = %f — battery took the surplus-only EV reserve", i, last) + } + store.Update("ferroamp", telemetry.DerBattery, last, ptrF64(0.5), nil) + store.Update("ferroamp", telemetry.DerMeter, -3000+last, nil, nil) + store.DriverHealthMut("ferroamp").RecordSuccess() } - if math.Abs(targets[0].TargetW-1000) > 1 { - t.Errorf("TargetW = %f — idle gate must leave surplus-only EV reserve; want ~1000", targets[0].TargetW) + if math.Abs(last-1000) > 1 { + t.Errorf("TargetW = %f — idle gate must leave surplus-only EV reserve; want ~1000", last) } } @@ -5497,20 +5508,19 @@ func TestEnergyDispatchClampsDischargeWhenEVActuallyCharging(t *testing.T) { // charge battery, EV is on surplus_only at 2.5 kW with 11 kW max, // and 3 kW is currently exporting at the real meter. // -// dispatch.go:685 subtracts EVChargingW from gridW before the home- -// battery decision so the battery sees "what export would exist -// without the EV", which is 3000 + 2500 = 5500 W in this scenario. -// The reserve cap then carves out reserveRemaining for the EV to -// step up into. +// The car comes before battery charge, so the battery sees the +// export the car leaves: the real 3000 W, not the 5500 W there would +// be without the car. The reserve cap then carves out +// reserveRemaining for the EV to step up into. // // Pre-fix (reserve = full MaxChargeW = 11000): reserveRemaining -// = 11000 - 2500 = 8500. ceiling = 5500 - 8500 = -3000 → 0. Battery +// = 11000 - 2500 = 8500. ceiling = 3000 - 8500 → 0. Battery // idles; surplus dumps to grid. // // Post-fix (reserve = CurrentPowerW + EVRampHeadroomW = 4500): -// reserveRemaining = 4500 - 2500 = 2000. ceiling = 5500 - 2000 = -// 3500. Battery picks up the bulk of the surplus while leaving 2 kW -// of headroom for the EV to ramp up. +// reserveRemaining = 4500 - 2500 = 2000. ceiling = 3000 - 2000 = +// 1000. Battery takes the surplus beyond 2 kW of headroom for the +// EV to ramp up, and none of the car's own 2.5 kW. // // The test sets EVSurplusOnlyReserveW directly to the value // loadpoint.SurplusReserveW would produce; the helper itself is @@ -5542,12 +5552,12 @@ func TestEnergyDispatchAbsorbsSurplusBeyondEVReserveActualDraw(t *testing.T) { t.Fatalf("want 1 target, got %d", len(targets)) } got := targets[0].TargetW - // Want ≈ 3500 W. Allow ±400 W slack for time drift / formula edge. - if got < 3100 { - t.Errorf("TargetW = %.0f W — battery should absorb the surplus that the EV's adaptive reserve no longer hoards (want ≈ 3500 W, was 0 pre-fix)", got) + // Want ≈ 1000 W. Allow ±100 W slack for time drift / formula edge. + if got < 900 { + t.Errorf("TargetW = %.0f W — battery should absorb the surplus that the EV's adaptive reserve no longer hoards (want ≈ 1000 W, was 0 pre-fix)", got) } - if got > 3900 { - t.Errorf("TargetW = %.0f W — battery overshoot, must leave EVRampHeadroomW (2 kW) of headroom for EV ramp-up (want ≈ 3500 W)", got) + if got > 1100 { + t.Errorf("TargetW = %.0f W — battery overshoot, must leave the car's draw and EVRampHeadroomW (2 kW) of headroom for EV ramp-up (want ≈ 1000 W)", got) } } diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 593a4fb5f..b415ffdbf 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -370,7 +370,8 @@ type State struct { EVCurtailHeadroomW float64 // BatteryCoversEV lets the battery discharge into the EV. Off, EV // load is taken out of the meter before the PI so the battery does - // not feed the car. + // not feed the car. Either way the car comes before battery charge: + // the battery charges only from the surplus the car leaves. BatteryCoversEV bool // BatteryBoostEVChargingW is the live charging draw belonging to @@ -1489,12 +1490,16 @@ func ComputeDispatch( // discharge keeps its old opt-in guard so Self does not fill the home // battery from a car by default. gridW := rawGridW - if state.Mode != ModeSelfConsumption && !state.BatteryCoversEV { - gridW -= state.uncoveredEVChargingW() - } if !state.BatteryCoversEV { gridW -= vehicleFlow.V2XDischargeW } + // The car comes before battery charge: charge comes only from what the + // meter shows left after the car. The car leaves the signal below so + // the battery never discharges for it. + chargeGridW := gridW + if state.Mode != ModeSelfConsumption && !state.BatteryCoversEV { + gridW -= state.uncoveredEVChargingW() + } // ---- Gather online batteries ---- batteries := make([]batteryInfo, 0, len(driverCapacities)) @@ -1567,6 +1572,14 @@ func ComputeDispatch( for _, b := range onlineBats { currentTotal += b.currentW } + // Without the car the meter may show export the car is using. Where + // the battery would charge, it sees the meter with the car instead: + // it charges only from the surplus after the car, and never turns to + // discharge for it. + noCarGridW := gridW + if gridW < chargeGridW { + gridW = math.Max(gridW, math.Min(chargeGridW, currentTotal)) + } surplus := newSurplusAccounting(rawGridW, gridW, currentTotal, state) // passive_arbitrage idle slot + live PV surplus: don't absorb. Forecasts @@ -1749,15 +1762,19 @@ func ComputeDispatch( // Leave PV for a surplus-only EV. A planned import of at least // 100 W keeps its charge. Discharge is left alone. - if state.EVSurplusOnlyReserveW > 0 && targetTotalW > 0 { - deliberateGridCharge := currentDirective.HasPlannedGridW && currentDirective.PlannedGridW >= 100 - if !deliberateGridCharge { - ceiling := surplus.chargeCeilingAfterEVReserveW() - if targetTotalW > ceiling { - targetTotalW = ceiling - } + deliberateGridCharge := currentDirective.HasPlannedGridW && currentDirective.PlannedGridW >= 100 + if state.EVSurplusOnlyReserveW > 0 && targetTotalW > 0 && !deliberateGridCharge { + ceiling := surplus.chargeCeilingAfterEVReserveW() + if targetTotalW > ceiling { + targetTotalW = ceiling } } + // The car before battery charge: a charge the plan makes from PV + // takes only the surplus the car leaves. + pvCharge := currentDirective.HasPlannedGridW && !deliberateGridCharge + if targetTotalW > 0 && pvCharge && gridW > noCarGridW { + targetTotalW = math.Min(targetTotalW, currentTotal-gridW) + } // Charge slots only. If PV drops, the energy budget would hold the // planned charge on grid import until the replan, about 10 minutes @@ -1765,7 +1782,8 @@ func ComputeDispatch( // Below 100 W is meter noise. if currentDirective.HasPlannedGridW && targetTotalW > 0 { const planGridDeadband = 100.0 - projectedGridW := gridW + (targetTotalW - currentTotal) + // The plan's grid leaves out the car the battery does not cover. + projectedGridW := noCarGridW + (targetTotalW - currentTotal) gridErr := projectedGridW - currentDirective.PlannedGridW if gridErr > planGridDeadband { adjusted := targetTotalW - gridErr @@ -1989,6 +2007,11 @@ func ComputeDispatch( "mode", string(effectiveMode)) } totalCorrection = allowed - currentTotal + // The house alone has surplus, so a discharge would feed the + // car. Stop it now rather than over several PI steps. + if gridW > noCarGridW && currentTotal+totalCorrection < 0 { + totalCorrection = -currentTotal + } // Surplus-only EV reserve cap: stack on top of the meter clamp. // Mirror the energy-path cap so the battery target on the diff --git a/go/internal/control/ev_car_before_battery_test.go b/go/internal/control/ev_car_before_battery_test.go new file mode 100644 index 000000000..dbd687e02 --- /dev/null +++ b/go/internal/control/ev_car_before_battery_test.go @@ -0,0 +1,183 @@ +package control + +import ( + "math" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// runCarBeforeBattery drives planner_self in a charge slot against a plant +// whose meter is the site without the battery plus the battery's last +// target. siteW is house plus car minus PV, site-signed. It returns every +// target the battery received. +func runCarBeforeBattery(t *testing.T, coversEV bool, siteW, carW, startBatteryW float64) []float64 { + t.Helper() + now := time.Now() + dir := SlotDirective{ + SlotStart: now, + SlotEnd: now.Add(15 * time.Minute), + BatteryEnergyWh: 350, // a PV charge slot: 1.4 kW for 15 minutes + Strategy: "self_consumption", + } + store := seedStore(siteW+startBatteryW, []struct { + name string + currentW, soc float64 + }{ + {"ferroamp", startBatteryW, 0.5}, + }) + st := NewState(0, 50, "ferroamp") + st.Mode = ModePlannerSelf + st.UseEnergyDispatch = true + st.SlotDirective = func(time.Time) (SlotDirective, bool) { return dir, true } + st.EVChargingW = carW + st.BatteryCoversEV = coversEV + st.SlewRateW = 100000 + st.MinDispatchIntervalS = 0 + const fuseW = 3 * 25 * 230 // keep the fuse out of this policy check + batteryW := startBatteryW + var got []float64 + for i := 0; i < 20; i++ { + targets := ComputeDispatch(store, st, caps(map[string]float64{"ferroamp": 15200}), fuseW) + if len(targets) == 1 { + batteryW = targets[0].TargetW + got = append(got, batteryW) + } + store.Update("ferroamp", telemetry.DerBattery, batteryW, ptrF64(0.5), nil) + store.Update("ferroamp", telemetry.DerMeter, siteW+batteryW, nil, nil) + store.DriverHealthMut("ferroamp").RecordSuccess() + } + return got +} + +func lastOr(v []float64, def float64) float64 { + if len(v) == 0 { + return def + } + return v[len(v)-1] +} + +// Seeds 207535, 207539 and 207530: PV 5 kW, house 3.6 kW, car 11 kW. The +// site imports about 10 kW, yet with battery_covers_ev off the battery +// charged from the PV the car was using. The car comes first: the battery +// charges only from what is left after the car, and is never discharged +// for the car. +func TestCarBeforeBatteryChargeWhenCoverIsOff(t *testing.T) { + const pvW, houseW, carW = 5000.0, 3611.0, 11040.0 + got := runCarBeforeBattery(t, false, houseW+carW-pvW, carW, 632) + for i, w := range got { + if w > 632+1 { + t.Fatalf("tick %d: battery charge rose to %.0f W while the site imports for the car", i, w) + } + if w < -1 { + t.Fatalf("tick %d: battery discharged %.0f W into the car with battery_covers_ev off", i, w) + } + } + if final := lastOr(got, 632); math.Abs(final) > 1 { + t.Errorf("battery settled at %.0f W, want 0 W: the car uses all PV", final) + } +} + +// With PV beyond house and car, the battery takes exactly the surplus the +// car leaves. +func TestCarBeforeBatteryChargesOnlyTheSurplusAfterTheCar(t *testing.T) { + for _, coversEV := range []bool{false, true} { + const pvW, houseW, carW = 16000.0, 3000.0, 11040.0 + got := runCarBeforeBattery(t, coversEV, houseW+carW-pvW, carW, 0) + const wantW = pvW - houseW - carW + for i, w := range got { + if w > wantW+60 { + t.Fatalf("covers_ev=%v tick %d: battery charge %.0f W takes PV the car uses (surplus after car %.0f W)", coversEV, i, w, wantW) + } + } + if final := lastOr(got, 0); math.Abs(final-wantW) > 60 { + t.Errorf("covers_ev=%v: battery settled at %.0f W, want about %.0f W", coversEV, final, wantW) + } + } +} + +// battery_covers_ev off still covers the house, never the car. +func TestCarBeforeBatteryCoverOffDischargesForHouseOnly(t *testing.T) { + const pvW, houseW, carW = 1000.0, 3000.0, 11040.0 + got := runCarBeforeBattery(t, false, houseW+carW-pvW, carW, 0) + const wantW = pvW - houseW // -2000 W: the house, not the car + for i, w := range got { + if w < wantW-60 { + t.Fatalf("tick %d: battery discharged %.0f W, past the house's %.0f W", i, w, wantW) + } + } + if final := lastOr(got, 0); math.Abs(final-wantW) > 60 { + t.Errorf("battery settled at %.0f W, want about %.0f W", final, wantW) + } +} + +// battery_covers_ev on lets the battery feed the car instead of charging. +func TestCarBeforeBatteryCoverOnDischargesForTheCar(t *testing.T) { + const pvW, houseW, carW = 5000.0, 3611.0, 11040.0 + got := runCarBeforeBattery(t, true, houseW+carW-pvW, carW, 632) + for i, w := range got { + if w > 632+1 { + t.Fatalf("tick %d: battery charge rose to %.0f W while the site imports", i, w) + } + } + if final := lastOr(got, 632); final > -1000 { + t.Errorf("battery settled at %.0f W, want a discharge that covers the car", final) + } +} + +// The energy path follows the same rule: a planned PV charge takes only +// the surplus the car leaves, while a planned purchase keeps its charge. +func TestCarBeforeBatteryEnergyPathPVChargeOnly(t *testing.T) { + const pvW, houseW, carW = 8000.0, 500.0, 6000.0 + for _, tc := range []struct { + name string + plannedW float64 + wantW float64 + }{ + {"pv charge", -1000, pvW - houseW - carW}, + {"planned purchase", 2000, 4000}, + } { + for _, coversEV := range []bool{false, true} { + now := time.Now() + dir := SlotDirective{ + SlotStart: now, + SlotEnd: now.Add(15 * time.Minute), + BatteryEnergyWh: 1000, // 4 kW for 15 minutes + Strategy: "cheap", + PlannedGridW: tc.plannedW, + HasPlannedGridW: true, + } + store := seedStore(houseW+carW-pvW, []struct { + name string + currentW, soc float64 + }{ + {"ferroamp", 0, 0.5}, + }) + st := NewState(0, 50, "ferroamp") + st.Mode = ModePlannerCheap + st.UseEnergyDispatch = true + st.SlotDirective = func(time.Time) (SlotDirective, bool) { return dir, true } + st.EVChargingW = carW + st.BatteryCoversEV = coversEV + st.SlewRateW = 100000 + targets := ComputeDispatch(store, st, caps(map[string]float64{"ferroamp": 15200}), 3*25*230) + if len(targets) != 1 { + t.Fatalf("%s covers_ev=%v: want 1 target, got %+v", tc.name, coversEV, targets) + } + got := targets[0].TargetW + if coversEV { + // The plan's grid check sees the car on the meter and + // backs the charge off further; only the car-first bound + // matters here. + if tc.plannedW < 100 && got > tc.wantW+1 { + t.Errorf("%s covers_ev=true: battery target %.0f W takes PV the car uses (want at most %.0f W)", tc.name, got, tc.wantW) + } + continue + } + if math.Abs(got-tc.wantW) > 1 { + t.Errorf("%s covers_ev=false: battery target %.0f W, want %.0f W", tc.name, got, tc.wantW) + } + } + } +} diff --git a/go/internal/control/ev_site_test.go b/go/internal/control/ev_site_test.go index 6a079b0d8..8458c3998 100644 --- a/go/internal/control/ev_site_test.go +++ b/go/internal/control/ev_site_test.go @@ -178,10 +178,12 @@ func TestEVSiteScheduledEVMayImportOnCheapNight(t *testing.T) { } } -func TestEVSiteSurplusOnlyDoesNotClaimPVSoakWhenTogetherTheyWouldImport(t *testing.T) { +func TestEVSiteSurplusOnlyTakesPVSoakWithoutImport(t *testing.T) { // Battery plan 4 kW of 7.5 kW leftover — soak, not Pixii buying. - // The old live reader treated any meter import as grid-charge and - // offered the full leftover, so a 3Φ snap held while soak+EV imported. + // The car comes before battery charge (owner decision P1, 27 Oct + // 2026), so the car may take the soak; the battery takes what the + // car leaves. Together they never import, and the battery never + // discharges for the car. start := evComboSiteStart() site := newSiteClock(t, evSiteConfig{ Start: start, @@ -191,14 +193,17 @@ func TestEVSiteSurplusOnlyDoesNotClaimPVSoakWhenTogetherTheyWouldImport(t *testi PVW: evComboPVW, }) site.run(12) - const soakHeadroom = 3500.0 // leftover 7500 − soak 4000 for _, rec := range site.ticks { if rec.N < 4 { continue } - if rec.EVW > soakHeadroom+loadpoint.SitePowerEpsW { - t.Fatalf("tick %d: surplus-only EV %.0f W claimed PV-soak (headroom %.0f); ticks=%s", - rec.N, rec.EVW, soakHeadroom, site.dumpTicks()) + if rec.GridW > loadpoint.SitePowerEpsW { + t.Fatalf("tick %d: surplus-only EV %.0f W and battery %.0f W import %.0f W; ticks=%s", + rec.N, rec.EVW, rec.BatW, rec.GridW, site.dumpTicks()) + } + if rec.BatW < -loadpoint.SitePowerEpsW { + t.Fatalf("tick %d: battery discharged %.0f W beside surplus-only EV %.0f W; ticks=%s", + rec.N, rec.BatW, rec.EVW, site.dumpTicks()) } } } diff --git a/go/internal/control/testdata/golden/seeded_ev_boost.json b/go/internal/control/testdata/golden/seeded_ev_boost.json index f4fd9c77b..89eadd288 100644 --- a/go/internal/control/testdata/golden/seeded_ev_boost.json +++ b/go/internal/control/testdata/golden/seeded_ev_boost.json @@ -1913,12 +1913,12 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": 588, + "target_w": 0, "clamped": false }, { "driver": "sungrow", - "target_w": 588, + "target_w": 0, "clamped": false } ], @@ -1941,9 +1941,9 @@ }, "site_totals": { "battery_current_w": -3117, - "battery_target_sum_w": 1176, + "battery_target_sum_w": 0, "raw_grid_w": -1466, - "projected_grid_w": 2827 + "projected_grid_w": 1651 } }, { @@ -2506,14 +2506,12 @@ "per_driver_targets": [ { "driver": "ferroamp", - "target_w": 5000, - "clamped": true + "target_w": 3950, + "clamped": false } ], "clamp_attributions": { - "clamped_drivers": [ - "ferroamp" - ], + "clamped_drivers": [], "all_targets_zero_clamped": false, "plan_sign_intent": 1, "plan_sign_floor_zeroed": false, @@ -2531,9 +2529,9 @@ }, "site_totals": { "battery_current_w": 1982, - "battery_target_sum_w": 5000, + "battery_target_sum_w": 3950, "raw_grid_w": -2307, - "projected_grid_w": 711 + "projected_grid_w": -339 } }, { diff --git a/go/internal/control/testdata/golden/slew_limiter.json b/go/internal/control/testdata/golden/slew_limiter.json index 21eec3639..60263128f 100644 --- a/go/internal/control/testdata/golden/slew_limiter.json +++ b/go/internal/control/testdata/golden/slew_limiter.json @@ -10653,7 +10653,7 @@ }, { "driver": "sungrow", - "target_w": 635.7936507936507, + "target_w": 0, "clamped": false } ], @@ -10678,9 +10678,9 @@ }, "site_totals": { "battery_current_w": -2923, - "battery_target_sum_w": 491.7936507936507, + "battery_target_sum_w": -144, "raw_grid_w": -1903, - "projected_grid_w": 1511.7936507936506 + "projected_grid_w": 876 } }, { From eb553dd7ff2a11cfaa569ee6dd4a64ce9ca476b9 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Tue, 27 Oct 2026 23:52:33 +0100 Subject: [PATCH 34/68] fix(control): peak shaving drops a running charge for the car Manual peak_shaving gave zero error for any import under the peak limit, so a battery charge that was running when the car started held while the site imported for the car, with battery_covers_ev on or off. When the site imports while the car and the battery both charge, the charge now comes down by the import, to 0 at most. Under the peak limit the battery still never discharges. Co-Authored-By: Claude Opus 5.5 --- .changeset/p1-car-before-battery-charge.md | 2 +- go/internal/control/dispatch.go | 6 ++ .../control/ev_car_before_battery_test.go | 68 +++++++++++++++++++ 3 files changed, 75 insertions(+), 1 deletion(-) diff --git a/.changeset/p1-car-before-battery-charge.md b/.changeset/p1-car-before-battery-charge.md index 9895c3b79..ed9f223d8 100644 --- a/.changeset/p1-car-before-battery-charge.md +++ b/.changeset/p1-car-before-battery-charge.md @@ -2,4 +2,4 @@ "ftw": patch --- -The car comes before home battery charging, also when the battery does not cover the car. The battery now charges only from the solar surplus the car leaves. Before, with battery cover off, FTW took the car out of the meter reading, so the battery charged from solar the car was using while the site imported up to 10 kW. Battery cover off still means the battery never discharges into the car. A planned grid purchase keeps its charge. +The car comes before home battery charging, also when the battery does not cover the car. The battery now charges only from the solar surplus the car leaves. Before, with battery cover off, FTW took the car out of the meter reading, so the battery charged from solar the car was using while the site imported up to 10 kW. Battery cover off still means the battery never discharges into the car. A planned grid purchase keeps its charge. In manual peak shaving, a battery charge that was running when the car started now comes off while the site imports, instead of holding under the peak limit. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index b415ffdbf..f671cbf6b 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -1877,6 +1877,12 @@ func ComputeDispatch( errW = gridW - state.PeakLimitW } else if gridW < 0 { errW = gridW // exporting → charge with surplus + } else if chargeGridW > 0 && currentTotal > 0 && state.EVChargingW > evActiveThresholdW { + // The car before battery charge: the site imports while + // the car and the battery both charge. Take the charge + // down by the import, to 0 at most; under the peak limit + // the battery does not discharge. + errW = math.Min(chargeGridW, currentTotal) } else { errW = 0 } diff --git a/go/internal/control/ev_car_before_battery_test.go b/go/internal/control/ev_car_before_battery_test.go index dbd687e02..bce40ca2d 100644 --- a/go/internal/control/ev_car_before_battery_test.go +++ b/go/internal/control/ev_car_before_battery_test.go @@ -181,3 +181,71 @@ func TestCarBeforeBatteryEnergyPathPVChargeOnly(t *testing.T) { } } } + +// runPeakShavingCar drives manual peak_shaving against the same plant as +// runCarBeforeBattery. The peak limit sits far above the site, so the +// import the car causes lands in peak_shaving's dead zone. +func runPeakShavingCar(t *testing.T, coversEV bool, siteW, carW, startBatteryW float64) []float64 { + t.Helper() + store := seedStore(siteW+startBatteryW, []struct { + name string + currentW, soc float64 + }{ + {"ferroamp", startBatteryW, 0.5}, + }) + st := NewState(0, 50, "ferroamp") + st.Mode = ModePeakShaving + st.PeakLimitW = 30000 + st.EVChargingW = carW + st.BatteryCoversEV = coversEV + st.SlewRateW = 100000 + st.MinDispatchIntervalS = 0 + const fuseW = 3 * 25 * 230 + batteryW := startBatteryW + var got []float64 + for i := 0; i < 20; i++ { + targets := ComputeDispatch(store, st, caps(map[string]float64{"ferroamp": 15200}), fuseW) + if len(targets) == 1 { + batteryW = targets[0].TargetW + } + got = append(got, batteryW) + store.Update("ferroamp", telemetry.DerBattery, batteryW, ptrF64(0.5), nil) + store.Update("ferroamp", telemetry.DerMeter, siteW+batteryW, nil, nil) + store.DriverHealthMut("ferroamp").RecordSuccess() + } + return got +} + +// The 207535 shape in manual peak_shaving. The battery was charging 871 W +// from the house surplus when the car started. The site now imports for +// the car, inside peak_shaving's dead zone, so nothing used to cut the +// charge. The car comes first: the charge goes, and the battery never +// discharges, because the import is under the peak limit. +func TestCarBeforeBatteryPeakShavingDropsARunningCharge(t *testing.T) { + const pv, house, car = 5000.0, 3611.0, 11040.0 + for _, cover := range []bool{false, true} { + got := runPeakShavingCar(t, cover, house+car-pv, car, 871) + for i, w := range got { + if w < -1 { + t.Fatalf("cover=%v tick %d: battery discharges %.0f W under the peak limit: %v", cover, i, w, got) + } + } + if final := lastOr(got, 871); final > 1 { + t.Fatalf("cover=%v: battery still charges %.0f W while the site imports %.0f W for the car: %v", + cover, final, house+car-pv+final, got) + } + } +} + +// With more PV than house and car together, peak_shaving still charges +// from what the car leaves: 18000 − 3611 − 11040 = 3349 W. +func TestCarBeforeBatteryPeakShavingChargesTheSurplusAfterTheCar(t *testing.T) { + const pv, house, car = 18000.0, 3611.0, 11040.0 + want := pv - house - car + for _, cover := range []bool{false, true} { + got := runPeakShavingCar(t, cover, house+car-pv, car, 0) + if final := lastOr(got, 0); math.Abs(final-want) > 60 { + t.Fatalf("cover=%v: battery settled at %.0f W, want the %.0f W left after the car: %v", cover, final, want, got) + } + } +} From ef7ca516382bc6520c6e55423924281739ebbfd1 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 00:06:56 +0100 Subject: [PATCH 35/68] fix(control): after a restart the battery credits the car the meter shows After a restart, the 0 A orders FTW sent while the meter was stale counted as the EV base the meter shows. With the car still drawing 8.2 kW from before, a new 6.2 kW order then counted as a 9 A rise to come, and the battery was held in discharge for the car (seed 207532). Until a charger's first order of this run can have landed, the battery side now counts the charger's live measured draw as in the reading, never above the latest order and never above the consumption the site meter shows. The car's own limit does not read it. Co-Authored-By: Claude Opus 5.5 --- .changeset/s4-ev-base-after-restart.md | 5 + .../control/ev_base_after_restart_test.go | 156 ++++++++++++++++++ go/internal/control/ev_battery_headroom.go | 16 +- go/internal/control/ev_fuse_budget.go | 42 ++++- 4 files changed, 212 insertions(+), 7 deletions(-) create mode 100644 .changeset/s4-ev-base-after-restart.md create mode 100644 go/internal/control/ev_base_after_restart_test.go diff --git a/.changeset/s4-ev-base-after-restart.md b/.changeset/s4-ev-base-after-restart.md new file mode 100644 index 000000000..919abe45d --- /dev/null +++ b/.changeset/s4-ev-base-after-restart.md @@ -0,0 +1,5 @@ +--- +"ftw": patch +--- + +After a restart, the home battery no longer stays in discharge for a car the meter already shows charging. Until the charger's first order of the new run can have landed, the battery counts the car's measured draw as part of the meter reading, never above FTW's latest order to the car and never above the consumption the site meter shows. Before, the 0 A orders FTW sent while the meter was still starting counted as the car's draw, so a lower order looked like a rise and the battery kept discharging toward its floor. diff --git a/go/internal/control/ev_base_after_restart_test.go b/go/internal/control/ev_base_after_restart_test.go new file mode 100644 index 000000000..49efc3088 --- /dev/null +++ b/go/internal/control/ev_base_after_restart_test.go @@ -0,0 +1,156 @@ +package control + +import ( + "encoding/json" + "math" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/loadpoint" + "github.com/srcfl/ftw/go/internal/sitesim" + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// restartFixture is seed 207532 just after Core restarted: a 16 A site with +// no margin, a battery FTW found discharging 5 kW, and a charger whose first +// logged offers of this run are 0 A, sent while the meter was stale, then +// 6,210 W (9 A on three phases) 2 s ago. The charger takes 40 s to apply an +// order, so the car still draws what it drew before the restart. evW is +// what the charger measures; the site meter reads gridW with the phase +// currents phaseA, and the PV inverter pvW. +func restartFixture(t *testing.T, gridW float64, phaseA [3]float64, batteryW, pvW, evW float64) (*telemetry.Store, *State) { + t.Helper() + store := telemetry.NewStore() + raw, _ := json.Marshal(map[string]any{"l1_a": phaseA[0], "l2_a": phaseA[1], "l3_a": phaseA[2]}) + store.Update("meter", telemetry.DerMeter, gridW, nil, raw) + store.RecordDriverSuccess("meter") + store.Update("sungrow", telemetry.DerBattery, batteryW, ptrF64(.3), nil) + store.RecordDriverSuccess("sungrow") + if pvW != 0 { + store.Update("pv", telemetry.DerPV, pvW, nil, nil) + store.RecordDriverSuccess("pv") + } + store.Update("charger", telemetry.DerEV, evW, nil, nil) + store.RecordDriverSuccess("charger") + + state := NewState(0, 0, "meter") + now := time.Now() + state.clock = func() time.Time { return now } + state.SiteFuseAmps, state.SiteFuseVoltage, state.SiteFusePhases, state.SiteFuseSafetyA = 16, 230, 3, 0 + state.DriverLimits = map[string]PowerLimits{"sungrow": {MaxChargeW: 5000, MaxDischargeW: 5000}} + state.batteryCommands = map[string]commandLog{"sungrow": commandLog{}.add(now.Add(-2*time.Second), batteryW)} + state.evFuseDemands = []evFuseDemand{{"garage", 6210, "3p"}} + state.EVCommandedW = 6210 + found := sentCommand{at: now.Add(-6 * time.Second), w: 0, a: 0, n: 3} + state.evLimit.set = true + state.evLimit.offers = map[string]chargerOffers{"garage": { + log: commandLog{found, {at: now.Add(-4 * time.Second), w: 0, a: 0, n: 3}, {at: now.Add(-2 * time.Second), w: 6210, a: 9, n: 3}}, + settle: evUnknownSettle, found: found, driver: "charger", + }} + return store, state +} + +// C10 (27 Oct triage, seed 207532): after a restart, the 0 A offers sent +// while the meter was stale counted as the EV base the meter shows, while +// the meter showed the car at 8.2 kW. The new 6.2 kW order then counted as +// a 9 A rise to come, and the battery was held in discharge for the car +// with battery_covers_ev off, down toward its floor. The car's measured +// draw is in the reading: the 6.2 kW order is a cut, and ending the +// discharge needs no room for it. +func TestEVBaseAfterRestartCreditsMeasuredDraw(t *testing.T) { + store, state := restartFixture(t, 780, [3]float64{2.03, 4.97, .47}, -5000, -3000, 8222) + out := clampEVBatteryHeadroom([]DispatchTarget{{Driver: "sungrow", TargetW: 0}}, store, state, 16*230*3) + if got := targetW(out, "sungrow"); got < -1 { + t.Fatalf("battery held at %.0f W for a car the meter already shows at 8.2 kW; want 0 W", got) + } +} + +// The credit stays on the safe side. A charger reading the meter cannot +// contain counts only up to the consumption the meter shows: here the +// charger claims 8.2 kW, but the site consumes 680 W, so 5,530 W of the +// 6,210 W order is still a rise to come, and the battery keeps the +// discharge that the busiest phase has no room to end. +func TestEVBaseAfterRestartCreditStaysInsideTheMeter(t *testing.T) { + store, state := restartFixture(t, 680, [3]float64{4.97, -1, -1}, 0, 0, 8222) + state.batteryCommands["sungrow"] = commandLog{}.add(state.now().Add(-time.Second), -5000) + out := clampEVBatteryHeadroom([]DispatchTarget{{Driver: "sungrow", TargetW: 0}}, store, state, 16*230*3) + riseA := (6210 - 680) / 690.0 + want := -(5000 - (16-4.97-riseA)*690) + if got := targetW(out, "sungrow"); math.Abs(got-want) > 1 { + t.Fatalf("battery %.0f W, want %.0f W: the charger's reading counts only up to the meter's 680 W", got, want) + } +} + +// The credit never exceeds the latest offer, needs a live charger reading, +// and ends once the charger's first offer of this run has had its settle +// time: then the offers alone say what the meter shows. +func TestEVFoundDrawWBounds(t *testing.T) { + for _, tc := range []struct { + name string + edit func(*telemetry.Store, *State) + want float64 + }{ + {"latest offer bounds the draw", func(*telemetry.Store, *State) {}, 6210}, + {"measured draw below the offer", func(store *telemetry.Store, _ *State) { + store.Update("charger", telemetry.DerEV, 4000, nil, nil) + }, 4000}, + {"charger offline", func(store *telemetry.Store, _ *State) { + store.DriverHealthMut("charger").SetOffline() + }, 0}, + {"no restart", func(_ *telemetry.Store, state *State) { + c := state.evLimit.offers["garage"] + c.found = sentCommand{} + state.evLimit.offers["garage"] = c + }, 0}, + {"first offer settled", func(_ *telemetry.Store, state *State) { + c := state.evLimit.offers["garage"] + c.found.at = state.now().Add(-c.settle) + state.evLimit.offers["garage"] = c + }, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + store, state := restartFixture(t, 780, [3]float64{2.03, 4.97, .47}, -5000, -3000, 8222) + tc.edit(store, state) + if got := state.evFoundDrawW(store, state.now(), 1e6, 0); math.Abs(got-tc.want) > 1e-6 { + t.Fatalf("credit %.0f W, want %.0f W", got, tc.want) + } + }) + } +} + +// Seed 207532's shape on the plant: Core restarts beside a car drawing +// 12 A from before, on a charger that takes 40 s to apply an order. For +// its first 6 s the meter is silent and the inverter unreachable, holding +// the 5 kW discharge it had (C1), so Core logs 0 A offers. Then Core asks +// 9 A for the car. PV covers the house, the plan is stale and +// battery_covers_ev is off: the battery ends its discharge as fast as its +// slew allows, and no phase passes the fuse line on the way. +func TestSiteSimRestartEndsDischargeForACarAlreadyDrawing(t *testing.T) { + p := simPlant(simStart) + p.Fuse.RatingA, p.HouseW, p.PVW = 16, houseA(4, 9, 2), -6000 + p.EVSE.Delay, p.EVSE.ReadbackLag = 40*time.Second, 0 + p.EVSE.OfferA, p.EVSE.OfferPhases = 12, 3 + p.Battery = &sitesim.Battery{Phases: 3, MaxChargeW: 5000, MaxDischargeW: 5000, CapacityWh: 10000, SoC: .3, Latency: 2 * time.Second, W: -5000} + p.Events = []sitesim.Event{ + {Kind: sitesim.MeterSilent, For: 6 * time.Second}, + {Kind: sitesim.DriverOffline, Device: "battery", For: 6 * time.Second}, + } + s := &simSite{p: p, lp: simLoadpoint()} + s.setup = func(s *simSite) { + s.state.Mode = ModePlannerSelf + s.state.SiteFuseSafetyA = 0 + s.ctrl.SetManualHold(s.lp.ID, loadpoint.ManualHold{PowerW: 6210, PhaseMode: "3p", Persistent: true, StartedAt: s.p.Now, UpdatedAt: s.p.Now}) + } + s.boot() + s.run(14 * time.Second) + if s.offerW != 6210 || s.p.EVSE.DrawW != 8280 { + t.Fatalf("not the seed's state: offer %.0f W, car %.0f W", s.offerW, s.p.EVSE.DrawW) + } + if s.batteryCmdW < -1 { + t.Fatalf("battery held at %.0f W 8 s after the meter returned, with the car already in the reading", s.batteryCmdW) + } + s.run(2 * time.Minute) + if s.failure != "" { + t.Fatal(s.failure) + } +} diff --git a/go/internal/control/ev_battery_headroom.go b/go/internal/control/ev_battery_headroom.go index 0ea1d3201..2c27e43cd 100644 --- a/go/internal/control/ev_battery_headroom.go +++ b/go/internal/control/ev_battery_headroom.go @@ -7,16 +7,17 @@ import ( ) // clampEVBatteryHeadroom keeps optional battery charge out of room an EV -// still needs. It reads only the site meter and our own commands; no charger -// reading takes part, and a battery's own reading only bounds how much of a -// discharge we ordered it may keep. The EV still needs its demand less the -// offers the meter surely shows (evShownW). +// still needs. It reads the site meter and our own commands. A battery's own +// reading only bounds how much of a discharge we ordered it may keep. A +// charger's reading counts only before any of its offers of this run has +// surely landed, and only up to what the meter shows (evFoundDrawW). The EV +// still needs its demand less the offers the meter surely shows (evShownW) +// and that draw. func clampEVBatteryHeadroom(targets []DispatchTarget, store *telemetry.Store, state *State, fuseMaxW float64) []DispatchTarget { if store == nil || state == nil || len(targets) == 0 || fuseMaxW <= 0 { return targets } now := state.now() - offeredW := state.evShownW(now) var demandW float64 phases := 3.0 // No phase placement promise for 1p or auto chargers. for _, demand := range state.evFuseDemands { @@ -28,7 +29,6 @@ func clampEVBatteryHeadroom(targets []DispatchTarget, store *telemetry.Store, st if len(state.evFuseDemands) == 0 { return targets } - needW := math.Max(0, demandW-offeredW) meter := store.Get(state.SiteMeterDriver, telemetry.DerMeter) if meter == nil { return floorPositiveEVBatteryTargets(targets) @@ -37,6 +37,10 @@ func clampEVBatteryHeadroom(targets []DispatchTarget, store *telemetry.Store, st if !finiteFuseValue(gridW) || !finiteFuseValue(fuseMaxW) { return floorPositiveEVBatteryTargets(targets) } + offeredW := state.evShownW(now) + consumptionW := gridW - sumOnlineSignedW(store, telemetry.DerBattery) - sumOnlineSignedW(store, telemetry.DerPV) - store.SumOnlineV2XW() + offeredW += state.evFoundDrawW(store, now, consumptionW, offeredW) + needW := math.Max(0, demandW-offeredW) latest := make(map[string]float64, len(targets)) lowest := make(map[string]float64, len(targets)) targeted := make(map[string]bool, len(targets)) diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index 37b108dc8..63c97047a 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -179,6 +179,10 @@ type chargerOffers struct { // charger as 0 before it; a cut takes it as shown, since the reading is // all Core knows of it. found sentCommand + // driver is the charger's driver, whose power reading only the battery + // side reads, and only before any offer of this run has surely landed + // (evFoundDrawW). + driver string // carPhases is how many phases the car draws on, as the loadpoint saw // it on the site meter: 1 or 3, or 0 when unknown. carPhase is the phase // a car on one phase draws on, 1-3. @@ -366,6 +370,42 @@ func (s *State) evShownW(at time.Time) float64 { return w } +// evFoundDrawW is EV draw the battery side may count as shown beyond +// evShownW (shownW) while a charger has no order of this run that has +// surely landed: after a restart or a plug-in, until its first logged offer +// is older than its settle time. Core then does not know which offer the +// charger runs on, and its first offers (often 0 A) say nothing of what the +// meter shows. A car seen drawing in that window is in the reading: each +// such charger counts its live measured draw, the lower of raw and smoothed, +// never above its latest offer, and in all no more than the consumption the +// site meter shows (consumptionW) less shownW. The car's own limit never +// reads this; only how much of our latest offers the battery reserves as a +// rise to come. +func (s *State) evFoundDrawW(store *telemetry.Store, at time.Time, consumptionW, shownW float64) float64 { + if store == nil || !finiteFuseValue(consumptionW) { + return 0 + } + var w float64 + for _, c := range s.evLimit.offers { + n := len(c.log) + if n == 0 || c.found.at.IsZero() || at.Sub(c.found.at) >= c.settle || c.driver == "" { + continue + } + r := store.Get(c.driver, telemetry.DerEV) + if r == nil || !store.DriverHealth(c.driver).TelemetryLive() { + continue + } + drawW := math.Min(r.RawW, r.SmoothedW) + if !finiteFuseValue(drawW) { + continue + } + unshown, _ := c.log.unshown(at, c.batterySettle()) + latest := c.log[n-1].w + w += math.Max(0, math.Min(latest, drawW)-math.Max(0, latest-unshown)) + } + return math.Max(0, math.Min(w, consumptionW-shownW)) +} + // batterySettle is how long the battery side counts a raise of this // charger's as unshown: its declared response time, else evSettle // (evShownW). @@ -466,7 +506,7 @@ func (s *State) recordEVOffers(store *telemetry.Store, points []loadpoint.State) continue } c := s.evLimit.offers[point.ID] - c.settle, c.declared, c.carPhases, c.carPhase = evUnknownSettle, false, point.CarPhases, point.CarPhase + c.settle, c.declared, c.carPhases, c.carPhase, c.driver = evUnknownSettle, false, point.CarPhases, point.CarPhase, point.DriverName if r := store.Get(point.DriverName, telemetry.DerEV); r != nil { if declared := telemetry.DeclaredPowerMaxAge(r.Data); declared > 0 { c.settle, c.declared = max(evSettle, declared), true From e53aa4b046e41c1f7cd7e0ee821d8b70f6ff42ee Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 00:33:05 +0100 Subject: [PATCH 36/68] fix(control): credit a found car only from a current charger sample Review of #1926 found two ways the restart credit let the battery end a discharge into room the car's pending rise still needs: - The charger reading counted with no check that it was current. A held reading after a failed poll, or a sample older than the site reading, could show a car that a fast charger had already stopped. The draw now counts only when the last poll succeeded and the charger measured it within one control interval of the site reading. - The consumption bound subtracted the smoothed battery, PV and V2X values, which lag an output that just fell. It now takes the higher of raw and smoothed for each, so the bound stays at or below what the meter shows. New tests pin both, plus the shown-offer subtractions and a window that outlasts evSettle. Co-Authored-By: Claude Opus 5.5 --- .changeset/s4-ev-base-after-restart.md | 2 +- .../control/ev_base_after_restart_test.go | 98 ++++++++++++++++++- go/internal/control/ev_battery_headroom.go | 3 +- go/internal/control/ev_fuse_budget.go | 49 ++++++++-- 4 files changed, 137 insertions(+), 15 deletions(-) diff --git a/.changeset/s4-ev-base-after-restart.md b/.changeset/s4-ev-base-after-restart.md index 919abe45d..8fcee1181 100644 --- a/.changeset/s4-ev-base-after-restart.md +++ b/.changeset/s4-ev-base-after-restart.md @@ -2,4 +2,4 @@ "ftw": patch --- -After a restart, the home battery no longer stays in discharge for a car the meter already shows charging. Until the charger's first order of the new run can have landed, the battery counts the car's measured draw as part of the meter reading, never above FTW's latest order to the car and never above the consumption the site meter shows. Before, the 0 A orders FTW sent while the meter was still starting counted as the car's draw, so a lower order looked like a rise and the battery kept discharging toward its floor. +After a restart, the home battery no longer stays in discharge for a car the meter already shows charging. Until the charger's first order of the new run can have landed, the battery counts the car's measured draw as part of the meter reading, never above FTW's latest order to the car and never above the consumption the site meter shows. The draw counts only when the charger measured it within one control interval of the site reading and its last poll succeeded. Before, the 0 A orders FTW sent while the meter was still starting counted as the car's draw, so a lower order looked like a rise and the battery kept discharging toward its floor. diff --git a/go/internal/control/ev_base_after_restart_test.go b/go/internal/control/ev_base_after_restart_test.go index 49efc3088..772ac34bc 100644 --- a/go/internal/control/ev_base_after_restart_test.go +++ b/go/internal/control/ev_base_after_restart_test.go @@ -91,8 +91,9 @@ func TestEVFoundDrawWBounds(t *testing.T) { want float64 }{ {"latest offer bounds the draw", func(*telemetry.Store, *State) {}, 6210}, - {"measured draw below the offer", func(store *telemetry.Store, _ *State) { + {"measured draw below the offer", func(store *telemetry.Store, state *State) { store.Update("charger", telemetry.DerEV, 4000, nil, nil) + store.Get("charger", telemetry.DerEV).UpdatedAt = state.now() }, 4000}, {"charger offline", func(store *telemetry.Store, _ *State) { store.DriverHealthMut("charger").SetOffline() @@ -107,12 +108,103 @@ func TestEVFoundDrawWBounds(t *testing.T) { c.found.at = state.now().Add(-c.settle) state.evLimit.offers["garage"] = c }, 0}, + {"a 40 s charger's window outlasts evSettle", func(_ *telemetry.Store, state *State) { + c := state.evLimit.offers["garage"] + c.settle, c.declared = 40*time.Second, true + c.found.at = state.now().Add(-30 * time.Second) + c.log[0].at = c.found.at + state.evLimit.offers["garage"] = c + }, 6210}, + {"the shown part of the latest offer is not counted twice", func(_ *telemetry.Store, state *State) { + c := state.evLimit.offers["garage"] + c.found.at = state.now().Add(-60 * time.Second) + c.log = commandLog{c.found, {at: state.now().Add(-25 * time.Second), w: 6210, a: 9, n: 3}} + state.evLimit.offers["garage"] = c + }, 0}, } { t.Run(tc.name, func(t *testing.T) { store, state := restartFixture(t, 780, [3]float64{2.03, 4.97, .47}, -5000, -3000, 8222) tc.edit(store, state) - if got := state.evFoundDrawW(store, state.now(), 1e6, 0); math.Abs(got-tc.want) > 1e-6 { - t.Fatalf("credit %.0f W, want %.0f W", got, tc.want) + shownW := state.evShownW(state.now()) + if got := state.evFoundDrawW(store, store.Get("meter", telemetry.DerMeter), state.now(), shownW); math.Abs(got-tc.want) > 1e-6 { + t.Fatalf("credit %.0f W beside %.0f W shown, want %.0f W", got, shownW, tc.want) + } + }) + } +} + +// Offers the meter already shows come off the consumption the credit may +// fill: here another charger's 5 kW is shown, so of the 8,780 W the meter +// shows as consumption only 3,780 W is left for this car. +func TestEVFoundDrawWLeavesOutShownOffers(t *testing.T) { + store, state := restartFixture(t, 780, [3]float64{2.03, 4.97, .47}, -5000, -3000, 8222) + if got := state.evFoundDrawW(store, store.Get("meter", telemetry.DerMeter), state.now(), 5000); math.Abs(got-3780) > 1e-6 { + t.Fatalf("credit %.0f W, want 3780 W", got) + } +} + +// A charger reading the meter may not show gives no credit. A fast charger +// applied the 0 A sent while the meter was silent, so the car draws +// nothing, but its reading still shows the 8.2 kW from before: held after a +// failed poll, or a sample older than the site reading (an OCPP +// MeterValues interval). The house draws 7 kW on balanced phases, the +// battery runs the -5 kW discharge Core ordered in this run, and the meter +// shows 2.9 A per phase. The 9 A order still to come leaves room to end +// only (16 - 2.9 - 9) × 690 W of the discharge. +func TestEVBaseAfterRestartNeedsACurrentChargerSample(t *testing.T) { + for _, tc := range []struct { + name string + edit func(*telemetry.Store, *State) + }{ + {"last poll failed", func(store *telemetry.Store, _ *State) { + store.RecordDriverError("charger", "timeout") + }}, + {"sample older than the site reading", func(store *telemetry.Store, state *State) { + data, _ := json.Marshal(map[string]any{"power_observed_at": state.now().Add(-10 * time.Second).Format(time.RFC3339Nano)}) + store.Update("charger", telemetry.DerEV, 8222, nil, data) + store.Get("charger", telemetry.DerEV).UpdatedAt = state.now() + store.RecordDriverSuccess("charger") + }}, + {"site reading older than the sample", func(store *telemetry.Store, state *State) { + store.Get("meter", telemetry.DerMeter).UpdatedAt = state.now().Add(-10 * time.Second) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + store, state := restartFixture(t, 2000, [3]float64{2.9, 2.9, 2.9}, -5000, 0, 8222) + tc.edit(store, state) + out := clampEVBatteryHeadroom([]DispatchTarget{{Driver: "sungrow", TargetW: 0}}, store, state, 16*230*3) + got := targetW(out, "sungrow") + if afterA := 2.9 + (got+5000)/690 + 9; afterA > 16+1e-6 { + t.Fatalf("battery ends its discharge to %.0f W on a charger reading the meter may not show: %.2f A per phase once the car's order lands", got, afterA) + } + }) + } +} + +// The consumption bound reads the devices as the meter does. A battery +// that just ended a discharge, or PV that just dropped, still shows its old +// output in the smoothed value; counting that would raise the consumption +// the meter shows, and the credit with it, by the lag. +func TestEVBaseAfterRestartConsumptionReadsCurrentOutput(t *testing.T) { + for _, tc := range []struct { + name string + pvW float64 + driver string + kind telemetry.DerType + consumptionW float64 + }{ + {"battery ended its discharge", 0, "sungrow", telemetry.DerBattery, 680}, + {"PV dropped", -500, "pv", telemetry.DerPV, 1180}, + } { + t.Run(tc.name, func(t *testing.T) { + store, state := restartFixture(t, 680, [3]float64{4.97, -1, -1}, 0, tc.pvW, 8222) + store.Get(tc.driver, tc.kind).SmoothedW = -3000 + state.batteryCommands["sungrow"] = commandLog{}.add(state.now().Add(-time.Second), -5000) + out := clampEVBatteryHeadroom([]DispatchTarget{{Driver: "sungrow", TargetW: 0}}, store, state, 16*230*3) + riseA := (6210 - tc.consumptionW) / 690 + want := -(5000 - (16-4.97-riseA)*690) + if got := targetW(out, "sungrow"); math.Abs(got-want) > 1 { + t.Fatalf("battery %.0f W, want %.0f W: the meter shows %.0f W of consumption", got, want, tc.consumptionW) } }) } diff --git a/go/internal/control/ev_battery_headroom.go b/go/internal/control/ev_battery_headroom.go index 2c27e43cd..a2d57eda4 100644 --- a/go/internal/control/ev_battery_headroom.go +++ b/go/internal/control/ev_battery_headroom.go @@ -38,8 +38,7 @@ func clampEVBatteryHeadroom(targets []DispatchTarget, store *telemetry.Store, st return floorPositiveEVBatteryTargets(targets) } offeredW := state.evShownW(now) - consumptionW := gridW - sumOnlineSignedW(store, telemetry.DerBattery) - sumOnlineSignedW(store, telemetry.DerPV) - store.SumOnlineV2XW() - offeredW += state.evFoundDrawW(store, now, consumptionW, offeredW) + offeredW += state.evFoundDrawW(store, meter, now, offeredW) needW := math.Max(0, demandW-offeredW) latest := make(map[string]float64, len(targets)) lowest := make(map[string]float64, len(targets)) diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index 63c97047a..ef650fa5b 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -375,16 +375,27 @@ func (s *State) evShownW(at time.Time) float64 { // surely landed: after a restart or a plug-in, until its first logged offer // is older than its settle time. Core then does not know which offer the // charger runs on, and its first offers (often 0 A) say nothing of what the -// meter shows. A car seen drawing in that window is in the reading: each -// such charger counts its live measured draw, the lower of raw and smoothed, +// meter shows. A car seen drawing in that window is in the reading when the +// charger measured it within one control interval of the site reading: a +// fast charger may have applied a 0 A offer since an older sample, and a +// held reading after a failed poll says nothing of now. Each such charger +// counts its measured draw, the lowest of the sample, raw and smoothed, // never above its latest offer, and in all no more than the consumption the -// site meter shows (consumptionW) less shownW. The car's own limit never -// reads this; only how much of our latest offers the battery reserves as a -// rise to come. -func (s *State) evFoundDrawW(store *telemetry.Store, at time.Time, consumptionW, shownW float64) float64 { - if store == nil || !finiteFuseValue(consumptionW) { +// site meter shows (siteConsumptionW) less shownW. The car's own limit +// never reads this; only how much of our latest offers the battery reserves +// as a rise to come. +func (s *State) evFoundDrawW(store *telemetry.Store, meter *telemetry.DerReading, at time.Time, shownW float64) float64 { + if store == nil || meter == nil { return 0 } + consumptionW := siteConsumptionW(store, meter.RawW) + if !finiteFuseValue(consumptionW) { + return 0 + } + skew := time.Duration(s.ControlIntervalS) * time.Second + if skew <= 0 { + skew = 2 * time.Second // config's default control_interval_s + } var w float64 for _, c := range s.evLimit.offers { n := len(c.log) @@ -392,10 +403,14 @@ func (s *State) evFoundDrawW(store *telemetry.Store, at time.Time, consumptionW, continue } r := store.Get(c.driver, telemetry.DerEV) - if r == nil || !store.DriverHealth(c.driver).TelemetryLive() { + if h := store.DriverHealth(c.driver); r == nil || !h.TelemetryLive() || h.LastReadFailed() { continue } - drawW := math.Min(r.RawW, r.SmoothedW) + p, ok := qualifiedFuseObservation(r, at) + if !ok || p.Seen().Before(meter.UpdatedAt.Add(-skew)) || p.At.After(meter.UpdatedAt.Add(skew)) { + continue + } + drawW := math.Min(p.PowerW, math.Min(r.RawW, r.SmoothedW)) if !finiteFuseValue(drawW) { continue } @@ -406,6 +421,22 @@ func (s *State) evFoundDrawW(store *telemetry.Store, at time.Time, consumptionW, return math.Max(0, math.Min(w, consumptionW-shownW)) } +// siteConsumptionW is the consumption a site reading of gridW shows: grid +// less each live battery, PV and V2X reading, each at the higher of raw and +// smoothed. A smoothed value lags an output that just fell; the higher one +// keeps the estimate at or below what the meter shows. +func siteConsumptionW(store *telemetry.Store, gridW float64) float64 { + w := gridW + for _, t := range []telemetry.DerType{telemetry.DerBattery, telemetry.DerPV, telemetry.DerV2X} { + for _, r := range store.ReadingsByType(t) { + if store.DriverHealth(r.Driver).TelemetryLive() { + w -= math.Max(r.RawW, r.SmoothedW) + } + } + } + return w +} + // batterySettle is how long the battery side counts a raise of this // charger's as unshown: its declared response time, else evSettle // (evShownW). From bbb5f1bf062c2e3ab2d04ab6c6748190844a4712 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 01:04:32 +0100 Subject: [PATCH 37/68] test(control): run the site sim at the new 0 A default margin simFuseSafetyA follows the config default, now 0. fitScenario takes the room under the line and sets the house from simFuseSafetyA, so its exact fit stays twelve whole steps at any margin. "charger's own load balancer" passes at margin 0, so its known line goes. Co-Authored-By: Claude Opus 5.5 --- .../control/fuse_line_property_test.go | 27 ++++++++++--------- go/internal/control/sitesim_test.go | 4 +-- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/go/internal/control/fuse_line_property_test.go b/go/internal/control/fuse_line_property_test.go index 1cc28fe92..a4aa32241 100644 --- a/go/internal/control/fuse_line_property_test.go +++ b/go/internal/control/fuse_line_property_test.go @@ -225,10 +225,11 @@ func testFuseLineIdleStart(t *testing.T, inA float64, phases int, marginA, lineA } } -// fitScenario runs a 3 × 16 A site, safety margin 0.5 A, with houseLoadA of -// house on each phase. At 3.5 A twelve steps of the car fit exactly under -// the 15.5 A line. The car asks for 16 A. -func fitScenario(houseLoadA float64, run time.Duration, noise func() float64) *simSite { +// fitScenario runs a 3 × 16 A site with the default safety margin and +// enough house on each phase to leave roomA under the line. With 12 A of +// room, twelve steps of the car fit exactly. The car asks for 16 A. +func fitScenario(roomA float64, run time.Duration, noise func() float64) *simSite { + houseLoadA := 16 - simFuseSafetyA - roomA sc := simScenario{name: "exact fit", run: run, plant: func(p *sitesim.Plant) { p.Fuse.RatingA = 16 @@ -240,12 +241,12 @@ func fitScenario(houseLoadA float64, run time.Duration, noise func() float64) *s // Closed loop: the car climbs to the line and stays there for 30 min. func TestSiteSimCarEndsAtTheLine(t *testing.T) { - s := fitScenario(3.5, 30*time.Minute, nil) + s := fitScenario(12, 30*time.Minute, nil) if s.failure != "" { t.Fatal(s.failure) } lineA := s.state.fuseLineA() - if want := (lineA - 3.5) * 690; s.p.EVSE.DrawW != want || s.peakA > lineA+1e-6 { + if want := 12.0 * 690; s.p.EVSE.DrawW != want || s.peakA > lineA+1e-6 { t.Fatalf("car %.0f W, peak phase %.3f A; want %.0f W with every phase at most %.1f A", s.p.EVSE.DrawW, s.peakA, want, lineA) } var last float64 @@ -275,16 +276,16 @@ func TestSiteSimCarEndsAtTheLine(t *testing.T) { // faster hunt fails. func TestSiteSimNoisyLineCyclesSlowly(t *testing.T) { for _, tc := range []struct { - houseA, sigma float64 - cutsPerHour float64 // the most allowed after the climb - dropSteps float64 // the furthest below the top + roomA, sigma float64 + cutsPerHour float64 // the most allowed after the climb + dropSteps float64 // the furthest below the top }{ - {3.25, .1, 0, 0}, {3.75, .2, 0, 0}, // part of a step left - {3.5, .03, 5, 1}, {3.5, .1, 5, 1}, {3.5, .2, 5, 2}, // exact fit + {12.25, .1, 0, 0}, {11.75, .2, 0, 0}, // part of a step left + {12, .03, 5, 1}, {12, .1, 5, 1}, {12, .2, 5, 2}, // exact fit } { - t.Run(fmt.Sprintf("house_%.2fA/noise_%.2fA", tc.houseA, tc.sigma), func(t *testing.T) { + t.Run(fmt.Sprintf("room_%.2fA/noise_%.2fA", tc.roomA, tc.sigma), func(t *testing.T) { rng := rand.New(rand.NewPCG(1, 0)) - s := fitScenario(tc.houseA, 2*time.Hour, func() float64 { return tc.sigma * rng.NormFloat64() }) + s := fitScenario(tc.roomA, 2*time.Hour, func() float64 { return tc.sigma * rng.NormFloat64() }) if s.failure != "" { t.Fatal(s.failure) } diff --git a/go/internal/control/sitesim_test.go b/go/internal/control/sitesim_test.go index 04dd9690c..943ef7fdf 100644 --- a/go/internal/control/sitesim_test.go +++ b/go/internal/control/sitesim_test.go @@ -21,7 +21,7 @@ import ( const simCoreEvery = 2 * time.Second // simFuseSafetyA is the site's fuse.safety_margin_a, the config default. -const simFuseSafetyA = .5 +const simFuseSafetyA = 0 // simSite runs Core's control tick against a sitesim.Plant in main.go's // order: site import, charger tick, then battery dispatch. Core's settings @@ -647,7 +647,7 @@ func simScenarios() []simScenario { plant: func(p *sitesim.Plant) { p.HouseW, p.PVW = houseA(2, 2, 2), -22*690 }}, {name: "export start, unsigned phase currents", run: 5 * time.Minute, plant: func(p *sitesim.Plant) { p.HouseW, p.PVW, p.Meter.Unsigned = houseA(2, 2, 2), -22*690, true }}, - {name: "charger's own load balancer", known: "a cut comes off an offer the car does not draw, ev_fuse_budget.go:172", run: 20 * time.Minute, + {name: "charger's own load balancer", run: 20 * time.Minute, plant: func(p *sitesim.Plant) { p.HouseW, p.EVSE.LoadBalancerA = houseA(12, 12, 12), 25 p.Events = []sitesim.Event{ From 3cf26fda0e796f88aea627b63090bf6509034359 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 01:04:32 +0100 Subject: [PATCH 38/68] docs(changeset): say what margin 0 moves once the fuse stack lands With the stack under it, the default moves the car's and the battery's per-phase line as well as the site totals. 0.5 A stops being the default, so #1910's changeset no longer calls it that. Co-Authored-By: Claude Opus 5.5 --- .changeset/b-ev-fuse-line-at-rating.md | 2 +- .changeset/d-fuse-margin-default-0.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/b-ev-fuse-line-at-rating.md b/.changeset/b-ev-fuse-line-at-rating.md index f28801459..a886e5268 100644 --- a/.changeset/b-ev-fuse-line-at-rating.md +++ b/.changeset/b-ev-fuse-line-at-rating.md @@ -2,4 +2,4 @@ "ftw": patch --- -The car now charges up to the fuse rating less `fuse.safety_margin_a`, not a fixed 1 A below it. A charging car rises one step once that step fits under the line, instead of needing two steps of room and keeping one free; an idle car starts with all the room it has. Home battery charge beside a car uses the same line, with no 1 A floor. On a three-phase site with the default 0.5 A margin, a car near the fuse gets 0.5 A to 1.5 A more on each phase. Cuts above the line still wait for the fuse's heat budget, and the hour's import limit keeps its own margins. A car never rises or starts into battery discharge that the fuse guard added. +The car now charges up to the fuse rating less `fuse.safety_margin_a`, not a fixed 1 A below it. A charging car rises one step once that step fits under the line, instead of needing two steps of room and keeping one free; an idle car starts with all the room it has. Home battery charge beside a car uses the same line, with no 1 A floor. On a three-phase site with a 0.5 A margin, a car near the fuse gets 0.5 A to 1.5 A more on each phase. Cuts above the line still wait for the fuse's heat budget, and the hour's import limit keeps its own margins. A car never rises or starts into battery discharge that the fuse guard added. diff --git a/.changeset/d-fuse-margin-default-0.md b/.changeset/d-fuse-margin-default-0.md index 3a82a6eb7..2d91f84de 100644 --- a/.changeset/d-fuse-margin-default-0.md +++ b/.changeset/d-fuse-margin-default-0.md @@ -2,4 +2,4 @@ "ftw": patch --- -`fuse.safety_margin_a` now defaults to 0. On a site with no saved margin, the limits FTW puts on the site's total import and export rise to the fuse rating, 0.5 A per phase higher than before. A margin is opt-in, for an inverter whose own phase limiter trips at the rating. FTW keeps any margin you have saved. If yours is exactly 0.5 A, FTW's old default, the log says so once at startup; set 0 to drop it. +`fuse.safety_margin_a` now defaults to 0. On a site with no saved margin, FTW works to the fuse rating: the car, the home battery's charge and fuse relief, and the site's total import and export limits each move up 0.5 A per phase, to the rating. A margin is opt-in, for an inverter whose own phase limiter trips at the rating. FTW keeps any margin you have saved. If yours is exactly 0.5 A, FTW's old default, the log says so once at startup; set 0 to drop it. From 4ecebfd205d1abcb103713fb5a35b47cef9f81ed Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 01:21:54 +0100 Subject: [PATCH 39/68] test(control): keep the load-balancer bug as a known line above the line At the 0 A default the scenario passes only because the charger's own balancer sits at 25 A, the rating and so the line. The bug is still in Core: a cut comes off an offer the car does not draw. Two known variants keep it tracked and turn red once it is fixed: the stored 0.5 A margin (over 24.5 A for more than 11 s) and a balancer at 25.5 A at margin 0 (over 25 A for more than 11 s). Co-Authored-By: Claude Opus 5.5 --- go/internal/control/sitesim_test.go | 37 ++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/go/internal/control/sitesim_test.go b/go/internal/control/sitesim_test.go index 943ef7fdf..9757eea3e 100644 --- a/go/internal/control/sitesim_test.go +++ b/go/internal/control/sitesim_test.go @@ -609,6 +609,23 @@ func simDay(p *sitesim.Plant) { } func simScenarios() []simScenario { + // A charger whose own load balancer holds each phase to balancerA. + loadBalancer := func(balancerA float64) simScenario { + name := "charger's own load balancer" + if balancerA != 25 { + name = fmt.Sprintf("%s at %.1f A", name, balancerA) + } + return simScenario{name: name, run: 20 * time.Minute, + plant: func(p *sitesim.Plant) { + p.HouseW, p.EVSE.LoadBalancerA = houseA(12, 12, 12), balancerA + p.Events = []sitesim.Event{ + {At: 5 * time.Minute, Do: func(p *sitesim.Plant) { p.HouseW = houseA(18, 12, 12) }}, + {At: 10 * time.Minute, Do: func(p *sitesim.Plant) { p.HouseW = houseA(4, 4, 4) }}, + {At: 15 * time.Minute, Do: func(p *sitesim.Plant) { p.HouseW = houseA(20, 20, 20) }}, + } + }} + } + const loadBalancerBug = "a cut comes off an offer the car does not draw, stepEVMeterLimit (ev_fuse_budget.go:769)" slowCharger := func(delay time.Duration) func(*sitesim.Plant) { return func(p *sitesim.Plant) { p.HouseW, p.EVSE.Delay = houseA(15, 15, 15), delay } } @@ -647,15 +664,11 @@ func simScenarios() []simScenario { plant: func(p *sitesim.Plant) { p.HouseW, p.PVW = houseA(2, 2, 2), -22*690 }}, {name: "export start, unsigned phase currents", run: 5 * time.Minute, plant: func(p *sitesim.Plant) { p.HouseW, p.PVW, p.Meter.Unsigned = houseA(2, 2, 2), -22*690, true }}, - {name: "charger's own load balancer", run: 20 * time.Minute, - plant: func(p *sitesim.Plant) { - p.HouseW, p.EVSE.LoadBalancerA = houseA(12, 12, 12), 25 - p.Events = []sitesim.Event{ - {At: 5 * time.Minute, Do: func(p *sitesim.Plant) { p.HouseW = houseA(18, 12, 12) }}, - {At: 10 * time.Minute, Do: func(p *sitesim.Plant) { p.HouseW = houseA(4, 4, 4) }}, - {At: 15 * time.Minute, Do: func(p *sitesim.Plant) { p.HouseW = houseA(20, 20, 20) }}, - } - }}, + loadBalancer(25), + // The balancer sits at the rating, so at the default 0 A margin it + // never lets the car past Core's line. Above the line the bug shows. + withKnown(withSafetyMarginA(loadBalancer(25), .5), loadBalancerBug), + withKnown(loadBalancer(25.5), loadBalancerBug), {name: "slow cloud charger 60 s", run: 15 * time.Minute, plant: slowCharger(time.Minute)}, {name: "slow cloud charger 120 s", run: 15 * time.Minute, @@ -783,6 +796,12 @@ func simScenarios() []simScenario { } } +// withKnown marks sc as failing on the finding known. +func withKnown(sc simScenario, known string) simScenario { + sc.known = known + return sc +} + // withSafetyMarginA runs sc with an opt-in fuse.safety_margin_a. The // default is 0; a site that keeps the old 0.5 A must still pass. func withSafetyMarginA(sc simScenario, a float64) simScenario { From 97eb612129fbeec39530fe2c1cc70f4eed16faa4 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 01:42:33 +0100 Subject: [PATCH 40/68] fix(control): EV room reads battery relief through live telemetry evFuseReliefW read each battery's cached RawW, which survives a driver going offline. It now reads Store.OnlineRawW. A battery with no live reading counts its whole recorded relief, so the car never builds on discharge Core can no longer hold. fuseSaverEarlyExit read each battery's SmoothedW a second time to record relief. It now records against the live snapshot the fuse-saver decision already took (fleetAtLivePower), so it adds no read of its own. Co-Authored-By: Claude Opus 5.5 --- go/internal/control/dispatch.go | 43 +++++++++++-------- .../control/ev_battery_sequence_test.go | 17 ++++++++ go/internal/control/ev_fuse_budget.go | 10 +++-- 3 files changed, 49 insertions(+), 21 deletions(-) diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index ae69f7d2c..4b239c2df 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -4272,20 +4272,14 @@ func fuseSaverEarlyExit( driverCapacities map[string]float64, fuseMaxW float64, ) []DispatchTarget { - out := fuseSaverFromLivePower(store, state, driverCapacities, fuseMaxW) + out, live := fuseSaverAtLivePower(store, state, driverCapacities, fuseMaxW) out = state.stopFullBatteries(out, store, driverCapacities) if out == nil || state == nil { return out } // The early path starts from live power, so relief is discharge below - // what each battery reads now. Without a command the last one stands, - // and so does its relief. - live := make([]DispatchTarget, 0, len(out)) - for _, t := range out { - if r := store.Get(t.Driver, telemetry.DerBattery); r != nil { - live = append(live, DispatchTarget{Driver: t.Driver, TargetW: r.SmoothedW}) - } - } + // the live power the decision read. Without a command the last one + // stands, and so does its relief. state.recordFuseRelief(live, out) state.LastTargets = out now := state.now() @@ -4668,16 +4662,29 @@ func fuseSaverFromLivePower( driverCapacities map[string]float64, fuseMaxW float64, ) []DispatchTarget { + out, _ := fuseSaverAtLivePower(store, state, driverCapacities, fuseMaxW) + return out +} + +// fuseSaverAtLivePower is fuseSaverFromLivePower that also returns the live +// power of each online battery it started from, so the caller records relief +// against the same reading the decision used. +func fuseSaverAtLivePower( + store *telemetry.Store, + state *State, + driverCapacities map[string]float64, + fuseMaxW float64, +) (out, rawLive []DispatchTarget) { if fuseMaxW <= 0 || len(driverCapacities) == 0 || store == nil || state == nil { - return nil + return nil, nil } meter := store.Get(state.SiteMeterDriver, telemetry.DerMeter) if meter == nil { - return nil + return nil, nil } rawLive, safeBaseline, batteryReadings := fleetAtLivePower(store, driverCapacities, state.DriverLimits) if len(rawLive) == 0 { - return nil + return nil, nil } // A command-safe baseline may differ from the live snapshot even when the // site is safe. Preserve the deadband in that case: this early-return path @@ -4685,7 +4692,7 @@ func fuseSaverFromLivePower( // moved battery merely because its reading sits outside a command cap. requiredRelief := fuseReliefFromSnapshot(rawLive, batteryReadings, meter, state, fuseMaxW, false) if requiredRelief <= 0 { - return nil + return nil, nil } _, _, predictedRaw := predictedGridFromSnapshot(rawLive, batteryReadings, meter) maxRelief := predictedRaw + state.effectiveExportCeilingW(fuseMaxW) @@ -4699,9 +4706,9 @@ func fuseSaverFromLivePower( maxRelief, ) if len(safeBaseline) == 0 { - return nil + return nil, nil } - out := forceFuseDischargeWithSnapshot(safeBaseline, batteryReadings, meter, state, driverCapacities, fuseMaxW, true) + out = forceFuseDischargeWithSnapshot(safeBaseline, batteryReadings, meter, state, driverCapacities, fuseMaxW, true) rawByDriver := make(map[string]DispatchTarget, len(rawLive)) for _, t := range rawLive { rawByDriver[t.Driver] = t @@ -4710,12 +4717,12 @@ func fuseSaverFromLivePower( rawTarget, ok := rawByDriver[t.Driver] if !ok || t.TargetW != rawTarget.TargetW || t.Clamped != rawTarget.Clamped { if !fuseSnapshotStillCurrent(store, state, meter.UpdatedAt, batteryReadings, out) { - return nil + return nil, nil } - return out + return out, rawLive } } - return nil + return nil, nil } // fuseReliefFromSnapshot returns the import-side relief required for one diff --git a/go/internal/control/ev_battery_sequence_test.go b/go/internal/control/ev_battery_sequence_test.go index cb65b46e6..b8d8b63d2 100644 --- a/go/internal/control/ev_battery_sequence_test.go +++ b/go/internal/control/ev_battery_sequence_test.go @@ -555,6 +555,23 @@ func TestFuseReliefIsOnlyAddedDischarge(t *testing.T) { } } +// The car's room counts a battery's relief only as far as a live reading +// shows it. An offline battery's cached discharge is no reading: its whole +// relief counts, since Core can no longer hold that discharge. +func TestEVFuseReliefReadsOnlyLiveBatteries(t *testing.T) { + store := telemetry.NewStore() + store.Update("live", telemetry.DerBattery, -500, nil, nil) + store.DriverHealthMut("live").RecordSuccess() + store.Update("offline", telemetry.DerBattery, -500, nil, nil) + store.DriverHealthMut("offline").RecordSuccess() + store.DriverHealthMut("offline").SetOffline() + s := &State{batteryFuseRelief: map[string]float64{"live": 2000, "offline": 2000, "unread": 300}} + // live: min(2000, 500); offline and unread: the whole relief. + if got := s.evFuseReliefW(store); math.Abs(got-(500+2000+300)) > 1e-9 { + t.Fatalf("relief %.0f W, want 2,800 W", got) + } +} + // Only the hour's import limit leaves watts to an EV cut, only those the cut // removes, and only during the first evSettle of the overage it was sent // for. The fuse acts on every reading, on each phase too. diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index 4150ceb0a..34e03b725 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -572,13 +572,17 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea } // evFuseReliefW is the fuse guard's battery relief the meter may show now: -// each battery's recorded relief, at most the discharge it reads. +// each battery's recorded relief, at most the discharge it reads. A battery +// with no live reading (watchdog-offline, or none yet) counts its whole +// relief: Core can no longer hold that discharge, and the car must not +// build on it. func (s *State) evFuseReliefW(store *telemetry.Store) float64 { var w float64 for driver, relief := range s.batteryFuseRelief { - if r := store.Get(driver, telemetry.DerBattery); r != nil && finiteFuseValue(r.RawW) { - w += math.Min(relief, math.Max(0, -r.RawW)) + if raw, _, ok := store.OnlineRawW(driver, telemetry.DerBattery); ok { + relief = math.Min(relief, math.Max(0, -raw)) } + w += relief } return w } From daad277a684b867ffdc5fab06b608b236832c507 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 01:55:05 +0100 Subject: [PATCH 41/68] test(site): only a rise extends a stretch; raises after a step are FTW's Second review of #1920: - A house event that is no fault extends a step's stretch only if the worst phase rose 0.5 A or more within 3 s. Load events that change nothing and the inverter's own return no longer chain the allowance. - The inverter is back at the end of its outage, so at its return the battery is the 2 s lever, not the charger. - A window does not explain a stretch if FTW raised the car after the window's meter delay and before the stretch: FTW's raise after a step or after a Core restart is its own. - A stretch stays open across dips while a phase's heat is over the fuse, so a warm fuse held 3 s over and 1 s under fails. A window that opens after the allowance, with no over second in between, still gives a new step its own time. - Tests pin the export lever, the heat clock for steps and the 60 s restart window. Co-Authored-By: Claude Opus 5.5 --- go/test/site/random_test.go | 106 ++++++++++--- go/test/site/random_unit_test.go | 246 +++++++++++++++++++++++++++++-- 2 files changed, 317 insertions(+), 35 deletions(-) diff --git a/go/test/site/random_test.go b/go/test/site/random_test.go index beab667e1..eded2dd55 100644 --- a/go/test/site/random_test.go +++ b/go/test/site/random_test.go @@ -225,10 +225,22 @@ func within(ws []eventWindow, t, afterS float64) bool { return false } +// during is whether t falls in one of ws, up to but not at its end: at its +// end the device is back. +func during(ws []eventWindow, t float64) bool { + for _, w := range ws { + if t >= w.from && t < w.to { + return true + } + } + return false +} + // stepWindow is a change FTW did not make, and how long FTW may take to // answer it: until from + extraS + its lever's time + 2 s for the meter and // the tick + 3 s. type stepWindow struct { + plain bool // a house event that is no fault: it extends a stretch only if it raised the current from, extraS float64 leverS float64 // > 0: the only lever that can answer (the charger, for a car FTW did not start) untilT float64 // > 0: the window ends here, whatever the lever (a Core restart) @@ -331,6 +343,7 @@ func judgeInvariants(d *runData) (metrics, []criterion) { w.noBattery = true } } + w.plain = until == 0 windows = append(windows, w) } // The battery's floor: the higher of the inverter's own floor and the @@ -387,10 +400,11 @@ func judgeInvariants(d *runData) (metrics, []criterion) { // lever is how long FTW's fastest lever takes, from t, to take overA off // the worst phase: the battery, in 2 s, while its inverter runs and its // spare power covers the overage; otherwise the charger. At its floor - // the battery may only charge less, never discharge more. + // the battery may only charge less, never discharge more. The inverter + // is back at the end of its outage. lever := func(t, overA float64, export bool) float64 { r := d.at(t) - if r == nil || within(inverterOut, t, 0) || (r.Bat.Running != nil && !*r.Bat.Running) { + if r == nil || during(inverterOut, t) || (r.Bat.Running != nil && !*r.Bat.Running) { return chargerLever(t) } spare := rigBatteryMaxW + r.BatW // discharge more, or charge less @@ -424,8 +438,37 @@ func judgeInvariants(d *runData) (metrics, []criterion) { // 1, 2: the fuse holds; over the limit only as long as an outside step // allows, and at most 3 s after FTW's own raise. Between the fuse and // 1.2 x the fuse the 60 s heat is the budget (heatOver): the clock - // starts when the heat passes the fuse, as Core's cut does. + // starts when the heat passes the fuse, as Core's cut does. A stretch + // runs on across dips under the fuse while the heat stays over it. blownAny := anyBlown(run) + // raisedIn is whether FTW sent the car a higher order in (a, b]. + raisedIn := func(a, b float64) bool { + prev, ok := 0.0, false + for _, p := range orders { + if p.T > b { + break + } + if ok && p.T > a && p.offerW() > prev+1 { + return true + } + prev, ok = p.offerW(), true + } + return false + } + // raisedAt is whether the worst phase rose 0.5 A or more in the 3 s + // from t. + raisedAt := func(t float64) bool { + b := d.at(t - 0.5) + if b == nil { + return true + } + for _, r := range d.window(t, t+3) { + if maxAbsI(r) >= maxAbsI(b)+0.5 { + return true + } + } + return false + } unexplained, longestOwn := 0.0, 0.0 var firstBad float64 bad := func(t float64) { @@ -453,9 +496,11 @@ func judgeInvariants(d *runData) (metrics, []criterion) { return // the heat budget covers it } c := clock.T + // A window explains the stretch unless FTW raised the car after + // the window's meter delay and before the stretch began. to, explained, own := math.Inf(-1), false, false for _, w := range windows { - if x := until(w, s, overA, export); w.from <= s && s <= x { + if x := until(w, s, overA, export); w.from <= s && s <= x && !raisedIn(w.from+2, s) { to, explained = math.Max(to, x), true } } @@ -465,14 +510,36 @@ func judgeInvariants(d *runData) (metrics, []criterion) { if !own && c > s { // Core answers once the heat says so to = math.Max(to, c+lever(c, overA, export)+2+3) } - // Every window that opens inside a step's stretch while it is still - // allowed extends it: a second step, an outage or a Core restart. - // FTW's own raise stays its own. - for grown := !own; grown; { + // brokeAt is the first time from t on that the stretch is over the + // fuse; an over sample holds until the next one. + brokeAt := func(t float64) float64 { + for i, r := range stretch { + next := end + if i+1 < len(stretch) { + next = stretch[i+1].T + } + if maxAbsI(r) > fuse && next > t { + return math.Max(r.T, t) + } + } + return math.Inf(1) + } + // A window that opens inside the stretch before it broke its + // allowance extends it: a second step, an outage or a Core restart. + // A plain house event counts only if it raised the current. Inside + // FTW's own raise a window counts only once the raise is answered: + // after its 3 s, with the current under the fuse until the window. + for grown := true; grown; { grown = false for _, w := range windows { - if x := until(w, w.from, overA, export); w.from >= s && w.from <= math.Min(end, to) && x > to { - to, grown = x, true + if w.from < s || w.from > math.Min(end, brokeAt(to)) || (own && w.from <= to) { + continue + } + if w.plain && !raisedAt(w.from) { + continue + } + if x := until(w, w.from, overA, export); x > to { + to, grown, own = x, true, false } } } @@ -491,18 +558,17 @@ func judgeInvariants(d *runData) (metrics, []criterion) { bad(to) } } - from := -1 + from, last := -1, -1 for i, r := range run { - over := maxAbsI(r) > fuse - if over && from < 0 { - from = i - } - if (!over || i == len(run)-1) && from >= 0 { - hi := i - if over { - hi = i + 1 + if maxAbsI(r) > fuse { + if from < 0 { + from = i } - judgeStretch(run[from:hi], r.T) + last = i + } + open := last == i || (from >= 0 && max(r.HeatA[0], r.HeatA[1], r.HeatA[2]) > fuse) + if (!open || i == len(run)-1) && from >= 0 { + judgeStretch(run[from:last+1], run[min(last+1, len(run)-1)].T) from = -1 } } diff --git a/go/test/site/random_unit_test.go b/go/test/site/random_unit_test.go index ea502de39..78df6f046 100644 --- a/go/test/site/random_unit_test.go +++ b/go/test/site/random_unit_test.go @@ -71,6 +71,7 @@ func TestInvariantsExtendAStretchByEveryWindowInsideIt(t *testing.T) { {"restart 1 s into the stretch", 120, true}, {"no restart", 0, false}, {"restart after the step's time", 130, false}, + {"restart 0.2 s after the step's time", 121.9, false}, } { // 20 A fuse; 26 A (1.3 x) from 119 to 143 s, after a load step // at 114.7 s. The battery's 5 kW (7.2 A) covers the 6 A overage, @@ -157,8 +158,8 @@ func TestInvariantsCarStartingOnItsOwnIsAStep(t *testing.T) { // R5, seed 207536: between the fuse and 1.2 x the fuse the 60 s heat is the // budget (owner rule, 27 Oct 2026). 27.84 A on 25 A for 15 s from 15 A // passes; above 1.2 x it fails once the step's time is up; so does the same -// 27.84 A held until the heat passes the fuse, and 25.5 A on a fuse already -// warm at its rating. +// 27.84 A held past the lever's time after the heat passes the fuse, and +// 25.5 A on a fuse already warm at its rating. func TestInvariantsJudgeBetweenFuseAndInstantByHeat(t *testing.T) { for _, c := range []struct { name string @@ -170,6 +171,9 @@ func TestInvariantsJudgeBetweenFuseAndInstantByHeat(t *testing.T) { {"30.1 A for 15 s", 15, 30.1, 50, 65, false}, {"27.84 A for 200 s", 15, 27.84, 50, 250, false}, {"25.5 A for 15 s on a warm fuse", 25, 25.5, 50, 65, false}, + // The heat passes the fuse at 127 s; the battery then has 2 + 5 s. + {"27.84 A until 7 s after the heat passes the fuse", 15, 27.84, 50, 134, true}, + {"27.84 A until 8 s after the heat passes the fuse", 15, 27.84, 50, 135, false}, } { d := randomRun(301, 25, c.base, func(i int, r *sample) { if i >= c.from && i < c.to { @@ -274,7 +278,8 @@ func TestInvariantsFloorJudgesFTWsOrders(t *testing.T) { // An over-limit stretch no outside change explains is FTW's own, whichever // way the current flows and however it is cut up: FTW's discharge pushing // export over the fuse, and a warm fuse held over its rating with a 1 s dip -// every 7 s. Both fail after 3 s. +// every 7 s, or every 4 s. A dip does not end a stretch while the heat stays +// over the fuse. All fail after 3 s. func TestInvariantsAStretchWithNoStepIsFTWsOwn(t *testing.T) { export := randomRun(121, 16, -10, func(i int, r *sample) { w := 0.0 @@ -286,12 +291,15 @@ func TestInvariantsAStretchWithNoStepIsFTWsOwn(t *testing.T) { r.PhaseA = [3]float64{-21, -21, -21} } }) - dips := randomRun(601, 25, 25.5, func(i int, r *sample) { - if i%7 == 6 { - r.PhaseA = [3]float64{24.9, 24.9, 24.9} - } - }) - for name, d := range map[string]*runData{"export 6 s at 1.31 x In": export, "600 s on a warm fuse, with dips": dips} { + dips := func(every int) *runData { + return randomRun(601, 25, 25.5, func(i int, r *sample) { + if i%every == every-1 { + r.PhaseA = [3]float64{24.9, 24.9, 24.9} + } + }) + } + for name, d := range map[string]*runData{"export 6 s at 1.31 x In": export, + "600 s on a warm fuse, a dip every 7 s": dips(7), "600 s on a warm fuse, 3 s over and 1 s under": dips(4)} { withCharger(t, d, 5, 0) if v := judged(d); v[limitOwn] { t.Errorf("%s: %q passed", name, limitOwn) @@ -301,23 +309,35 @@ func TestInvariantsAStretchWithNoStepIsFTWsOwn(t *testing.T) { // A window that opens inside FTW's own raise does not turn it into a step: // FTW raises the car at 45 s and the phases sit at 31 A (1.24 x 25 A) from -// 50 to 60 s; PV rising at 51 s changes nothing. The battery is at its -// floor, so the 40 s charger would be a step's lever. +// 50 to 60 s; PV moving at 51 s changes nothing, and a load step at 51 s +// that adds 1 A comes after FTW's raise broke the line. The battery is at +// its floor, so the 40 s charger would be a step's lever. func TestInvariantsAnEventInsideFTWsRaiseLeavesItOwn(t *testing.T) { - for _, withEvent := range []bool{false, true} { + for _, c := range []struct { + name string + event string // at 51 s; "": none + addA float64 + }{ + {"no event", "", 0}, + {"PV moves", "pv", 0}, + {"a load step adds 1 A", "loads", 1}, + } { d := randomRun(121, 25, 10, func(i int, r *sample) { r.Bat.SoCPct = 6 if i >= 50 && i < 60 { r.PhaseA = [3]float64{31, 31, 31} } + if i >= 51 && i < 60 { + r.PhaseA[0] += c.addA + } }) withCharger(t, d, 40, 0) d.frames = []frame{profileAt(40, 0), profileAt(45, 16)} - if withEvent { - d.events = []houseEventLine{{T: 51, Event: houseEvent{Do: "pv", Device: "inverter"}}} + if c.event != "" { + d.events = []houseEventLine{{T: 51, Event: houseEvent{Do: c.event}}} } if v := judged(d); v[limitOwn] { - t.Errorf("event %v: FTW's raise held 10 s at 1.24 x In and passed", withEvent) + t.Errorf("%s: FTW's raise held 10 s at 1.24 x In and passed", c.name) } } } @@ -413,3 +433,199 @@ func TestRecordedRandomFindsSeedRuns(t *testing.T) { t.Fatalf("recordedRandom = %v", got) } } + +// R2 after the second review of #1920: a house event that is no fault +// extends a step's stretch only if the worst phase rose 0.5 A or more +// within 3 s of it. 16 A fuse, the battery at its floor and a 40 s charger, +// so a step allows 45 s; 20 A on L1 (1.25 x) from 12 s, after a load step +// at 10 s. +func TestInvariantsOnlyARiseExtendsAStretch(t *testing.T) { + for _, c := range []struct { + name string + to int // 20 A on L1 until here + riseAt int // L1 rises to 21 A from here; 0: never + every float64 // a load event that changes nothing, this often; 0: none + want bool + }{ + {"a load event at 50 s raises L1", 80, 50, 0, true}, + {"load events every 40 s change nothing", 290, 0, 40, false}, + } { + d := randomRun(301, 16, 8, func(i int, r *sample) { + r.Bat.SoCPct = 6 + if i >= 12 && i < c.to { + r.PhaseA = [3]float64{20, 12, 12} + if c.riseAt > 0 && i >= c.riseAt { + r.PhaseA[0] = 21 + } + } + }) + withCharger(t, d, 40, 0) + d.events = []houseEventLine{{T: 10, Event: houseEvent{Do: "loads"}}} + if c.riseAt > 0 { + d.events = append(d.events, houseEventLine{T: float64(c.riseAt), Event: houseEvent{Do: "loads"}}) + } + for t0 := 50.0; c.every > 0 && t0 < 290; t0 += c.every { + d.events = append(d.events, houseEventLine{T: t0, Event: houseEvent{Do: "loads"}}) + } + if got := judged(d)[limitStep]; got != c.want { + t.Errorf("%s: %q = %v, want %v", c.name, limitStep, got, c.want) + } + } +} + +// The inverter is back at the end of its outage: its return is no step +// unless the current rises, and then the battery answers in 2 s, not the +// charger. 16 A fuse, a 40 s charger, the inverter out from 10 to 40 s; +// the outage allows until 55 s. +func TestInvariantsTheInverterIsBackAtItsReturn(t *testing.T) { + for _, c := range []struct { + name string + from, to int // 20 A on L1 in [from, to) + }{ + {"over from 12 to 80 s, the return changes nothing", 12, 80}, + {"the current rises at the return, over until 60 s", 40, 60}, + } { + d := randomRun(121, 16, 8, func(i int, r *sample) { + run := !(i >= 10 && i < 40) + r.Bat.Running = &run + if i >= c.from && i < c.to { + r.PhaseA = [3]float64{20, 12, 12} + } + }) + withCharger(t, d, 40, 0) + d.events = []houseEventLine{ + {T: 10, Event: houseEvent{Do: "offline", Device: "inverter", ForS: 30}}, + {T: 40, Event: houseEvent{Do: "online", Device: "inverter"}}, + } + if judged(d)[limitStep] { + t.Errorf("%s: %q passed", c.name, limitStep) + } + } +} + +// R4 after the second review of #1920: a car raise FTW sends after a +// step's meter delay, or after a Core restart, is FTW's own; one sent +// before the meter shows the step is part of the step. 25 A fuse, the +// battery at its floor and a 40 s charger; the phases sit at 31 A +// (1.24 x) from 50 to 80 s. +func TestInvariantsARaiseAfterAStepIsFTWsOwn(t *testing.T) { + for _, c := range []struct { + name string + raiseAt float64 + event bool // PV moves at 40 s + restart bool // Core restarts at 30 s and is back at 35 s + want bool // both limit criteria hold + }{ + {"FTW raises 5 s after PV moved", 45, true, false, false}, + {"FTW raises 1 s after PV moved", 41, true, false, true}, + {"FTW raises 15 s after Core is back", 50, false, true, false}, + } { + d := randomRun(121, 25, 10, func(i int, r *sample) { + r.Bat.SoCPct = 6 + if i >= 50 && i < 80 { + r.PhaseA = [3]float64{31, 31, 31} + r.CarW[0] = 11040 + } + }) + withCharger(t, d, 40, 0) + d.frames = []frame{profileAt(20, 0), profileAt(c.raiseAt, 16)} + if c.event { + d.events = []houseEventLine{{T: 40, Event: houseEvent{Do: "pv", Device: "inverter"}}} + } + if c.restart { + d.allMarks = []markLine{{T: 30, Label: "ftw:restart"}, {T: 35, Label: "ftw:up"}} + } + v := judged(d) + if got := v[limitStep] && v[limitOwn]; got != c.want { + t.Errorf("%s: step %v, own %v; want both %v", c.name, v[limitStep], v[limitOwn], c.want) + } + } +} + +// A Core restart explains a stretch for 60 s from the restart. 16 A fuse, +// Core restarts at 50 s and is back at 55 s; 20 A on L1 (1.25 x). +func TestInvariantsARestartExplainsAMinute(t *testing.T) { + for _, c := range []struct { + name string + from, to int + want bool + }{ + {"over from 100 to 108 s", 100, 108, true}, + {"over from 115 to 125 s", 115, 125, false}, + } { + d := randomRun(201, 16, 8, func(i int, r *sample) { + if i >= c.from && i < c.to { + r.PhaseA = [3]float64{20, 12, 12} + } + }) + withCharger(t, d, 5, 0) + d.allMarks = []markLine{{T: 50, Label: "ftw:restart"}, {T: 55, Label: "ftw:up"}} + v := judged(d) + if got := v[limitStep] && v[limitOwn]; got != c.want { + t.Errorf("%s: step %v, own %v; want both %v", c.name, v[limitStep], v[limitOwn], c.want) + } + } +} + +// For export the battery's spare is what it can charge more: a battery +// charging 4 kW has 1 kW, too little for a 4 A overage, so the 5 s charger +// answers; one discharging 4 kW has 9 kW and answers in 2 s, even at its +// floor. 16 A fuse; -20 A on L1 from 50 to 59 s after a step at 49.5 s. +func TestInvariantsBatteryLeverForExport(t *testing.T) { + for _, c := range []struct { + name string + batW float64 + socPct float64 + want bool + }{ + {"charging 4 kW", 4000, 50, true}, + {"discharging 4 kW", -4000, 50, false}, + {"idle at its floor", 0, 6, false}, + } { + d := randomRun(101, 16, -8, func(i int, r *sample) { + r.BatW, r.Bat.SoCPct = c.batW, c.socPct + if i >= 50 && i < 59 { + r.PhaseA = [3]float64{-20, -12, -12} + } + }) + withCharger(t, d, 5, 0) + d.events = []houseEventLine{{T: 49.5, Event: houseEvent{Do: "pv", Device: "inverter"}}} + if got := judged(d)[limitStep]; got != c.want { + t.Errorf("%s: %q = %v, want %v", c.name, limitStep, got, c.want) + } + } +} + +// A dip under the fuse keeps the stretch open while the heat stays over +// it, but a new step after the dip still gets its own time (2 + 5 s for +// the battery), after a step or after FTW's own raise that was cut in +// time. A step held past its time fails as a step. 16 A fuse at 15.95 A, +// so the heat stays over the fuse for a minute after a few seconds at 20 A +// on L1. +func TestInvariantsAStepAfterADipGetsItsTime(t *testing.T) { + for _, c := range []struct { + name string + first []houseEventLine // the change before 50 s; none: FTW's own + stepTo int // the step at 80 s holds 20 A until here + wantStep, wantOwn bool + }{ + {"after a step", []houseEventLine{{T: 49.5, Event: houseEvent{Do: "loads"}}}, 84, true, true}, + {"after FTW's own raise", nil, 84, true, true}, + {"held 8 s after FTW's own raise", nil, 88, false, true}, + } { + d := randomRun(201, 16, 15.95, func(i int, r *sample) { + if (i >= 50 && i < 53) || (i >= 80 && i < c.stepTo) { + r.PhaseA[0] = 20 + } + }) + withCharger(t, d, 5, 0) + d.events = append(c.first, houseEventLine{T: 80, Event: houseEvent{Do: "loads"}}) + d.warm() + if h := d.at(79).HeatA[0]; h <= 16 { + t.Fatalf("%s: heat %.2f A at 79 s, want over the fuse", c.name, h) + } + if v := judged(d); v[limitStep] != c.wantStep || v[limitOwn] != c.wantOwn { + t.Errorf("%s: step %v, own %v; want %v, %v", c.name, v[limitStep], v[limitOwn], c.wantStep, c.wantOwn) + } + } +} From 4985523a1680be07b4156f4ed94acfb822fdeba5 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 02:19:30 +0100 Subject: [PATCH 42/68] test(site): a raise over the fuse on import is FTW's own The random judge credited FTW's own raises to a step in three shapes from the third review of #1920: - a car raise sent while a step's import stretch was over the fuse passed as part of the step; - a house event that changed nothing, opening as that raise landed, took the rise and gave the stretch a fresh lever time; - a battery charge raise after a Core restart or a step's meter delay was never counted (triage C2), so the restart window excused it. For import, a window no longer explains a stretch when FTW raised the battery's charge after the window's meter delay and before the stretch, or raised the car or the battery while the stretch was over the fuse. A raise in a dip under the fuse still counts as allowed, a battery order moved while the inverter is off reaches no battery, and raising the car into export stays the right answer. The 10 recorded seeds keep every verdict and allowance. Co-Authored-By: Claude Opus 5.5 --- go/test/site/random_test.go | 40 +++++++++-- go/test/site/random_unit_test.go | 120 +++++++++++++++++++++++++++++++ 2 files changed, 155 insertions(+), 5 deletions(-) diff --git a/go/test/site/random_test.go b/go/test/site/random_test.go index eded2dd55..fee2fee33 100644 --- a/go/test/site/random_test.go +++ b/go/test/site/random_test.go @@ -441,20 +441,48 @@ func judgeInvariants(d *runData) (metrics, []criterion) { // starts when the heat passes the fuse, as Core's cut does. A stretch // runs on across dips under the fuse while the heat stays over it. blownAny := anyBlown(run) - // raisedIn is whether FTW sent the car a higher order in (a, b]. - raisedIn := func(a, b float64) bool { + // raisedIn is whether FTW sent the car a higher order in (a, b]; with + // over, only one sent while the meter showed the fuse passed. + raisedIn := func(a, b float64, over bool) bool { prev, ok := 0.0, false for _, p := range orders { if p.T > b { break } - if ok && p.T > a && p.offerW() > prev+1 { + if ok && p.T > a && p.offerW() > prev+1 && (!over || maxAbsI(d.at(p.T)) > fuse) { return true } prev, ok = p.offerW(), true } return false } + // batRaisedIn is the same for the battery: FTW moved its order more + // than 100 W toward import while the inverter ran. An order moved + // while the inverter is out reaches no battery. No order counts as 0. + batRaisedIn := func(a, b float64, over bool) bool { + prev, ok := 0.0, false + for _, r := range d.samples { + if r.T < a-5 { + continue + } + if r.T > b { + break + } + w, has := dispatchW(r) + running := !during(inverterOut, r.T) && (r.Bat.Running == nil || *r.Bat.Running) + if ok && has && r.T > a && w > prev+100 && running && (!over || maxAbsI(r) > fuse) { + return true + } + prev, ok = w, true + } + return false + } + // ownImport is whether FTW raised the battery's charge in (a, s], or + // raised the car or the battery while an import stretch from s to end + // was over the fuse. Raising the car into export is the right answer. + ownImport := func(a, s, end float64) bool { + return batRaisedIn(a, s, false) || raisedIn(s, end, true) || batRaisedIn(s, end, true) + } // raisedAt is whether the worst phase rose 0.5 A or more in the 3 s // from t. raisedAt := func(t float64) bool { @@ -497,10 +525,12 @@ func judgeInvariants(d *runData) (metrics, []criterion) { } c := clock.T // A window explains the stretch unless FTW raised the car after - // the window's meter delay and before the stretch began. + // the window's meter delay and before the stretch began. For + // import, a battery raise there, or a raise of either while the + // stretch is over the fuse, makes it FTW's own too. to, explained, own := math.Inf(-1), false, false for _, w := range windows { - if x := until(w, s, overA, export); w.from <= s && s <= x && !raisedIn(w.from+2, s) { + if x := until(w, s, overA, export); w.from <= s && s <= x && !raisedIn(w.from+2, s, false) && (export || !ownImport(w.from+2, s, end)) { to, explained = math.Max(to, x), true } } diff --git a/go/test/site/random_unit_test.go b/go/test/site/random_unit_test.go index 78df6f046..53ea30ff4 100644 --- a/go/test/site/random_unit_test.go +++ b/go/test/site/random_unit_test.go @@ -629,3 +629,123 @@ func TestInvariantsAStepAfterADipGetsItsTime(t *testing.T) { } } } + +// R4 after the third review of #1920: a car or battery raise FTW sends +// while an import stretch is over the fuse is FTW's own, after a step's +// meter delay too, and a house event that changes nothing does not take +// the rise from it. One sent in a dip under the fuse, with the heat still +// over it, is allowed: the step after it gets its time. Raising the car +// into export is the right answer. 40 s charger, the battery at its +// floor. +func TestInvariantsARaiseOverTheFuseIsFTWsOwn(t *testing.T) { + for _, c := range []struct { + name string + fuse float64 + set func(i int, r *sample) + frames []frame + events []houseEventLine + want bool // both limit criteria hold + }{ + {"0 -> 16 A at 1.24 x In after PV moved", 25, func(i int, r *sample) { + if i >= 41 && i < 84 { + r.PhaseA = [3]float64{31, 31, 31} + } + if i >= 52 && i < 84 { + r.PhaseA = [3]float64{42, 42, 42} + } + }, []frame{profileAt(20, 0), profileAt(50, 16)}, + []houseEventLine{{T: 40, Event: houseEvent{Do: "pv", Device: "inverter"}}}, false}, + {"6 -> 10 A at 1.25 x In, a load event that changes nothing as it lands", 16, func(i int, r *sample) { + if i >= 11 && i < 75 { + r.PhaseA = [3]float64{20, 12, 12} + } + if i >= 32 && i < 75 { + r.PhaseA[0] = 22 + } + }, []frame{profileAt(1, 6), profileAt(30, 10)}, + []houseEventLine{{T: 10, Event: houseEvent{Do: "loads"}}, {T: 31, Event: houseEvent{Do: "loads"}}}, false}, + {"battery charge 0 -> 3 kW at 1.25 x In after a load step", 16, func(i int, r *sample) { + r.Status = &ftwStatus{Dispatch: []ftwDispatch{{Driver: "sungrow", TargetW: 0}}} + if i >= 30 { + r.Status.Dispatch[0].TargetW, r.BatW = 3000, 3000 + } + if i >= 11 && i < 55 { + r.PhaseA = [3]float64{20, 12, 12} + } + if i >= 32 && i < 55 { + r.PhaseA = [3]float64{22, 16, 16} + } + }, nil, []houseEventLine{{T: 10, Event: houseEvent{Do: "loads"}}}, false}, + {"car and battery raised in a dip under the fuse, a step after it", 16, func(i int, r *sample) { + r.Status = &ftwStatus{Dispatch: []ftwDispatch{{Driver: "sungrow", TargetW: 0}}} + if i >= 56 { + r.Status.Dispatch[0].TargetW = 2000 + } + switch { + case i >= 11 && i < 45, i >= 71 && i < 76: + r.PhaseA = [3]float64{22, 12, 12} + case i >= 45 && i < 71: + r.PhaseA = [3]float64{15, 12, 12} + } + }, []frame{profileAt(1, 6), profileAt(55, 8)}, + []houseEventLine{{T: 10, Event: houseEvent{Do: "loads"}}, {T: 70, Event: houseEvent{Do: "loads"}}}, true}, + {"0 -> 16 A into export over the fuse after PV moved", 16, func(i int, r *sample) { + r.PhaseA, r.BatW = [3]float64{-8, -8, -8}, 4000 + if i >= 11 && i < 45 { + r.PhaseA = [3]float64{-24, -12, -12} + } + }, []frame{profileAt(1, 0), profileAt(20, 16)}, + []houseEventLine{{T: 10, Event: houseEvent{Do: "pv", Device: "inverter"}}}, true}, + } { + d := randomRun(121, c.fuse, 12, func(i int, r *sample) { + r.Bat.SoCPct = 6 + c.set(i, r) + }) + withCharger(t, d, 40, 0) + d.frames, d.events = c.frames, c.events + v := judged(d) + if got := v[limitStep] && v[limitOwn]; got != c.want { + t.Errorf("%s: step %v, own %v; want both %v", c.name, v[limitStep], v[limitOwn], c.want) + } + } +} + +// R4 for the battery: a charge raise FTW sends after a Core restart is +// its own, as a car raise is (triage C2). An order moved while the +// inverter is off reaches no battery. 16 A fuse, Core restarts at 50 s +// and is back at 55 s; the order goes 0 -> 4 kW at 60 s; 21 A on L1 +// (1.31 x) from 61 to 105 s. +func TestInvariantsABatteryRaiseAfterARestartIsFTWsOwn(t *testing.T) { + for _, c := range []struct { + name string + running bool // the inverter runs from 55 to 70 s + want bool + }{ + {"the inverter runs", true, false}, + {"the inverter is off", false, true}, + } { + d := randomRun(201, 16, 8, func(i int, r *sample) { + w := 0.0 + if i >= 60 { + w = 4000 + } + r.Status = &ftwStatus{Dispatch: []ftwDispatch{{Driver: "sungrow", TargetW: w}}} + if i >= 55 && i < 70 { + run := c.running + r.Bat.Running = &run + } + if i >= 61 && c.running { + r.BatW = w + } + if i >= 61 && i < 105 { + r.PhaseA = [3]float64{21, 13, 13} + } + }) + withCharger(t, d, 5, 0) + d.allMarks = []markLine{{T: 50, Label: "ftw:restart"}, {T: 55, Label: "ftw:up"}} + v := judged(d) + if got := v[limitStep] && v[limitOwn]; got != c.want { + t.Errorf("%s: step %v, own %v; want both %v", c.name, v[limitStep], v[limitOwn], c.want) + } + } +} From 8150b45b75bba3241ad3bd0756c83c143f758d7f Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 02:20:05 +0100 Subject: [PATCH 43/68] fix(control): an offline battery's fuse relief ends after evSettle With no battery online, ComputeDispatch returns before it records relief, so batteryFuseRelief kept its last value and evFuseReliefW counted all of it for as long as the battery stayed offline. The car was held up to the whole relief below the line. The relief now counts in full until the default mode Core sent at the transition can have reached the meter (evSettle), then ends. Co-Authored-By: Claude Opus 5.5 --- .changeset/b-ev-fuse-line-at-rating.md | 2 +- go/internal/control/dispatch.go | 5 ++ .../control/ev_battery_sequence_test.go | 47 ++++++++++++++++++- go/internal/control/ev_fuse_budget.go | 19 +++++++- 4 files changed, 70 insertions(+), 3 deletions(-) diff --git a/.changeset/b-ev-fuse-line-at-rating.md b/.changeset/b-ev-fuse-line-at-rating.md index f28801459..a3ca2c991 100644 --- a/.changeset/b-ev-fuse-line-at-rating.md +++ b/.changeset/b-ev-fuse-line-at-rating.md @@ -2,4 +2,4 @@ "ftw": patch --- -The car now charges up to the fuse rating less `fuse.safety_margin_a`, not a fixed 1 A below it. A charging car rises one step once that step fits under the line, instead of needing two steps of room and keeping one free; an idle car starts with all the room it has. Home battery charge beside a car uses the same line, with no 1 A floor. On a three-phase site with the default 0.5 A margin, a car near the fuse gets 0.5 A to 1.5 A more on each phase. Cuts above the line still wait for the fuse's heat budget, and the hour's import limit keeps its own margins. A car never rises or starts into battery discharge that the fuse guard added. +The car now charges up to the fuse rating less `fuse.safety_margin_a`, not a fixed 1 A below it. A charging car rises one step once that step fits under the line, instead of needing two steps of room and keeping one free; an idle car starts with all the room it has. Home battery charge beside a car uses the same line, with no 1 A floor. On a three-phase site with the default 0.5 A margin, a car near the fuse gets 0.5 A to 1.5 A more on each phase. Cuts above the line still wait for the fuse's heat budget, and the hour's import limit keeps its own margins. A car never rises or starts into battery discharge that the fuse guard added. When no battery is online, that discharge counts for 20 s, the time Core gives the battery's default mode to reach the meter, and then stops holding the car back. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 4b239c2df..f25d26b76 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -403,6 +403,9 @@ type State struct { // the site fits without it, so an EV rise or start never counts it as // room (evFuseReliefW). batteryFuseRelief map[string]float64 + // batteriesOfflineSince is when dispatch first found no battery online + // (expireOfflineFuseRelief). + batteriesOfflineSince time.Time // PI controller (outer, site-level) PI *PIController @@ -1540,10 +1543,12 @@ func ComputeDispatch( } } if len(onlineBats) == 0 { + state.expireOfflineFuseRelief() publishBatterylessEVFuseBudget(store, state, fuseMaxW) state.LastTargets = nil return nil } + state.batteriesOfflineSince = time.Time{} // Planner slots that are idle/charge-only must not leave an individual // battery discharging just because slew anchored from a negative live // reading. Plain self_consumption remains the classic grid-zero mode: diff --git a/go/internal/control/ev_battery_sequence_test.go b/go/internal/control/ev_battery_sequence_test.go index b8d8b63d2..6fa5b6eb7 100644 --- a/go/internal/control/ev_battery_sequence_test.go +++ b/go/internal/control/ev_battery_sequence_test.go @@ -183,6 +183,7 @@ type evBatterySite struct { batteryDelay time.Duration // 0: the battery follows within a tick batteryCommands []evTimed meterW, targetW []evTimed // every site reading and battery target + batteryOffline bool // the battery reports nothing and gets no target } func newEVBatterySite(t *testing.T, houseW float64) *evBatterySite { @@ -259,7 +260,9 @@ func (s *evBatterySite) step() { } s.maxGridW = math.Max(s.maxGridW, s.gridW()) s.meterW = append(s.meterW, evTimed{s.now, s.gridW()}) - s.emit("pixii", telemetry.DerBattery, s.batteryW) + if !s.batteryOffline { + s.emit("pixii", telemetry.DerBattery, s.batteryW) + } s.emit("charger", telemetry.DerEV, s.evW) s.emit("meter", telemetry.DerMeter, s.gridW()) s.state.ObserveSiteImport(s.store) @@ -267,6 +270,12 @@ func (s *evBatterySite) step() { s.state.SetEVCommanded(s.mgr.States()) s.state.SetEVFuseDemands(s.ctrl.FuseDemands()) targets := ComputeDispatch(s.store, s.state, caps(map[string]float64{"pixii": 15000}), 17250) + if s.batteryOffline { + if len(targets) != 0 { + s.t.Fatalf("offline battery got targets %+v", targets) + } + return + } if len(targets) != 1 { s.t.Fatalf("targets %+v", targets) } @@ -536,6 +545,42 @@ func TestFuseOverageGetsBatteryReliefUntilEVCutShows(t *testing.T) { } } +// The only battery goes offline in the middle of fuse relief and drops to +// 0 W; then the house load falls. Its relief counts whole until the default +// mode Core sent it can have reached the meter, and then it ends: the car +// gets back up to the 24 A line instead of being held below it for as long +// as the battery stays offline. +func TestOfflineBatteryReliefEndsAfterSettle(t *testing.T) { + s := newIdleBatteryEVSite(t, 3000, 0) + s.run(5 * time.Minute) + stepAt := s.now + s.houseW += 8000 + s.run(3 * time.Second) + reliefW := -s.batteryW + if reliefW <= 0 || s.state.batteryFuseRelief["pixii"] <= 0 { + t.Fatalf("setup: battery %.0f W relief %v", s.batteryW, s.state.batteryFuseRelief) + } + s.store.DriverHealthMut("pixii").SetOffline() + s.batteryOffline, s.batteryW = true, 0 + offlineAt := s.now + for s.now.Sub(offlineAt) < evSettle-time.Second { + s.step() + if got := s.state.evFuseReliefW(s.store); math.Abs(got-reliefW) > 1e-6 { + t.Fatalf("%v after offline: relief %.0f W, want the whole %.0f W", s.now.Sub(offlineAt), got, reliefW) + } + } + s.run(time.Minute - s.now.Sub(stepAt)) + s.houseW -= 4000 // 7,000 W of house. + s.run(9 * time.Minute) + t.Logf("offer %.0f W, %.2f A on each phase, relief %v", s.offer(), s.gridW()/690, s.state.batteryFuseRelief) + if got := s.state.evFuseReliefW(s.store); got != 0 { + t.Fatalf("relief %.0f W still counted %v after offline", got, s.now.Sub(offlineAt)) + } + if s.offer() != 8970 || s.gridW()/690 > 24+1e-6 { + t.Fatalf("offer %.0f W at %.2f A, want 8,970 W: 13 A beside 10.1 A of house under the 24 A line", s.offer(), s.gridW()/690) + } +} + // Relief is only the discharge the fuse guard added: a cancelled charge or // the planner's own discharge stays room for the car. func TestFuseReliefIsOnlyAddedDischarge(t *testing.T) { diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index 34e03b725..56a73a4ee 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -575,7 +575,7 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea // each battery's recorded relief, at most the discharge it reads. A battery // with no live reading (watchdog-offline, or none yet) counts its whole // relief: Core can no longer hold that discharge, and the car must not -// build on it. +// build on it. expireOfflineFuseRelief ends it once no battery is online. func (s *State) evFuseReliefW(store *telemetry.Store) float64 { var w float64 for driver, relief := range s.batteryFuseRelief { @@ -587,6 +587,23 @@ func (s *State) evFuseReliefW(store *telemetry.Store) float64 { return w } +// expireOfflineFuseRelief ends the recorded relief evSettle after dispatch +// first finds no battery online. Core sent each battery its default mode +// then, and that command reaches the meter within evSettle, as ours do. +// Until then the car must not build on a discharge that may still stand; +// after it, holding the car below the line for relief Core no longer +// orders would be a hidden margin. With a battery online, every recorded +// dispatch rewrites the relief and drops the offline batteries. +func (s *State) expireOfflineFuseRelief() { + now := s.now() + if s.batteriesOfflineSince.IsZero() { + s.batteriesOfflineSince = now + } + if now.Sub(s.batteriesOfflineSince) >= evSettle { + s.batteryFuseRelief = nil + } +} + // wholeStepsW rounds w down to whole charger amps on the pool's phases, one // step each. Chargers round an offer to the nearest amp, so a cap at the // line's exact room could land half an amp over it. This is step From 652df2cbca05eb4778281e6a58d346b8706eba37 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 02:36:32 +0100 Subject: [PATCH 44/68] test(site): judge FTW's battery orders as the inverter sees them Fourth review of #1920 (4985523a): - A missing status.dispatch (Core down, or before its first tick) keeps the last order, as the inverter does, instead of reading as 0 W. A charge order restored after a restart is no raise. - A battery move counts from 0.5 A a phase (345 W), as raisedAt does, so a one-sample closed-loop wobble is no raise. - A car raise before a stretch makes it FTW's own only on import. - On export, a battery order moved toward export after a window's meter delay, or while the stretch is over the fuse, makes the stretch FTW's own, so a Core restart no longer excuses it. Co-Authored-By: Claude Opus 5.5 --- go/test/site/random_test.go | 39 +++--- go/test/site/random_unit_test.go | 215 +++++++++++++++++++++++++++++++ 2 files changed, 239 insertions(+), 15 deletions(-) diff --git a/go/test/site/random_test.go b/go/test/site/random_test.go index fee2fee33..7cfc0aed1 100644 --- a/go/test/site/random_test.go +++ b/go/test/site/random_test.go @@ -456,10 +456,12 @@ func judgeInvariants(d *runData) (metrics, []criterion) { } return false } - // batRaisedIn is the same for the battery: FTW moved its order more - // than 100 W toward import while the inverter ran. An order moved - // while the inverter is out reaches no battery. No order counts as 0. - batRaisedIn := func(a, b float64, over bool) bool { + // batMovedIn is the same for the battery: FTW moved its order 0.5 A a + // phase or more toward import (dir +1) or export (dir -1) while the + // inverter ran. An order moved while the inverter is out reaches no + // battery. While Core is down or has no order yet the inverter keeps + // the last one, so a missing order keeps it too. + batMovedIn := func(a, b float64, over bool, dir float64) bool { prev, ok := 0.0, false for _, r := range d.samples { if r.T < a-5 { @@ -469,19 +471,28 @@ func judgeInvariants(d *runData) (metrics, []criterion) { break } w, has := dispatchW(r) + if !has && ok { + continue + } running := !during(inverterOut, r.T) && (r.Bat.Running == nil || *r.Bat.Running) - if ok && has && r.T > a && w > prev+100 && running && (!over || maxAbsI(r) > fuse) { + if ok && has && r.T > a && dir*(w-prev) >= 0.5*3*volt && running && (!over || maxAbsI(r) > fuse) { return true } prev, ok = w, true } return false } - // ownImport is whether FTW raised the battery's charge in (a, s], or - // raised the car or the battery while an import stretch from s to end - // was over the fuse. Raising the car into export is the right answer. - ownImport := func(a, s, end float64) bool { - return batRaisedIn(a, s, false) || raisedIn(s, end, true) || batRaisedIn(s, end, true) + // ownRaise is whether FTW pushed a stretch from s to end over the fuse + // itself: it moved the battery toward the stretch's direction in + // (a, s], or moved it, or raised the car on import, while the stretch + // was over the fuse. On import a car raise in (a, s] counts too. On + // export, raising the car is the right answer. + ownRaise := func(a, s, end float64, export bool) bool { + if export { + return batMovedIn(a, s, false, -1) || batMovedIn(s, end, true, -1) + } + return raisedIn(a, s, false) || batMovedIn(a, s, false, 1) || + raisedIn(s, end, true) || batMovedIn(s, end, true, 1) } // raisedAt is whether the worst phase rose 0.5 A or more in the 3 s // from t. @@ -524,13 +535,11 @@ func judgeInvariants(d *runData) (metrics, []criterion) { return // the heat budget covers it } c := clock.T - // A window explains the stretch unless FTW raised the car after - // the window's meter delay and before the stretch began. For - // import, a battery raise there, or a raise of either while the - // stretch is over the fuse, makes it FTW's own too. + // A window explains the stretch unless FTW pushed it over the + // fuse after the window's meter delay (ownRaise). to, explained, own := math.Inf(-1), false, false for _, w := range windows { - if x := until(w, s, overA, export); w.from <= s && s <= x && !raisedIn(w.from+2, s, false) && (export || !ownImport(w.from+2, s, end)) { + if x := until(w, s, overA, export); w.from <= s && s <= x && !ownRaise(w.from+2, s, end, export) { to, explained = math.Max(to, x), true } } diff --git a/go/test/site/random_unit_test.go b/go/test/site/random_unit_test.go index 53ea30ff4..72626ed23 100644 --- a/go/test/site/random_unit_test.go +++ b/go/test/site/random_unit_test.go @@ -749,3 +749,218 @@ func TestInvariantsABatteryRaiseAfterARestartIsFTWsOwn(t *testing.T) { } } } + +// Fourth review of #1920: what FTW's battery order did, read correctly. +// While Core is down, or before its first tick, status has no dispatch, +// but the inverter keeps the last order: a missing order is no move. A +// move counts from 0.5 A a phase (345 W), as raisedAt does, so a one- +// sample 158 W wobble of Core's closed loop (seed 207539 at 151.7 s) is +// no raise. 16 A fuse, a load step at 40 s puts 20 A on L1. +func TestInvariantsABatteryOrderMovesOnlyWhenFTWMovesIt(t *testing.T) { + order := func(r *sample, w float64) { + r.Status = &ftwStatus{Dispatch: []ftwDispatch{{Driver: "sungrow", TargetW: w}}} + } + for _, c := range []struct { + name string + set func(i int, r *sample) + down bool // Core restarts at 44 s and is back at 49 s + want bool // both limit criteria hold + }{ + // At 6 % SoC the battery charging 1 kW cannot take 4 A a phase + // off, so the charger is the lever; Core's restart extends the + // stretch to 104 s. + {"1 kW order kept while Core is down", func(i int, r *sample) { + r.BatW, r.Bat.SoCPct = 1000, 6 + order(r, 1000) + if i >= 41 && i < 80 { + r.PhaseA = [3]float64{20, 8, 8} + } + }, true, true}, + {"1 kW order missing while Core is down, then restored", func(i int, r *sample) { + r.BatW, r.Bat.SoCPct = 1000, 6 + if i < 44 || i >= 50 { + order(r, 1000) + } + if i >= 41 && i < 80 { + r.PhaseA = [3]float64{20, 8, 8} + } + }, true, true}, + {"0 W order missing while Core is down, then 1 kW", func(i int, r *sample) { + r.Bat.SoCPct = 6 + switch { + case i < 44: + order(r, 0) + case i >= 50: + order(r, 1000) + r.BatW = 1000 + } + if i >= 41 && i < 80 { + r.PhaseA = [3]float64{20, 8, 8} + } + }, true, false}, + // The battery discharges 4 999 W and answers in 2 s: allowed + // until 47 s. + {"steady discharge order", func(i int, r *sample) { + r.BatW = -4999 + order(r, -4999) + if i >= 41 && i < 46 { + r.PhaseA = [3]float64{20, 8, 8} + } + }, false, true}, + {"one 158 W wobble toward import", func(i int, r *sample) { + r.BatW = -4999 + order(r, -4999) + if i == 43 { + order(r, -4841) + } + if i >= 41 && i < 46 { + r.PhaseA = [3]float64{20, 8, 8} + } + }, false, true}, + {"one 360 W move toward import", func(i int, r *sample) { + r.BatW = -4999 + order(r, -4999) + if i == 43 { + order(r, -4639) + } + if i >= 41 && i < 46 { + r.PhaseA = [3]float64{20, 8, 8} + } + }, false, false}, + } { + d := randomRun(121, 16, 8, c.set) + withCharger(t, d, 40, 0) + d.events = []houseEventLine{{T: 40, Event: houseEvent{Do: "loads"}}} + if c.down { + d.allMarks = []markLine{{T: 44, Label: "ftw:restart"}, {T: 49, Label: "ftw:up"}} + } + m, _ := judgeInvariants(d) + v := judged(d) + if got := v[limitStep] && v[limitOwn]; got != c.want { + t.Errorf("%s: step %v, own %v; want both %v; judged %v", c.name, v[limitStep], v[limitOwn], c.want, m["over_limit_judged"]) + } + } +} + +// Export is judged by what pushes export. A car raise before an export +// stretch soaks it up, so the stretch keeps its step's time. A battery +// pushed toward export after a Core restart is FTW's own push: the +// restart's minute does not excuse it. +func TestInvariantsExportIsFTWsOwnOnlyWhenFTWPushedExport(t *testing.T) { + t.Run("car raise before an export stretch", func(t *testing.T) { + off := false + d := randomRun(121, 16, 0, func(i int, r *sample) { + r.Bat.Running = &off + if i >= 45 && i < 80 { + r.PhaseA = [3]float64{-20, -20, -20} + } + }) + withCharger(t, d, 40, 0) + d.frames = []frame{profileAt(20, 0), profileAt(43, 16)} + d.events = []houseEventLine{{T: 40, Event: houseEvent{Do: "pv", Device: "inverter"}}} + m, _ := judgeInvariants(d) + if v := judged(d); !(v[limitStep] && v[limitOwn]) { + t.Errorf("step %v, own %v; judged %v", v[limitStep], v[limitOwn], m["over_limit_judged"]) + } + }) + for _, c := range []struct { + name string + running bool // the inverter runs from 55 s + want bool + }{ + {"battery pushed 0 -> -5 kW after a restart", true, false}, + {"the same order with the inverter off", false, true}, + } { + t.Run(c.name, func(t *testing.T) { + d := randomRun(201, 16, 0, func(i int, r *sample) { + w := 0.0 + if i >= 57 { + w = -5000 + } + r.Status = &ftwStatus{Dispatch: []ftwDispatch{{Driver: "sungrow", TargetW: w}}} + if i >= 55 && !c.running { + run := false + r.Bat.Running = &run + } + if i >= 58 && c.running { + r.BatW = w + } + if i >= 58 && i < 100 { + r.PhaseA = [3]float64{-21, -10, -10} + } + }) + withCharger(t, d, 5, 0) + d.allMarks = []markLine{{T: 50, Label: "ftw:restart"}, {T: 55, Label: "ftw:up"}} + m, _ := judgeInvariants(d) + v := judged(d) + if got := v[limitStep] && v[limitOwn]; got != c.want { + t.Errorf("step %v, own %v; want both %v; judged %v", v[limitStep], v[limitOwn], c.want, m["over_limit_judged"]) + } + }) + } + // Inside an export stretch after a PV step. The battery charges at + // its maximum, so the 40 s charger is the lever. Moving its order + // toward export while the meter is over the fuse is FTW's own; the + // same move in a dip under the fuse, with a step after it, is not. + for _, c := range []struct { + name string + moveAt int // the order goes 5 -> 4 kW; 0: no move + dip bool + want bool + }{ + {"no move", 0, false, true}, + {"battery moved toward export over the fuse", 20, false, false}, + {"the same move in a dip, a step after it", 56, true, true}, + } { + t.Run(c.name, func(t *testing.T) { + d := randomRun(121, 16, -12, func(i int, r *sample) { + r.BatW = rigBatteryMaxW + w := rigBatteryMaxW + if c.moveAt > 0 && i >= c.moveAt { + w = 4000 + } + r.Status = &ftwStatus{Dispatch: []ftwDispatch{{Driver: "sungrow", TargetW: w}}} + switch { + case !c.dip && i >= 11 && i < 45: + r.PhaseA = [3]float64{-22, -12, -12} + case c.dip && (i >= 11 && i < 45 || i >= 71 && i < 76): + r.PhaseA = [3]float64{-22, -12, -12} + case c.dip && i >= 45 && i < 71: + r.PhaseA = [3]float64{-15, -12, -12} + } + }) + withCharger(t, d, 40, 0) + d.events = []houseEventLine{{T: 10, Event: houseEvent{Do: "pv", Device: "inverter"}}} + if c.dip { + d.events = append(d.events, houseEventLine{T: 70, Event: houseEvent{Do: "pv", Device: "inverter"}}) + } + m, _ := judgeInvariants(d) + v := judged(d) + if got := v[limitStep] && v[limitOwn]; got != c.want { + t.Errorf("step %v, own %v; want both %v; judged %v", v[limitStep], v[limitOwn], c.want, m["over_limit_judged"]) + } + }) + } +} + +// The line is In, not 1.2 x In: a car raise sent while the meter shows +// 1.1 x In (under the instant cut, the heat still cool) is sent over the +// line, and the stretch is FTW's own. +func TestInvariantsARaiseBetweenFuseAndInstantIsOwn(t *testing.T) { + d := randomRun(121, 25, 12, func(i int, r *sample) { + r.Bat.SoCPct = 6 + if i >= 41 && i < 84 { + r.PhaseA = [3]float64{27.5, 27.5, 27.5} + } + if i >= 52 && i < 84 { + r.PhaseA = [3]float64{42, 42, 42} + } + }) + withCharger(t, d, 40, 0) + d.frames = []frame{profileAt(20, 0), profileAt(50, 16)} + d.events = []houseEventLine{{T: 40, Event: houseEvent{Do: "pv", Device: "inverter"}}} + m, _ := judgeInvariants(d) + if v := judged(d); v[limitStep] && v[limitOwn] { + t.Errorf("a raise sent at 1.1 x In passed; judged %v", m["over_limit_judged"]) + } +} From ddab1229d172b64daf4825257f79a4fdfdc23628 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 02:38:45 +0100 Subject: [PATCH 45/68] fix(control): each offline battery's fuse relief ends after evSettle The expiry in 8150b45b ran only when no battery was online. With a second battery online, an offline battery's relief stayed until a recorded dispatch rewrote the map: never while the legacy modes sat in the deadband, and on the first tick when one did record, so the car could rise onto discharge Core ordered a second earlier. Each offline battery now has its own clock: its relief counts whole for evSettle and then ends, on every dispatch path. A battery back online leaves the clock, so its next offline period counts whole again; a test now covers that reset. Co-Authored-By: Claude Opus 5.5 --- .changeset/b-ev-fuse-line-at-rating.md | 2 +- go/internal/control/dispatch.go | 18 ++-- .../control/ev_battery_sequence_test.go | 89 +++++++++++++++++++ go/internal/control/ev_fuse_budget.go | 50 ++++++++--- 4 files changed, 138 insertions(+), 21 deletions(-) diff --git a/.changeset/b-ev-fuse-line-at-rating.md b/.changeset/b-ev-fuse-line-at-rating.md index a3ca2c991..71934e1cb 100644 --- a/.changeset/b-ev-fuse-line-at-rating.md +++ b/.changeset/b-ev-fuse-line-at-rating.md @@ -2,4 +2,4 @@ "ftw": patch --- -The car now charges up to the fuse rating less `fuse.safety_margin_a`, not a fixed 1 A below it. A charging car rises one step once that step fits under the line, instead of needing two steps of room and keeping one free; an idle car starts with all the room it has. Home battery charge beside a car uses the same line, with no 1 A floor. On a three-phase site with the default 0.5 A margin, a car near the fuse gets 0.5 A to 1.5 A more on each phase. Cuts above the line still wait for the fuse's heat budget, and the hour's import limit keeps its own margins. A car never rises or starts into battery discharge that the fuse guard added. When no battery is online, that discharge counts for 20 s, the time Core gives the battery's default mode to reach the meter, and then stops holding the car back. +The car now charges up to the fuse rating less `fuse.safety_margin_a`, not a fixed 1 A below it. A charging car rises one step once that step fits under the line, instead of needing two steps of room and keeping one free; an idle car starts with all the room it has. Home battery charge beside a car uses the same line, with no 1 A floor. On a three-phase site with the default 0.5 A margin, a car near the fuse gets 0.5 A to 1.5 A more on each phase. Cuts above the line still wait for the fuse's heat budget, and the hour's import limit keeps its own margins. A car never rises or starts into battery discharge that the fuse guard added. When a battery goes offline, its share of that discharge counts for 20 s, the time Core gives the battery's default mode to reach the meter, and then stops holding the car back, whether or not another battery is online. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index f25d26b76..b5451e62c 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -403,9 +403,9 @@ type State struct { // the site fits without it, so an EV rise or start never counts it as // room (evFuseReliefW). batteryFuseRelief map[string]float64 - // batteriesOfflineSince is when dispatch first found no battery online - // (expireOfflineFuseRelief). - batteriesOfflineSince time.Time + // batteriesOfflineSince is, per battery whose relief still counts, + // when dispatch first found it offline (expireOfflineFuseRelief). + batteriesOfflineSince map[string]time.Time // PI controller (outer, site-level) PI *PIController @@ -1542,13 +1542,12 @@ func ComputeDispatch( onlineBats = append(onlineBats, b) } } + state.expireOfflineFuseRelief(onlineBats) if len(onlineBats) == 0 { - state.expireOfflineFuseRelief() publishBatterylessEVFuseBudget(store, state, fuseMaxW) state.LastTargets = nil return nil } - state.batteriesOfflineSince = time.Time{} // Planner slots that are idle/charge-only must not leave an individual // battery discharging just because slew anchored from a negative live // reading. Plain self_consumption remains the classic grid-zero mode: @@ -2445,7 +2444,9 @@ func applyDispatchSafetyPipeline( // recordFuseRelief keeps, per battery, the discharge in the final command // that the fuse guard added: below both the command before forceFuseDischarge -// and 0 W. Planner or operator discharge is not relief. +// and 0 W. Planner or operator discharge is not relief. An offline battery +// gets no command, so its relief carries over until +// expireOfflineFuseRelief ends it. func (s *State) recordFuseRelief(before, after []DispatchTarget) { if s == nil { return @@ -2464,6 +2465,11 @@ func (s *State) recordFuseRelief(before, after []DispatchTarget) { relief[driver] = r } } + for driver := range s.batteriesOfflineSince { + if _, ok := post[driver]; !ok && s.batteryFuseRelief[driver] > 0 { + relief[driver] = s.batteryFuseRelief[driver] + } + } s.batteryFuseRelief = relief } diff --git a/go/internal/control/ev_battery_sequence_test.go b/go/internal/control/ev_battery_sequence_test.go index 6fa5b6eb7..d75dd72ad 100644 --- a/go/internal/control/ev_battery_sequence_test.go +++ b/go/internal/control/ev_battery_sequence_test.go @@ -581,6 +581,95 @@ func TestOfflineBatteryReliefEndsAfterSettle(t *testing.T) { } } +// Two batteries: "b2" goes offline holding 1500 W of fuse relief while +// "bat" stays online. Its relief counts whole for evSettle and then ends, +// whether dispatch sits in the deadband and sends nothing or sends "bat" a +// command every tick. Before, a quiet dispatch kept it for as long as the site +// stayed quiet, and a command dropped it on the first tick. +func TestOfflineBatteryReliefEndsBesideAnOnlineBattery(t *testing.T) { + for _, tc := range []struct { + name string + gridW float64 + }{ + {"deadband", 0}, + {"commanded", 3000}, + } { + t.Run(tc.name, func(t *testing.T) { + store, state, caps := setupPerPhase(tc.gridW, 6, 6, 6, 0.6, 10000) + soc := 0.6 + store.Update("b2", telemetry.DerBattery, -1500, &soc, nil) + caps["b2"] = 15200 + state.DriverLimits["b2"] = PowerLimits{MaxChargeW: 10000, MaxDischargeW: 10000} + state.Mode = ModeSelfConsumption + now := time.Now() + state.clock = func() time.Time { return now } + state.batteryFuseRelief = map[string]float64{"b2": 1500} + store.DriverHealthMut("b2").SetOffline() + commands := 0 + for start := now; now.Sub(start) < 2*time.Minute; { + now = now.Add(time.Second) + store.Update("meter", telemetry.DerMeter, tc.gridW, nil, []byte(`{"l1_a":6,"l2_a":6,"l3_a":6}`)) + store.Get("meter", telemetry.DerMeter).UpdatedAt = now + store.DriverHealthMut("meter").RecordSuccess() + store.Update("bat", telemetry.DerBattery, 0, &soc, nil) + store.Get("bat", telemetry.DerBattery).UpdatedAt = now + store.DriverHealthMut("bat").RecordSuccess() + if len(ComputeDispatch(store, state, caps, 11040)) > 0 { + commands++ + } + // The first dispatch, a second in, finds b2 offline. + want := 0.0 + if now.Sub(start) <= evSettle { + want = 1500 + } + if got := state.evFuseReliefW(store); got != want { + t.Fatalf("%v offline, %d commands: relief %.0f W, want %.0f W (%v)", now.Sub(start), commands, got, want, state.batteryFuseRelief) + } + } + if (commands > 0) != (tc.gridW != 0) { + t.Fatalf("setup: %d dispatches with a command", commands) + } + }) + } +} + +// The battery goes offline in relief, its relief ends, it comes back and +// takes new relief, and it goes offline again. The second offline period +// counts the new relief whole for evSettle: Core ordered that discharge a +// second ago, and the old offline clock must not end it at once. +func TestReturningBatteryReliefCountsWholeAgain(t *testing.T) { + s := newIdleBatteryEVSite(t, 3000, 0) + s.run(5 * time.Minute) + s.houseW += 8000 + s.run(3 * time.Second) + if s.state.batteryFuseRelief["pixii"] <= 0 { + t.Fatalf("setup: no relief %v", s.state.batteryFuseRelief) + } + s.store.DriverHealthMut("pixii").SetOffline() + s.batteryOffline, s.batteryW = true, 0 + s.run(2 * time.Minute) + if got := s.state.evFuseReliefW(s.store); got != 0 { + t.Fatalf("first offline period: relief %.0f W still counted", got) + } + s.batteryOffline = false + s.run(2 * time.Minute) + s.houseW += 2000 + s.run(3 * time.Second) + reliefW := s.state.batteryFuseRelief["pixii"] + if reliefW <= 0 { + t.Fatalf("setup: no new relief, battery %.0f W relief %v", s.batteryW, s.state.batteryFuseRelief) + } + s.store.DriverHealthMut("pixii").SetOffline() + s.batteryOffline = true + offlineAt := s.now + for s.now.Sub(offlineAt) < evSettle-time.Second { + s.step() + if got := s.state.evFuseReliefW(s.store); math.Abs(got-reliefW) > 1e-6 { + t.Fatalf("%v into the second offline period: relief %.0f W, want the whole %.0f W", s.now.Sub(offlineAt), got, reliefW) + } + } +} + // Relief is only the discharge the fuse guard added: a cancelled charge or // the planner's own discharge stays room for the car. func TestFuseReliefIsOnlyAddedDischarge(t *testing.T) { diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index 56a73a4ee..6925686a0 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -575,7 +575,7 @@ func (s *State) stepEVMeterLimit(store *telemetry.Store, meter *telemetry.DerRea // each battery's recorded relief, at most the discharge it reads. A battery // with no live reading (watchdog-offline, or none yet) counts its whole // relief: Core can no longer hold that discharge, and the car must not -// build on it. expireOfflineFuseRelief ends it once no battery is online. +// build on it. expireOfflineFuseRelief ends it evSettle after it went offline. func (s *State) evFuseReliefW(store *telemetry.Store) float64 { var w float64 for driver, relief := range s.batteryFuseRelief { @@ -587,21 +587,43 @@ func (s *State) evFuseReliefW(store *telemetry.Store) float64 { return w } -// expireOfflineFuseRelief ends the recorded relief evSettle after dispatch -// first finds no battery online. Core sent each battery its default mode -// then, and that command reaches the meter within evSettle, as ours do. -// Until then the car must not build on a discharge that may still stand; -// after it, holding the car below the line for relief Core no longer -// orders would be a hidden margin. With a battery online, every recorded -// dispatch rewrites the relief and drops the offline batteries. -func (s *State) expireOfflineFuseRelief() { +// expireOfflineFuseRelief ends each offline battery's recorded relief +// evSettle after dispatch first finds that battery offline. Core sent it its +// default mode then, and that command reaches the meter within evSettle, as +// ours do. Until then the car must not build on a discharge that may still +// stand; after it, holding the car below the line for relief Core no longer +// orders would be a hidden margin. It runs on every dispatch, whatever the +// other batteries do, so a dispatch that sends no command still ends it. A +// battery back online drops out of the clock: the next time it goes offline +// its relief counts whole again. +func (s *State) expireOfflineFuseRelief(online []batteryInfo) { now := s.now() - if s.batteriesOfflineSince.IsZero() { - s.batteriesOfflineSince = now - } - if now.Sub(s.batteriesOfflineSince) >= evSettle { - s.batteryFuseRelief = nil + live := make(map[string]bool, len(online)) + for _, b := range online { + live[b.driver] = true + } + var relief map[string]float64 + var since map[string]time.Time + for driver, w := range s.batteryFuseRelief { + if !live[driver] { + at, ok := s.batteriesOfflineSince[driver] + if !ok { + at = now + } + if now.Sub(at) >= evSettle { + continue + } + if since == nil { + since = make(map[string]time.Time) + } + since[driver] = at + } + if relief == nil { + relief = make(map[string]float64) + } + relief[driver] = w } + s.batteryFuseRelief, s.batteriesOfflineSince = relief, since } // wholeStepsW rounds w down to whole charger amps on the pool's phases, one From 6a5a5f55981232ee75854efc8969b9961ee6539c Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 03:01:09 +0100 Subject: [PATCH 46/68] fix(control): battery phase relief neither pins mixed phases nor winds up The last-command bound held the battery at its last command when one phase sat at the import line and another was over the export line: the guard cut the discharge for the exporting phase and the bound put it back. Now the bound gives way on one side while any phase is over the other side's line, and phaseFuseReliefW's least-over move decides. When the meter does not show the battery's move (a frozen meter, or a worst phase a one-phase battery cannot reach), each tick added the same overage again and the order ran out to the discharge limit. Now the relief toward the worst phase stops at the last command once the batteries' raw power has moved one ampere per phase since the worst phase last moved by half an ampere. One ampere is the step in which P1 meters report phase current. Co-Authored-By: Claude Opus 5.5 --- .changeset/a5-battery-fuse-signed-phases.md | 2 +- go/internal/control/dispatch.go | 114 ++++++++-- .../fuse_battery_phase_direction_test.go | 215 +++++++++++++++++- 3 files changed, 305 insertions(+), 26 deletions(-) diff --git a/.changeset/a5-battery-fuse-signed-phases.md b/.changeset/a5-battery-fuse-signed-phases.md index cfe5e70bb..16129a16d 100644 --- a/.changeset/a5-battery-fuse-signed-phases.md +++ b/.changeset/a5-battery-fuse-signed-phases.md @@ -2,4 +2,4 @@ "ftw": patch --- -The home battery now protects each fuse phase in the direction its current flows. It no longer discharges into a phase that already exports past the fuse, and no longer cuts a discharge that keeps an importing phase under it. It counts its own share of each phase, so it holds a steady relief instead of switching between full relief and none on every dispatch, also when its own power reading lags the meter. It relieves to the fuse less `safety_margin_a`, the same line the car uses. +The home battery now protects each fuse phase in the direction its current flows. It no longer discharges into a phase that already exports past the fuse, and no longer cuts a discharge that keeps an importing phase under it. It counts its own share of each phase, so it holds a steady relief instead of switching between full relief and none on every dispatch, also when its own power reading lags the meter. When one phase imports past the line and another exports past it, it takes the move that leaves the worse phase least over instead of holding its last command. When the meter does not show its moves, because the meter repeats one reading or the phase over the line is one the battery does not reach, it stops adding relief once it has moved one ampere per phase, instead of running out to its discharge limit. It relieves to the fuse less `safety_margin_a`, the same line the car uses. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index e61da53e4..8dc885084 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "log/slog" + "maps" "math" "sort" "time" @@ -406,6 +407,9 @@ type State struct { // batteriesOfflineSince is, per battery whose relief still counts, // when dispatch first found it offline (expireOfflineFuseRelief). batteriesOfflineSince map[string]time.Time + // phaseResponse is the reading the batteries' phase relief last saw + // the worst phase move in (phaseUnresponsive). + phaseResponse phaseResponse // PI controller (outer, site-level) PI *PIController @@ -4022,34 +4026,36 @@ func livePhaseSample(store *telemetry.Store, driver string, meter *telemetry.Der // // sentW is the same change from the command each battery got in the last // dispatch, for a battery that got one, and from its reading otherwise. -func (p phaseSample) moveW(state *State, targets []DispatchTarget, batteries map[string]*telemetry.DerReading) (moveW, sentW float64, ok bool) { +// +// rawW is each battery's raw power in this reading. +func (p phaseSample) moveW(state *State, targets []DispatchTarget, batteries map[string]*telemetry.DerReading) (moveW, sentW float64, rawW map[string]float64, ok bool) { if p.store == nil { - return 0, 0, false + return 0, 0, nil, false } - seen := make(map[string]bool, len(targets)) + rawW = make(map[string]float64, len(targets)) for _, t := range targets { moveW += t.TargetW sentW += t.TargetW - if seen[t.Driver] { + if _, seen := rawW[t.Driver]; seen { continue } - seen[t.Driver] = true r := batteries[t.Driver] if r == nil { - return 0, 0, false + return 0, 0, nil, false } - rawW, at, ok := p.store.OnlineRawW(t.Driver, telemetry.DerBattery) + w, at, ok := p.store.OnlineRawW(t.Driver, telemetry.DerBattery) if !ok || !at.Equal(r.UpdatedAt) { - return 0, 0, false + return 0, 0, nil, false } - moveW -= rawW - if w, sent := state.lastDispatchedW(t.Driver); sent { - sentW -= w + rawW[t.Driver] = w + moveW -= w + if last, sent := state.lastDispatchedW(t.Driver); sent { + sentW -= last } else { - sentW -= rawW + sentW -= w } } - return moveW, sentW, true + return moveW, sentW, rawW, true } // lastDispatchedW is the command driver got in the last dispatch, if it @@ -4077,14 +4083,81 @@ func (s *State) lastDispatchedW(driver string) (float64, bool) { // shows it and the relief goes on top of it. The order runs further out // each time. So a move from the last command may not pass the room the // meter shows either (phaseSentReliefW). +// +// The relief also counts on the meter showing the batteries' move. When it +// does not, because the meter repeats one reading or the worst phase is one +// the batteries do not reach, each tick finds the same overage and adds it +// to a battery already moved for it: the order runs out to the battery's +// limit. Once the meter fails to show a move it should +// (phaseUnresponsive), the relief toward the worst phase stops at the last +// command. func phaseReliefForTargets(p phaseSample, state *State, targets []DispatchTarget, batteries map[string]*telemetry.DerReading) (importW, exportW float64) { - moveW, sentW, ok := p.moveW(state, targets, batteries) + moveW, sentW, rawW, ok := p.moveW(state, targets, batteries) if !ok { return 0, 0 } importW, exportW = phaseFuseReliefW(p, state, moveW) sentImportW, sentExportW := phaseSentReliefW(p, state, sentW) - return math.Max(importW, sentImportW), math.Max(exportW, sentExportW) + importW, exportW = math.Max(importW, sentImportW), math.Max(exportW, sentExportW) + if amps, ok := p.signedA(state); ok { + if worst, stuck := state.phaseUnresponsive(amps, rawW); stuck { + if worst > 0 { + importW = math.Min(importW, math.Max(0, sentW)) + } else { + exportW = math.Min(exportW, math.Max(0, -sentW)) + } + } + } + return importW, exportW +} + +// phaseResponseA is the current a battery move must change on every phase +// before any meter is sure to show it: one ampere, the step in which P1 +// meters report phase current. A phase that changed by less than half of +// it has not moved. +const phaseResponseA = 1.0 + +// phaseResponse is the reading in which the worst phase last moved, with +// each battery's raw power at that reading (phaseUnresponsive). +type phaseResponse struct { + amps []float64 + rawW map[string]float64 +} + +// phaseUnresponsive reports whether the batteries' raw power has changed by +// phaseResponseA or more per phase since the worst phase last moved, while +// that phase has not moved since: the meter does not show the batteries. +// worstA is the worst phase's signed current, + import. A reading in which +// the worst phase moved becomes the new reference. +func (s *State) phaseUnresponsive(amps []float64, rawW map[string]float64) (worstA float64, stuck bool) { + if s == nil || len(amps) == 0 { + return 0, false + } + worst := 0 + for i, a := range amps { + if math.Abs(a) > math.Abs(amps[worst]) { + worst = i + } + } + ref := &s.phaseResponse + if len(ref.amps) != len(amps) || math.Abs(amps[worst]-ref.amps[worst]) >= phaseResponseA/2 { + ref.amps = append([]float64(nil), amps...) + ref.rawW = maps.Clone(rawW) + return amps[worst], false + } + var changedW float64 + for driver, w := range rawW { + if was, ok := ref.rawW[driver]; ok { + changedW += w - was + } else { + if ref.rawW == nil { + ref.rawW = make(map[string]float64, len(rawW)) + } + ref.rawW[driver] = w + } + } + perA := s.SiteFuseVoltage * float64(s.SiteFusePhases) + return amps[worst], math.Abs(changedW) >= phaseResponseA*perA } // phaseSentReliefW is the relief that keeps sentW, the batteries' move from @@ -4092,7 +4165,10 @@ func phaseReliefForTargets(p phaseSample, state *State, targets []DispatchTarget // phase already over the line has no room; its overage is // phaseFuseReliefW's. So this relief never asks for more than to stay at // the last command, and a battery that cannot reach its command does not -// wind the relief up. +// wind the relief up. With a phase over the export line, holding the last +// command against the import line would pin that overage where it is, so +// the import side gives way to phaseFuseReliefW's least-over move; the +// same holds the other way round. func phaseSentReliefW(p phaseSample, state *State, sentW float64) (importW, exportW float64) { amps, ok := p.signedA(state) if !ok { @@ -4101,15 +4177,17 @@ func phaseSentReliefW(p phaseSample, state *State, sentW float64) (importW, expo perA := state.SiteFuseVoltage * float64(state.SiteFusePhases) limitA := state.fuseLineA() hi, lo := math.Inf(-1), math.Inf(1) + overImport, overExport := false, false for _, a := range amps { + overImport, overExport = overImport || a > limitA, overExport || a < -limitA a = math.Max(-limitA, math.Min(limitA, a)) + sentW/perA hi, lo = math.Max(hi, a), math.Min(lo, a) } importW, exportW = math.Max(0, hi-limitA)*perA, math.Max(0, -limitA-lo)*perA - if importW < 1 { + if importW < 1 || overExport { importW = 0 } - if exportW < 1 { + if exportW < 1 || overImport { exportW = 0 } return importW, exportW diff --git a/go/internal/control/fuse_battery_phase_direction_test.go b/go/internal/control/fuse_battery_phase_direction_test.go index 9e48abe66..bd80d6677 100644 --- a/go/internal/control/fuse_battery_phase_direction_test.go +++ b/go/internal/control/fuse_battery_phase_direction_test.go @@ -351,6 +351,30 @@ func TestFuseReliefStaysAtTheLineAfterPVDrop(t *testing.T) { // readLag ticks earlier. maxDischargeW > 0 caps what the battery delivers // without Core knowing it. func pvDropLoop(readLag int, maxDischargeW float64) (targets, l1 []float64, line float64) { + r := pvDropRun(pvDropCase{readLag: readLag, maxDischargeW: maxDischargeW}) + return r.targets, r.l1, r.line +} + +// pvDropCase varies pvDropLoop. freezeFrom > 0 makes the meter repeat its +// reading from that tick on. onePhase puts the battery on that phase only +// (1-3), which Core reads as balanced. load replaces the house and car +// current per phase. +type pvDropCase struct { + readLag int + maxDischargeW float64 + freezeFrom int + onePhase int + load [3]float64 +} + +type pvDropResult struct { + targets, l1 []float64 + // batPhase is the true current on the battery's phase when onePhase > 0. + batPhase []float64 + line float64 +} + +func pvDropRun(c pvDropCase) (r pvDropResult) { st := phaseDirectionState(0) now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) st.clock = func() time.Time { return now } @@ -358,9 +382,14 @@ func pvDropLoop(readLag int, maxDischargeW float64) (targets, l1 []float64, line store := telemetry.NewStore() load := [3]float64{23.44, 11.04, 11.54} // house and car, A import per phase + if c.load != ([3]float64{}) { + load = c.load + } pvW := -3200.0 actual := []float64{-3005} - line = st.fuseLineA() + r.line = st.fuseLineA() + var frozen json.RawMessage + var frozenW float64 for tick := 0; tick < 40; tick++ { switch tick { case 5: @@ -374,15 +403,27 @@ func pvDropLoop(readLag int, maxDischargeW float64) (targets, l1 []float64, line var totalW float64 for i := range a { a[i] = load[i] + (pvW+batW)/690 + if c.onePhase > 0 { + a[i] = load[i] + pvW/690 + if i == c.onePhase-1 { + a[i] += batW / 230 + } + } data[fmt.Sprintf("l%d_a", i+1)] = math.Abs(a[i]) data[fmt.Sprintf("l%d_w", i+1)] = a[i] * 230 totalW += a[i] * 230 } raw, _ := json.Marshal(data) + if c.freezeFrom > 0 && tick >= c.freezeFrom { + if frozen == nil { + frozen, frozenW = raw, totalW + } + raw, totalW = frozen, frozenW + } store.Update("meter", telemetry.DerMeter, totalW, nil, raw) store.DriverHealthMut("meter").RecordSuccess() soc := 0.6 - store.Update("bat", telemetry.DerBattery, actual[max(0, len(actual)-1-readLag)], &soc, nil) + store.Update("bat", telemetry.DerBattery, actual[max(0, len(actual)-1-c.readLag)], &soc, nil) store.DriverHealthMut("bat").RecordSuccess() order := batW @@ -392,15 +433,18 @@ func pvDropLoop(readLag int, maxDischargeW float64) (targets, l1 []float64, line } } batW = order - if maxDischargeW > 0 { - batW = math.Max(order, -maxDischargeW) + if c.maxDischargeW > 0 { + batW = math.Max(order, -c.maxDischargeW) } actual = append(actual, batW) - targets = append(targets, math.Round(order)) - l1 = append(l1, math.Round(a[0]*100)/100) + r.targets = append(r.targets, math.Round(order)) + r.l1 = append(r.l1, math.Round(a[0]*100)/100) + if c.onePhase > 0 { + r.batPhase = append(r.batPhase, math.Round(a[c.onePhase-1]*100)/100) + } now = now.Add(5 * time.Second) } - return targets, l1, line + return r } // assertHeldAtTheLine wants L1 at the line while PV is low, and one crossing @@ -464,3 +508,160 @@ func TestFuseReliefSettlesWhenTheBatteryFallsShort(t *testing.T) { t.Logf("L1 %v", l1) } } + +// Mixed directions, three-phase battery holding -2000 W: L1 imports at the +// 16 A line, and a one-phase PV inverter on L3 steps from -15 A to -18 A +// of export. No move fits both phases. The least-over move cuts the +// discharge by 690 W and leaves L1 at 17 A and L3 at -17 A. Before, the +// last-command bound read L1 at the import line as a reason to keep +// -2000 W, put back every cut the export side made, and left L3 at -18 A. +func TestFuseReliefLeavesMixedPhasesLeastOver(t *testing.T) { + st := phaseDirectionState(0) + now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) + st.clock = func() time.Time { return now } + st.SetBatteryManualHold(BatteryManualHold{PowerW: -2000, ExpiresAt: now.Add(time.Hour)}) + store := telemetry.NewStore() + base := [3]float64{18.9, 8, -12.1} // A without the battery, + import + batW := -2000.0 + var orders, worst []float64 + for tick := 0; tick < 20; tick++ { + if tick == 3 { + base[2] = -15.1 + } + data := map[string]any{} + var totalW, w float64 + for i := range base { + a := base[i] + batW/690 + data[fmt.Sprintf("l%d_a", i+1)] = math.Abs(a) + data[fmt.Sprintf("l%d_w", i+1)] = a * 230 + totalW += a * 230 + w = math.Max(w, math.Abs(a)) + } + raw, _ := json.Marshal(data) + store.Update("meter", telemetry.DerMeter, totalW, nil, raw) + store.DriverHealthMut("meter").RecordSuccess() + soc := 0.6 + store.Update("bat", telemetry.DerBattery, batW, &soc, nil) + store.DriverHealthMut("bat").RecordSuccess() + for _, o := range ComputeDispatch(store, st, map[string]float64{"bat": 15200}, 16*230*3) { + if o.Driver == "bat" { + batW = o.TargetW + } + } + orders = append(orders, math.Round(batW)) + worst = append(worst, math.Round(w*100)/100) + now = now.Add(5 * time.Second) + } + for i := 8; i < 20; i++ { + if worst[i] > 17.05 { + t.Errorf("tick %d: worst phase %.2f A, want at most 17 A (L1 17, L3 -17)", i, worst[i]) + } + } + if t.Failed() { + t.Logf("orders %v", orders) + t.Logf("worst phase |A| %v", worst) + } +} + +// A one-phase battery on L2, which Core reads as balanced, with L1 at 18 A +// while PV is low. Once PV returns, L1 still sits at 16.14 A, which the +// battery cannot reach. Before, the last-command bound held the -4882 W +// discharge for L1 and left L2 exporting 19.86 A, past 1.2 x In, on every +// tick. Now L2 comes back inside the line and the order holds. +func TestFuseReliefLetsAOnePhaseBatteryOffItsOwnPhase(t *testing.T) { + r := pvDropRun(pvDropCase{onePhase: 2, load: [3]float64{20.78, 6, 11.54}}) + for i := 31; i < 40; i++ { + if math.Abs(r.batPhase[i]) > r.line+0.01 { + t.Errorf("tick %d: L2 %.2f A, want inside the %.1f A line", i, r.batPhase[i], r.line) + } + if r.targets[i] != r.targets[31] { + t.Errorf("tick %d: order %.0f W, want the %.0f W order held", i, r.targets[i], r.targets[31]) + } + } + if t.Failed() { + t.Logf("targets %v", r.targets) + t.Logf("L1 %v", r.l1) + t.Logf("L2 %v", r.batPhase) + } +} + +// The meter repeats its 16.3 A reading from the PV step on (frozen@5) +// while the battery follows its orders. Before, every tick found the same +// 0.3 A overage and added it to a battery already moved for it: -3214, +// -3422, ... -10000 W, with the true L1 down at 4.3 A. Now the relief stops +// once the battery has moved one ampere per phase (690 W) and L1 has not +// moved: at most that ampere and one step past the first relief. +func TestFuseReliefStopsWhenTheMeterIsFrozen(t *testing.T) { + r := pvDropRun(pvDropCase{freezeFrom: 5}) + assertReliefStops(t, r) +} + +// A one-phase battery on L2 and L1 at 16.3 A while PV is low. The battery +// cannot reach L1, so L1 never shows its move. Before, the relief grew by +// 0.3 A of overage a tick to -4512 W and drove L2 to -16.4 A of export, +// then -18.25 A on the PV return tick. Now it stops the same way as for a +// frozen meter, and L2 stays inside the line. +func TestFuseReliefStopsWhenTheBatteryCannotReachTheWorstPhase(t *testing.T) { + r := pvDropRun(pvDropCase{onePhase: 2, load: [3]float64{19.08, 6, 11.54}}) + assertReliefStops(t, r) + for i, a := range r.batPhase { + if math.Abs(a) > r.line+0.01 { + t.Errorf("tick %d: L2 %.2f A, want inside the %.1f A line", i, a, r.line) + } + } +} + +// assertReliefStops wants the order no further out than one ampere per +// phase and one 0.3 A step past the first relief (-3214 W), and held from +// tick 9 until PV returns. +func assertReliefStops(t *testing.T, r pvDropResult) { + t.Helper() + const floorW = -3214 - phaseResponseA*690 - 0.3*690 + for i := 5; i < 30; i++ { + if r.targets[i] < floorW { + t.Errorf("tick %d: order %.0f W, past %.0f W", i, r.targets[i], floorW) + } + if i >= 9 && r.targets[i] != r.targets[9] { + t.Errorf("tick %d: order %.0f W, want the %.0f W order held", i, r.targets[i], r.targets[9]) + } + } + if t.Failed() { + t.Logf("targets %v", r.targets) + t.Logf("L1 %v", r.l1) + if r.batPhase != nil { + t.Logf("battery phase %v", r.batPhase) + } + } +} + +// The meter fails to show the batteries only once they moved one ampere +// per phase (phaseResponseA, 690 W here) and the worst phase moved less +// than half an ampere. A phase that moves becomes the new reference. +func TestPhaseUnresponsiveNeedsOneAmpereOfBatteryMove(t *testing.T) { + st := phaseDirectionState(0) + step := func(l1, batW float64) bool { + _, stuck := st.phaseUnresponsive([]float64{l1, 9, 9.5}, map[string]float64{"bat": batW}) + return stuck + } + if step(16.3, -3000) { + t.Fatal("first reading: stuck, want a reference") + } + if step(16.3, -3689) { + t.Error("689 W moved, L1 still: stuck, want not yet") + } + if !step(16.3, -3690) { + t.Error("690 W moved, L1 still: not stuck") + } + if !step(16.79, -3690) { + t.Error("690 W moved, L1 0.49 A: not stuck") + } + if step(15.8, -3690) { + t.Error("L1 moved 0.5 A: stuck, want a new reference") + } + if step(15.8, -3690) { + t.Error("same reading again: stuck") + } + if !step(15.8, -3000) { + t.Error("690 W back, L1 still: not stuck") + } +} From c0668921b2ac958f00d177290b73dc04d859c6f1 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 03:28:03 +0100 Subject: [PATCH 47/68] fix(control): battery phase anti-windup stops only when the meter cannot show the move phaseUnresponsive stopped the relief whenever the batteries had moved 690 W and the worst phase had not moved half an ampere. On a live meter that also happens when a load cancels the move (a balanced load starting with the relief step, or a slow rise on the worst phase), and when the battery's reading catches up with an order the meter already showed. The relief then held over the line with no end. Now it stops only when the meter repeats its phases exactly while the batteries moved one ampere per phase, or when another phase moved by twice the balanced share of that move (a battery off the worst phase). The repeat is measured from the reading the meter last changed in, so a meter that freezes on any reading is still caught. Co-Authored-By: Claude Opus 5.5 --- .changeset/a5-battery-fuse-signed-phases.md | 2 +- go/internal/control/dispatch.go | 76 +++++-- .../fuse_battery_phase_direction_test.go | 191 +++++++++++++++--- 3 files changed, 220 insertions(+), 49 deletions(-) diff --git a/.changeset/a5-battery-fuse-signed-phases.md b/.changeset/a5-battery-fuse-signed-phases.md index 16129a16d..1c3158645 100644 --- a/.changeset/a5-battery-fuse-signed-phases.md +++ b/.changeset/a5-battery-fuse-signed-phases.md @@ -2,4 +2,4 @@ "ftw": patch --- -The home battery now protects each fuse phase in the direction its current flows. It no longer discharges into a phase that already exports past the fuse, and no longer cuts a discharge that keeps an importing phase under it. It counts its own share of each phase, so it holds a steady relief instead of switching between full relief and none on every dispatch, also when its own power reading lags the meter. When one phase imports past the line and another exports past it, it takes the move that leaves the worse phase least over instead of holding its last command. When the meter does not show its moves, because the meter repeats one reading or the phase over the line is one the battery does not reach, it stops adding relief once it has moved one ampere per phase, instead of running out to its discharge limit. It relieves to the fuse less `safety_margin_a`, the same line the car uses. +The home battery now protects each fuse phase in the direction its current flows. It no longer discharges into a phase that already exports past the fuse, and no longer cuts a discharge that keeps an importing phase under it. It counts its own share of each phase, so it holds a steady relief instead of switching between full relief and none on every dispatch, also when its own power reading lags the meter. When one phase imports past the line and another exports past it, it takes the move that leaves the worse phase least over instead of holding its last command. When the meter does not show its moves, because the meter repeats one reading or the battery sits on a phase other than the one over the line, it stops adding relief once it has moved one ampere per phase, instead of running out to its discharge limit. A load that cancels its move on a live meter does not stop it. It relieves to the fuse less `safety_margin_a`, the same line the car uses. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 8dc885084..f32d33f12 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -7,6 +7,7 @@ import ( "log/slog" "maps" "math" + "slices" "sort" "time" @@ -407,8 +408,8 @@ type State struct { // batteriesOfflineSince is, per battery whose relief still counts, // when dispatch first found it offline (expireOfflineFuseRelief). batteriesOfflineSince map[string]time.Time - // phaseResponse is the reading the batteries' phase relief last saw - // the worst phase move in (phaseUnresponsive). + // phaseResponse holds the readings the batteries' phase relief checks + // the meter against (phaseUnresponsive). phaseResponse phaseResponse // PI controller (outer, site-level) @@ -4117,18 +4118,29 @@ func phaseReliefForTargets(p phaseSample, state *State, targets []DispatchTarget // it has not moved. const phaseResponseA = 1.0 -// phaseResponse is the reading in which the worst phase last moved, with -// each battery's raw power at that reading (phaseUnresponsive). +// phaseResponse holds the readings phaseUnresponsive measures from, each +// with the batteries' raw power at that reading: the one in which the +// worst phase last moved, and the one in which any phase last changed. type phaseResponse struct { - amps []float64 - rawW map[string]float64 + amps, changedAmps []float64 + rawW, changedRawW map[string]float64 } -// phaseUnresponsive reports whether the batteries' raw power has changed by -// phaseResponseA or more per phase since the worst phase last moved, while -// that phase has not moved since: the meter does not show the batteries. -// worstA is the worst phase's signed current, + import. A reading in which -// the worst phase moved becomes the new reference. +// phaseUnresponsive reports whether the meter fails to show the batteries +// on the worst phase. worstA is the worst phase's signed current, + +// import. It is stuck when the batteries' raw power has changed by +// phaseResponseA or more per phase since either +// +// - the meter's phases last changed at all: the meter repeats one +// reading (C5 makes such a meter stale), or +// - the worst phase last moved, while another phase moved by twice the +// even share of that change or more. A balanced battery moves each +// phase by that share, so this battery sits off the worst phase. +// +// A live meter on which the worst phase does not move is not enough: a +// load on that phase can cancel the move, at once or step by step, and +// there the relief must go on. A reading in which the worst phase moved +// becomes the new reference. func (s *State) phaseUnresponsive(amps []float64, rawW map[string]float64) (worstA float64, stuck bool) { if s == nil || len(amps) == 0 { return 0, false @@ -4140,24 +4152,44 @@ func (s *State) phaseUnresponsive(amps []float64, rawW map[string]float64) (wors } } ref := &s.phaseResponse + perA := s.SiteFuseVoltage * float64(s.SiteFusePhases) + if !slices.Equal(amps, ref.changedAmps) { + ref.changedAmps, ref.changedRawW = slices.Clone(amps), maps.Clone(rawW) + } + if math.Abs(batteriesMovedW(&ref.changedRawW, rawW)) >= phaseResponseA*perA { + return amps[worst], true + } if len(ref.amps) != len(amps) || math.Abs(amps[worst]-ref.amps[worst]) >= phaseResponseA/2 { - ref.amps = append([]float64(nil), amps...) - ref.rawW = maps.Clone(rawW) + ref.amps, ref.rawW = slices.Clone(amps), maps.Clone(rawW) + return amps[worst], false + } + movedW := batteriesMovedW(&ref.rawW, rawW) + if math.Abs(movedW) < phaseResponseA*perA { return amps[worst], false } - var changedW float64 + for i, a := range amps { + if i != worst && (a-ref.amps[i])/(movedW/perA) >= 2 { + return amps[worst], true + } + } + return amps[worst], false +} + +// batteriesMovedW is the batteries' raw power change from ref. A battery +// that ref has not seen joins it at its present power. +func batteriesMovedW(ref *map[string]float64, rawW map[string]float64) (movedW float64) { for driver, w := range rawW { - if was, ok := ref.rawW[driver]; ok { - changedW += w - was - } else { - if ref.rawW == nil { - ref.rawW = make(map[string]float64, len(rawW)) + was, ok := (*ref)[driver] + if !ok { + if *ref == nil { + *ref = make(map[string]float64, len(rawW)) } - ref.rawW[driver] = w + (*ref)[driver] = w + continue } + movedW += w - was } - perA := s.SiteFuseVoltage * float64(s.SiteFusePhases) - return amps[worst], math.Abs(changedW) >= phaseResponseA*perA + return movedW } // phaseSentReliefW is the relief that keeps sentW, the batteries' move from diff --git a/go/internal/control/fuse_battery_phase_direction_test.go b/go/internal/control/fuse_battery_phase_direction_test.go index bd80d6677..d281ce1fb 100644 --- a/go/internal/control/fuse_battery_phase_direction_test.go +++ b/go/internal/control/fuse_battery_phase_direction_test.go @@ -358,13 +358,17 @@ func pvDropLoop(readLag int, maxDischargeW float64) (targets, l1 []float64, line // pvDropCase varies pvDropLoop. freezeFrom > 0 makes the meter repeat its // reading from that tick on. onePhase puts the battery on that phase only // (1-3), which Core reads as balanced. load replaces the house and car -// current per phase. +// current per phase. ticks > 0 replaces the 40 ticks, pvW the PV step, and +// extra adds import current per phase at a tick. type pvDropCase struct { readLag int maxDischargeW float64 freezeFrom int onePhase int load [3]float64 + ticks int + pvW func(tick int) float64 + extra func(tick int) [3]float64 } type pvDropResult struct { @@ -390,21 +394,32 @@ func pvDropRun(c pvDropCase) (r pvDropResult) { r.line = st.fuseLineA() var frozen json.RawMessage var frozenW float64 - for tick := 0; tick < 40; tick++ { + ticks := 40 + if c.ticks > 0 { + ticks = c.ticks + } + for tick := 0; tick < ticks; tick++ { switch tick { case 5: pvW = -1920 case 30: pvW = -3200 } + if c.pvW != nil { + pvW = c.pvW(tick) + } + var extra [3]float64 + if c.extra != nil { + extra = c.extra(tick) + } batW := actual[len(actual)-1] var a [3]float64 data := map[string]any{} var totalW float64 for i := range a { - a[i] = load[i] + (pvW+batW)/690 + a[i] = load[i] + extra[i] + (pvW+batW)/690 if c.onePhase > 0 { - a[i] = load[i] + pvW/690 + a[i] = load[i] + extra[i] + pvW/690 if i == c.onePhase-1 { a[i] += batW / 230 } @@ -596,6 +611,37 @@ func TestFuseReliefStopsWhenTheMeterIsFrozen(t *testing.T) { assertReliefStops(t, r) } +// The meter freezes on a reading that is not the worst phase's reference: +// L1 reads 16.3 A on the PV step, the relief brings it to 16.0 A, and a +// 0.2 A load on L1 starts at tick 8, the reading the meter then repeats. +// L1 moved only 0.1 A from 16.3 A, so the stop counts the battery's move +// from the reading the meter repeats, not from that reference: the order +// stops once the battery has moved one ampere per phase since the freeze. +func TestFuseReliefStopsWhenTheMeterFreezesOffTheReference(t *testing.T) { + r := pvDropRun(pvDropCase{ + freezeFrom: 8, + extra: func(tick int) [3]float64 { + if tick >= 8 { + return [3]float64{0.2, 0, 0} + } + return [3]float64{} + }, + }) + const floorW = -3214 - 0.2*690 - phaseResponseA*690 - 0.2*690 + for i := 8; i < 30; i++ { + if r.targets[i] < floorW { + t.Errorf("tick %d: order %.0f W, past %.0f W", i, r.targets[i], floorW) + } + if i >= 15 && r.targets[i] != r.targets[15] { + t.Errorf("tick %d: order %.0f W, want the %.0f W order held", i, r.targets[i], r.targets[15]) + } + } + if t.Failed() { + t.Logf("targets %v", r.targets) + t.Logf("L1 %v", r.l1) + } +} + // A one-phase battery on L2 and L1 at 16.3 A while PV is low. The battery // cannot reach L1, so L1 never shows its move. Before, the relief grew by // 0.3 A of overage a tick to -4512 W and drove L2 to -16.4 A of export, @@ -635,33 +681,126 @@ func assertReliefStops(t *testing.T, r pvDropResult) { } // The meter fails to show the batteries only once they moved one ampere -// per phase (phaseResponseA, 690 W here) and the worst phase moved less -// than half an ampere. A phase that moves becomes the new reference. +// per phase (phaseResponseA, 690 W here) and either the meter repeated its +// reading all the while, or the worst phase moved less than half an ampere +// while another phase carried the move. A phase that moves becomes the new +// reference. func TestPhaseUnresponsiveNeedsOneAmpereOfBatteryMove(t *testing.T) { st := phaseDirectionState(0) - step := func(l1, batW float64) bool { - _, stuck := st.phaseUnresponsive([]float64{l1, 9, 9.5}, map[string]float64{"bat": batW}) - return stuck - } - if step(16.3, -3000) { - t.Fatal("first reading: stuck, want a reference") - } - if step(16.3, -3689) { - t.Error("689 W moved, L1 still: stuck, want not yet") - } - if !step(16.3, -3690) { - t.Error("690 W moved, L1 still: not stuck") + for _, c := range []struct { + name string + amps []float64 + batW float64 + stuck bool + }{ + {"first reading: a reference", []float64{16.3, 9, 9.5}, -3000, false}, + {"689 W moved, same reading", []float64{16.3, 9, 9.5}, -3689, false}, + {"690 W moved, same reading", []float64{16.3, 9, 9.5}, -3690, true}, + {"L1 0.49 A, L2 and L3 still: a load cancels the move", []float64{16.79, 9, 9.5}, -3690, false}, + {"L1 0.49 A, L2 and L3 one share each: a load on L1", []float64{16.79, 8, 8.5}, -3690, false}, + {"L1 0.49 A, L2 1.99 shares", []float64{16.79, 7.01, 9.5}, -3690, false}, + {"L1 0.49 A, L2 two shares: a battery off L1", []float64{16.79, 7, 9.5}, -3690, true}, + {"L1 moved 0.5 A: a new reference", []float64{15.8, 9, 9.5}, -3690, false}, + {"same reading again", []float64{15.8, 9, 9.5}, -3690, false}, + {"690 W back, same reading", []float64{15.8, 9, 9.5}, -3000, true}, + {"L1 0.1 A, L2 and L3 still", []float64{15.9, 9, 9.5}, -3000, false}, + {"690 W back again, the meter repeats L1 0.1 A off the reference", []float64{15.9, 9, 9.5}, -2310, true}, + } { + if _, got := st.phaseUnresponsive(c.amps, map[string]float64{"bat": c.batW}); got != c.stuck { + t.Errorf("%s: stuck %v, want %v", c.name, got, c.stuck) + } } - if !step(16.79, -3690) { - t.Error("690 W moved, L1 0.49 A: not stuck") +} + +// pvLowAfter5 drops PV to -440 W from tick 5 on, which puts L1 at 18.45 A +// under the -3005 W hold. +func pvLowAfter5(tick int) float64 { + if tick >= 5 { + return -440 } - if step(15.8, -3690) { - t.Error("L1 moved 0.5 A: stuck, want a new reference") + return -3200 +} + +// The battery's reading lags the meter by a tick (207537). L1 reads +// 18.45 A at tick 5, and one relief step of -4694 W brings it to the line. +// The reading then catches up with that order while the meter stays put. A +// 0.4 A load on L1 starts at tick 15 and stays. Before, the catch-up +// counted as a move the meter did not show: the order stayed at -4694 W +// and L1 at 16.4 A to the end, and the heat model trips that after about +// three minutes. The catch-up is no new move, so the relief follows the +// load. +func TestFuseReliefFollowsALoadAfterTheReadingCatchesUp(t *testing.T) { + r := pvDropRun(pvDropCase{ + ticks: 60, + readLag: 1, + pvW: pvLowAfter5, + extra: func(tick int) [3]float64 { + if tick >= 15 { + return [3]float64{0.4, 0, 0} + } + return [3]float64{} + }, + }) + assertL1AtTheLine(t, r, 17, 60) +} + +// L1 reads 18.45 A at tick 5 and the relief step is -4694 W. A balanced +// 2 A load per phase (a three-phase heat pump) starts in the reading that +// shows the step, so L1 reads 18.0 A, a move of 0.45 A. Before, that +// counted as a meter that does not show the battery: the order stayed at +// -4694 W with L1 at 18 A (1.125 x In) to the end, and the heat model +// trips that after about 94 s. The meter is live, so the relief goes on. +func TestFuseReliefGoesOnWhenALoadMasksTheStep(t *testing.T) { + r := pvDropRun(pvDropCase{ + pvW: pvLowAfter5, + extra: func(tick int) [3]float64 { + if tick >= 6 { + return [3]float64{2, 2, 2} + } + return [3]float64{} + }, + }) + assertL1AtTheLine(t, r, 7, 40) +} + +// A one-phase load on L1 rises 0.15 A a tick from tick 10 to tick 39, +// after the PV step has put L1 at the line. The battery follows, so L1 +// never moves half an ampere, while L2 and L3 move with the battery. +// Before, after 690 W of following, the relief stopped until L1 had risen +// half an ampere past its 16.3 A reference: L1 climbed to 16.9 A, fell +// back and climbed again. Now L1 stays within one tick's rise of the line, +// and at the line once the rise stops. +func TestFuseReliefFollowsASlowLoadRise(t *testing.T) { + r := pvDropRun(pvDropCase{ + ticks: 50, + pvW: func(tick int) float64 { + if tick >= 5 { + return -1920 + } + return -3200 + }, + extra: func(tick int) [3]float64 { + return [3]float64{0.15 * float64(min(max(tick-9, 0), 30)), 0, 0} + }, + }) + for i := 10; i < 40; i++ { + if r.l1[i] > r.line+0.16 { + t.Errorf("tick %d: L1 %.2f A, more than one 0.15 A rise over the %.1f A line", i, r.l1[i], r.line) + } } - if step(15.8, -3690) { - t.Error("same reading again: stuck") + assertL1AtTheLine(t, r, 41, 50) +} + +// assertL1AtTheLine wants L1 at or under the line on ticks [from, to). +func assertL1AtTheLine(t *testing.T, r pvDropResult, from, to int) { + t.Helper() + for i := from; i < to; i++ { + if r.l1[i] > r.line+0.01 { + t.Errorf("tick %d: L1 %.2f A, over the %.1f A line with a battery that has room", i, r.l1[i], r.line) + } } - if !step(15.8, -3000) { - t.Error("690 W back, L1 still: not stuck") + if t.Failed() { + t.Logf("targets %v", r.targets) + t.Logf("L1 %v", r.l1) } } From 8c3ae3cd7eb7b5eba63e942f75e31f5997dd8534 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 04:02:45 +0100 Subject: [PATCH 48/68] fix(control): battery off the worst phase goes back, and a stale reference ends Fourth review of the phase anti-windup (c0668921): - The worst phase's reference had no end while that phase sat over the line. A relief that follows a slow drift keeps it there, so the reference stayed while the battery moved hundreds of watts, and a load that later switched off on another phase read as a battery off the worst phase. The relief then held L1 up to 0.49 A over the line with no time limit. The reference now also ends when the worst phase is at or inside the line, or when another phase becomes the worst. - An off-phase verdict no longer holds the last command. The batteries go back to their power when the worst phase last moved: what they moved since did not reach it. A one-phase battery no longer holds its own phase at -17.97 A for the whole overage (and -19.83 A, past 1.2 x In, when PV returns). A false verdict on a balanced battery moves the worst phase by at least one ampere on the next reading, which ends the reference, so it costs one tick instead of an open-ended hold. The verdict holds until the reference ends, so the relief does not go out again once the battery is back. - The frozen-meter test now also compares the meter's total. A P1 meter reports whole amperes, so a live meter can repeat its phases while its total moves; that latched the relief at 1.11 x In. Co-Authored-By: Claude Opus 5.5 --- .changeset/a5-battery-fuse-signed-phases.md | 2 +- go/internal/control/dispatch.go | 88 ++++++-- .../fuse_battery_phase_direction_test.go | 205 ++++++++++++++++-- 3 files changed, 258 insertions(+), 37 deletions(-) diff --git a/.changeset/a5-battery-fuse-signed-phases.md b/.changeset/a5-battery-fuse-signed-phases.md index 1c3158645..089343709 100644 --- a/.changeset/a5-battery-fuse-signed-phases.md +++ b/.changeset/a5-battery-fuse-signed-phases.md @@ -2,4 +2,4 @@ "ftw": patch --- -The home battery now protects each fuse phase in the direction its current flows. It no longer discharges into a phase that already exports past the fuse, and no longer cuts a discharge that keeps an importing phase under it. It counts its own share of each phase, so it holds a steady relief instead of switching between full relief and none on every dispatch, also when its own power reading lags the meter. When one phase imports past the line and another exports past it, it takes the move that leaves the worse phase least over instead of holding its last command. When the meter does not show its moves, because the meter repeats one reading or the battery sits on a phase other than the one over the line, it stops adding relief once it has moved one ampere per phase, instead of running out to its discharge limit. A load that cancels its move on a live meter does not stop it. It relieves to the fuse less `safety_margin_a`, the same line the car uses. +The home battery now protects each fuse phase in the direction its current flows. It no longer discharges into a phase that already exports past the fuse, and no longer cuts a discharge that keeps an importing phase under it. It counts its own share of each phase, so it holds a steady relief instead of switching between full relief and none on every dispatch, also when its own power reading lags the meter. When one phase imports past the line and another exports past it, it takes the move that leaves the worse phase least over instead of holding its last command. When the meter does not show its moves, because the meter repeats one reading or the battery sits on a phase other than the one over the line, it stops adding relief once it has moved one ampere per phase, instead of running out to its discharge limit. A battery on another phase then goes back to its power from before that relief, so it does not hold its own phase past the line. A load that cancels its move on a live meter does not stop it, nor do phase currents that a whole-ampere meter rounds to the same value while its total moves. It relieves to the fuse less `safety_margin_a`, the same line the car uses. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index f32d33f12..2a63140be 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -4090,8 +4090,11 @@ func (s *State) lastDispatchedW(driver string) (float64, bool) { // the batteries do not reach, each tick finds the same overage and adds it // to a battery already moved for it: the order runs out to the battery's // limit. Once the meter fails to show a move it should -// (phaseUnresponsive), the relief toward the worst phase stops at the last -// command. +// (phaseUnresponsive), the relief toward the worst phase stops. On a +// meter that repeats its reading it stops at the last command. On a +// battery off the worst phase it goes back to the batteries' power when +// that phase last moved: what they moved since did not reach it, and it +// pushes their own phase toward its line. func phaseReliefForTargets(p phaseSample, state *State, targets []DispatchTarget, batteries map[string]*telemetry.DerReading) (importW, exportW float64) { moveW, sentW, rawW, ok := p.moveW(state, targets, batteries) if !ok { @@ -4101,17 +4104,40 @@ func phaseReliefForTargets(p phaseSample, state *State, targets []DispatchTarget sentImportW, sentExportW := phaseSentReliefW(p, state, sentW) importW, exportW = math.Max(importW, sentImportW), math.Max(exportW, sentExportW) if amps, ok := p.signedA(state); ok { - if worst, stuck := state.phaseUnresponsive(amps, rawW); stuck { + if worst, stuck, backTo := state.phaseUnresponsive(amps, p.totalW, rawW); stuck { + capW := sentW + if backTo != nil { + capW = targetsMoveFromW(targets, backTo, rawW) + } if worst > 0 { - importW = math.Min(importW, math.Max(0, sentW)) + importW = math.Min(importW, math.Max(0, capW)) } else { - exportW = math.Min(exportW, math.Max(0, -sentW)) + exportW = math.Min(exportW, math.Max(0, -capW)) } } } return importW, exportW } +// targetsMoveFromW is the targets' change from the batteries' power in +// from. A battery that from has not seen counts at its power in rawW. +func targetsMoveFromW(targets []DispatchTarget, from, rawW map[string]float64) (moveW float64) { + seen := make(map[string]bool, len(targets)) + for _, t := range targets { + moveW += t.TargetW + if seen[t.Driver] { + continue + } + seen[t.Driver] = true + if w, ok := from[t.Driver]; ok { + moveW -= w + } else { + moveW -= rawW[t.Driver] + } + } + return moveW +} + // phaseResponseA is the current a battery move must change on every phase // before any meter is sure to show it: one ampere, the step in which P1 // meters report phase current. A phase that changed by less than half of @@ -4120,10 +4146,15 @@ const phaseResponseA = 1.0 // phaseResponse holds the readings phaseUnresponsive measures from, each // with the batteries' raw power at that reading: the one in which the -// worst phase last moved, and the one in which any phase last changed. +// worst phase last moved (amps), and the one in which the meter's phases +// or total last changed (changed: the phases, then the total). offPhase +// is set once the batteries are found off the worst phase, phase +// offPhaseAt, and holds until that phase's reference ends. type phaseResponse struct { - amps, changedAmps []float64 + amps, changed []float64 rawW, changedRawW map[string]float64 + offPhase bool + offPhaseAt int } // phaseUnresponsive reports whether the meter fails to show the batteries @@ -4131,19 +4162,27 @@ type phaseResponse struct { // import. It is stuck when the batteries' raw power has changed by // phaseResponseA or more per phase since either // -// - the meter's phases last changed at all: the meter repeats one -// reading (C5 makes such a meter stale), or +// - the meter last changed at all, phases or total: the meter repeats +// one reading (C5 makes such a meter stale). A P1 meter reports phase +// current in whole amperes, so a live one can repeat its phases while +// its total moves. backTo is nil: the relief holds the last command. // - the worst phase last moved, while another phase moved by twice the // even share of that change or more. A balanced battery moves each // phase by that share, so this battery sits off the worst phase. +// backTo is the batteries' power when the worst phase last moved. The +// verdict holds until that reference ends, so the relief does not go +// out again once the batteries are back. // // A live meter on which the worst phase does not move is not enough: a // load on that phase can cancel the move, at once or step by step, and -// there the relief must go on. A reading in which the worst phase moved -// becomes the new reference. -func (s *State) phaseUnresponsive(amps []float64, rawW map[string]float64) (worstA float64, stuck bool) { +// there the relief must go on. The worst phase's reference ends when that +// phase moves, when it is at or inside the line (fuseLineA), or when +// another phase becomes the worst. Without the second, a reference kept +// while the relief holds the phase at the line would count a load that +// later changes on another phase against all the batteries moved since. +func (s *State) phaseUnresponsive(amps []float64, totalW float64, rawW map[string]float64) (worstA float64, stuck bool, backTo map[string]float64) { if s == nil || len(amps) == 0 { - return 0, false + return 0, false, nil } worst := 0 for i, a := range amps { @@ -4153,26 +4192,31 @@ func (s *State) phaseUnresponsive(amps []float64, rawW map[string]float64) (wors } ref := &s.phaseResponse perA := s.SiteFuseVoltage * float64(s.SiteFusePhases) - if !slices.Equal(amps, ref.changedAmps) { - ref.changedAmps, ref.changedRawW = slices.Clone(amps), maps.Clone(rawW) + if changed := append(slices.Clone(amps), totalW); !slices.Equal(changed, ref.changed) { + ref.changed, ref.changedRawW = changed, maps.Clone(rawW) } if math.Abs(batteriesMovedW(&ref.changedRawW, rawW)) >= phaseResponseA*perA { - return amps[worst], true + return amps[worst], true, nil } - if len(ref.amps) != len(amps) || math.Abs(amps[worst]-ref.amps[worst]) >= phaseResponseA/2 { - ref.amps, ref.rawW = slices.Clone(amps), maps.Clone(rawW) - return amps[worst], false + if len(ref.amps) != len(amps) || math.Abs(amps[worst]-ref.amps[worst]) >= phaseResponseA/2 || + math.Abs(amps[worst]) <= s.fuseLineA() || (ref.offPhase && worst != ref.offPhaseAt) { + ref.amps, ref.rawW, ref.offPhase = slices.Clone(amps), maps.Clone(rawW), false + return amps[worst], false, nil } movedW := batteriesMovedW(&ref.rawW, rawW) + if ref.offPhase { + return amps[worst], true, ref.rawW + } if math.Abs(movedW) < phaseResponseA*perA { - return amps[worst], false + return amps[worst], false, nil } for i, a := range amps { if i != worst && (a-ref.amps[i])/(movedW/perA) >= 2 { - return amps[worst], true + ref.offPhase, ref.offPhaseAt = true, worst + return amps[worst], true, ref.rawW } } - return amps[worst], false + return amps[worst], false, nil } // batteriesMovedW is the batteries' raw power change from ref. A battery diff --git a/go/internal/control/fuse_battery_phase_direction_test.go b/go/internal/control/fuse_battery_phase_direction_test.go index d281ce1fb..592d3db12 100644 --- a/go/internal/control/fuse_battery_phase_direction_test.go +++ b/go/internal/control/fuse_battery_phase_direction_test.go @@ -359,7 +359,9 @@ func pvDropLoop(readLag int, maxDischargeW float64) (targets, l1 []float64, line // reading from that tick on. onePhase puts the battery on that phase only // (1-3), which Core reads as balanced. load replaces the house and car // current per phase. ticks > 0 replaces the 40 ticks, pvW the PV step, and -// extra adds import current per phase at a tick. +// extra adds import current per phase at a tick. resA > 0 makes the meter +// report phase current in steps of resA, as a P1 meter does in whole +// amperes. type pvDropCase struct { readLag int maxDischargeW float64 @@ -369,6 +371,7 @@ type pvDropCase struct { ticks int pvW func(tick int) float64 extra func(tick int) [3]float64 + resA float64 } type pvDropResult struct { @@ -425,6 +428,9 @@ func pvDropRun(c pvDropCase) (r pvDropResult) { } } data[fmt.Sprintf("l%d_a", i+1)] = math.Abs(a[i]) + if c.resA > 0 { + data[fmt.Sprintf("l%d_a", i+1)] = math.Round(math.Abs(a[i])/c.resA) * c.resA + } data[fmt.Sprintf("l%d_w", i+1)] = a[i] * 230 totalW += a[i] * 230 } @@ -579,18 +585,33 @@ func TestFuseReliefLeavesMixedPhasesLeastOver(t *testing.T) { } // A one-phase battery on L2, which Core reads as balanced, with L1 at 18 A -// while PV is low. Once PV returns, L1 still sits at 16.14 A, which the -// battery cannot reach. Before, the last-command bound held the -4882 W -// discharge for L1 and left L2 exporting 19.86 A, past 1.2 x In, on every -// tick. Now L2 comes back inside the line and the order holds. +// while PV is low. The first relief step, -1378 W, lands on L2 alone and +// takes it to -17.97 A of export. That step is what shows the battery off +// L1. Before, the relief then held that step: L2 stayed at -17.97 A for +// all 24 PV-low ticks and reached -19.83 A, past 1.2 x In, on the PV +// return tick. Now the battery goes back to its power before the step, +// and L2 is inside the line from the next tick until PV returns. +// +// Once PV returns, L1 still sits at 16.14 A, which the battery cannot +// reach, and L2 has less than 3 A of room (690 W on one phase). The relief +// creeps out to L2's line before the battery has moved the one ampere per +// phase the rule needs, and the least-over move then leaves L2 about as +// far past the export line as L1 is past the import line. That is the +// known limit of a one-phase battery read as balanced. func TestFuseReliefLetsAOnePhaseBatteryOffItsOwnPhase(t *testing.T) { r := pvDropRun(pvDropCase{onePhase: 2, load: [3]float64{20.78, 6, 11.54}}) - for i := 31; i < 40; i++ { - if math.Abs(r.batPhase[i]) > r.line+0.01 { - t.Errorf("tick %d: L2 %.2f A, want inside the %.1f A line", i, r.batPhase[i], r.line) + for i := 6; i < 40; i++ { + if math.Abs(r.batPhase[i]) > fuseInstantFactor*16 { + t.Errorf("tick %d: L2 %.2f A, past %.1f x In", i, r.batPhase[i], fuseInstantFactor) + } + if i >= 8 && i < 30 && math.Abs(r.batPhase[i]) > r.line+0.01 { + t.Errorf("tick %d: L2 %.2f A, want inside the %.1f A line while PV is low", i, r.batPhase[i], r.line) } - if r.targets[i] != r.targets[31] { - t.Errorf("tick %d: order %.0f W, want the %.0f W order held", i, r.targets[i], r.targets[31]) + if i >= 9 && i < 30 && r.targets[i] != r.targets[4] { + t.Errorf("tick %d: order %.0f W, want the %.0f W order from before the step", i, r.targets[i], r.targets[4]) + } + if i >= 30 && math.Abs(r.batPhase[i]) > r.line+0.25 { + t.Errorf("tick %d: L2 %.2f A, more than 0.25 A past the %.1f A line", i, r.batPhase[i], r.line) } } if t.Failed() { @@ -645,16 +666,29 @@ func TestFuseReliefStopsWhenTheMeterFreezesOffTheReference(t *testing.T) { // A one-phase battery on L2 and L1 at 16.3 A while PV is low. The battery // cannot reach L1, so L1 never shows its move. Before, the relief grew by // 0.3 A of overage a tick to -4512 W and drove L2 to -16.4 A of export, -// then -18.25 A on the PV return tick. Now it stops the same way as for a -// frozen meter, and L2 stays inside the line. +// then -18.25 A on the PV return tick. Now it stops once the battery has +// moved one ampere per phase, and goes back to the -3005 W hold: what it +// moved did not reach L1. L2 stays inside the line. func TestFuseReliefStopsWhenTheBatteryCannotReachTheWorstPhase(t *testing.T) { r := pvDropRun(pvDropCase{onePhase: 2, load: [3]float64{19.08, 6, 11.54}}) - assertReliefStops(t, r) + const floorW = -3214 - phaseResponseA*690 - 0.3*690 + for i := range r.targets { + if r.targets[i] < floorW { + t.Errorf("tick %d: order %.0f W, past %.0f W", i, r.targets[i], floorW) + } + if i >= 10 && r.targets[i] != -3005 { + t.Errorf("tick %d: order %.0f W, want the -3005 W hold back", i, r.targets[i]) + } + } for i, a := range r.batPhase { if math.Abs(a) > r.line+0.01 { t.Errorf("tick %d: L2 %.2f A, want inside the %.1f A line", i, a, r.line) } } + if t.Failed() { + t.Logf("targets %v", r.targets) + t.Logf("L2 %v", r.batPhase) + } } // assertReliefStops wants the order no further out than one ampere per @@ -706,7 +740,7 @@ func TestPhaseUnresponsiveNeedsOneAmpereOfBatteryMove(t *testing.T) { {"L1 0.1 A, L2 and L3 still", []float64{15.9, 9, 9.5}, -3000, false}, {"690 W back again, the meter repeats L1 0.1 A off the reference", []float64{15.9, 9, 9.5}, -2310, true}, } { - if _, got := st.phaseUnresponsive(c.amps, map[string]float64{"bat": c.batW}); got != c.stuck { + if _, got, _ := st.phaseUnresponsive(c.amps, 0, map[string]float64{"bat": c.batW}); got != c.stuck { t.Errorf("%s: stuck %v, want %v", c.name, got, c.stuck) } } @@ -804,3 +838,146 @@ func assertL1AtTheLine(t *testing.T, r pvDropResult, from, to int) { t.Logf("L1 %v", r.l1) } } + +// A P1 meter reports phase current in whole amperes. L1 reads 18 A after +// a 2070 W PV drop, and the relief steps -1380 W. A balanced 1.8 A load +// per phase starts in the reading that shows the step, so every phase +// rounds to the same ampere as before while the meter's total moves. +// Before, that counted as a frozen meter: the order stayed at -4385 W and +// the true L1 at 17.8 A (1.11 x In) to the end. A frozen meter repeats its +// total too, so the relief goes on. +func TestFuseReliefGoesOnWhenAWholeAmpereMeterRepeatsItsPhases(t *testing.T) { + r := pvDropRun(pvDropCase{ + resA: 1, + load: [3]float64{15 + 3005.0/690, 5 + 3005.0/690, 5 + 3005.0/690}, + pvW: func(tick int) float64 { + if tick >= 5 { + return 2070 + } + return 0 + }, + extra: func(tick int) [3]float64 { + if tick >= 6 { + return [3]float64{1.8, 1.8, 1.8} + } + return [3]float64{} + }, + }) + assertL1AtTheLine(t, r, 8, 40) +} + +// The relief holds L1 at the line through a slow PV fall, 69 W a tick. +// L1 stays within 0.1 A of its 16.3 A reading from the PV step, so that +// reading stayed the reference while the battery moved 899 W. A 2 kW +// one-phase load on L3 then switches off, which moves L3 by 6.9 balanced +// shares of that move, and a 0.4 A load starts on L1. Before, that read as +// a battery off L1: the order stayed at -3904 W and L1 at 16.4 A to the +// end. L1 at or inside the line ends the reference, so the relief goes on. +func TestFuseReliefFollowsALoadAfterADriftAtTheLine(t *testing.T) { + r := pvDropRun(pvDropCase{ + ticks: 50, + pvW: func(tick int) float64 { + switch { + case tick < 5: + return -3200 + case tick < 10: + return -1920 + case tick < 20: + return -1920 + 69*float64(tick-9) + } + return -1920 + 690 + }, + extra: func(tick int) [3]float64 { + var e [3]float64 + if tick >= 20 { + e[2] = -2000.0 / 230 + } + if tick >= 22 { + e[0] = 0.4 + } + return e + }, + }) + assertL1AtTheLine(t, r, 24, 50) +} + +// The same with a PV fall of 23 W a tick that goes on through the load +// change, so L1 reads 16.03 A, over the line, on every tick and the +// reference stays. A 1 kW load on L3 switches off at tick 30, 3 balanced +// shares of the battery's move, and a 0.4 A load starts on L1 at tick 32. +// Before, the order stayed at -3697 W and L1 climbed to 16.7 A, where it +// stayed. Now the battery goes back to its power when L1 last moved, which +// moves L1 by more than half an ampere on the next tick and ends the +// reference: L1 is at 16.9 A for that one tick, then at the line again. +func TestFuseReliefRecoversFromAFalseOffPhaseVerdict(t *testing.T) { + r := pvDropRun(pvDropCase{ + ticks: 60, + pvW: func(tick int) float64 { + switch { + case tick < 5: + return -3200 + case tick < 10: + return -1920 + case tick < 40: + return -1920 + 23*float64(tick-9) + } + return -1920 + 23*30 + }, + extra: func(tick int) [3]float64 { + var e [3]float64 + if tick >= 30 { + e[2] = -1000.0 / 230 + } + if tick >= 32 { + e[0] = 0.4 + } + return e + }, + }) + over := 0 + for i := 30; i < 60; i++ { + if r.l1[i] > r.line+0.05 { + over++ + } + if r.l1[i] > r.line+1 { + t.Errorf("tick %d: L1 %.2f A, more than 1 A over the %.1f A line", i, r.l1[i], r.line) + } + } + if over > 2 { + t.Errorf("L1 over the %.1f A line on %d ticks after the load change, want 2 at most", r.line, over) + } + assertL1AtTheLine(t, r, 40, 60) +} + +// The off-phase verdict holds until the worst phase's reference ends, and +// gives the batteries' power at that reference. The reference ends when +// the worst phase moves half an ampere, comes inside the line, or another +// phase becomes the worst. A meter whose phases repeat while its total +// moves is not frozen. +func TestPhaseUnresponsiveOffPhaseVerdictHoldsUntilTheReferenceEnds(t *testing.T) { + st := phaseDirectionState(0) + for _, c := range []struct { + name string + amps []float64 + totalW float64 + batW float64 + stuck bool + backTo float64 + }{ + {"first reading: a reference", []float64{16.3, -16.2, 9.5}, 1000, -3000, false, 0}, + {"L3 two shares: a battery off L1", []float64{16.3, -16.2, 7.5}, 300, -3690, true, -3000}, + {"battery back, L3 back: the verdict holds", []float64{16.3, -16.2, 9.5}, 1000, -3000, true, -3000}, + {"L1 0.15 A down, L2 the worst: a new reference", []float64{16.15, -16.2, 9.5}, 950, -3000, false, 0}, + {"L1 the worst again, no move", []float64{16.3, -15, 9.5}, 1300, -3000, false, 0}, + {"L3 two shares again", []float64{16.3, -15, 7.5}, 600, -3690, true, -3000}, + {"L1 at the line: a new reference", []float64{16, -15, 7.5}, 500, -3690, false, 0}, + {"L1 over, no move", []float64{16.3, -15, 7.5}, 600, -3690, false, 0}, + {"same phases, total moved: not frozen", []float64{16.3, -15, 7.5}, 650, -4380, false, 0}, + {"same phases, same total: frozen", []float64{16.3, -15, 7.5}, 650, -5070, true, 0}, + } { + _, stuck, backTo := st.phaseUnresponsive(c.amps, c.totalW, map[string]float64{"bat": c.batW}) + if stuck != c.stuck || backTo["bat"] != c.backTo { + t.Errorf("%s: stuck %v back to %v, want %v back to %v", c.name, stuck, backTo, c.stuck, c.backTo) + } + } +} From b36e95122075c74a89607efda987fc92c2160e86 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 04:03:58 +0100 Subject: [PATCH 49/68] test(control): the drift test also wants no verdict on the load change With L1 at the line ending the reference, no off-phase verdict comes when the load on L3 switches off. Without it, the step back still ends the hold, but with L1 at 16.8 and 17.7 A for two ticks; the test now sees that. Co-Authored-By: Claude Opus 5.5 --- go/internal/control/fuse_battery_phase_direction_test.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/go/internal/control/fuse_battery_phase_direction_test.go b/go/internal/control/fuse_battery_phase_direction_test.go index 592d3db12..199b43585 100644 --- a/go/internal/control/fuse_battery_phase_direction_test.go +++ b/go/internal/control/fuse_battery_phase_direction_test.go @@ -872,7 +872,10 @@ func TestFuseReliefGoesOnWhenAWholeAmpereMeterRepeatsItsPhases(t *testing.T) { // one-phase load on L3 then switches off, which moves L3 by 6.9 balanced // shares of that move, and a 0.4 A load starts on L1. Before, that read as // a battery off L1: the order stayed at -3904 W and L1 at 16.4 A to the -// end. L1 at or inside the line ends the reference, so the relief goes on. +// end. L1 at or inside the line ends the reference, so no verdict comes: +// L1 is over the line only on the tick the 0.4 A load starts. (Without +// that end, the step back of the next test ends the hold too, at the cost +// of two ticks with L1 at 16.8 and 17.7 A.) func TestFuseReliefFollowsALoadAfterADriftAtTheLine(t *testing.T) { r := pvDropRun(pvDropCase{ ticks: 50, @@ -898,7 +901,8 @@ func TestFuseReliefFollowsALoadAfterADriftAtTheLine(t *testing.T) { return e }, }) - assertL1AtTheLine(t, r, 24, 50) + assertL1AtTheLine(t, r, 20, 22) + assertL1AtTheLine(t, r, 23, 50) } // The same with a PV fall of 23 W a tick that goes on through the load From 281f9f63fb8b477a8ecaea087df6236cf570ac8b Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 04:18:08 +0100 Subject: [PATCH 50/68] test(control): our battery order's move is not the car's cut landing The guard in seeOffers that stops reading the meter while our battery order moves had no test; removing it left every test green. A battery order that lands and goes back while a cut travels to a 40 s charger now must not lead to a second cut. Co-Authored-By: Claude Opus 5.5 --- .../control/ev_fuse_cut_netting_test.go | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/go/internal/control/ev_fuse_cut_netting_test.go b/go/internal/control/ev_fuse_cut_netting_test.go index dcd70dafe..a19722814 100644 --- a/go/internal/control/ev_fuse_cut_netting_test.go +++ b/go/internal/control/ev_fuse_cut_netting_test.go @@ -482,3 +482,33 @@ func TestEVFuseOnePhaseHouseMoveIsNotTheCutLanding(t *testing.T) { } }) } + +// While our own battery order moves the phases, a move of every phase +// alike may be the battery's, so it is not read as the car's cut landing. +// A 3 A cut travels to a charger that declares 40 s. A battery order of +// 1 A a phase discharge lands and goes back: L1 reads 28, 27, then 28 A +// again. Read as the cut landing, the 1 A drop took a third of the cut's +// cover, and Core cut a second time, to 8,280 W, for an overage the first +// cut already covers. +func TestEVFuseBatteryOrderMoveIsNotTheCutLanding(t *testing.T) { + r := newCutRig(t, 11040, 40) // 16 A + for range 120 { + r.read([3]float64{20, 15, 15}) + } + for i := 0; i < 120 && r.offerW == 11040; i++ { + r.read([3]float64{28, 15, 15}) // 3 A over the 25 A line + } + if r.offerW != 8970 { + t.Fatalf("heat cut to %.0f W, want 8,970 W", r.offerW) + } + r.state.batteryCommands = map[string]commandLog{"bat": commandLog{}.add(r.now.Add(-time.Minute), 0).add(r.now, -690)} + for range 3 { + r.read([3]float64{27, 14, 14}) + } + r.state.batteryCommands["bat"] = r.state.batteryCommands["bat"].add(r.now, 0) + for range 8 { + if r.read([3]float64{28, 15, 15}); r.offerW != 8970 { + t.Fatalf("offer %.0f W after our battery order came and went, want the one cut to 8,970 W", r.offerW) + } + } +} From f29e96c300e5753cf5cb1a7136c2bdc0491a5d45 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 04:20:23 +0100 Subject: [PATCH 51/68] test(control): the car-first discharge stop has its own test Removing the PI path's immediate discharge stop left every named test green; only the golden replay caught it. A peak_shaving loop with battery_covers_ev off, starting from a 2.9 kW discharge while the house alone has surplus, now requires that no order discharges into the car. The comment on the plan back-off said the plan's grid leaves out the car. It counts the car it planned; the comment now says so. Co-Authored-By: Claude Opus 5.5 --- go/internal/control/dispatch.go | 5 ++++- go/internal/control/ev_car_before_battery_test.go | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 9c3922683..cc24ee053 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -1791,7 +1791,10 @@ func ComputeDispatch( // Below 100 W is meter noise. if currentDirective.HasPlannedGridW && targetTotalW > 0 { const planGridDeadband = 100.0 - // The plan's grid leaves out the car the battery does not cover. + // As before the car came first, the projection leaves out the + // car the battery does not cover, while the plan's grid counts + // the car it planned. The car's draw never starts this + // back-off. projectedGridW := noCarGridW + (targetTotalW - currentTotal) gridErr := projectedGridW - currentDirective.PlannedGridW if gridErr > planGridDeadband { diff --git a/go/internal/control/ev_car_before_battery_test.go b/go/internal/control/ev_car_before_battery_test.go index bce40ca2d..65e899c62 100644 --- a/go/internal/control/ev_car_before_battery_test.go +++ b/go/internal/control/ev_car_before_battery_test.go @@ -249,3 +249,18 @@ func TestCarBeforeBatteryPeakShavingChargesTheSurplusAfterTheCar(t *testing.T) { } } } + +// On the PI path with battery_covers_ev off, a discharge stops at once +// when the house alone has surplus: what it gives now goes to the car. The +// battery was discharging 2,900 W; 5 kW of PV beats the 3.6 kW house, and +// the car draws 11 kW. No order may discharge, not even as a PI step on +// the way to 0 W. +func TestCarBeforeBatteryCoverOffStopsADischargeForTheCarAtOnce(t *testing.T) { + const pv, house, car = 5000.0, 3611.0, 11040.0 + got := runPeakShavingCar(t, false, house+car-pv, car, -2900) + for i, w := range got { + if w < -1 { + t.Fatalf("tick %d: battery discharges %.0f W into the car with battery_covers_ev off: %v", i, w, got) + } + } +} From c9b52c3636c60ec19b41aa8c69e9cff4856743fc Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 04:25:38 +0100 Subject: [PATCH 52/68] fix(control): the battery rise check reads only live battery power fitBatteryRisesToFuse, unshownBatteryW and recordBatteryReadings read the battery's cached RawW, which survives the driver going offline, and added three direct telemetry reads that the repo-hygiene check refuses. They now use Store.OnlineRawW, as phaseSample.moveW does: an offline battery's last value no longer sets the rise base or the shown level. Co-Authored-By: Claude Opus 5.5 --- go/internal/control/dispatch.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index b75c30321..19bc2aafe 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -4065,8 +4065,8 @@ func (s *State) unshownBatteryW(now time.Time, store *telemetry.Store) float64 { if read, _, _, seen := s.batteryReadings[driver].span(now); seen { low = math.Min(low, read) } - if r := store.Get(driver, telemetry.DerBattery); r != nil { - low = math.Min(low, r.RawW) + if w, _, live := store.OnlineRawW(driver, telemetry.DerBattery); live { + low = math.Min(low, w) } unshown += math.Max(0, latest-low) } @@ -4081,14 +4081,14 @@ func (s *State) recordBatteryReadings(targets []DispatchTarget, store *telemetry } now := s.now() for _, t := range targets { - r := store.Get(t.Driver, telemetry.DerBattery) - if r == nil { + w, _, live := store.OnlineRawW(t.Driver, telemetry.DerBattery) + if !live { continue } if s.batteryReadings == nil { s.batteryReadings = map[string]commandLog{} } - s.batteryReadings[t.Driver] = s.batteryReadings[t.Driver].add(now, r.RawW) + s.batteryReadings[t.Driver] = s.batteryReadings[t.Driver].add(now, w) } } @@ -4133,8 +4133,8 @@ func fitBatteryRisesToFuse(targets []DispatchTarget, store *telemetry.Store, sta var base float64 if _, _, latest, sent := state.batteryCommands[t.Driver].span(now); sent { base = latest - } else if r := store.Get(t.Driver, telemetry.DerBattery); r != nil { - base = r.RawW + } else if w, _, live := store.OnlineRawW(t.Driver, telemetry.DerBattery); live { + base = w } roomW -= math.Max(0, math.Min(0, t.TargetW)-math.Min(0, base)) holds[i] = math.Min(t.TargetW, math.Max(0, base)) From ab027102ccbaf217db6f01625ce4c8d891babcd4 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 05:05:22 +0100 Subject: [PATCH 53/68] fix(control): judge a raise's landing from the meter's rise C4 counted a raise as landed only when a reading-to-reading move had a charger's shape. A slow ramp, or a house load on another phase that moved in the landing reading, left the whole raise counted as on its way on top of a reading that already held it, and Core cut a raise that fit under the line. The rise still to come now reads the meter's own rise since the raise went out: the smallest across the phases for a three-phase order, the car's phase for a one-phase car. For a three-phase order, a move on one phase alone no longer moves the shown level of a car not yet seen. A load cycling on the phase over the line took the cut's cover off on each drop and never gave it back, so Core cut again and again. Co-Authored-By: Claude Opus 5.5 --- .changeset/s1-ev-cut-landed-and-unshown.md | 2 +- go/internal/control/ev_fuse_budget.go | 88 ++++++++++--- .../control/ev_fuse_cut_netting_test.go | 120 +++++++++++++++--- 3 files changed, 171 insertions(+), 39 deletions(-) diff --git a/.changeset/s1-ev-cut-landed-and-unshown.md b/.changeset/s1-ev-cut-landed-and-unshown.md index 3e8cdb1fa..837c8c5e2 100644 --- a/.changeset/s1-ev-cut-landed-and-unshown.md +++ b/.changeset/s1-ev-cut-landed-and-unshown.md @@ -2,4 +2,4 @@ "ftw": patch --- -The car's fuse cut now acts on what the site meter shows. A cut the meter already shows no longer counts as still on its way, so when the house adds load after it, FTW cuts again once the fuse's heat budget is spent instead of waiting up to three minutes. A house load that moves on one phase alone is not taken for the car's cut landing, so it no longer stacks a second cut on a slow charger. A raise that is on its way but no longer fits now comes off before it lands, when it would take a phase above 1.2 times the fuse rating, or over the line on a phase whose heat budget is spent. For a car the site meter has shown on three phases, this also holds when the house steps up on one phase alone. +The car's fuse cut now acts on what the site meter shows. A cut the meter already shows no longer counts as still on its way, so when the house adds load after it, FTW cuts again once the fuse's heat budget is spent instead of waiting up to three minutes. A house load that moves on one phase alone is not taken for the car's cut landing, so it no longer stacks a second cut on a slow charger. A raise that is on its way but no longer fits now comes off before it lands, when it would take a phase above 1.2 times the fuse rating, or over the line on a phase whose heat budget is spent. FTW judges how much of the raise has landed from the meter's smallest rise across the phases, so a house step on one phase does not hide a raise that has not landed. diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index d6d5601e1..34534c1b3 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -188,6 +188,14 @@ type chargerOffers struct { // cannot. shownA [3]float64 unsure bool + // riseBaseA is the site meter's phase currents when a raise went out + // with no other raise still to show, and riseFromA the most of the + // charger's offers that reading may have shown. riseAheadA measures the + // rise still to come against them; riseSet is false while no raise is + // on its way. + riseBaseA [3]float64 + riseFromA float64 + riseSet bool } // evMoveA is half a charger step. An order landing shows on the site meter @@ -230,17 +238,16 @@ func chargerMoveA(prev, now []float64) (alikeA, oneA float64, phase int) { // car the loadpoint has seen draw on one phase, or a one-phase order, is // one level on every phase: every phase dropping alike moves it, and so // does a move on the car's phase alone, or on any one phase while that -// phase is not known. A three-phase order moves every phase alike; for a -// car not yet seen on three phases, a phase that moves alone moves only -// its own level, since a one-phase car would draw there. A house load on -// one phase then never moves the level of the other two. -// The shown current moves only toward the latest offer, and stays within -// the offers the reading may show. While our own battery order moves, a -// move of every phase alike may be the battery's, so no reading counts; -// after a reading that did not count, the shown current is known again -// once only one offer may show. A house load that moves in a charger's -// shape reads as ours. It can only take cover off a cut, or leave our rise -// to the meter as before. +// phase is not known. A three-phase order moves only on every phase alike: +// a phase that moves alone is a house load, or a car not yet seen that +// draws on one phase, and Core cannot tell which. The shown current moves +// only toward the latest offer, and stays within the offers the reading +// may show. While our own battery order moves, a move of every phase alike +// may be the battery's, so no reading counts; after a reading that did not +// count, the shown current is known again once only one offer may show. A +// house load that moves in a charger's shape reads as ours. It can only +// take cover off a cut. The rise a raise has still to show reads the meter +// differently (riseAheadA). func (s *State) seeOffers(meter *telemetry.DerReading, gridW float64) { lim := &s.evLimit amps, _, valid := phaseCurrentsA(meter, s, gridW) @@ -266,13 +273,11 @@ func (s *State) seeOffers(meter *telemetry.DerReading, gridW float64) { } moveA = [3]float64{m, m, m} default: - // A three-phase order moves every phase alike. A car not - // yet seen may draw on one phase: a phase that moves alone - // moves only its own level. + // A three-phase order moves every phase alike. Read as the + // car, a load cycling on the phase over the line took the + // cut's cover off there on each drop and never gave it + // back, and Core cut again and again. moveA = [3]float64{alikeA, alikeA, alikeA} - if c.carPhases != 3 && phase > 0 { - moveA[phase-1] += oneA - } } // The charger moves toward its latest offer, never past it. latestA := c.log[len(c.log)-1].a @@ -291,6 +296,9 @@ func (s *State) seeOffers(meter *telemetry.DerReading, gridW float64) { c.shownA[i] = math.Min(high, math.Max(low, c.shownA[i])) } c.unsure = c.unsure && low < high + if ahead := s.riseAheadA(c); low >= high || ahead == [3]float64{} { + c.riseSet = false + } lim.offers[id] = c } } @@ -397,9 +405,9 @@ func (s *State) pendingLoad(at time.Time) pendingLoad { // Where the meter tells what it shows of the charger (seeOffers), a cut // covers no more than the meter has still to show on each phase: a cut the // meter shows covers no overage that comes after it. aheadA is then the -// rise on each phase the meter has still to show of the latest offers, -// which a raise's own trigger reads (stepEVMeterLimit), and rise counts at -// least that much. Elsewhere aheadA is 0. +// rise on each phase the meter has still to show of the latest offers +// (riseAheadA), which a raise's own trigger reads (stepEVMeterLimit), and +// rise counts at least that much. Elsewhere aheadA is 0. func (s *State) unshownOrders(at time.Time, perPhase bool) (rise, cover pendingLoad, aheadA [3]float64, latestW float64) { lim := &s.evLimit for _, c := range lim.offers { @@ -425,10 +433,10 @@ func (s *State) unshownOrders(at time.Time, perPhase bool) (rise, cover pendingL phaseCoverA, phaseRiseA, ahead := [3]float64{coverA, coverA, coverA}, [3]float64{riseA, riseA, riseA}, [3]float64{} if perPhase && lim.phasesSeen && len(lim.offers) == 1 && s.SiteFusePhases >= 2 && c.readable() && !c.unsure { low, high := c.offerRangeA(at) + ahead = s.riseAheadA(c) for i := range min(s.SiteFusePhases, len(ahead)) { toComeA := latest.a - math.Min(high, math.Max(low, c.shownA[i])) phaseCoverA[i] = math.Min(coverA, math.Max(0, -toComeA)) - ahead[i] = math.Max(0, toComeA) phaseRiseA[i] = math.Max(riseA, ahead[i]) } } @@ -444,6 +452,42 @@ func (s *State) unshownOrders(at time.Time, perPhase bool) (rise, cover pendingL return rise, cover, aheadA, latestW } +// riseAheadA is the rise on each phase the site meter has still to show +// of the charger's latest offer: the raise since riseFromA less the meter's +// own rise since the raise went out, within the offers the reading may +// show. A three-phase order takes the smallest rise across the phases: a +// house step on some phases does not show the raise on the rest. A car on +// one phase takes its own phase's rise, or the largest where the phase is +// not known. A landing counts in whatever shape it comes, a slow ramp or +// beside a house load that moves in the same reading. A house load that +// drops while the raise travels still reads as raise not shown yet, by +// as much as it dropped. +func (s *State) riseAheadA(c chargerOffers) (ahead [3]float64) { + lim := &s.evLimit + n := min(s.SiteFusePhases, len(ahead)) + if !c.riseSet || !lim.phasesSeen || n < 2 || len(c.log) == 0 { + return ahead + } + latest := c.log[len(c.log)-1] + rises := make([]float64, n) + for i := range rises { + rises[i] = lim.phasesA[i] - c.riseBaseA[i] + } + riseA, phases := slices.Min(rises), ahead[:n] + switch { + case c.carPhase > 0 && c.carPhase <= n: + riseA, phases = rises[c.carPhase-1], ahead[c.carPhase-1:c.carPhase] + case c.carPhases == 1 || latest.n == 1: + riseA = slices.Max(rises) + } + low, high := c.offerRangeA(lim.readingAt) + toComeA := math.Max(0, latest.a-math.Min(high, math.Max(low, c.riseFromA+riseA))) + for i := range phases { + phases[i] = toComeA + } + return ahead +} + // recordEVOffers keeps each plugged charger's offers, with the current each // puts on the phases its command names, for the longer of evSettle and the // power_max_age_s its driver declares, or evUnknownSettle when it declares @@ -472,6 +516,8 @@ func (s *State) recordEVOffers(store *telemetry.Store, points []loadpoint.State) if n := len(c.log); n == 0 || c.log[n-1].w != sent.w || c.log[n-1].a != sent.a || c.log[n-1].n != sent.n { if n == 0 && !s.evLimit.set { c.found, c.shownA = sent, [3]float64{sent.a, sent.a, sent.a} + } else if _, high := c.offerRangeA(now); sent.a > high && !c.riseSet && s.evLimit.phasesSeen { + c.riseBaseA, c.riseFromA, c.riseSet = s.evLimit.phasesA, high, true } c.log = c.log.keep(sent, read.Add(-c.settle)) } diff --git a/go/internal/control/ev_fuse_cut_netting_test.go b/go/internal/control/ev_fuse_cut_netting_test.go index a19722814..d7291b1ae 100644 --- a/go/internal/control/ev_fuse_cut_netting_test.go +++ b/go/internal/control/ev_fuse_cut_netting_test.go @@ -415,23 +415,24 @@ func TestEVFuseRaiseOnItsWayThatNoLongerFitsCutsAtOnce(t *testing.T) { } } -// The C4 case as the triage wrote it, with only L1 moving, for a car the -// loadpoint has seen draw on three phases. A house step on L1 alone is then -// not the raise landing: the raise would take L1 to 25.7 A, over 1.2 x In, -// so it comes off on that reading. For a car not yet seen, a step on one -// phase may be a one-phase car taking the raise; the meter judges it then. -func TestEVFuseRaiseOnItsWayCutsForACarSeenOnThreePhases(t *testing.T) { - r := newCutRig(t, 4140, 40) - r.state.SiteFuseAmps, r.carPhases = 16, 3 - for range 60 { - r.read([3]float64{6, 6, 6}) - } - r.offerW = 11040 // 6 -> 16 A - for range 30 { - r.read([3]float64{6, 6, 6}) - } - if r.read([3]float64{15.7, 6, 6}); r.offerW > 4140 { - t.Fatalf("offer %.0f W with L1 at 15.7 A and 10 A on its way, want 4,140 W or less", r.offerW) +// The C4 case as the triage wrote it, with only L1 moving. L2 and L3 have +// not risen, so the three-phase raise has not landed, whether or not the +// loadpoint has seen the car draw on three phases: the raise would take L1 +// to 25.7 A, over 1.2 x In, so it comes off on that reading. +func TestEVFuseRaiseOnItsWayCutsOnAOnePhaseHouseStep(t *testing.T) { + for _, carPhases := range []int{0, 3} { + r := newCutRig(t, 4140, 40) + r.state.SiteFuseAmps, r.carPhases = 16, carPhases + for range 60 { + r.read([3]float64{6, 6, 6}) + } + r.offerW = 11040 // 6 -> 16 A + for range 30 { + r.read([3]float64{6, 6, 6}) + } + if r.read([3]float64{15.7, 6, 6}); r.offerW > 4140 { + t.Fatalf("car phases %d: offer %.0f W with L1 at 15.7 A and 10 A on its way, want 4,140 W or less", carPhases, r.offerW) + } } } @@ -512,3 +513,88 @@ func TestEVFuseBatteryOrderMoveIsNotTheCutLanding(t *testing.T) { } } } + +// A raise that fits lands, and no phase passes the line, so nothing cuts. +// 16 A fuse, charger that declares 40 s, car from 6 A to 14 A while every +// phase has 8 A of room. Before, C4 counted a landing only when the move +// had a charger's shape. A house load on L2 that switched off in the +// landing reading, or a car that ramped 0.4 A a reading, left the whole +// raise counted as on its way on top of a reading that already held it: +// 14 + 8 A read as over 1.2 x In, and Core cut to 5,520 or 6,900 W. +func TestEVFuseRaiseThatLandedIsNotCountedTwice(t *testing.T) { + for _, tc := range []struct { + name string + l2 float64 // L2 before the landing; it reads 14 A after + carPhases int + }{ + {"clean", 6, 0}, + {"house_off_on_L2_1.2A", 7.2, 0}, + {"house_off_on_L2_2A", 8, 0}, + {"house_off_on_L2_2A_car_seen_on_three_phases", 8, 3}, + } { + t.Run(tc.name, func(t *testing.T) { + r := newCutRig(t, 4140, 40) + r.state.SiteFuseAmps, r.carPhases = 16, tc.carPhases + for range 60 { + r.read([3]float64{6, tc.l2, 6}) + } + r.offerW = 9660 // 6 -> 14 A + for range 10 { + r.read([3]float64{6, tc.l2, 6}) + } + for i := range 120 { + if r.read([3]float64{14, 14, 14}); r.offerW != 9660 { + t.Fatalf("raise that landed at 14/14/14 A cut to %.0f W after %d s", r.offerW, i+1) + } + } + }) + } + for _, carPhases := range []int{0, 3} { + t.Run(fmt.Sprintf("slow_ramp_car_phases_%d", carPhases), func(t *testing.T) { + r := newCutRig(t, 4140, 40) + r.state.SiteFuseAmps, r.carPhases = 16, carPhases + for range 60 { + r.read([3]float64{6, 6, 6}) + } + r.offerW = 9660 + r.read([3]float64{6, 6, 6}) + a := 6.0 + for i := range 120 { + a = math.Min(14, a+0.4) + if r.read([3]float64{a, a, a}); r.offerW != 9660 { + t.Fatalf("raise ramping to 14 A cut to %.0f W at %.1f A after %d s", r.offerW, a, i+1) + } + } + }) + } +} + +// A one-phase load that cycles on a phase is not a three-phase cut landing, +// even for a car not yet seen on three phases. The house falls from 18 to +// 10 A a phase, so the car rises toward the line, while 1.5 A on L2 +// toggles. Before, each drop of the load read as the cut landing on L2 and +// took its cover off there; the load's return could not give it back, so +// Core cut again and again: 9,660 down to 4,830 W and up, 21 cuts in 20 min +// with a 40 s charger. #1913 cut once. +func TestEVFuseLoadCyclingOnTheOverPhaseDoesNotHunt(t *testing.T) { + for _, period := range []int{3, 11} { + t.Run(fmt.Sprintf("every_%ds", period), func(t *testing.T) { + s := newEVMeterSite(t, 0, 18*690) + s.chargerDelay, s.chargerMaxAgeS = 40*time.Second, 40 + s.run(5 * time.Minute) + s.setHouse(10 * 690) + stepAt := s.now + loadA := 1.5 + for i := range 20 * 60 { + if i%period == 0 { + s.addHouseA(0, loadA, 0) + loadA = -loadA + } + s.step() + } + if cuts := offerWatts(s.cutsSince(stepAt)); len(cuts) > 1 { + t.Fatalf("cuts %v; one is enough", cuts) + } + }) + } +} From 53b8aa3410be12a209a2a7802822e03d40865584 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 05:10:32 +0100 Subject: [PATCH 54/68] fix(control): a car not yet seen may take a raise on one phase The smallest rise across the phases read a one-phase car not yet seen as a raise that had not landed: its phase rose, the other two did not. Core then cut the car from 11040 W to 0 with every phase under the line (field matrix, car1p cases). One phase that has risen alone since the raise went out, the others within half a step, now counts as that car taking the raise, as the shape tracker read it before. The changeset again says what holds: the one-phase house step case is closed for a car seen on three phases. Co-Authored-By: Claude Opus 5.5 --- .changeset/s1-ev-cut-landed-and-unshown.md | 2 +- go/internal/control/ev_fuse_budget.go | 7 +++- .../control/ev_fuse_cut_netting_test.go | 35 +++++++++---------- 3 files changed, 24 insertions(+), 20 deletions(-) diff --git a/.changeset/s1-ev-cut-landed-and-unshown.md b/.changeset/s1-ev-cut-landed-and-unshown.md index 837c8c5e2..3e8cdb1fa 100644 --- a/.changeset/s1-ev-cut-landed-and-unshown.md +++ b/.changeset/s1-ev-cut-landed-and-unshown.md @@ -2,4 +2,4 @@ "ftw": patch --- -The car's fuse cut now acts on what the site meter shows. A cut the meter already shows no longer counts as still on its way, so when the house adds load after it, FTW cuts again once the fuse's heat budget is spent instead of waiting up to three minutes. A house load that moves on one phase alone is not taken for the car's cut landing, so it no longer stacks a second cut on a slow charger. A raise that is on its way but no longer fits now comes off before it lands, when it would take a phase above 1.2 times the fuse rating, or over the line on a phase whose heat budget is spent. FTW judges how much of the raise has landed from the meter's smallest rise across the phases, so a house step on one phase does not hide a raise that has not landed. +The car's fuse cut now acts on what the site meter shows. A cut the meter already shows no longer counts as still on its way, so when the house adds load after it, FTW cuts again once the fuse's heat budget is spent instead of waiting up to three minutes. A house load that moves on one phase alone is not taken for the car's cut landing, so it no longer stacks a second cut on a slow charger. A raise that is on its way but no longer fits now comes off before it lands, when it would take a phase above 1.2 times the fuse rating, or over the line on a phase whose heat budget is spent. For a car the site meter has shown on three phases, this also holds when the house steps up on one phase alone. diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index 34534c1b3..1747f0b96 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -458,7 +458,9 @@ func (s *State) unshownOrders(at time.Time, perPhase bool) (rise, cover pendingL // show. A three-phase order takes the smallest rise across the phases: a // house step on some phases does not show the raise on the rest. A car on // one phase takes its own phase's rise, or the largest where the phase is -// not known. A landing counts in whatever shape it comes, a slow ramp or +// not known. For a car not yet seen on three phases, one phase that has +// risen alone, the others within evMoveA, may be the car taking the raise +// on one phase. A landing counts in whatever shape it comes, a slow ramp or // beside a house load that moves in the same reading. A house load that // drops while the raise travels still reads as raise not shown yet, by // as much as it dropped. @@ -474,11 +476,14 @@ func (s *State) riseAheadA(c chargerOffers) (ahead [3]float64) { rises[i] = lim.phasesA[i] - c.riseBaseA[i] } riseA, phases := slices.Min(rises), ahead[:n] + _, oneA, _ := chargerMoveA(c.riseBaseA[:n], lim.phasesA[:n]) switch { case c.carPhase > 0 && c.carPhase <= n: riseA, phases = rises[c.carPhase-1], ahead[c.carPhase-1:c.carPhase] case c.carPhases == 1 || latest.n == 1: riseA = slices.Max(rises) + case c.carPhases != 3 && oneA > 0: + riseA = oneA // A car not yet seen may draw on the one phase that rose. } low, high := c.offerRangeA(lim.readingAt) toComeA := math.Max(0, latest.a-math.Min(high, math.Max(low, c.riseFromA+riseA))) diff --git a/go/internal/control/ev_fuse_cut_netting_test.go b/go/internal/control/ev_fuse_cut_netting_test.go index d7291b1ae..9ee869a12 100644 --- a/go/internal/control/ev_fuse_cut_netting_test.go +++ b/go/internal/control/ev_fuse_cut_netting_test.go @@ -415,24 +415,23 @@ func TestEVFuseRaiseOnItsWayThatNoLongerFitsCutsAtOnce(t *testing.T) { } } -// The C4 case as the triage wrote it, with only L1 moving. L2 and L3 have -// not risen, so the three-phase raise has not landed, whether or not the -// loadpoint has seen the car draw on three phases: the raise would take L1 -// to 25.7 A, over 1.2 x In, so it comes off on that reading. -func TestEVFuseRaiseOnItsWayCutsOnAOnePhaseHouseStep(t *testing.T) { - for _, carPhases := range []int{0, 3} { - r := newCutRig(t, 4140, 40) - r.state.SiteFuseAmps, r.carPhases = 16, carPhases - for range 60 { - r.read([3]float64{6, 6, 6}) - } - r.offerW = 11040 // 6 -> 16 A - for range 30 { - r.read([3]float64{6, 6, 6}) - } - if r.read([3]float64{15.7, 6, 6}); r.offerW > 4140 { - t.Fatalf("car phases %d: offer %.0f W with L1 at 15.7 A and 10 A on its way, want 4,140 W or less", carPhases, r.offerW) - } +// The C4 case as the triage wrote it, with only L1 moving, for a car the +// loadpoint has seen draw on three phases. A house step on L1 alone is then +// not the raise landing: the raise would take L1 to 25.7 A, over 1.2 x In, +// so it comes off on that reading. For a car not yet seen, a step on one +// phase may be a one-phase car taking the raise; the meter judges it then. +func TestEVFuseRaiseOnItsWayCutsForACarSeenOnThreePhases(t *testing.T) { + r := newCutRig(t, 4140, 40) + r.state.SiteFuseAmps, r.carPhases = 16, 3 + for range 60 { + r.read([3]float64{6, 6, 6}) + } + r.offerW = 11040 // 6 -> 16 A + for range 30 { + r.read([3]float64{6, 6, 6}) + } + if r.read([3]float64{15.7, 6, 6}); r.offerW > 4140 { + t.Fatalf("offer %.0f W with L1 at 15.7 A and 10 A on its way, want 4,140 W or less", r.offerW) } } From 8a10b27dcaa60fbac0f5f3b852b5e0f1303ef814 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 06:00:30 +0100 Subject: [PATCH 55/68] fix(control): judge a one-phase landing reading by reading For a car not yet seen on three phases, a raise counted as landed on one phase only while the other phases stayed within 0.5 A of their reading when the raise went out. That window spans the charger's whole response time, so 0.6 A of house drift on another phase made the full raise count as still to come on top of a reading that already showed it, and Core cut the car with every phase under the line (field matrix with 0.7 A on L2: car1p cut 11100 -> 0 W). Each phase now keeps its rise over the readings in which the other phases moved less than a step (aloneA). A rise of a step or more there may be the car on that phase. Drift between readings, or under a step in the landing reading, no longer hides it; a house load that moves a step or more on another phase in the same reading still does. Co-Authored-By: Claude Opus 5.5 --- go/internal/control/ev_fuse_budget.go | 50 +++++++++++++++---- .../control/ev_fuse_cut_netting_test.go | 42 ++++++++++++++++ 2 files changed, 82 insertions(+), 10 deletions(-) diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index 1747f0b96..95b41bd1e 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -196,6 +196,10 @@ type chargerOffers struct { riseBaseA [3]float64 riseFromA float64 riseSet bool + // aloneA is each phase's rise since riseBaseA counted only over the + // readings in which the other phases moved less than a step: the rise + // a car on that one phase may have made (riseAheadA). + aloneA [3]float64 } // evMoveA is half a charger step. An order landing shows on the site meter @@ -261,6 +265,9 @@ func (s *State) seeOffers(meter *telemetry.DerReading, gridW float64) { alikeA, oneA, phase = chargerMoveA(prev[:len(amps)], now[:len(amps)]) } for id, c := range lim.offers { + if read && c.riseSet { + c.aloneA = addAloneA(c.aloneA, prev[:len(amps)], now[:len(amps)]) + } if read && c.readable() { var moveA [3]float64 switch { @@ -303,6 +310,22 @@ func (s *State) seeOffers(meter *telemetry.DerReading, gridW float64) { } } +// addAloneA adds to each phase's alone rise its move from one reading to +// the next when every other phase moved less than a step (evStepA): no +// charger step landed there, so the move may be a car on that one phase. +func addAloneA(aloneA [3]float64, prev, now []float64) [3]float64 { + for p := range now { + held := true + for q := range now { + held = held && (q == p || math.Abs(now[q]-prev[q]) < evStepA) + } + if held { + aloneA[p] += now[p] - prev[p] + } + } + return aloneA +} + // batteryOrderMoves reports whether one of our battery orders of the last // evSettle moves the site's phases by evMoveA or more. func (s *State) batteryOrderMoves() bool { @@ -458,12 +481,15 @@ func (s *State) unshownOrders(at time.Time, perPhase bool) (rise, cover pendingL // show. A three-phase order takes the smallest rise across the phases: a // house step on some phases does not show the raise on the rest. A car on // one phase takes its own phase's rise, or the largest where the phase is -// not known. For a car not yet seen on three phases, one phase that has -// risen alone, the others within evMoveA, may be the car taking the raise -// on one phase. A landing counts in whatever shape it comes, a slow ramp or -// beside a house load that moves in the same reading. A house load that -// drops while the raise travels still reads as raise not shown yet, by -// as much as it dropped. +// not known. For a car not yet seen on three phases, a phase that has +// risen a step or more alone may be the car taking the raise on one phase: +// its rise over the readings in which the other phases moved less than a +// step (aloneA). Each reading is judged against the one before, so house +// drift on another phase while the raise travels, or under a step in the +// landing reading, does not hide it. A landing counts in whatever shape +// it comes, a slow ramp or beside a house load that moves in the same +// reading. A house load that drops while the raise travels still reads as +// raise not shown yet, by as much as it dropped. func (s *State) riseAheadA(c chargerOffers) (ahead [3]float64) { lim := &s.evLimit n := min(s.SiteFusePhases, len(ahead)) @@ -476,14 +502,18 @@ func (s *State) riseAheadA(c chargerOffers) (ahead [3]float64) { rises[i] = lim.phasesA[i] - c.riseBaseA[i] } riseA, phases := slices.Min(rises), ahead[:n] - _, oneA, _ := chargerMoveA(c.riseBaseA[:n], lim.phasesA[:n]) switch { case c.carPhase > 0 && c.carPhase <= n: riseA, phases = rises[c.carPhase-1], ahead[c.carPhase-1:c.carPhase] case c.carPhases == 1 || latest.n == 1: riseA = slices.Max(rises) - case c.carPhases != 3 && oneA > 0: - riseA = oneA // A car not yet seen may draw on the one phase that rose. + case c.carPhases != 3: + // A car not yet seen may draw on a phase that rose alone. + for i := range rises { + if c.aloneA[i] >= 2*evMoveA { + riseA = math.Max(riseA, math.Min(c.aloneA[i], rises[i])) + } + } } low, high := c.offerRangeA(lim.readingAt) toComeA := math.Max(0, latest.a-math.Min(high, math.Max(low, c.riseFromA+riseA))) @@ -522,7 +552,7 @@ func (s *State) recordEVOffers(store *telemetry.Store, points []loadpoint.State) if n == 0 && !s.evLimit.set { c.found, c.shownA = sent, [3]float64{sent.a, sent.a, sent.a} } else if _, high := c.offerRangeA(now); sent.a > high && !c.riseSet && s.evLimit.phasesSeen { - c.riseBaseA, c.riseFromA, c.riseSet = s.evLimit.phasesA, high, true + c.riseBaseA, c.riseFromA, c.riseSet, c.aloneA = s.evLimit.phasesA, high, true, [3]float64{} } c.log = c.log.keep(sent, read.Add(-c.settle)) } diff --git a/go/internal/control/ev_fuse_cut_netting_test.go b/go/internal/control/ev_fuse_cut_netting_test.go index 9ee869a12..6a6e0479b 100644 --- a/go/internal/control/ev_fuse_cut_netting_test.go +++ b/go/internal/control/ev_fuse_cut_netting_test.go @@ -568,6 +568,48 @@ func TestEVFuseRaiseThatLandedIsNotCountedTwice(t *testing.T) { } } +// A one-phase car the loadpoint has not seen yet takes a three-phase raise +// on L1 while the house drifts on L2. 25 A fuse, 40 s charger: the car goes +// from 6 to 16 A, L1 lands at 24 A, and no phase is ever over the line. +// Before, the one-phase landing counted only while L2 stayed within 0.5 A +// of its reading when the raise went out, over the whole response time: +// 0.6 A of drift made the raise count as still to come, L1 read 34 A, and +// Core cut to 4,830 W one second after the landing (field matrix with +// 0.7 A on L2 every 17 s: car1p cut 11,100 -> 0 W). The landing now counts +// when L2 moves less than a step in the reading it lands on, or drifts +// before it. +func TestEVFuseUnseenOnePhaseCarLandsBesideDrift(t *testing.T) { + for _, tc := range []struct { + name string + before, landA float64 // L2 drift before the landing, and in its reading + }{ + {"no_drift", 0, 0}, + {"drift_0.6A_before", 0.6, 0}, + {"drift_1A_before", 1, 0}, + {"drift_-0.6A_before", -0.6, 0}, + {"drift_0.7A_in_the_landing_reading", 0, 0.7}, + {"drift_-0.7A_in_the_landing_reading", 0, -0.7}, + } { + t.Run(tc.name, func(t *testing.T) { + r := newCutRig(t, 4140, 40) // 6 A a phase ordered + for range 120 { + r.read([3]float64{14, 5, 5}) // car 6 A on L1, house 8 A + } + r.offerW = 11040 // 16 A + r.read([3]float64{14, 5, 5}) + for range 10 { + r.read([3]float64{14, 5 + tc.before, 5}) + } + l2 := 5 + tc.before + tc.landA + for i := range 120 { + if r.read([3]float64{24, l2, 5}); r.offerW != 11040 { + t.Fatalf("one-phase car landed at 24 A on a 25 A fuse, L2 %.1f A: cut to %.0f W after %d s", l2, r.offerW, i+1) + } + } + }) + } +} + // A one-phase load that cycles on a phase is not a three-phase cut landing, // even for a car not yet seen on three phases. The house falls from 18 to // 10 A a phase, so the car rises toward the line, while 1.5 A on L2 From 6b10baa1d8ad158e37415efa7e8317727fcffb07 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 06:19:41 +0100 Subject: [PATCH 56/68] fix(control): restart credit keeps room for the car's rise to its max After a restart Core does not know the offer in force on the charger, so a car drawing below it may still rise before Core's order lands. The credit now counts only the draw less that possible rise past the latest offer, with the rise measured to the loadpoint's max_charge_w; a charger with no max_charge_w gets no credit. The charger and output reads move into health-gated telemetry accessors (OnlineLowerW, SumOnlineHigherW). Tests cover the raw and smoothed guards, a 10 s OCPP sample cadence on the plant, and the review's car rising under a 16 A offer in force. Co-Authored-By: Claude Opus 5.5 --- .changeset/s4-ev-base-after-restart.md | 2 +- .../control/ev_base_after_restart_test.go | 167 +++++++++++++++--- go/internal/control/ev_battery_headroom.go | 2 +- go/internal/control/ev_fuse_budget.go | 63 +++---- go/internal/control/sitesim_test.go | 18 +- go/internal/telemetry/store.go | 30 ++++ go/internal/telemetry/telemetry_test.go | 43 +++++ 7 files changed, 264 insertions(+), 61 deletions(-) diff --git a/.changeset/s4-ev-base-after-restart.md b/.changeset/s4-ev-base-after-restart.md index 8fcee1181..4e7dcd404 100644 --- a/.changeset/s4-ev-base-after-restart.md +++ b/.changeset/s4-ev-base-after-restart.md @@ -2,4 +2,4 @@ "ftw": patch --- -After a restart, the home battery no longer stays in discharge for a car the meter already shows charging. Until the charger's first order of the new run can have landed, the battery counts the car's measured draw as part of the meter reading, never above FTW's latest order to the car and never above the consumption the site meter shows. The draw counts only when the charger measured it within one control interval of the site reading and its last poll succeeded. Before, the 0 A orders FTW sent while the meter was still starting counted as the car's draw, so a lower order looked like a rise and the battery kept discharging toward its floor. +After a restart, the home battery no longer stays in discharge for a car the meter already shows charging. Until the charger's first order of the new run can have landed, the battery counts the car's measured draw as part of the meter reading, never above FTW's latest order to the car and never above the consumption the site meter shows. FTW does not know the charger's offer in force then, so the battery still keeps room for the car to rise from its draw to the charger's max_charge_w; a charger with no max_charge_w gets no such credit. The draw counts only when the charger measured it within one control interval of the site reading and its last poll succeeded, so a charger that samples every 30 s or more rarely gets it. Before, the 0 A orders FTW sent while the meter was still starting counted as the car's draw, so a lower order looked like a rise and the battery kept discharging toward its floor. diff --git a/go/internal/control/ev_base_after_restart_test.go b/go/internal/control/ev_base_after_restart_test.go index 772ac34bc..a4691b164 100644 --- a/go/internal/control/ev_base_after_restart_test.go +++ b/go/internal/control/ev_base_after_restart_test.go @@ -15,9 +15,10 @@ import ( // no margin, a battery FTW found discharging 5 kW, and a charger whose first // logged offers of this run are 0 A, sent while the meter was stale, then // 6,210 W (9 A on three phases) 2 s ago. The charger takes 40 s to apply an -// order, so the car still draws what it drew before the restart. evW is -// what the charger measures; the site meter reads gridW with the phase -// currents phaseA, and the PV inverter pvW. +// order, so the car still draws what it drew before the restart. Its +// max_charge_w is 11,040 W (16 A). evW is what the charger measures; the +// site meter reads gridW with the phase currents phaseA, and the PV +// inverter pvW. func restartFixture(t *testing.T, gridW float64, phaseA [3]float64, batteryW, pvW, evW float64) (*telemetry.Store, *State) { t.Helper() store := telemetry.NewStore() @@ -45,7 +46,7 @@ func restartFixture(t *testing.T, gridW float64, phaseA [3]float64, batteryW, pv state.evLimit.set = true state.evLimit.offers = map[string]chargerOffers{"garage": { log: commandLog{found, {at: now.Add(-4 * time.Second), w: 0, a: 0, n: 3}, {at: now.Add(-2 * time.Second), w: 6210, a: 9, n: 3}}, - settle: evUnknownSettle, found: found, driver: "charger", + settle: evUnknownSettle, found: found, driver: "charger", maxW: 11040, }} return store, state } @@ -54,14 +55,35 @@ func restartFixture(t *testing.T, gridW float64, phaseA [3]float64, batteryW, pv // while the meter was stale counted as the EV base the meter shows, while // the meter showed the car at 8.2 kW. The new 6.2 kW order then counted as // a 9 A rise to come, and the battery was held in discharge for the car -// with battery_covers_ev off, down toward its floor. The car's measured -// draw is in the reading: the 6.2 kW order is a cut, and ending the -// discharge needs no room for it. +// with battery_covers_ev off, down toward its floor (-3,599 W here). The +// car's measured draw is in the reading: the 6.2 kW order is a cut. Until +// it lands the car may still rise to the 16 A of an offer Core does not +// know, so the battery keeps only the discharge that rise needs on L2. func TestEVBaseAfterRestartCreditsMeasuredDraw(t *testing.T) { store, state := restartFixture(t, 780, [3]float64{2.03, 4.97, .47}, -5000, -3000, 8222) out := clampEVBatteryHeadroom([]DispatchTarget{{Driver: "sungrow", TargetW: 0}}, store, state, 16*230*3) - if got := targetW(out, "sungrow"); got < -1 { - t.Fatalf("battery held at %.0f W for a car the meter already shows at 8.2 kW; want 0 W", got) + riseA := (11040 - 8222) / 690.0 + want := -(5000 - (16-4.97-riseA)*690) + if got := targetW(out, "sungrow"); math.Abs(got-want) > 1 { + t.Fatalf("battery %.0f W, want %.0f W: only the car's rise to its 16 A max needs room", got, want) + } +} + +// Review of #1926: a car below the offer in force. The car draws 8.2 kW, +// fresh and inside what the meter shows, but the charger's offer from +// before the restart, or its own default, is 16 A. Until Core's 6.2 kW +// order lands the car may rise to 11 kW (a ramp, a heater). The battery +// keeps the discharge that rise needs. +func TestEVBaseAfterRestartCarBelowOfferInForce(t *testing.T) { + houseA := 3.0 + evW, batW := 8222.0, -5000.0 + gridW := houseA*690 + evW + batW + phaseA := gridW / 690 + store, state := restartFixture(t, gridW, [3]float64{phaseA, phaseA, phaseA}, batW, 0, evW) + out := clampEVBatteryHeadroom([]DispatchTarget{{Driver: "sungrow", TargetW: 0}}, store, state, 16*230*3) + got := targetW(out, "sungrow") + if afterA := phaseA + (got-batW)/690 + (11040-evW)/690; afterA > 16+1e-6 { + t.Fatalf("battery ends discharge to %.0f W; a car rising to its offer in force puts %.2f A on each phase", got, afterA) } } @@ -81,20 +103,46 @@ func TestEVBaseAfterRestartCreditStaysInsideTheMeter(t *testing.T) { } } -// The credit never exceeds the latest offer, needs a live charger reading, -// and ends once the charger's first offer of this run has had its settle -// time: then the offers alone say what the meter shows. +// setMaxW sets the fixture charger's max_charge_w. +func setMaxW(state *State, w float64) { + c := state.evLimit.offers["garage"] + c.maxW = w + state.evLimit.offers["garage"] = c +} + +// The credit never exceeds the latest offer, keeps room for the car's rise +// to its max, takes the lowest of the sample, raw and smoothed draw, needs +// a live charger reading, and ends once the charger's first offer of this +// run has had its settle time: then the offers alone say what the meter +// shows. func TestEVFoundDrawWBounds(t *testing.T) { for _, tc := range []struct { name string edit func(*telemetry.Store, *State) want float64 }{ - {"latest offer bounds the draw", func(*telemetry.Store, *State) {}, 6210}, + {"the car may still rise to its max", func(*telemetry.Store, *State) {}, 8222 - (11040 - 6210)}, + {"no max_charge_w", func(_ *telemetry.Store, state *State) { setMaxW(state, 0) }, 0}, + {"latest offer bounds the draw", func(_ *telemetry.Store, state *State) { setMaxW(state, 6210) }, 6210}, {"measured draw below the offer", func(store *telemetry.Store, state *State) { + setMaxW(state, 6210) store.Update("charger", telemetry.DerEV, 4000, nil, nil) store.Get("charger", telemetry.DerEV).UpdatedAt = state.now() }, 4000}, + {"smoothed draw below the sample", func(store *telemetry.Store, state *State) { + setMaxW(state, 6210) + store.Get("charger", telemetry.DerEV).SmoothedW = 5000 + }, 5000}, + {"raw draw below the sample", func(store *telemetry.Store, state *State) { + setMaxW(state, 6210) + r := store.Get("charger", telemetry.DerEV) + r.Data = json.RawMessage(`{"control_power_w":8222}`) + r.RawW = 5000 + }, 5000}, + {"control sample below raw and smoothed", func(store *telemetry.Store, state *State) { + setMaxW(state, 6210) + store.Get("charger", telemetry.DerEV).Data = json.RawMessage(`{"control_power_w":5000}`) + }, 5000}, {"charger offline", func(store *telemetry.Store, _ *State) { store.DriverHealthMut("charger").SetOffline() }, 0}, @@ -114,7 +162,7 @@ func TestEVFoundDrawWBounds(t *testing.T) { c.found.at = state.now().Add(-30 * time.Second) c.log[0].at = c.found.at state.evLimit.offers["garage"] = c - }, 6210}, + }, 8222 - (11040 - 6210)}, {"the shown part of the latest offer is not counted twice", func(_ *telemetry.Store, state *State) { c := state.evLimit.offers["garage"] c.found.at = state.now().Add(-60 * time.Second) @@ -126,7 +174,8 @@ func TestEVFoundDrawWBounds(t *testing.T) { store, state := restartFixture(t, 780, [3]float64{2.03, 4.97, .47}, -5000, -3000, 8222) tc.edit(store, state) shownW := state.evShownW(state.now()) - if got := state.evFoundDrawW(store, store.Get("meter", telemetry.DerMeter), state.now(), shownW); math.Abs(got-tc.want) > 1e-6 { + meter := store.Get("meter", telemetry.DerMeter) + if got := state.evFoundDrawW(store, meter.RawW, meter.UpdatedAt, state.now(), shownW); math.Abs(got-tc.want) > 1e-6 { t.Fatalf("credit %.0f W beside %.0f W shown, want %.0f W", got, shownW, tc.want) } }) @@ -138,7 +187,9 @@ func TestEVFoundDrawWBounds(t *testing.T) { // shows as consumption only 3,780 W is left for this car. func TestEVFoundDrawWLeavesOutShownOffers(t *testing.T) { store, state := restartFixture(t, 780, [3]float64{2.03, 4.97, .47}, -5000, -3000, 8222) - if got := state.evFoundDrawW(store, store.Get("meter", telemetry.DerMeter), state.now(), 5000); math.Abs(got-3780) > 1e-6 { + setMaxW(state, 6210) + meter := store.Get("meter", telemetry.DerMeter) + if got := state.evFoundDrawW(store, meter.RawW, meter.UpdatedAt, state.now(), 5000); math.Abs(got-3780) > 1e-6 { t.Fatalf("credit %.0f W, want 3780 W", got) } } @@ -210,16 +261,27 @@ func TestEVBaseAfterRestartConsumptionReadsCurrentOutput(t *testing.T) { } } -// Seed 207532's shape on the plant: Core restarts beside a car drawing -// 12 A from before, on a charger that takes 40 s to apply an order. For -// its first 6 s the meter is silent and the inverter unreachable, holding -// the 5 kW discharge it had (C1), so Core logs 0 A offers. Then Core asks -// 9 A for the car. PV covers the house, the plan is stale and -// battery_covers_ev is off: the battery ends its discharge as fast as its -// slew allows, and no phase passes the fuse line on the way. -func TestSiteSimRestartEndsDischargeForACarAlreadyDrawing(t *testing.T) { +// The consumption bound subtracts each output at the higher of raw and +// smoothed. A battery whose reading already shows a new 3 kW discharge, +// smoothed still at 1 kW, may be ahead of the site reading; so may PV. +func TestSiteConsumptionWTakesTheSmallerOutput(t *testing.T) { + store, _ := restartFixture(t, 680, [3]float64{4.97, -1, -1}, -3000, -2000, 8222) + store.Get("sungrow", telemetry.DerBattery).SmoothedW = -1000 + store.Get("pv", telemetry.DerPV).SmoothedW = -500 + if got := siteConsumptionW(store, 680); math.Abs(got-2180) > 1e-6 { + t.Fatalf("consumption %.0f W, want 2180 W: 680 W less -1,000 W battery and -500 W PV", got) + } +} + +// restartSim is seed 207532's shape on the plant: Core restarts beside a +// car drawing 12 A from before, on a charger that takes 40 s to apply an +// order. For its first 6 s the meter is silent and the inverter +// unreachable, holding the 5 kW discharge it had (C1), so Core logs 0 A +// offers. Then Core asks 9 A for the car. PV covers the house total, the +// plan is stale and battery_covers_ev is off. +func restartSim(house [3]float64) *simSite { p := simPlant(simStart) - p.Fuse.RatingA, p.HouseW, p.PVW = 16, houseA(4, 9, 2), -6000 + p.Fuse.RatingA, p.HouseW, p.PVW = 16, house, -6000 p.EVSE.Delay, p.EVSE.ReadbackLag = 40*time.Second, 0 p.EVSE.OfferA, p.EVSE.OfferPhases = 12, 3 p.Battery = &sitesim.Battery{Phases: 3, MaxChargeW: 5000, MaxDischargeW: 5000, CapacityWh: 10000, SoC: .3, Latency: 2 * time.Second, W: -5000} @@ -233,16 +295,67 @@ func TestSiteSimRestartEndsDischargeForACarAlreadyDrawing(t *testing.T) { s.state.SiteFuseSafetyA = 0 s.ctrl.SetManualHold(s.lp.ID, loadpoint.ManualHold{PowerW: 6210, PhaseMode: "3p", Persistent: true, StartedAt: s.p.Now, UpdatedAt: s.p.Now}) } + return s +} + +// The seed on the plant: the battery ends its discharge as fast as its +// slew allows, down to what the car's rise to its 16 A max still needs on +// L2 (the 9 A of house load PV does not cover there), and no phase passes +// the fuse line on the way. +func TestSiteSimRestartEndsDischargeForACarAlreadyDrawing(t *testing.T) { + s := restartSim(houseA(4, 9, 2)) s.boot() s.run(14 * time.Second) if s.offerW != 6210 || s.p.EVSE.DrawW != 8280 { t.Fatalf("not the seed's state: offer %.0f W, car %.0f W", s.offerW, s.p.EVSE.DrawW) } - if s.batteryCmdW < -1 { - t.Fatalf("battery held at %.0f W 8 s after the meter returned, with the car already in the reading", s.batteryCmdW) + if want := -(9*230 - 2000.0) * 3; s.batteryCmdW < want-1 { + t.Fatalf("battery held at %.0f W 8 s after the meter returned, with the car already in the reading; want %.0f W", s.batteryCmdW, want) + } + s.run(2 * time.Minute) + if s.failure != "" { + t.Fatal(s.failure) + } +} + +// The seed's charger is OCPP and samples every 10 s (MeterValues). Its +// sample counts only on the ticks just after it, so the battery holds its +// discharge between samples. It still ends it before the 9 A order counts +// as shown (evSettle after it went out, about 28 s in), and no phase +// passes the fuse line. A charger sampling every 30 s or more gets no +// credit in that time: the fix is partial for it. +func TestSiteSimRestartTenSecondSamples(t *testing.T) { + s := restartSim(houseA(4, 9, 2)) + s.evEvery = 10 * time.Second + s.boot() + s.run(20 * time.Second) + if s.offerW != 6210 || s.p.EVSE.DrawW != 8280 { + t.Fatalf("not the seed's state: offer %.0f W, car %.0f W", s.offerW, s.p.EVSE.DrawW) + } + if want := -(9*230 - 2000.0) * 3; s.batteryCmdW < want-1 { + t.Fatalf("battery held at %.0f W 14 s after the meter returned; want %.0f W", s.batteryCmdW, want) } s.run(2 * time.Minute) if s.failure != "" { t.Fatal(s.failure) } } + +// Review of #1926 on the plant: the charger's offer in force is 16 A, and +// the car limits itself to 12 A at the restart, then lifts that 14 s +// later, before the 40 s charger has applied Core's order. L2 carries 12 A +// of house. The battery keeps the discharge the car's rise needs: no phase +// reaches 1.2 x In, and time over In stays within the heat model. +func TestSiteSimRestartCarRisesUnderOfferInForce(t *testing.T) { + s := restartSim(houseA(4, 12, 2)) + s.p.EVSE.OfferA, s.p.Car.MaxW = 16, 8280 + s.p.Events = append(s.p.Events, sitesim.Event{At: 14 * time.Second, Kind: sitesim.Change, Do: func(p *sitesim.Plant) { p.Car.MaxW = 11040 }}) + s.boot() + s.run(2 * time.Minute) + if s.failure != "" { + t.Fatal(s.failure) + } + if s.peakA >= fuseInstantFactor*16 { + t.Fatalf("a phase reached %.2f A", s.peakA) + } +} diff --git a/go/internal/control/ev_battery_headroom.go b/go/internal/control/ev_battery_headroom.go index a2d57eda4..7098a2c74 100644 --- a/go/internal/control/ev_battery_headroom.go +++ b/go/internal/control/ev_battery_headroom.go @@ -38,7 +38,7 @@ func clampEVBatteryHeadroom(targets []DispatchTarget, store *telemetry.Store, st return floorPositiveEVBatteryTargets(targets) } offeredW := state.evShownW(now) - offeredW += state.evFoundDrawW(store, meter, now, offeredW) + offeredW += state.evFoundDrawW(store, gridW, meter.UpdatedAt, now, offeredW) needW := math.Max(0, demandW-offeredW) latest := make(map[string]float64, len(targets)) lowest := make(map[string]float64, len(targets)) diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index b3f036221..eb320f7ef 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -181,8 +181,10 @@ type chargerOffers struct { found sentCommand // driver is the charger's driver, whose power reading only the battery // side reads, and only before any offer of this run has surely landed - // (evFoundDrawW). + // (evFoundDrawW). maxW is the loadpoint's max_charge_w, the most the car + // may draw on an offer Core does not know; zero when not configured. driver string + maxW float64 // carPhases is how many phases the car draws on, as the loadpoint saw // it on the site meter: 1 or 3, or 0 when unknown. carPhase is the phase // a car on one phase draws on, 1-3. @@ -403,23 +405,31 @@ func (s *State) evShownW(at time.Time) float64 { // evFoundDrawW is EV draw the battery side may count as shown beyond // evShownW (shownW) while a charger has no order of this run that has -// surely landed: after a restart or a plug-in, until its first logged offer -// is older than its settle time. Core then does not know which offer the -// charger runs on, and its first offers (often 0 A) say nothing of what the -// meter shows. A car seen drawing in that window is in the reading when the -// charger measured it within one control interval of the site reading: a -// fast charger may have applied a 0 A offer since an older sample, and a -// held reading after a failed poll says nothing of now. Each such charger -// counts its measured draw, the lowest of the sample, raw and smoothed, -// never above its latest offer, and in all no more than the consumption the +// surely landed: from the first offer Core logs for it with no fuse limit +// set (at Core's start, or at a plug-in once no other managed charger was +// plugged), until that offer is older than the charger's settle time. Core +// then does not know which offer the charger runs on, and its first offers +// (often 0 A) say nothing of what the meter shows. A car seen drawing in +// that window is in the reading when the charger measured it within one +// control interval of the site reading: a fast charger may have applied a +// 0 A offer since an older sample, and a held reading after a failed poll +// says nothing of now. A charger that samples less often (OCPP MeterValues +// every 10 s or more) counts only on the ticks just after a sample, and +// holds its battery's discharge between them. The measured draw is the +// lowest of the sample, raw and smoothed. Until the latest offer lands, the +// car may still rise from that draw to the offer in force, up to the +// loadpoint's max_charge_w; that rise past the latest offer stays reserved, +// and a charger with no max_charge_w counts nothing. Each charger counts no +// more than its latest offer, and in all no more than the consumption the // site meter shows (siteConsumptionW) less shownW. The car's own limit // never reads this; only how much of our latest offers the battery reserves // as a rise to come. -func (s *State) evFoundDrawW(store *telemetry.Store, meter *telemetry.DerReading, at time.Time, shownW float64) float64 { - if store == nil || meter == nil { +// gridW is the site reading, taken at meterAt. +func (s *State) evFoundDrawW(store *telemetry.Store, gridW float64, meterAt, at time.Time, shownW float64) float64 { + if store == nil { return 0 } - consumptionW := siteConsumptionW(store, meter.RawW) + consumptionW := siteConsumptionW(store, gridW) if !finiteFuseValue(consumptionW) { return 0 } @@ -430,24 +440,25 @@ func (s *State) evFoundDrawW(store *telemetry.Store, meter *telemetry.DerReading var w float64 for _, c := range s.evLimit.offers { n := len(c.log) - if n == 0 || c.found.at.IsZero() || at.Sub(c.found.at) >= c.settle || c.driver == "" { + if n == 0 || c.found.at.IsZero() || at.Sub(c.found.at) >= c.settle || c.driver == "" || !(c.maxW > 0) || !finiteFuseValue(c.maxW) { continue } - r := store.Get(c.driver, telemetry.DerEV) - if h := store.DriverHealth(c.driver); r == nil || !h.TelemetryLive() || h.LastReadFailed() { + lowerW, live := store.OnlineLowerW(c.driver, telemetry.DerEV) + if !live { continue } - p, ok := qualifiedFuseObservation(r, at) - if !ok || p.Seen().Before(meter.UpdatedAt.Add(-skew)) || p.At.After(meter.UpdatedAt.Add(skew)) { + p, ok := qualifiedFuseObservation(store.Get(c.driver, telemetry.DerEV), at) + if !ok || p.Seen().Before(meterAt.Add(-skew)) || p.At.After(meterAt.Add(skew)) { continue } - drawW := math.Min(p.PowerW, math.Min(r.RawW, r.SmoothedW)) + drawW := math.Min(p.PowerW, lowerW) if !finiteFuseValue(drawW) { continue } unshown, _ := c.log.unshown(at, c.batterySettle()) latest := c.log[n-1].w - w += math.Max(0, math.Min(latest, drawW)-math.Max(0, latest-unshown)) + inLatestW := math.Min(latest, drawW-math.Max(0, c.maxW-latest)) + w += math.Max(0, inLatestW-math.Max(0, latest-unshown)) } return math.Max(0, math.Min(w, consumptionW-shownW)) } @@ -457,15 +468,7 @@ func (s *State) evFoundDrawW(store *telemetry.Store, meter *telemetry.DerReading // smoothed. A smoothed value lags an output that just fell; the higher one // keeps the estimate at or below what the meter shows. func siteConsumptionW(store *telemetry.Store, gridW float64) float64 { - w := gridW - for _, t := range []telemetry.DerType{telemetry.DerBattery, telemetry.DerPV, telemetry.DerV2X} { - for _, r := range store.ReadingsByType(t) { - if store.DriverHealth(r.Driver).TelemetryLive() { - w -= math.Max(r.RawW, r.SmoothedW) - } - } - } - return w + return gridW - store.SumOnlineHigherW(telemetry.DerBattery, telemetry.DerPV, telemetry.DerV2X) } // batterySettle is how long the battery side counts a raise of this @@ -616,7 +619,7 @@ func (s *State) recordEVOffers(store *telemetry.Store, points []loadpoint.State) continue } c := s.evLimit.offers[point.ID] - c.settle, c.declared, c.carPhases, c.carPhase, c.driver = evUnknownSettle, false, point.CarPhases, point.CarPhase, point.DriverName + c.settle, c.declared, c.carPhases, c.carPhase, c.driver, c.maxW = evUnknownSettle, false, point.CarPhases, point.CarPhase, point.DriverName, point.MaxChargeW if r := store.Get(point.DriverName, telemetry.DerEV); r != nil { if declared := telemetry.DeclaredPowerMaxAge(r.Data); declared > 0 { c.settle, c.declared = max(evSettle, declared), true diff --git a/go/internal/control/sitesim_test.go b/go/internal/control/sitesim_test.go index 09e8c1a42..36abc4603 100644 --- a/go/internal/control/sitesim_test.go +++ b/go/internal/control/sitesim_test.go @@ -45,6 +45,10 @@ type simSite struct { // evMaxAge is the power_max_age_s the charger driver declares outside // the field matrix; zero declares none. evMaxAge time.Duration + // evEvery is how often the charger samples its draw, as OCPP + // MeterValues do: between samples each poll repeats the last sample + // with its own time. Zero samples on every poll. + evEvery time.Duration // meterNoise is added to each phase current Core reads, not to the // plant's own; nil reads the plant exactly. meterNoise func() float64 @@ -240,8 +244,18 @@ func (s *simSite) step() { s.emit("battery", telemetry.DerBattery, b.W, &b.SoC, nil) } if e := tick.EV; e != nil { - s.ev, s.evAt = *e, now - s.emit(s.lp.DriverName, telemetry.DerEV, e.W, nil, s.evData()) + if s.evEvery <= 0 || s.evAt.IsZero() || now.Sub(s.evAt) >= s.evEvery { + s.ev, s.evAt = *e, now + } + data := s.evData() + if s.evEvery > 0 { + data = maps.Clone(data) + if data == nil { + data = map[string]any{} + } + data["control_power_observed_at"] = s.evAt.Format(time.RFC3339Nano) + } + s.emit(s.lp.DriverName, telemetry.DerEV, s.ev.W, nil, data) } if !now.Before(s.nextTick) { s.nextTick = now.Add(s.coreEvery()) diff --git a/go/internal/telemetry/store.go b/go/internal/telemetry/store.go index 32e668501..b87d97cb7 100644 --- a/go/internal/telemetry/store.go +++ b/go/internal/telemetry/store.go @@ -5,6 +5,7 @@ import ( "fmt" "log/slog" "math" + "slices" "strings" "sync" "time" @@ -688,6 +689,35 @@ func (s *Store) SumOnlineV2XW() float64 { return sum } +// OnlineLowerW returns the lower of a driver's raw and smoothed power of +// one type, while the driver is still reporting and its latest poll +// succeeded. A held reading after a failed poll returns false. +func (s *Store) OnlineLowerW(driver string, t DerType) (float64, bool) { + s.mu.RLock() + defer s.mu.RUnlock() + r, found := s.readings[key(driver, t)] + h, known := s.health[driver] + if !found || !known || !h.TelemetryLive() || h.LastReadFailed() { + return 0, false + } + w := math.Min(r.RawW, r.SmoothedW) + return w, !math.IsNaN(w) && !math.IsInf(w, 0) +} + +// SumOnlineHigherW sums the higher of raw and smoothed power over the +// readings of these types whose drivers are still reporting. +func (s *Store) SumOnlineHigherW(types ...DerType) float64 { + s.mu.RLock() + defer s.mu.RUnlock() + var sum float64 + for _, r := range s.readings { + if h, ok := s.health[r.Driver]; ok && h.TelemetryLive() && slices.Contains(types, r.DerType) { + sum += math.Max(r.RawW, r.SmoothedW) + } + } + return sum +} + // OnlineMeterW returns a site meter's latest power and when it arrived, // while its driver is still reporting. A watchdog-offline meter returns // false, so its last value never counts as a new reading. diff --git a/go/internal/telemetry/telemetry_test.go b/go/internal/telemetry/telemetry_test.go index 2ac3d4412..56895f170 100644 --- a/go/internal/telemetry/telemetry_test.go +++ b/go/internal/telemetry/telemetry_test.go @@ -572,6 +572,49 @@ func TestSumOnlineV2XWIsSignedAndSkipsOffline(t *testing.T) { } } +func TestOnlineLowerWNeedsALivePoll(t *testing.T) { + s := NewStore() + s.Update("charger", DerEV, 8000, nil, nil) + s.DriverHealthMut("charger").RecordSuccess() + s.Get("charger", DerEV).SmoothedW = 5000 + if w, ok := s.OnlineLowerW("charger", DerEV); !ok || w != 5000 { + t.Fatalf("got %v %v, want the lower 5000 W", w, ok) + } + s.Get("charger", DerEV).RawW = 4000 + if w, ok := s.OnlineLowerW("charger", DerEV); !ok || w != 4000 { + t.Fatalf("got %v %v, want the lower 4000 W", w, ok) + } + s.DriverHealthMut("charger").RecordError("timeout") + if _, ok := s.OnlineLowerW("charger", DerEV); ok { + t.Fatal("a reading held after a failed poll counted") + } + s.DriverHealthMut("charger").RecordSuccess() + s.DriverHealthMut("charger").SetOffline() + if _, ok := s.OnlineLowerW("charger", DerEV); ok { + t.Fatal("an offline driver's reading counted") + } + if _, ok := s.OnlineLowerW("missing", DerEV); ok { + t.Fatal("a missing reading counted") + } +} + +func TestSumOnlineHigherWSumsTheNamedTypes(t *testing.T) { + s := NewStore() + s.Update("battery", DerBattery, -3000, nil, nil) + s.Update("pv", DerPV, -2000, nil, nil) + s.Update("ev", DerEV, 7000, nil, nil) + s.Update("offline", DerBattery, -9000, nil, nil) + for _, d := range []string{"battery", "pv", "ev"} { + s.DriverHealthMut(d).RecordSuccess() + } + s.DriverHealthMut("offline").SetOffline() + s.Get("battery", DerBattery).SmoothedW = -1000 + s.Get("pv", DerPV).SmoothedW = -2500 + if got := s.SumOnlineHigherW(DerBattery, DerPV); got != -3000 { + t.Fatalf("got %v, want -1000 W battery plus -2000 W PV", got) + } +} + func TestWatchdogPerDriverOverride(t *testing.T) { s := NewStore() // Two drivers: one with the site-default tolerance, one with a From 19d8a2983a9e6f58bb0cd4d2c45dcf58adfd8c37 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 06:25:50 +0100 Subject: [PATCH 57/68] test(control): Charge now landing shown before Core logs its offer Site rig s1-16, s1-25 and s15-25 failed on c9b52c36: the charger answered within a second, and the meter reading that showed the car at 15.9 A came in 7 ms before the tick that first logged the 16 A offer. The reading could not show an offer logged after it, so the landing counted as a raise still to come, 15.9 + 16 A passed 1.2 x In, and Core cut 11,040 W to 5,520 W with 9 A of room on every phase. The same run of the base at 281f9f63, without this branch's commits, fails the same way; #1923's ab027102, merged here in c0a52740, reads the meter's own rise and fixes it. This test pins that rig shape. Co-Authored-By: Claude Opus 5.5 --- .../control/ev_fuse_offer_logged_late_test.go | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 go/internal/control/ev_fuse_offer_logged_late_test.go diff --git a/go/internal/control/ev_fuse_offer_logged_late_test.go b/go/internal/control/ev_fuse_offer_logged_late_test.go new file mode 100644 index 000000000..d8674a3b2 --- /dev/null +++ b/go/internal/control/ev_fuse_offer_logged_late_test.go @@ -0,0 +1,60 @@ +package control + +import ( + "encoding/json" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/telemetry" +) + +// Site rig s1 and s15 (28 Oct 2026, c9b52c36): Charge now from idle on a +// 25 A or 16 A fuse, 3 A of house per phase covered by the battery, so every phase +// reads 0 A. The charger answers in about a second. Core logs an offer when +// the next control tick reads the loadpoint's command, 2 s after it went +// out, and that tick's meter reading came in 7 ms before it. The reading +// already shows the car at 15.9 A, but it is older than the logged offer. +// The landing then read as a raise not shown yet: 15.9 + 16 A passed +// 1.2 x In, and Core cut 11,040 W to 5,520 W with 9 A of room on every +// phase ("EV hard limit: site meter over limit ... worst_phase_a=15.9 +// rise_on_its_way_a=[16 16 16] cap_w=5520"). The car then crept back 1 A +// at a time and held 9,660 W on fuse_limit. Since #1923's ab027102 the +// rise still to come reads the meter's own rise since the raise went out. +func TestEVFuseRaiseShownBeforeItsOfferIsLogged(t *testing.T) { + for _, tc := range []struct { + name string + fuseA float64 + phases int + offerW float64 + landedA [3]float64 + }{ + {"s1_25A_fuse", 25, 3, 11040, [3]float64{15.9, 15.9, 15.9}}, + {"s1_16A_fuse", 16, 3, 10350, [3]float64{15, 15, 15}}, + {"s15_one_phase_charger_on_L1", 25, 1, 3680, [3]float64{16, 0, 0}}, + } { + t.Run(tc.name, func(t *testing.T) { + r := newCutRig(t, 0, 0) + r.phases, r.state.SiteFuseAmps = tc.phases, tc.fuseA + // Each reading comes in 7 ms before the tick that reads it. + read := func(phaseA [3]float64) { + t.Helper() + data, _ := json.Marshal(map[string]any{"l1_a": phaseA[0], "l2_a": phaseA[1], "l3_a": phaseA[2]}) + r.now = r.now.Add(2 * time.Second) + r.store.Update("meter", telemetry.DerMeter, (phaseA[0]+phaseA[1]+phaseA[2])*230, nil, data) + r.store.Get("meter", telemetry.DerMeter).UpdatedAt = r.now.Add(-7 * time.Millisecond) + _, _, points, configs := evMeterBudgetFixture(t, 0, nil, r.offerW, "3p") + points[0].CommandedPhases = r.phases + if capW, _ := EVFuseBudget(r.store, r.state, points, configs, tc.fuseA*690); capW < r.offerW { + t.Fatalf("offer %.0f W cut to %.0f W with the car at %v A on a %.0f A fuse", r.offerW, capW, phaseA, tc.fuseA) + } + } + for range 15 { + read([3]float64{}) + } + r.offerW = tc.offerW // sent at the last tick, logged at this one + for range 60 { + read(tc.landedA) + } + }) + } +} From caacc8d4435a4db0bf5608dbf09eb1fa057e5d1a Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 06:45:38 +0100 Subject: [PATCH 58/68] fix(control): restart credit counts no sample newer than the meter The battery side's restart credit (evFoundDrawW) had two gaps. A charger sample measured after the site reading counted as part of it. A car that rose in that gap was credited for draw the meter did not show yet, and the battery ended its discharge into room the rise had taken. With a 3 s meter, L2 reached 19.30 A. A sample now counts only when measured at or before the site reading. The rise reserve took max_charge_w as the most the unknown offer in force can be. A charger still on an offer from before a restart that lowered max_charge_w, or on its own higher default, could rise past it: 19.00 A per phase on the unit fixture, 19.30 A on the plant. The reserve now runs to the larger of max_charge_w and the site fuse's rating. Co-Authored-By: Claude Opus 5.5 --- .changeset/s4-ev-base-after-restart.md | 2 +- .../control/ev_base_after_restart_test.go | 86 +++++++++++++++++-- go/internal/control/ev_fuse_budget.go | 31 ++++--- 3 files changed, 96 insertions(+), 23 deletions(-) diff --git a/.changeset/s4-ev-base-after-restart.md b/.changeset/s4-ev-base-after-restart.md index 4e7dcd404..42917a3a5 100644 --- a/.changeset/s4-ev-base-after-restart.md +++ b/.changeset/s4-ev-base-after-restart.md @@ -2,4 +2,4 @@ "ftw": patch --- -After a restart, the home battery no longer stays in discharge for a car the meter already shows charging. Until the charger's first order of the new run can have landed, the battery counts the car's measured draw as part of the meter reading, never above FTW's latest order to the car and never above the consumption the site meter shows. FTW does not know the charger's offer in force then, so the battery still keeps room for the car to rise from its draw to the charger's max_charge_w; a charger with no max_charge_w gets no such credit. The draw counts only when the charger measured it within one control interval of the site reading and its last poll succeeded, so a charger that samples every 30 s or more rarely gets it. Before, the 0 A orders FTW sent while the meter was still starting counted as the car's draw, so a lower order looked like a rise and the battery kept discharging toward its floor. +After a restart, the home battery no longer stays in discharge for a car the meter already shows charging. Until the charger's first order of the new run can have landed, the battery counts the car's measured draw as part of the meter reading, never above FTW's latest order to the car and never above the consumption the site meter shows. FTW does not know the charger's offer in force then: one from before the restart, under an older max_charge_w, or the charger's own default. So the battery still keeps room for the car to rise from its draw to the larger of the charger's max_charge_w and the site fuse's rating. On a site whose fuse allows more than the car's draw plus FTW's latest order, that leaves no credit; a charger with no max_charge_w gets none either. The draw counts only when the charger measured it within one control interval before the site reading, not after it, and its last poll succeeded, so a charger that samples every 30 s or more rarely gets it. Before, the 0 A orders FTW sent while the meter was still starting counted as the car's draw, so a lower order looked like a rise and the battery kept discharging toward its floor. diff --git a/go/internal/control/ev_base_after_restart_test.go b/go/internal/control/ev_base_after_restart_test.go index a4691b164..98e484038 100644 --- a/go/internal/control/ev_base_after_restart_test.go +++ b/go/internal/control/ev_base_after_restart_test.go @@ -33,6 +33,8 @@ func restartFixture(t *testing.T, gridW float64, phaseA [3]float64, batteryW, pv } store.Update("charger", telemetry.DerEV, evW, nil, nil) store.RecordDriverSuccess("charger") + // The charger measured its draw with the site reading, not after it. + store.Get("charger", telemetry.DerEV).UpdatedAt = store.Get("meter", telemetry.DerMeter).UpdatedAt state := NewState(0, 0, "meter") now := time.Now() @@ -110,6 +112,13 @@ func setMaxW(state *State, w float64) { state.evLimit.offers["garage"] = c } +// setRiseCapW puts both max_charge_w and the site fuse at w, the most an +// offer in force may be, so a case can test the other bounds alone. +func setRiseCapW(state *State, w float64) { + setMaxW(state, w) + state.SiteFuseAmps = w / (state.SiteFuseVoltage * float64(state.SiteFusePhases)) +} + // The credit never exceeds the latest offer, keeps room for the car's rise // to its max, takes the lowest of the sample, raw and smoothed draw, needs // a live charger reading, and ends once the charger's first offer of this @@ -123,24 +132,31 @@ func TestEVFoundDrawWBounds(t *testing.T) { }{ {"the car may still rise to its max", func(*telemetry.Store, *State) {}, 8222 - (11040 - 6210)}, {"no max_charge_w", func(_ *telemetry.Store, state *State) { setMaxW(state, 0) }, 0}, - {"latest offer bounds the draw", func(_ *telemetry.Store, state *State) { setMaxW(state, 6210) }, 6210}, + {"max_charge_w below the fuse: the offer in force may still be the fuse's", func(_ *telemetry.Store, state *State) { + setMaxW(state, 7360) + }, 8222 - (11040 - 6210)}, + {"a charger sample measured after the site reading", func(store *telemetry.Store, state *State) { + store.Get("meter", telemetry.DerMeter).UpdatedAt = state.now().Add(-time.Second) + store.Get("charger", telemetry.DerEV).UpdatedAt = state.now() + }, 0}, + {"latest offer bounds the draw", func(_ *telemetry.Store, state *State) { setRiseCapW(state, 6210) }, 6210}, {"measured draw below the offer", func(store *telemetry.Store, state *State) { - setMaxW(state, 6210) + setRiseCapW(state, 6210) store.Update("charger", telemetry.DerEV, 4000, nil, nil) - store.Get("charger", telemetry.DerEV).UpdatedAt = state.now() + store.Get("charger", telemetry.DerEV).UpdatedAt = store.Get("meter", telemetry.DerMeter).UpdatedAt }, 4000}, {"smoothed draw below the sample", func(store *telemetry.Store, state *State) { - setMaxW(state, 6210) + setRiseCapW(state, 6210) store.Get("charger", telemetry.DerEV).SmoothedW = 5000 }, 5000}, {"raw draw below the sample", func(store *telemetry.Store, state *State) { - setMaxW(state, 6210) + setRiseCapW(state, 6210) r := store.Get("charger", telemetry.DerEV) r.Data = json.RawMessage(`{"control_power_w":8222}`) r.RawW = 5000 }, 5000}, {"control sample below raw and smoothed", func(store *telemetry.Store, state *State) { - setMaxW(state, 6210) + setRiseCapW(state, 6210) store.Get("charger", telemetry.DerEV).Data = json.RawMessage(`{"control_power_w":5000}`) }, 5000}, {"charger offline", func(store *telemetry.Store, _ *State) { @@ -187,7 +203,7 @@ func TestEVFoundDrawWBounds(t *testing.T) { // shows as consumption only 3,780 W is left for this car. func TestEVFoundDrawWLeavesOutShownOffers(t *testing.T) { store, state := restartFixture(t, 780, [3]float64{2.03, 4.97, .47}, -5000, -3000, 8222) - setMaxW(state, 6210) + setRiseCapW(state, 6210) meter := store.Get("meter", telemetry.DerMeter) if got := state.evFoundDrawW(store, meter.RawW, meter.UpdatedAt, state.now(), 5000); math.Abs(got-3780) > 1e-6 { t.Fatalf("credit %.0f W, want 3780 W", got) @@ -348,8 +364,17 @@ func TestSiteSimRestartTenSecondSamples(t *testing.T) { // reaches 1.2 x In, and time over In stays within the heat model. func TestSiteSimRestartCarRisesUnderOfferInForce(t *testing.T) { s := restartSim(houseA(4, 12, 2)) - s.p.EVSE.OfferA, s.p.Car.MaxW = 16, 8280 - s.p.Events = append(s.p.Events, sitesim.Event{At: 14 * time.Second, Kind: sitesim.Change, Do: func(p *sitesim.Plant) { p.Car.MaxW = 11040 }}) + carRisesUnderOldOffer(t, s, 8280, 14*time.Second) +} + +// carRisesUnderOldOffer runs s with the charger still on the 16 A offer it +// had before the restart, and a car that draws fromW until it lifts its own +// limit at riseAt. No phase may reach 1.2 x In, and the sim's fuse checks +// must pass. +func carRisesUnderOldOffer(t *testing.T, s *simSite, fromW float64, riseAt time.Duration) { + t.Helper() + s.p.EVSE.OfferA, s.p.Car.MaxW = 16, fromW + s.p.Events = append(s.p.Events, sitesim.Event{At: riseAt, Kind: sitesim.Change, Do: func(p *sitesim.Plant) { p.Car.MaxW = 11040 }}) s.boot() s.run(2 * time.Minute) if s.failure != "" { @@ -359,3 +384,46 @@ func TestSiteSimRestartCarRisesUnderOfferInForce(t *testing.T) { t.Fatalf("a phase reached %.2f A", s.peakA) } } + +// Third review of #1926: a site meter that samples every 3 s. The car draws +// 10 A under the 16 A offer in force and lifts its own limit 11 s in. The +// charger reads the rise before the next meter sample, so its sample is +// newer than the site reading, which still shows the old draw. That sample +// does not count as in the reading, and the battery keeps the discharge +// the rise needs. Before: L2 reached 19.30 A. +func TestSiteSimRestartCarRisesBetweenMeterSamples(t *testing.T) { + s := restartSim(houseA(4, 12, 2)) + s.p.Meter.Every = 3 * time.Second + carRisesUnderOldOffer(t, s, 6900, 11*time.Second) +} + +// Third review of #1926: max_charge_w is not the most an offer in force +// may be. The owner lowered it to 7,360 W (10.67 A) and restarted; the +// charger still runs the 16 A Core sent before. The car draws 7 kW and may +// rise to 11,040 W before the 6.2 kW order lands. The rise reserve runs to +// the site fuse, so the battery keeps the discharge that rise needs. +func TestEVBaseAfterRestartMaxChargeLoweredAtRestart(t *testing.T) { + house := 3.0 + evW, batW := 7000.0, -5000.0 + gridW := house*690 + evW + batW + phaseA := gridW / 690 + store, state := restartFixture(t, gridW, [3]float64{phaseA, phaseA, phaseA}, batW, 0, evW) + setMaxW(state, 7360) + out := clampEVBatteryHeadroom([]DispatchTarget{{Driver: "sungrow", TargetW: 0}}, store, state, 16*230*3) + got := targetW(out, "sungrow") + if afterA := phaseA + (got-batW)/690 + (11040-evW)/690; afterA > 16+1e-6 { + t.Fatalf("battery ends discharge to %.0f W; the car rising to the old 16 A offer puts %.2f A on each phase", got, afterA) + } +} + +// The plant form: max_charge_w is now 8,280 W (12 A), and the car lifts +// its own 12 A limit 14 s in, before the 40 s charger applies Core's order. +// Before: L2 reached 19.30 A. +func TestSiteSimRestartMaxChargeLoweredAtRestart(t *testing.T) { + s := restartSim(houseA(4, 12, 2)) + s.lp.MaxChargeW, s.lp.AllowedStepsW = 8280, []float64{0} + for a := 6.0; a <= 12; a++ { + s.lp.AllowedStepsW = append(s.lp.AllowedStepsW, a*690) + } + carRisesUnderOldOffer(t, s, 8280, 14*time.Second) +} diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index eb320f7ef..acabf847f 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -181,8 +181,8 @@ type chargerOffers struct { found sentCommand // driver is the charger's driver, whose power reading only the battery // side reads, and only before any offer of this run has surely landed - // (evFoundDrawW). maxW is the loadpoint's max_charge_w, the most the car - // may draw on an offer Core does not know; zero when not configured. + // (evFoundDrawW). maxW is the loadpoint's max_charge_w; zero when not + // configured. driver string maxW float64 // carPhases is how many phases the car draws on, as the loadpoint saw @@ -411,15 +411,19 @@ func (s *State) evShownW(at time.Time) float64 { // then does not know which offer the charger runs on, and its first offers // (often 0 A) say nothing of what the meter shows. A car seen drawing in // that window is in the reading when the charger measured it within one -// control interval of the site reading: a fast charger may have applied a -// 0 A offer since an older sample, and a held reading after a failed poll -// says nothing of now. A charger that samples less often (OCPP MeterValues -// every 10 s or more) counts only on the ticks just after a sample, and -// holds its battery's discharge between them. The measured draw is the -// lowest of the sample, raw and smoothed. Until the latest offer lands, the -// car may still rise from that draw to the offer in force, up to the -// loadpoint's max_charge_w; that rise past the latest offer stays reserved, -// and a charger with no max_charge_w counts nothing. Each charger counts no +// control interval before the site reading: a fast charger may have applied +// a 0 A offer since an older sample, a held reading after a failed poll +// says nothing of now, and a sample newer than the site reading may hold a +// rise the meter does not show yet. A charger that samples less often (OCPP +// MeterValues every 10 s or more) counts only on the ticks just after a +// sample, and holds its battery's discharge between them. The measured draw +// is the lowest of the sample, raw and smoothed. Until the latest offer +// lands, the car may still rise from that draw to the offer in force. Core +// does not know that offer: one from before a restart, under an older +// max_charge_w, or the charger's own default. The reserve takes it as the +// larger of the loadpoint's max_charge_w and the site fuse's rating, and +// keeps the rise past the latest offer; a charger with no max_charge_w +// counts nothing. Each charger counts no // more than its latest offer, and in all no more than the consumption the // site meter shows (siteConsumptionW) less shownW. The car's own limit // never reads this; only how much of our latest offers the battery reserves @@ -448,7 +452,7 @@ func (s *State) evFoundDrawW(store *telemetry.Store, gridW float64, meterAt, at continue } p, ok := qualifiedFuseObservation(store.Get(c.driver, telemetry.DerEV), at) - if !ok || p.Seen().Before(meterAt.Add(-skew)) || p.At.After(meterAt.Add(skew)) { + if !ok || p.Seen().Before(meterAt.Add(-skew)) || p.At.After(meterAt) { continue } drawW := math.Min(p.PowerW, lowerW) @@ -457,7 +461,8 @@ func (s *State) evFoundDrawW(store *telemetry.Store, gridW float64, meterAt, at } unshown, _ := c.log.unshown(at, c.batterySettle()) latest := c.log[n-1].w - inLatestW := math.Min(latest, drawW-math.Max(0, c.maxW-latest)) + capW := math.Max(c.maxW, s.siteFuseMaxW()) + inLatestW := math.Min(latest, drawW-math.Max(0, capW-latest)) w += math.Max(0, inLatestW-math.Max(0, latest-unshown)) } return math.Max(0, math.Min(w, consumptionW-shownW)) From 551febda5d5077e5bf14ffebd0920d205b150529 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 07:39:08 +0100 Subject: [PATCH 59/68] fix(control): restart credit holds against a charger clock behind Core's The restart credit compared a charger's sample time, stamped by the charger's own clock (OCPP MeterValues), with the time the site reading arrived on Core's clock. A charger clock 1 s or more behind Core's let a rise sampled after the reading count as already in it, and L2 reached 19.30 A on the third review's plant case. A sample now counts only when stamped evClockAllowance (5 s) before the reading arrived, and the draw is the lowest of that sample and every sample since. noteDraw keeps the charger's samples while the restart window is open. Also tests the max_charge_w half of the rise cap: a 22 kW charger on a 3 x 25 A fuse keeps the reserve up to max_charge_w. Co-Authored-By: Claude Opus 5.5 --- .changeset/s4-ev-base-after-restart.md | 2 +- .../control/ev_base_after_restart_test.go | 119 ++++++++++++++-- go/internal/control/ev_fuse_budget.go | 134 ++++++++++++++---- go/internal/control/sitesim_test.go | 8 +- 4 files changed, 216 insertions(+), 47 deletions(-) diff --git a/.changeset/s4-ev-base-after-restart.md b/.changeset/s4-ev-base-after-restart.md index 42917a3a5..02227f9ac 100644 --- a/.changeset/s4-ev-base-after-restart.md +++ b/.changeset/s4-ev-base-after-restart.md @@ -2,4 +2,4 @@ "ftw": patch --- -After a restart, the home battery no longer stays in discharge for a car the meter already shows charging. Until the charger's first order of the new run can have landed, the battery counts the car's measured draw as part of the meter reading, never above FTW's latest order to the car and never above the consumption the site meter shows. FTW does not know the charger's offer in force then: one from before the restart, under an older max_charge_w, or the charger's own default. So the battery still keeps room for the car to rise from its draw to the larger of the charger's max_charge_w and the site fuse's rating. On a site whose fuse allows more than the car's draw plus FTW's latest order, that leaves no credit; a charger with no max_charge_w gets none either. The draw counts only when the charger measured it within one control interval before the site reading, not after it, and its last poll succeeded, so a charger that samples every 30 s or more rarely gets it. Before, the 0 A orders FTW sent while the meter was still starting counted as the car's draw, so a lower order looked like a rise and the battery kept discharging toward its floor. +After a restart, the home battery no longer stays in discharge for a car the meter already shows charging. Until the charger's first order of the new run can have landed, the battery counts the car's measured draw as part of the meter reading, never above FTW's latest order to the car and never above the consumption the site meter shows. FTW does not know the charger's offer in force then: one from before the restart, under an older max_charge_w, or the charger's own default. So the battery still keeps room for the car to rise from its draw to the larger of the charger's max_charge_w and the site fuse's rating. On a site whose fuse allows more than the car's draw plus FTW's latest order, that leaves no credit; a charger with no max_charge_w gets none either. The draw counts only when the charger stamped a sample at least 5 s, and at most one control interval more, before the site reading arrived, and its last poll succeeded. The 5 s cover a charger clock running behind FTW's, as OCPP chargers stamp their own samples. The lowest sample since then counts, so a rise the meter does not show yet never does. A charger that samples every 30 s or more rarely gets the credit. Before, the 0 A orders FTW sent while the meter was still starting counted as the car's draw, so a lower order looked like a rise and the battery kept discharging toward its floor. diff --git a/go/internal/control/ev_base_after_restart_test.go b/go/internal/control/ev_base_after_restart_test.go index 98e484038..29c9ec0f4 100644 --- a/go/internal/control/ev_base_after_restart_test.go +++ b/go/internal/control/ev_base_after_restart_test.go @@ -2,6 +2,7 @@ package control import ( "encoding/json" + "maps" "math" "testing" "time" @@ -16,9 +17,9 @@ import ( // logged offers of this run are 0 A, sent while the meter was stale, then // 6,210 W (9 A on three phases) 2 s ago. The charger takes 40 s to apply an // order, so the car still draws what it drew before the restart. Its -// max_charge_w is 11,040 W (16 A). evW is what the charger measures; the -// site meter reads gridW with the phase currents phaseA, and the PV -// inverter pvW. +// max_charge_w is 11,040 W (16 A). evW is what the charger measures, +// stamped evClockAllowance before the site reading arrived; the site meter +// reads gridW with the phase currents phaseA, and the PV inverter pvW. func restartFixture(t *testing.T, gridW float64, phaseA [3]float64, batteryW, pvW, evW float64) (*telemetry.Store, *State) { t.Helper() store := telemetry.NewStore() @@ -31,10 +32,7 @@ func restartFixture(t *testing.T, gridW float64, phaseA [3]float64, batteryW, pv store.Update("pv", telemetry.DerPV, pvW, nil, nil) store.RecordDriverSuccess("pv") } - store.Update("charger", telemetry.DerEV, evW, nil, nil) - store.RecordDriverSuccess("charger") - // The charger measured its draw with the site reading, not after it. - store.Get("charger", telemetry.DerEV).UpdatedAt = store.Get("meter", telemetry.DerMeter).UpdatedAt + setChargerSample(store, evW, nil) state := NewState(0, 0, "meter") now := time.Now() @@ -105,6 +103,24 @@ func TestEVBaseAfterRestartCreditStaysInsideTheMeter(t *testing.T) { } } +// chargerData is the fixture charger's data: its sample stamped +// evClockAllowance before the site reading arrived, with extra fields. +func chargerData(store *telemetry.Store, extra map[string]any) json.RawMessage { + at := store.Get("meter", telemetry.DerMeter).UpdatedAt.Add(-evClockAllowance) + d := map[string]any{"control_power_observed_at": at.Format(time.RFC3339Nano)} + maps.Copy(d, extra) + raw, _ := json.Marshal(d) + return raw +} + +// setChargerSample makes w the fixture charger's reading (chargerData), +// arriving with the site reading. +func setChargerSample(store *telemetry.Store, w float64, extra map[string]any) { + store.Update("charger", telemetry.DerEV, w, nil, chargerData(store, extra)) + store.RecordDriverSuccess("charger") + store.Get("charger", telemetry.DerEV).UpdatedAt = store.Get("meter", telemetry.DerMeter).UpdatedAt +} + // setMaxW sets the fixture charger's max_charge_w. func setMaxW(state *State, w float64) { c := state.evLimit.offers["garage"] @@ -120,10 +136,11 @@ func setRiseCapW(state *State, w float64) { } // The credit never exceeds the latest offer, keeps room for the car's rise -// to its max, takes the lowest of the sample, raw and smoothed draw, needs -// a live charger reading, and ends once the charger's first offer of this -// run has had its settle time: then the offers alone say what the meter -// shows. +// to its max, takes the lowest of the sample, raw and smoothed draw and of +// every sample since the site reading, needs a live charger reading +// stamped evClockAllowance before the site reading, and ends once the +// charger's first offer of this run has had its settle time: then the +// offers alone say what the meter shows. func TestEVFoundDrawWBounds(t *testing.T) { for _, tc := range []struct { name string @@ -138,12 +155,35 @@ func TestEVFoundDrawWBounds(t *testing.T) { {"a charger sample measured after the site reading", func(store *telemetry.Store, state *State) { store.Get("meter", telemetry.DerMeter).UpdatedAt = state.now().Add(-time.Second) store.Get("charger", telemetry.DerEV).UpdatedAt = state.now() + store.Get("charger", telemetry.DerEV).Data = chargerData(store, map[string]any{"control_power_observed_at": state.now().Format(time.RFC3339Nano)}) + }, 0}, + {"a sample stamped less than evClockAllowance before the site reading", func(store *telemetry.Store, _ *State) { + at := store.Get("meter", telemetry.DerMeter).UpdatedAt.Add(-evClockAllowance + time.Second) + store.Get("charger", telemetry.DerEV).Data = chargerData(store, map[string]any{"control_power_observed_at": at.Format(time.RFC3339Nano)}) + }, 0}, + {"only a sample older than one control interval before the reading", func(store *telemetry.Store, state *State) { + // The car may have stopped and started again since that sample; + // the current one, 1 s before the reading, may be ahead of it. + risenSince(store, state, 8222, 11040) + c := state.evLimit.offers["garage"] + c.draws[0].at = c.draws[0].at.Add(-10 * time.Second) + c.draws[0].seen = c.draws[0].at + state.evLimit.offers["garage"] = c }, 0}, + {"a sample since the site reading reads less", func(store *telemetry.Store, state *State) { + risenSince(store, state, 8222, 6000) + }, 6000 - (11040 - 6210)}, + // Review of #1926: OCPP stamps MeterValues with the charger's own + // clock. One running 1 s behind Core's stamps a rise sampled after + // the site reading as 1 s before it. The draw stays the one sampled + // before the reading. + {"a rise stamped before the reading by a charger clock behind Core's", func(store *telemetry.Store, state *State) { + risenSince(store, state, 6900, 11040) + }, 6900 - (11040 - 6210)}, {"latest offer bounds the draw", func(_ *telemetry.Store, state *State) { setRiseCapW(state, 6210) }, 6210}, {"measured draw below the offer", func(store *telemetry.Store, state *State) { setRiseCapW(state, 6210) - store.Update("charger", telemetry.DerEV, 4000, nil, nil) - store.Get("charger", telemetry.DerEV).UpdatedAt = store.Get("meter", telemetry.DerMeter).UpdatedAt + setChargerSample(store, 4000, nil) }, 4000}, {"smoothed draw below the sample", func(store *telemetry.Store, state *State) { setRiseCapW(state, 6210) @@ -152,12 +192,12 @@ func TestEVFoundDrawWBounds(t *testing.T) { {"raw draw below the sample", func(store *telemetry.Store, state *State) { setRiseCapW(state, 6210) r := store.Get("charger", telemetry.DerEV) - r.Data = json.RawMessage(`{"control_power_w":8222}`) + r.Data = chargerData(store, map[string]any{"control_power_w": 8222}) r.RawW = 5000 }, 5000}, {"control sample below raw and smoothed", func(store *telemetry.Store, state *State) { setRiseCapW(state, 6210) - store.Get("charger", telemetry.DerEV).Data = json.RawMessage(`{"control_power_w":5000}`) + store.Get("charger", telemetry.DerEV).Data = chargerData(store, map[string]any{"control_power_w": 5000}) }, 5000}, {"charger offline", func(store *telemetry.Store, _ *State) { store.DriverHealthMut("charger").SetOffline() @@ -198,6 +238,20 @@ func TestEVFoundDrawWBounds(t *testing.T) { } } +// risenSince keeps the fixture charger's sample of fromW, stamped +// evClockAllowance before the site reading, as noteDraw does, and makes +// its current reading toW, stamped 1 s before the site reading arrived. +func risenSince(store *telemetry.Store, state *State, fromW, toW float64) { + setChargerSample(store, fromW, nil) + c := state.evLimit.offers["garage"] + c.noteDraw(store, state.now()) + state.evLimit.offers["garage"] = c + at := store.Get("meter", telemetry.DerMeter).UpdatedAt.Add(-time.Second) + setChargerSample(store, toW, map[string]any{"control_power_observed_at": at.Format(time.RFC3339Nano)}) + // The filter's smoothed value trails the rise; this case reads the sample. + store.Get("charger", telemetry.DerEV).SmoothedW = toW +} + // Offers the meter already shows come off the consumption the credit may // fill: here another charger's 5 kW is shown, so of the 8,780 W the meter // shows as consumption only 3,780 W is left for this car. @@ -427,3 +481,38 @@ func TestSiteSimRestartMaxChargeLoweredAtRestart(t *testing.T) { } carRisesUnderOldOffer(t, s, 8280, 14*time.Second) } + +// Review of #1926: OCPP stamps MeterValues with the charger's own clock, +// often cut to the whole second. With the charger's clock 1-3 s behind +// Core's, the third review's case (3 s meter, the car at 10 A under a 16 A +// offer in force lifting its own limit 11 s in) stamps the rise before the +// site reading that does not show it yet. The draw stays the one sampled +// before that reading. Before: L2 reached 19.30 A. +func TestSiteSimRestartChargerClockBehind(t *testing.T) { + for _, lag := range []time.Duration{time.Second, 2 * time.Second, 3 * time.Second} { + t.Run(lag.String(), func(t *testing.T) { + s := restartSim(houseA(4, 12, 2)) + s.p.Meter.Every = 3 * time.Second + s.evClockLag = lag + carRisesUnderOldOffer(t, s, 6900, 11*time.Second) + }) + } +} + +// Review of #1926: a 22 kW charger (32 A) on a 3 x 25 A main fuse. The +// offer in force may be the charger's 32 A, so the rise reserve runs to +// max_charge_w, not to the fuse's rating: of the 14 kW the car draws, +// 22,080 - 11,000 W may still come on top of Core's latest 11 kW offer. +func TestEVFoundDrawWMaxChargeAboveFuse(t *testing.T) { + evW := 14000.0 + store, state := restartFixture(t, 9000, [3]float64{13, 13, 13}, -5000, 0, evW) + state.SiteFuseAmps = 25 + setMaxW(state, 22080) + c := state.evLimit.offers["garage"] + c.log[len(c.log)-1].w = 11000 + state.evLimit.offers["garage"] = c + meter := store.Get("meter", telemetry.DerMeter) + if got, want := state.evFoundDrawW(store, meter.RawW, meter.UpdatedAt, state.now(), 0), evW-(22080-11000); math.Abs(got-want) > 1e-6 { + t.Fatalf("credit %.0f W, want %.0f W", got, want) + } +} diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index acabf847f..e34208170 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -185,6 +185,8 @@ type chargerOffers struct { // configured. driver string maxW float64 + // draws are the charger's samples while that window is open (noteDraw). + draws []evDraw // carPhases is how many phases the car draws on, as the loadpoint saw // it on the site meter: 1 or 3, or 0 when unknown. carPhase is the phase // a car on one phase draws on, 1-3. @@ -409,26 +411,36 @@ func (s *State) evShownW(at time.Time) float64 { // set (at Core's start, or at a plug-in once no other managed charger was // plugged), until that offer is older than the charger's settle time. Core // then does not know which offer the charger runs on, and its first offers -// (often 0 A) say nothing of what the meter shows. A car seen drawing in -// that window is in the reading when the charger measured it within one -// control interval before the site reading: a fast charger may have applied -// a 0 A offer since an older sample, a held reading after a failed poll -// says nothing of now, and a sample newer than the site reading may hold a -// rise the meter does not show yet. A charger that samples less often (OCPP -// MeterValues every 10 s or more) counts only on the ticks just after a -// sample, and holds its battery's discharge between them. The measured draw -// is the lowest of the sample, raw and smoothed. Until the latest offer -// lands, the car may still rise from that draw to the offer in force. Core -// does not know that offer: one from before a restart, under an older -// max_charge_w, or the charger's own default. The reserve takes it as the -// larger of the loadpoint's max_charge_w and the site fuse's rating, and -// keeps the rise past the latest offer; a charger with no max_charge_w -// counts nothing. Each charger counts no -// more than its latest offer, and in all no more than the consumption the -// site meter shows (siteConsumptionW) less shownW. The car's own limit -// never reads this; only how much of our latest offers the battery reserves -// as a rise to come. -// gridW is the site reading, taken at meterAt. +// (often 0 A) say nothing of what the meter shows. +// +// A car seen drawing in that window is in the site reading when the +// charger sampled that draw before the reading, and no sample since reads +// less. The charger stamps its samples with its own clock (OCPP +// MeterValues), often cut to the whole second, and the meter's reading +// arrives some time after it was measured; so a sample counts as before +// the reading only when stamped evClockAllowance before its arrival, and +// no more than one control interval before that: a fast charger may have +// applied a 0 A offer since an older sample. The draw is the lowest of +// that sample and every sample since (noteDraw, each the lowest of the +// sample, raw and smoothed), up to the charger's current reading. So a +// rise sampled after the reading never counts while the charger's clock +// runs behind Core's by less than evClockAllowance less the meter's own +// delay. A held reading after a failed poll says nothing of now. A charger +// that samples less often (OCPP MeterValues every 10 s or more) counts +// only on the ticks from evClockAllowance to one control interval more +// after a sample, and holds its battery's discharge between them. +// +// Until the latest offer lands, the car may still rise from that draw to +// the offer in force. Core does not know that offer: one from before a +// restart, under an older max_charge_w, or the charger's own default. The +// reserve takes it as the larger of the loadpoint's max_charge_w and the +// site fuse's rating, and keeps the rise past the latest offer; a charger +// with no max_charge_w counts nothing. Each charger counts no more than its +// latest offer, and in all no more than the consumption the site meter +// shows (siteConsumptionW) less shownW. The car's own limit never reads +// this; only how much of our latest offers the battery reserves as a rise +// to come. +// gridW is the site reading, which arrived at meterAt. func (s *State) evFoundDrawW(store *telemetry.Store, gridW float64, meterAt, at time.Time, shownW float64) float64 { if store == nil { return 0 @@ -441,22 +453,26 @@ func (s *State) evFoundDrawW(store *telemetry.Store, gridW float64, meterAt, at if skew <= 0 { skew = 2 * time.Second // config's default control_interval_s } + edge := meterAt.Add(-evClockAllowance) + from := edge.Add(-skew) var w float64 for _, c := range s.evLimit.offers { n := len(c.log) - if n == 0 || c.found.at.IsZero() || at.Sub(c.found.at) >= c.settle || c.driver == "" || !(c.maxW > 0) || !finiteFuseValue(c.maxW) { + if n == 0 || !c.foundOpen(at) || c.driver == "" || !(c.maxW > 0) || !finiteFuseValue(c.maxW) { continue } - lowerW, live := store.OnlineLowerW(c.driver, telemetry.DerEV) - if !live { + now, ok := readEVDraw(store, c.driver, at) + if !ok || now.seen.Before(from) { continue } - p, ok := qualifiedFuseObservation(store.Get(c.driver, telemetry.DerEV), at) - if !ok || p.Seen().Before(meterAt.Add(-skew)) || p.At.After(meterAt) { - continue + drawW, before := now.w, !now.at.After(edge) + for _, d := range c.draws { + if d.seen.Before(from) { + continue + } + drawW, before = math.Min(drawW, d.w), before || !d.at.After(edge) } - drawW := math.Min(p.PowerW, lowerW) - if !finiteFuseValue(drawW) { + if !before { continue } unshown, _ := c.log.unshown(at, c.batterySettle()) @@ -468,6 +484,64 @@ func (s *State) evFoundDrawW(store *telemetry.Store, gridW float64, meterAt, at return math.Max(0, math.Min(w, consumptionW-shownW)) } +// evClockAllowance is how much earlier than the site reading's arrival a +// charger's sample must be stamped to count as in that reading +// (evFoundDrawW). It covers a charger clock running behind Core's, a stamp +// cut to the whole second, and the meter's own delay from measurement to +// arrival, together. +const evClockAllowance = 5 * time.Second + +// evDraw is one charger sample: when the charger measured it (its own +// clock), when it last vouched for it, and the lowest of the sample, raw +// and smoothed. +type evDraw struct { + at, seen time.Time + w float64 +} + +// readEVDraw is the charger's current sample, while its telemetry is live, +// its last poll succeeded and the sample passes qualifiedFuseObservation. +func readEVDraw(store *telemetry.Store, driver string, at time.Time) (evDraw, bool) { + lowerW, live := store.OnlineLowerW(driver, telemetry.DerEV) + if !live { + return evDraw{}, false + } + p, ok := qualifiedFuseObservation(store.Get(driver, telemetry.DerEV), at) + w := math.Min(p.PowerW, lowerW) + return evDraw{at: p.At, seen: p.Seen(), w: w}, ok && finiteFuseValue(w) +} + +// foundOpen is true while the charger has no order of this run that has +// surely landed (evFoundDrawW). +func (c chargerOffers) foundOpen(at time.Time) bool { + return !c.found.at.IsZero() && at.Sub(c.found.at) < c.settle +} + +// noteDraw keeps the charger's samples while foundOpen, for evFoundDrawW, +// over telemetry.ControlWindowDuration. +func (c *chargerOffers) noteDraw(store *telemetry.Store, at time.Time) { + if !c.foundOpen(at) || c.driver == "" { + c.draws = nil + return + } + d, ok := readEVDraw(store, c.driver, at) + if !ok { + return + } + if n := len(c.draws); n > 0 && !d.at.After(c.draws[n-1].at) { + if last := &c.draws[n-1]; d.at.Equal(last.at) { + last.w = math.Min(last.w, d.w) + if d.seen.After(last.seen) { + last.seen = d.seen + } + } + return + } + c.draws = append(slices.DeleteFunc(c.draws, func(e evDraw) bool { + return at.Sub(e.seen) > telemetry.ControlWindowDuration + }), d) +} + // siteConsumptionW is the consumption a site reading of gridW shows: grid // less each live battery, PV and V2X reading, each at the higher of raw and // smoothed. A smoothed value lags an output that just fell; the higher one @@ -611,7 +685,8 @@ func (s *State) riseAheadA(c chargerOffers) (ahead [3]float64) { // recordEVOffers keeps each plugged charger's offers, with the current each // puts on the phases its command names, for the longer of evSettle and the // power_max_age_s its driver declares, or evUnknownSettle when it declares -// none. Our own commands only: a charger's power reading never counts. +// none. Our own commands only: a charger's power reading never counts. The +// samples kept for the battery side (noteDraw) take no part in the limit. func (s *State) recordEVOffers(store *telemetry.Store, points []loadpoint.State) { now := s.now() read := now @@ -641,6 +716,7 @@ func (s *State) recordEVOffers(store *telemetry.Store, points []loadpoint.State) } c.log = c.log.keep(sent, read.Add(-c.settle)) } + c.noteDraw(store, now) offers[point.ID] = c } s.evLimit.offers = offers diff --git a/go/internal/control/sitesim_test.go b/go/internal/control/sitesim_test.go index 36abc4603..3f9d4f103 100644 --- a/go/internal/control/sitesim_test.go +++ b/go/internal/control/sitesim_test.go @@ -49,6 +49,10 @@ type simSite struct { // MeterValues do: between samples each poll repeats the last sample // with its own time. Zero samples on every poll. evEvery time.Duration + // evClockLag is how far the charger's clock runs behind Core's: it + // stamps each sample that much early, as an OCPP charger stamps + // MeterValues with its own clock (or cuts the stamp to whole seconds). + evClockLag time.Duration // meterNoise is added to each phase current Core reads, not to the // plant's own; nil reads the plant exactly. meterNoise func() float64 @@ -248,12 +252,12 @@ func (s *simSite) step() { s.ev, s.evAt = *e, now } data := s.evData() - if s.evEvery > 0 { + if s.evEvery > 0 || s.evClockLag > 0 { data = maps.Clone(data) if data == nil { data = map[string]any{} } - data["control_power_observed_at"] = s.evAt.Format(time.RFC3339Nano) + data["control_power_observed_at"] = s.evAt.Add(-s.evClockLag).Format(time.RFC3339Nano) } s.emit(s.lp.DriverName, telemetry.DerEV, s.ev.W, nil, data) } From a5cdeaeb6c26f738a5c5543476425f4907253bf2 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 07:52:37 +0100 Subject: [PATCH 60/68] docs(control): the fuse margin is opt-in, and only the fuse ceilings move The SiteFuseSafetyA comment read as if the margin were needed by default; it now says zero is the default and when to set one. The changeset named "the site's total import and export limits", which reads as the hourly import_limit; that limit does not move. It now names the fuse's import and export ceilings. Co-Authored-By: Claude Opus 5.5 --- .changeset/d-fuse-margin-default-0.md | 2 +- go/internal/control/dispatch.go | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.changeset/d-fuse-margin-default-0.md b/.changeset/d-fuse-margin-default-0.md index 2d91f84de..4231621c6 100644 --- a/.changeset/d-fuse-margin-default-0.md +++ b/.changeset/d-fuse-margin-default-0.md @@ -2,4 +2,4 @@ "ftw": patch --- -`fuse.safety_margin_a` now defaults to 0. On a site with no saved margin, FTW works to the fuse rating: the car, the home battery's charge and fuse relief, and the site's total import and export limits each move up 0.5 A per phase, to the rating. A margin is opt-in, for an inverter whose own phase limiter trips at the rating. FTW keeps any margin you have saved. If yours is exactly 0.5 A, FTW's old default, the log says so once at startup; set 0 to drop it. +`fuse.safety_margin_a` now defaults to 0. On a site with no saved margin, FTW works to the fuse rating: the car, the home battery's charge and fuse relief, and the fuse's total import and export ceilings each move up 0.5 A per phase, to the rating. A margin is opt-in, for an inverter whose own phase limiter trips at the rating. FTW keeps any margin you have saved. If yours is exactly 0.5 A, FTW's old default, the log says so once at startup; set 0 to drop it. diff --git a/go/internal/control/dispatch.go b/go/internal/control/dispatch.go index 5f7df7068..da09c8f95 100644 --- a/go/internal/control/dispatch.go +++ b/go/internal/control/dispatch.go @@ -327,9 +327,10 @@ type State struct { SiteFuseVoltage float64 SiteFusePhases int - // SiteFuseSafetyA is amps held back from the breaker. Without it the - // inverter's own limiter trips first, output falls to 0, and dispatch - // ramps from idle. Zero disables the margin. + // SiteFuseSafetyA is an opt-in margin in amps per phase below the + // breaker; zero, the default, works to the rating. Set it for an + // inverter whose own limiter trips at the rating: output falls to 0 + // and dispatch ramps from idle. SiteFuseSafetyA float64 // Peak limit — enforced only in PeakShaving mode From 358da3babcacb56efa019c805638b021e652c073 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 08:01:27 +0100 Subject: [PATCH 61/68] test(control): battery beside a minimum-step car holds the fuse line (rig s18-16) On #1910 and #1891 the battery rises beside the car to the working limit, the fuse guard cuts it by the overage plus half of safety_margin_a and holds 30 s, and the battery rises again: it hunts between 15.0 and 15.5 A on a 16 A site. Where it stands when the house moves is chance, which is why rig s18-16 failed 3 of 57 runs on those heads. #1913's cut by the overage only keeps it on the line. Co-Authored-By: Claude Opus 5.5 --- .../ev_battery_fuse_hunt_sitesim_test.go | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 go/internal/control/ev_battery_fuse_hunt_sitesim_test.go diff --git a/go/internal/control/ev_battery_fuse_hunt_sitesim_test.go b/go/internal/control/ev_battery_fuse_hunt_sitesim_test.go new file mode 100644 index 000000000..049d0a0a6 --- /dev/null +++ b/go/internal/control/ev_battery_fuse_hunt_sitesim_test.go @@ -0,0 +1,83 @@ +package control + +import ( + "fmt" + "math" + "math/rand/v2" + "testing" + "time" + + "github.com/srcfl/ftw/go/internal/sitesim" +) + +// The site rig's s18 at 16 A: a 3 A house, Charge now for a car whose only +// step is 6 A on three phases, and a 6 kW battery charge hold beside it. The +// battery may charge up to the fuse's working limit (fuseLineA) beside the +// car. Its fuse guard must then land it on that line and keep it there; a +// guard that cuts below the line and lets it rise again after its hold makes +// the battery hunt, and where it stands when the house moves is chance. The +// rig judges that move: 0.1 A more house must come off the battery. +func TestBatteryBesideMinimumCarHoldsTheFuseLine(t *testing.T) { + const carW = 6 * 690.0 + start := simStart + p := simPlant(start) + p.Fuse.RatingA, p.HouseW = 16, houseA(3, 3, 3) + p.EVSE.Delay, p.EVSE.ReadbackLag = 2*time.Second, 0 + p.Car.MaxW = carW + p.Battery = &sitesim.Battery{Phases: 3, MaxChargeW: 6000, MaxDischargeW: 6000, CapacityWh: 10000, SoC: .4, Latency: 2 * time.Second} + p.Events = []sitesim.Event{{At: 8 * time.Minute, Kind: sitesim.Change, Do: func(p *sitesim.Plant) { p.HouseW = houseA(3.1, 3.1, 3.1) }}} + lp := simLoadpoint() + lp.MinChargeW, lp.MaxChargeW, lp.AllowedStepsW = carW, carW, []float64{0, carW} + // The rig's car draws a few watts either side of its offer, so the meter + // reads the phases a hundredth of an amp either side of the line. + jitter := rand.New(rand.NewPCG(18, 16)) + s := &simSite{p: p, lp: lp, meterNoise: func() float64 { return (jitter.Float64() - .5) * .02 }, + setup: func(s *simSite) { + s.state.SetBatteryManualHold(BatteryManualHold{PowerW: 6000, ExpiresAt: start.Add(time.Hour)}) + }} + s.boot() + + // The battery each second, from 3 min, once car and battery run. + var battery []float64 + s.run(3 * time.Minute) + for s.p.Now.Before(start.Add(11*time.Minute)) && s.failure == "" { + s.step() + battery = append(battery, s.p.Battery.W) + } + if s.failure != "" { + t.Fatal(s.failure) + } + if s.p.EVSE.DrawW < carW-.1 { + t.Fatalf("car draws %.0f W, want its %.0f W step", s.p.EVSE.DrawW, carW) + } + // Five minutes of a steady house: the battery stays where it is. + steady := battery[:5*60] + lo, hi := math.Inf(1), math.Inf(-1) + for _, w := range steady { + lo, hi = math.Min(lo, w), math.Max(hi, w) + } + if hi-lo > 60 { + var moves []string + last := math.NaN() + for _, c := range s.commands { + if c.device == "battery" && c.at.After(start.Add(3*time.Minute)) && c.at.Before(start.Add(8*time.Minute)) && !(math.Abs(c.w-last) < 50) { + moves, last = append(moves, fmt.Sprintf("%s %.0f", c.at.Sub(start), c.w)), c.w + } + } + t.Errorf("battery hunts under a steady house: %.0f..%.0f W; commands %v", lo, hi, moves) + } + // The rig's judge: the 20 s before the step against the 20 s before 11 min. + mean := func(w []float64) float64 { + var sum float64 + for _, x := range w { + sum += x + } + return sum / float64(len(w)) + } + before, after := mean(battery[5*60-20:5*60]), mean(battery[len(battery)-20:]) + if after > before-40 { + t.Errorf("battery %.0f W before 0.1 A more house, %.0f W after; want at least 40 W less", before, after) + } + t.Logf("battery %.0f..%.0f W steady, %.0f -> %.0f W across the step; peak phase %.2f A", + lo, hi, before, after, s.peakA) +} From fdfbfec6b44a5bc031fbf4dd26309aba069a33a8 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 08:19:16 +0100 Subject: [PATCH 62/68] test(config): an unset fuse margin reaches Core as 0 A mutation that restored a hidden 0.5 A margin at startup passed every suite. This test pins the value newControlStateFromConfig hands Core. Co-Authored-By: Claude Opus 5.5 --- go/cmd/ftw/control_state_test.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/go/cmd/ftw/control_state_test.go b/go/cmd/ftw/control_state_test.go index 8c516be71..5f4fad63d 100644 --- a/go/cmd/ftw/control_state_test.go +++ b/go/cmd/ftw/control_state_test.go @@ -167,6 +167,29 @@ func TestBatteryLimitConfigBothZeroUsesDefault(t *testing.T) { } } +// A config with no fuse.safety_margin_a reaches Core at the fuse rating, and +// an explicit value still wins. +func TestUnsetFuseMarginReachesCoreAsZero(t *testing.T) { + cfg := parseBatteryLimitConfig(t, "", " max_charge_w: 10000\n") + ctrl := newControlStateFromConfig(cfg) + if ctrl.SiteFuseSafetyA != 0 { + t.Fatalf("unset margin reached Core as %v A, want 0", ctrl.SiteFuseSafetyA) + } + // 63 A × 230 V × 3 = 43470 W is the ceiling with no margin. + if err := ctrl.SetPeakLimit(43470); err != nil { + t.Fatalf("peak limit at the fuse: %v", err) + } + if err := ctrl.SetPeakLimit(43471); err == nil { + t.Fatal("a peak limit 1 W over the fuse was accepted") + } + + half := 0.5 + cfg.Fuse.SafetyMarginA = &half + if got := newControlStateFromConfig(cfg).SiteFuseSafetyA; got != 0.5 { + t.Fatalf("explicit 0.5 A reached Core as %v A", got) + } +} + // A "NaN" saved from an MQTT command must not come back as the PI setpoint // on every boot. func TestRestoredGridTargetIgnoresNonFinite(t *testing.T) { From dbc4332eba8f3dc639a58f1201e4344aca720593 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 08:52:42 +0100 Subject: [PATCH 63/68] test(site): s18 judges own commands apart from the house's step At margin 0 Core holds the phases at the 16 A line. Rig s18-16's 0.1 A house step at small_step then lands over the line until Core cuts: on fdfbfec6 the phase read 16.101 A for 3 s and Core cut the battery 4851 -> 4719 W within 2 s. The criterion "own commands stay inside the rated fuse" counted that stretch as Core's and failed. The owner's rule judges an overage between In and 1.2 x In by the I2t model. The criterion now skips the 10 s after the step, the same gap the minor window already leaves. On the fdfbfec6 record Core's own commands peak at 16.008 A before the step and 16.005 A after it, inside 16.01 A. Co-Authored-By: Claude Opus 5.5 --- go/test/site/ev_battery_priority_test.go | 11 ++++++-- go/test/site/rig_unit_test.go | 36 ++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/go/test/site/ev_battery_priority_test.go b/go/test/site/ev_battery_priority_test.go index ab11ca8af..c0ef73233 100644 --- a/go/test/site/ev_battery_priority_test.go +++ b/go/test/site/ev_battery_priority_test.go @@ -2,6 +2,8 @@ package site +import "math" + // #1868: the car has only [0, 4140] W, while the battery can charge at // 6000 W. The actual devices run over Modbus and OCPP; marks and the // physical meter record let the judge see which device yielded. @@ -49,15 +51,20 @@ func judgeS18(d *runData) (metrics, []criterion) { carMin := func(w []*sample) float64 { return minOf(w, func(r *sample) float64 { return carW(r, 0) }) } restart := d.firstT(back, func(r *sample) bool { return carW(r, 0) >= 4100 }) batteryBefore, batteryAfter := meanOf(pre, batSigned), meanOf(d.window(none-20, none), batSigned) + // Core holds the phases at the fuse line, so the house's 0.1 A step + // lands over it until Core cuts; the I²t model judges that stretch. + // Own commands are the rest, as in the minor window. + ownI := math.Max(maxOf(d.window(t0, small), maxAbsI), maxOf(minor, maxAbsI)) m := metrics{"battery_before_w": batteryBefore, "battery_after_w": batteryAfter, "restart_s": restart, "car_before_w": carMin(pre), "car_small_step_w": carMin(minor), "car_recovered_w": carMin(recovered), - "fuse_blown": anyBlown(d.samples), "max_i_before_house_overload": maxOf(d.window(t0, none), maxAbsI)} + "fuse_blown": anyBlown(d.samples), "max_i_before_house_overload": maxOf(d.window(t0, none), maxAbsI), + "max_i_own_commands": ownI} return m, []criterion{ crit("setup: car and battery charge together", len(pre) > 0 && carMin(pre) >= 4100 && batteryBefore > 1000), crit("battery yields before the minimum-step car", len(minor) > 0 && carMin(minor) >= 4100 && batteryAfter < batteryBefore-40), crit("car stops when house leaves no room", len(paused) > 0 && maxOf(paused, func(r *sample) float64 { return carW(r, 0) }) < 100), crit("car restarts automatically within 150 s", le(restart, 150) && len(recovered) > 0 && carMin(recovered) >= 4100), - crit("own commands stay inside the rated fuse", maxOf(d.window(t0, none), maxAbsI) <= 16.01), + crit("own commands stay inside the rated fuse", ownI <= 16.01), crit("fuse holds", !anyBlown(d.samples)), } } diff --git a/go/test/site/rig_unit_test.go b/go/test/site/rig_unit_test.go index 7e921c2ad..021c82cd2 100644 --- a/go/test/site/rig_unit_test.go +++ b/go/test/site/rig_unit_test.go @@ -139,3 +139,39 @@ func TestInvariantsTellStepsFromOwnRaises(t *testing.T) { t.Fatalf("without a step: %v", f) } } + +// s18 at margin 0: Core holds the phases at the 16 A line, so the house's own +// 0.1 A step lands over it until Core cuts. That stretch is the house's, not +// an own command. The same overage at any other time is Core's and fails. +func TestS18OwnCommandsSkipTheHouseStep(t *testing.T) { + const own = "own commands stay inside the rated fuse" + mk := func(overFrom float64) *runData { + d := &runData{marks: map[string]float64{"charge_now": 0, "small_step": 100, "no_room": 200, "room_returns": 300, "end": 450}} + for i := 0; i <= 450; i++ { + a := 16.0 + if float64(i) >= overFrom && float64(i) < overFrom+4 { + a = 16.1 + } + d.samples = append(d.samples, &sample{T: float64(i), PhaseA: [3]float64{a, a, a}}) + } + return d + } + ok := func(d *runData) bool { + _, cs := judgeS18(d) + for _, c := range cs { + if c.Name == own { + return c.OK + } + } + t.Fatalf("no %q criterion", own) + return false + } + if !ok(mk(100)) { + t.Error("4 s at 16.1 A right after the house's step failed") + } + for _, at := range []float64{50, 150} { + if ok(mk(at)) { + t.Errorf("4 s at 16.1 A from %.0f s with no outside step passed", at) + } + } +} From 04151611f43a60fda2c241936639e29f258c21fd Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 09:29:24 +0100 Subject: [PATCH 64/68] test(site): R8 reads Core's reconnect backoff from source The judge's reconnectBackoffMaxS was a fixed 60 s, checked against modbus/client.go. #1930 cuts Core's cap to 10 s, so the check would fail whichever of the two lands second. The judge now reads the cap from the source the rig builds Core from, and the 207539 shapes are set relative to it. The unit tests pass with 60 s and with #1930's 10 s applied. Co-Authored-By: Claude Opus 5.5 --- go/test/site/random_test.go | 30 ++++++++++++++++++++--- go/test/site/random_unit_test.go | 42 ++++++++++++++++++-------------- 2 files changed, 50 insertions(+), 22 deletions(-) diff --git a/go/test/site/random_test.go b/go/test/site/random_test.go index d30d9979e..6c0e9c3af 100644 --- a/go/test/site/random_test.go +++ b/go/test/site/random_test.go @@ -9,7 +9,9 @@ import ( "math/rand" "os" "path/filepath" + "regexp" "sort" + "strconv" "strings" "syscall" "time" @@ -310,12 +312,32 @@ const ( // R8: how long a battery FTW does not dispatch may hold a forced mode, // and the Core timers that may delay it after the inverter returns. - inverterDriver = "sungrow" // the rig's inverter driver (stack_test.go) - forcedBudgetS = 10.0 - reconnectBackoffMaxS = 60.0 // modbus/client.go reconnectBackoffMax - defaultRetryMaxS = 30.0 // drivers/registry.go defaultRetryMax; 0 once #1915 (C11) lands + inverterDriver = "sungrow" // the rig's inverter driver (stack_test.go) + forcedBudgetS = 10.0 + defaultRetryMaxS = 30.0 // drivers/registry.go defaultRetryMax; 0 once #1915 (C11) lands ) +// reconnectBackoffMaxS is Core's Modbus reconnect backoff cap +// (modbus/client.go reconnectBackoffMax), read from the source the rig +// builds Core from, so R8 follows Core when the cap changes (60 s, then +// 10 s with #1930). +var reconnectBackoffMaxS = coreSeconds("modbus/client.go", "reconnectBackoffMax") + +// coreSeconds reads "name = N * time.Second" from a file under go/internal. +// It panics when the line is gone: the judge has no number to fall back on. +func coreSeconds(file, name string) float64 { + b, err := os.ReadFile(filepath.Join("..", "..", "internal", file)) + if err != nil { + panic(err) + } + m := regexp.MustCompile(name + `\s*=\s*(\d+)\s*\*\s*time\.Second`).FindSubmatch(b) + if m == nil { + panic(fmt.Sprintf("no %s = N * time.Second in Core's %s", name, file)) + } + n, _ := strconv.Atoi(string(m[1])) + return float64(n) +} + // dispatchW is Core's battery order on r, + charge; false when Core // dispatched no battery. func dispatchW(r *sample) (float64, bool) { diff --git a/go/test/site/random_unit_test.go b/go/test/site/random_unit_test.go index 57a97b28e..1c7b8c36b 100644 --- a/go/test/site/random_unit_test.go +++ b/go/test/site/random_unit_test.go @@ -445,6 +445,7 @@ func (c forcedCase) run() *runData { // and Core's first good read is Core's to take. func TestInvariantsNoForcedBatteryWithoutDispatch(t *testing.T) { const forced = "no forced battery mode FTW does not dispatch" + read207539 := 182 + reconnectBackoffMaxS - 4 for _, c := range []forcedCase{ // 207533: offline 576.6-644.7 s, Core reads 9 s later, 187 / // 2668 W until FTW dispatches again 236 s after the return (C1). @@ -464,15 +465,16 @@ func TestInvariantsNoForcedBatteryWithoutDispatch(t *testing.T) { // 10 s of Core's first good read. {name: "default 8 s after Core reads again", outage: "offline", outFrom: 100, outFor: 68, readAt: 177, cmd: 187, setW: 2668, forcedTo: 185, want: true}, - // 207539: offline 508.5-590.0 s, the Modbus backoff holds Core's - // first good read back 55.7 s, and FTW dispatches 20 s after it. + // 207539: offline 508.5-590.0 s, the Modbus backoff (60 s then) + // holds Core's first good read back 55.7 s, and FTW dispatches 20 s + // after it. Here the read comes 4 s before the backoff's cap ends. // Inside Core's timers; it fails once #1915 (C11) lands. - {name: "207539: Core's reconnect backoff and default retry", outage: "offline", outFrom: 100, outFor: 82, readAt: 238, - cmd: 187, setW: 814, forcedTo: 1201, dispatchFrom: 258, want: true}, - {name: "past the registry's 30 s retry", outage: "offline", outFrom: 100, outFor: 82, readAt: 238, - cmd: 187, setW: 814, forcedTo: 1201, dispatchFrom: 285, want: false}, - // Core never reads the inverter again: the count starts 60 s after - // the return all the same. + {name: "207539: Core's reconnect backoff and default retry", outage: "offline", outFrom: 100, outFor: 82, readAt: read207539, + cmd: 187, setW: 814, forcedTo: 1201, dispatchFrom: read207539 + 20, want: true}, + {name: "past the registry's 30 s retry", outage: "offline", outFrom: 100, outFor: 82, readAt: read207539, + cmd: 187, setW: 814, forcedTo: 1201, dispatchFrom: read207539 + 47, want: false}, + // Core never reads the inverter again: the count starts at the + // backoff's cap after the return all the same. {name: "Core never reads it again", outage: "offline", outFrom: 100, outFor: 82, readAt: 1201, cmd: 187, setW: 814, forcedTo: 1201, dispatchFrom: 290, want: false}, {name: "FTW dispatches the discharge", cmd: 187, setW: 3000, forcedTo: 1201, dispatchFrom: 1, want: true}, @@ -556,20 +558,22 @@ func TestInvariantsForcedBatteryCountsFromTheLatestReturn(t *testing.T) { // The triage line is 10 s from the return, so the judge records what it // forgave beyond that line instead of hiding it. func TestInvariantsRecordForcedSecondsInsideCoreTimers(t *testing.T) { - // 207539's shape: back at 182, Core reads at 238 and dispatches at 245, - // inside the backoff alone. Forced 183-244 with no dispatch; past - // 182+10 that is 193-244. - c := forcedCase{outage: "offline", outFrom: 100, outFor: 82, readAt: 238, - cmd: 187, setW: 814, forcedTo: 1201, dispatchFrom: 245} + // 207539's shape: back at 182, Core reads 4 s before the backoff's cap + // ends (238 with 60 s) and dispatches 7 s later, inside the backoff + // alone. Forced with no dispatch until then; past 182+10 that is from + // 193 (52 s with 60 s). + read := 182 + reconnectBackoffMaxS - 4 + c := forcedCase{outage: "offline", outFrom: 100, outFor: 82, readAt: read, + cmd: 187, setW: 814, forcedTo: 1201, dispatchFrom: read + 7} m, _ := judgeInvariants(c.run()) - if in, past := m["battery_forced_in_core_timers_s"], m["battery_forced_past_allowance_s"]; in != 52.0 || past != 0.0 { - t.Errorf("in Core's timers %v s, past the allowance %v s; want 52 and 0", in, past) + if in, past, want := m["battery_forced_in_core_timers_s"], m["battery_forced_past_allowance_s"], read+6-192; in != want || past != 0.0 { + t.Errorf("in Core's timers %v s, past the allowance %v s; want %v and 0", in, past, want) } // Forced to 299: from 193 to the allowance's end inside the timers, // the rest past them. c.dispatchFrom = 300 m, _ = judgeInvariants(c.run()) - end := 238 + defaultRetryMaxS + forcedBudgetS + end := read + defaultRetryMaxS + forcedBudgetS if in, past := m["battery_forced_in_core_timers_s"], m["battery_forced_past_allowance_s"]; in != end-192 || past != 299-end { t.Errorf("in Core's timers %v s, past the allowance %v s; want %v and %v", in, past, end-192, 299-end) } @@ -595,8 +599,10 @@ func TestForcedAllowancesMatchCore(t *testing.T) { n, _ := strconv.Atoi(m[1]) return float64(n) } - if got := seconds(src("modbus/client.go"), "reconnectBackoffMax"); got != reconnectBackoffMaxS { - t.Errorf("reconnectBackoffMaxS = %v, Core's reconnectBackoffMax is %v s", reconnectBackoffMaxS, got) + // reconnectBackoffMaxS is read from Core's source; the 207539 shapes + // below need a backoff that can hold Core's first read back past 4 s. + if reconnectBackoffMaxS < 5 { + t.Errorf("Core's reconnectBackoffMax is %v s; rework the 207539 shapes", reconnectBackoffMaxS) } registry := src("drivers/registry.go") // Today the registry sends the default on a failure and on its retry From dcf498247af3dfa5fa14bb01faaff4de2f0e0fcf Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 09:39:25 +0100 Subject: [PATCH 65/68] fix(control): no cut of an unseen car, no landing from a 1p house move Two regressions against #1913 from the final review. A car the loadpoint has not seen on three phases may draw on one phase Core does not know. The alone rise (aloneA) missed its landing when any other phase moved a step in the same reading, so the whole raise counted as still to come and C4 cut a car with every phase under the line, at most session starts with a 10 s meter. riseAheadA now takes the largest rise for such a car, as for a one-phase car whose phase is not known, and the smallest only once the car is seen on three phases. A one-phase order never knows the car's phase, so a house load moving alone on any phase read as its cut landing and took the cover off a cut still on its way. A one-phase move now counts only on a known car phase. Co-Authored-By: Claude Opus 5.5 --- .changeset/s1-ev-cut-landed-and-unshown.md | 2 +- go/internal/control/ev_fuse_budget.go | 63 +++++-------------- .../control/ev_fuse_cut_netting_test.go | 53 +++++++++++++--- 3 files changed, 60 insertions(+), 58 deletions(-) diff --git a/.changeset/s1-ev-cut-landed-and-unshown.md b/.changeset/s1-ev-cut-landed-and-unshown.md index 3e8cdb1fa..202e88fbf 100644 --- a/.changeset/s1-ev-cut-landed-and-unshown.md +++ b/.changeset/s1-ev-cut-landed-and-unshown.md @@ -2,4 +2,4 @@ "ftw": patch --- -The car's fuse cut now acts on what the site meter shows. A cut the meter already shows no longer counts as still on its way, so when the house adds load after it, FTW cuts again once the fuse's heat budget is spent instead of waiting up to three minutes. A house load that moves on one phase alone is not taken for the car's cut landing, so it no longer stacks a second cut on a slow charger. A raise that is on its way but no longer fits now comes off before it lands, when it would take a phase above 1.2 times the fuse rating, or over the line on a phase whose heat budget is spent. For a car the site meter has shown on three phases, this also holds when the house steps up on one phase alone. +The car's fuse cut now acts on what the site meter shows. A cut the meter already shows no longer counts as still on its way, so when the house adds load after it, FTW cuts again once the fuse's heat budget is spent instead of waiting up to three minutes. A house load that moves on one phase alone is not taken for the car's cut landing, so it no longer stacks a second cut on a slow charger. A raise that is on its way but no longer fits now comes off before it lands, when it would take a phase above 1.2 times the fuse rating, or over the line on a phase whose heat budget is spent. For a car the site meter has shown on three phases, this also holds when the house steps up on one phase alone. Until then, a rise on any phase counts as the raise landing, so a car on one phase is not cut while every phase is under the line. diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index 95b41bd1e..060db68fa 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -196,10 +196,6 @@ type chargerOffers struct { riseBaseA [3]float64 riseFromA float64 riseSet bool - // aloneA is each phase's rise since riseBaseA counted only over the - // readings in which the other phases moved less than a step: the rise - // a car on that one phase may have made (riseAheadA). - aloneA [3]float64 } // evMoveA is half a charger step. An order landing shows on the site meter @@ -241,8 +237,9 @@ func chargerMoveA(prev, now []float64) (alikeA, oneA float64, phase int) { // charger on each phase (shownA), in a shape the offers can take there. A // car the loadpoint has seen draw on one phase, or a one-phase order, is // one level on every phase: every phase dropping alike moves it, and so -// does a move on the car's phase alone, or on any one phase while that -// phase is not known. A three-phase order moves only on every phase alike: +// does a move on the car's phase alone where that phase is known. A move on +// one phase while the car's phase is not known may be a house load, so it +// does not count. A three-phase order moves only on every phase alike: // a phase that moves alone is a house load, or a car not yet seen that // draws on one phase, and Core cannot tell which. The shown current moves // only toward the latest offer, and stays within the offers the reading @@ -265,17 +262,14 @@ func (s *State) seeOffers(meter *telemetry.DerReading, gridW float64) { alikeA, oneA, phase = chargerMoveA(prev[:len(amps)], now[:len(amps)]) } for id, c := range lim.offers { - if read && c.riseSet { - c.aloneA = addAloneA(c.aloneA, prev[:len(amps)], now[:len(amps)]) - } if read && c.readable() { var moveA [3]float64 switch { case c.carPhase > 0 || c.log[0].n == 1: // One car on one phase: one level, moved by a drop of - // either shape or by its phase alone. + // every phase alike or by its known phase alone. m := math.Min(0, alikeA) - if c.carPhase == 0 || c.carPhase == phase { + if c.carPhase == phase { m += oneA } moveA = [3]float64{m, m, m} @@ -310,22 +304,6 @@ func (s *State) seeOffers(meter *telemetry.DerReading, gridW float64) { } } -// addAloneA adds to each phase's alone rise its move from one reading to -// the next when every other phase moved less than a step (evStepA): no -// charger step landed there, so the move may be a car on that one phase. -func addAloneA(aloneA [3]float64, prev, now []float64) [3]float64 { - for p := range now { - held := true - for q := range now { - held = held && (q == p || math.Abs(now[q]-prev[q]) < evStepA) - } - if held { - aloneA[p] += now[p] - prev[p] - } - } - return aloneA -} - // batteryOrderMoves reports whether one of our battery orders of the last // evSettle moves the site's phases by evMoveA or more. func (s *State) batteryOrderMoves() bool { @@ -478,18 +456,14 @@ func (s *State) unshownOrders(at time.Time, perPhase bool) (rise, cover pendingL // riseAheadA is the rise on each phase the site meter has still to show // of the charger's latest offer: the raise since riseFromA less the meter's // own rise since the raise went out, within the offers the reading may -// show. A three-phase order takes the smallest rise across the phases: a -// house step on some phases does not show the raise on the rest. A car on -// one phase takes its own phase's rise, or the largest where the phase is -// not known. For a car not yet seen on three phases, a phase that has -// risen a step or more alone may be the car taking the raise on one phase: -// its rise over the readings in which the other phases moved less than a -// step (aloneA). Each reading is judged against the one before, so house -// drift on another phase while the raise travels, or under a step in the -// landing reading, does not hide it. A landing counts in whatever shape -// it comes, a slow ramp or beside a house load that moves in the same -// reading. A house load that drops while the raise travels still reads as -// raise not shown yet, by as much as it dropped. +// show. A car the loadpoint has seen draw on three phases takes the +// smallest rise across the phases: a house step on some phases does not +// show the raise on the rest. A car on one phase takes its own phase's +// rise. Any other car takes the largest rise: until the loadpoint has seen +// it, it may draw on one phase Core does not know. A landing counts in +// whatever shape it comes, a slow ramp or beside a house load that moves +// in the same reading. A house load that drops while the raise travels +// still reads as raise not shown yet, by as much as it dropped. func (s *State) riseAheadA(c chargerOffers) (ahead [3]float64) { lim := &s.evLimit n := min(s.SiteFusePhases, len(ahead)) @@ -505,15 +479,8 @@ func (s *State) riseAheadA(c chargerOffers) (ahead [3]float64) { switch { case c.carPhase > 0 && c.carPhase <= n: riseA, phases = rises[c.carPhase-1], ahead[c.carPhase-1:c.carPhase] - case c.carPhases == 1 || latest.n == 1: + case c.carPhases != 3 || latest.n == 1: riseA = slices.Max(rises) - case c.carPhases != 3: - // A car not yet seen may draw on a phase that rose alone. - for i := range rises { - if c.aloneA[i] >= 2*evMoveA { - riseA = math.Max(riseA, math.Min(c.aloneA[i], rises[i])) - } - } } low, high := c.offerRangeA(lim.readingAt) toComeA := math.Max(0, latest.a-math.Min(high, math.Max(low, c.riseFromA+riseA))) @@ -552,7 +519,7 @@ func (s *State) recordEVOffers(store *telemetry.Store, points []loadpoint.State) if n == 0 && !s.evLimit.set { c.found, c.shownA = sent, [3]float64{sent.a, sent.a, sent.a} } else if _, high := c.offerRangeA(now); sent.a > high && !c.riseSet && s.evLimit.phasesSeen { - c.riseBaseA, c.riseFromA, c.riseSet, c.aloneA = s.evLimit.phasesA, high, true, [3]float64{} + c.riseBaseA, c.riseFromA, c.riseSet = s.evLimit.phasesA, high, true } c.log = c.log.keep(sent, read.Add(-c.settle)) } diff --git a/go/internal/control/ev_fuse_cut_netting_test.go b/go/internal/control/ev_fuse_cut_netting_test.go index 6a6e0479b..fdc60ce6a 100644 --- a/go/internal/control/ev_fuse_cut_netting_test.go +++ b/go/internal/control/ev_fuse_cut_netting_test.go @@ -103,7 +103,11 @@ func (r *cutRig) deliver(gridW float64, data []byte) float64 { r.now = r.now.Add(time.Second) r.store.Update("meter", telemetry.DerMeter, gridW, nil, data) r.store.Get("meter", telemetry.DerMeter).UpdatedAt = r.now - _, _, points, configs := evMeterBudgetFixture(r.t, 0, nil, r.offerW, "3p") + mode := "3p" + if r.phases == 1 { + mode = "1p" + } + _, _, points, configs := evMeterBudgetFixture(r.t, 0, nil, r.offerW, mode) points[0].CommandedPhases, points[0].CarPhases = r.phases, r.carPhases capW, _ := EVFuseBudget(r.store, r.state, points, configs, 17250) if capW < r.offerW { @@ -394,13 +398,14 @@ func TestEVFuseCutCoversOnlyThePhaseOverageItWasSentFor(t *testing.T) { // no longer fits cuts before the meter shows it. On a 16 A fuse with no // margin, a charger that declares 40 s takes the car from 6 A to 16 A with // L1 at 6 A: the step fits under the line. 30 s later the house adds 9.7 A -// on L1 and 3 A on L2 before the raise lands. L1 reads 15.7 A, under the -// line, but the raise would take it to 25.7 A, over 1.2 x In: on that -// reading the raise comes off as far as it takes L1 over the line, to 6 A -// in whole amps. Before, Core waited for the meter to show it. +// on L1 and 3 A on L2 before the raise lands. For a car the loadpoint has +// seen draw on three phases, L1 reads 15.7 A, under the line, but the raise +// would take it to 25.7 A, over 1.2 x In: on that reading the raise comes +// off as far as it takes L1 over the line, to 6 A in whole amps. Before, +// Core waited for the meter to show it. func TestEVFuseRaiseOnItsWayThatNoLongerFitsCutsAtOnce(t *testing.T) { r := newCutRig(t, 4140, 40) - r.state.SiteFuseAmps = 16 + r.state.SiteFuseAmps, r.carPhases = 16, 3 for range 60 { r.read([3]float64{6, 6, 6}) } @@ -575,9 +580,9 @@ func TestEVFuseRaiseThatLandedIsNotCountedTwice(t *testing.T) { // of its reading when the raise went out, over the whole response time: // 0.6 A of drift made the raise count as still to come, L1 read 34 A, and // Core cut to 4,830 W one second after the landing (field matrix with -// 0.7 A on L2 every 17 s: car1p cut 11,100 -> 0 W). The landing now counts -// when L2 moves less than a step in the reading it lands on, or drifts -// before it. +// 0.7 A on L2 every 17 s: car1p cut 11,100 -> 0 W). A house load of a +// step or more on L2 in the landing reading hid it too. Until the loadpoint +// has seen the car on three phases, the largest rise counts as the landing. func TestEVFuseUnseenOnePhaseCarLandsBesideDrift(t *testing.T) { for _, tc := range []struct { name string @@ -589,6 +594,8 @@ func TestEVFuseUnseenOnePhaseCarLandsBesideDrift(t *testing.T) { {"drift_-0.6A_before", -0.6, 0}, {"drift_0.7A_in_the_landing_reading", 0, 0.7}, {"drift_-0.7A_in_the_landing_reading", 0, -0.7}, + {"house_1.2A_on_L2_in_the_landing_reading", 0, 1.2}, + {"house_-1.2A_on_L2_in_the_landing_reading", 0, -1.2}, } { t.Run(tc.name, func(t *testing.T) { r := newCutRig(t, 4140, 40) // 6 A a phase ordered @@ -639,3 +646,31 @@ func TestEVFuseLoadCyclingOnTheOverPhaseDoesNotHunt(t *testing.T) { }) } } + +// A one-phase order's car phase is not known, so a house load that moves +// alone on another phase is not its cut landing. 25 A fuse, a charger that +// declares 40 s, 16 A ordered on one phase: L1 reads 28 A and the heat cut +// takes it to 13 A. While that cut travels, a 3 A load on L2 switches off. +// Before, that move took 3 A of cover off the cut still on its way, and +// Core cut again for an overage the first cut already covered. +func TestEVFuseOnePhaseOrderHouseMoveIsNotTheCutLanding(t *testing.T) { + r := newCutRig(t, 3680, 40) // 16 A on one phase + r.phases = 1 + r.snap = func(w float64) float64 { return math.Floor(w/230) * 230 } + for range 120 { + r.read([3]float64{20, 15, 12}) + } + for i := 0; i < 120 && r.offerW == 3680; i++ { + r.read([3]float64{28, 15, 12}) // 3 A over the 25 A line + } + first := r.offerW + if first >= 3680 { + t.Fatalf("no heat cut with L1 3 A over the line") + } + r.read([3]float64{28, 15, 12}) + for i := range 20 { + if r.read([3]float64{28, 12, 12}); r.offerW != first { + t.Fatalf("offer %.0f W %d s after a 3 A house load on L2 switched off, want the one cut to %.0f W", r.offerW, i+1, first) + } + } +} From 040ebb104ced1b2929c3acd4fe3e623da66ab97a Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 09:56:16 +0100 Subject: [PATCH 66/68] fix(control): judge a restart sample by its arrival, not its stamp The 5 s clock allowance let the restart credit count a charger sample taken 5-7 s before the site reading. A car that stopped after that sample (a fast charger applying the 0 A sent while the meter was stale, or the car pausing) still counted, the battery ended the discharge the car's return needed, and L2 reached 21 A on a 16 A fuse when it resumed. Core now judges a sample by when it first arrived on Core's clock. It counts as in the reading only when it arrived evMeterDelay (1 s) before the reading, and no more than one control interval before that. A sample already there when Core began to watch the charger arrived at a time Core does not know, so it never counts. The charger's stamp only tells samples apart, so a charger clock behind Core's no longer matters. Co-Authored-By: Claude Opus 5.5 --- .changeset/s4-ev-base-after-restart.md | 2 +- .../control/ev_base_after_restart_test.go | 70 ++++++++--- go/internal/control/ev_fuse_budget.go | 114 ++++++++++++------ 3 files changed, 128 insertions(+), 58 deletions(-) diff --git a/.changeset/s4-ev-base-after-restart.md b/.changeset/s4-ev-base-after-restart.md index 02227f9ac..b9eb43572 100644 --- a/.changeset/s4-ev-base-after-restart.md +++ b/.changeset/s4-ev-base-after-restart.md @@ -2,4 +2,4 @@ "ftw": patch --- -After a restart, the home battery no longer stays in discharge for a car the meter already shows charging. Until the charger's first order of the new run can have landed, the battery counts the car's measured draw as part of the meter reading, never above FTW's latest order to the car and never above the consumption the site meter shows. FTW does not know the charger's offer in force then: one from before the restart, under an older max_charge_w, or the charger's own default. So the battery still keeps room for the car to rise from its draw to the larger of the charger's max_charge_w and the site fuse's rating. On a site whose fuse allows more than the car's draw plus FTW's latest order, that leaves no credit; a charger with no max_charge_w gets none either. The draw counts only when the charger stamped a sample at least 5 s, and at most one control interval more, before the site reading arrived, and its last poll succeeded. The 5 s cover a charger clock running behind FTW's, as OCPP chargers stamp their own samples. The lowest sample since then counts, so a rise the meter does not show yet never does. A charger that samples every 30 s or more rarely gets the credit. Before, the 0 A orders FTW sent while the meter was still starting counted as the car's draw, so a lower order looked like a rise and the battery kept discharging toward its floor. +After a restart, the home battery no longer stays in discharge for a car the meter already shows charging. Until the charger's first order of the new run can have landed, the battery counts the car's measured draw as part of the meter reading, never above FTW's latest order to the car and never above the consumption the site meter shows. FTW does not know the charger's offer in force then: one from before the restart, under an older max_charge_w, or the charger's own default. So the battery still keeps room for the car to rise from its draw to the larger of the charger's max_charge_w and the site fuse's rating. On a site whose fuse allows more than the car's draw plus FTW's latest order, that leaves no credit; a charger with no max_charge_w gets none either. The draw counts only when the sample reached FTW at least 1 s, and at most one control interval more, before the site reading did, and the charger's last poll succeeded. FTW judges a sample by when it arrived, not by the charger's own stamp, so a charger clock running behind FTW's, as OCPP chargers stamp their own samples, does not matter. A sample already there when FTW started does not count. The lowest sample since then counts, so a rise the meter does not show yet never does. A charger that samples every 30 s or more rarely gets the credit. Before, the 0 A orders FTW sent while the meter was still starting counted as the car's draw, so a lower order looked like a rise and the battery kept discharging toward its floor. diff --git a/go/internal/control/ev_base_after_restart_test.go b/go/internal/control/ev_base_after_restart_test.go index 29c9ec0f4..830eb906d 100644 --- a/go/internal/control/ev_base_after_restart_test.go +++ b/go/internal/control/ev_base_after_restart_test.go @@ -18,8 +18,8 @@ import ( // 6,210 W (9 A on three phases) 2 s ago. The charger takes 40 s to apply an // order, so the car still draws what it drew before the restart. Its // max_charge_w is 11,040 W (16 A). evW is what the charger measures, -// stamped evClockAllowance before the site reading arrived; the site meter -// reads gridW with the phase currents phaseA, and the PV inverter pvW. +// arriving evMeterDelay before the site reading; the site meter reads +// gridW with the phase currents phaseA, and the PV inverter pvW. func restartFixture(t *testing.T, gridW float64, phaseA [3]float64, batteryW, pvW, evW float64) (*telemetry.Store, *State) { t.Helper() store := telemetry.NewStore() @@ -47,6 +47,7 @@ func restartFixture(t *testing.T, gridW float64, phaseA [3]float64, batteryW, pv state.evLimit.offers = map[string]chargerOffers{"garage": { log: commandLog{found, {at: now.Add(-4 * time.Second), w: 0, a: 0, n: 3}, {at: now.Add(-2 * time.Second), w: 6210, a: 9, n: 3}}, settle: evUnknownSettle, found: found, driver: "charger", maxW: 11040, + watchFrom: found.at, // Core saw the sample arrive }} return store, state } @@ -103,10 +104,10 @@ func TestEVBaseAfterRestartCreditStaysInsideTheMeter(t *testing.T) { } } -// chargerData is the fixture charger's data: its sample stamped -// evClockAllowance before the site reading arrived, with extra fields. +// chargerData is the fixture charger's data: its sample stamped on the +// charger's clock 5 s before the site reading arrived, with extra fields. func chargerData(store *telemetry.Store, extra map[string]any) json.RawMessage { - at := store.Get("meter", telemetry.DerMeter).UpdatedAt.Add(-evClockAllowance) + at := store.Get("meter", telemetry.DerMeter).UpdatedAt.Add(-5 * time.Second) d := map[string]any{"control_power_observed_at": at.Format(time.RFC3339Nano)} maps.Copy(d, extra) raw, _ := json.Marshal(d) @@ -114,11 +115,11 @@ func chargerData(store *telemetry.Store, extra map[string]any) json.RawMessage { } // setChargerSample makes w the fixture charger's reading (chargerData), -// arriving with the site reading. +// arriving evMeterDelay before the site reading. func setChargerSample(store *telemetry.Store, w float64, extra map[string]any) { store.Update("charger", telemetry.DerEV, w, nil, chargerData(store, extra)) store.RecordDriverSuccess("charger") - store.Get("charger", telemetry.DerEV).UpdatedAt = store.Get("meter", telemetry.DerMeter).UpdatedAt + store.Get("charger", telemetry.DerEV).UpdatedAt = store.Get("meter", telemetry.DerMeter).UpdatedAt.Add(-evMeterDelay) } // setMaxW sets the fixture charger's max_charge_w. @@ -137,8 +138,8 @@ func setRiseCapW(state *State, w float64) { // The credit never exceeds the latest offer, keeps room for the car's rise // to its max, takes the lowest of the sample, raw and smoothed draw and of -// every sample since the site reading, needs a live charger reading -// stamped evClockAllowance before the site reading, and ends once the +// every sample since the site reading, needs a live charger reading that +// arrived evMeterDelay before the site reading, and ends once the // charger's first offer of this run has had its settle time: then the // offers alone say what the meter shows. func TestEVFoundDrawWBounds(t *testing.T) { @@ -157,9 +158,10 @@ func TestEVFoundDrawWBounds(t *testing.T) { store.Get("charger", telemetry.DerEV).UpdatedAt = state.now() store.Get("charger", telemetry.DerEV).Data = chargerData(store, map[string]any{"control_power_observed_at": state.now().Format(time.RFC3339Nano)}) }, 0}, - {"a sample stamped less than evClockAllowance before the site reading", func(store *telemetry.Store, _ *State) { - at := store.Get("meter", telemetry.DerMeter).UpdatedAt.Add(-evClockAllowance + time.Second) - store.Get("charger", telemetry.DerEV).Data = chargerData(store, map[string]any{"control_power_observed_at": at.Format(time.RFC3339Nano)}) + // Final review of #1926: the charger's stamp does not say when the + // sample was measured on Core's clock; its arrival bounds that. + {"a sample that arrived with the site reading, however early its stamp", func(store *telemetry.Store, _ *State) { + store.Get("charger", telemetry.DerEV).UpdatedAt = store.Get("meter", telemetry.DerMeter).UpdatedAt }, 0}, {"only a sample older than one control interval before the reading", func(store *telemetry.Store, state *State) { // The car may have stopped and started again since that sample; @@ -167,7 +169,8 @@ func TestEVFoundDrawWBounds(t *testing.T) { risenSince(store, state, 8222, 11040) c := state.evLimit.offers["garage"] c.draws[0].at = c.draws[0].at.Add(-10 * time.Second) - c.draws[0].seen = c.draws[0].at + c.draws[0].got = c.draws[0].got.Add(-10 * time.Second) + c.draws[0].seen = c.draws[0].got state.evLimit.offers["garage"] = c }, 0}, {"a sample since the site reading reads less", func(store *telemetry.Store, state *State) { @@ -238,16 +241,18 @@ func TestEVFoundDrawWBounds(t *testing.T) { } } -// risenSince keeps the fixture charger's sample of fromW, stamped -// evClockAllowance before the site reading, as noteDraw does, and makes -// its current reading toW, stamped 1 s before the site reading arrived. +// risenSince keeps the fixture charger's sample of fromW, arrived +// evMeterDelay before the site reading, as noteDraw does, and makes its +// current reading toW, stamped 1 s before the site reading but arriving +// with it. func risenSince(store *telemetry.Store, state *State, fromW, toW float64) { setChargerSample(store, fromW, nil) c := state.evLimit.offers["garage"] c.noteDraw(store, state.now()) state.evLimit.offers["garage"] = c - at := store.Get("meter", telemetry.DerMeter).UpdatedAt.Add(-time.Second) - setChargerSample(store, toW, map[string]any{"control_power_observed_at": at.Format(time.RFC3339Nano)}) + meterAt := store.Get("meter", telemetry.DerMeter).UpdatedAt + setChargerSample(store, toW, map[string]any{"control_power_observed_at": meterAt.Add(-time.Second).Format(time.RFC3339Nano)}) + store.Get("charger", telemetry.DerEV).UpdatedAt = meterAt // The filter's smoothed value trails the rise; this case reads the sample. store.Get("charger", telemetry.DerEV).SmoothedW = toW } @@ -499,6 +504,35 @@ func TestSiteSimRestartChargerClockBehind(t *testing.T) { } } +// Final review of #1926: a sample from before the car stopped. A fast +// charger (2 s) applies the 0 A sent while the meter was silent at about +// 3 s, and the car resumes only at 11 s, after Core's 9 A order has +// landed. The charger samples every 10 s (OCPP MeterValues), at 2 s and +// 12 s. The readings from 6 s on show the car at 0 W. Core began to watch +// the charger at 7 s and does not know when the 8,280 W sample arrived, so +// it gives no credit, and the battery keeps the discharge the car's return +// needs. Judged by the charger's stamp against a 5 s allowance, that +// sample counted at 9 s, the battery ended its discharge, and L2 reached +// 21 A when the car resumed. With no credit at all, the peak is 18.10 A. +func TestSiteSimRestartOldSampleOfACarThatStopped(t *testing.T) { + s := restartSim(houseA(4, 12, 2)) + s.p.PVW = 0 + s.p.EVSE.Delay = 2 * time.Second + s.evEvery = 10 * time.Second + s.p.Events = append(s.p.Events, + sitesim.Event{At: 3 * time.Second, Kind: sitesim.Change, Do: func(p *sitesim.Plant) { p.Car.MaxW = 0 }}, + sitesim.Event{At: 11 * time.Second, Kind: sitesim.Change, Do: func(p *sitesim.Plant) { p.Car.MaxW = 11040 }}) + s.boot() + s.evAt = s.p.Now.Add(2*time.Second - s.evEvery) // samples at 2 s and 12 s + s.run(time.Minute) + if s.failure != "" { + t.Fatal(s.failure) + } + if s.peakA > 18.11 { + t.Fatalf("a phase reached %.2f A; with no credit it peaks at 18.10 A", s.peakA) + } +} + // Review of #1926: a 22 kW charger (32 A) on a 3 x 25 A main fuse. The // offer in force may be the charger's 32 A, so the rise reserve runs to // max_charge_w, not to the fuse's rating: of the 14 kW the car draws, diff --git a/go/internal/control/ev_fuse_budget.go b/go/internal/control/ev_fuse_budget.go index 3eb4ae82c..c782d3819 100644 --- a/go/internal/control/ev_fuse_budget.go +++ b/go/internal/control/ev_fuse_budget.go @@ -185,8 +185,11 @@ type chargerOffers struct { // configured. driver string maxW float64 - // draws are the charger's samples while that window is open (noteDraw). - draws []evDraw + // draws are the charger's samples while that window is open (noteDraw), + // and watchFrom the receipt of the first reading noteDraw took there: + // a sample already there then may have arrived at any earlier time. + draws []evDraw + watchFrom time.Time // carPhases is how many phases the car draws on, as the loadpoint saw // it on the site meter: 1 or 3, or 0 when unknown. carPhase is the phase // a car on one phase draws on, 1-3. @@ -394,19 +397,19 @@ func (s *State) evShownW(at time.Time) float64 { // A car seen drawing in that window is in the site reading when the // charger sampled that draw before the reading, and no sample since reads // less. The charger stamps its samples with its own clock (OCPP -// MeterValues), often cut to the whole second, and the meter's reading -// arrives some time after it was measured; so a sample counts as before -// the reading only when stamped evClockAllowance before its arrival, and -// no more than one control interval before that: a fast charger may have -// applied a 0 A offer since an older sample. The draw is the lowest of -// that sample and every sample since (noteDraw, each the lowest of the -// sample, raw and smoothed), up to the charger's current reading. So a -// rise sampled after the reading never counts while the charger's clock -// runs behind Core's by less than evClockAllowance less the meter's own -// delay. A held reading after a failed poll says nothing of now. A charger -// that samples less often (OCPP MeterValues every 10 s or more) counts -// only on the ticks from evClockAllowance to one control interval more -// after a sample, and holds its battery's discharge between them. +// MeterValues), which may run behind Core's by any amount, so Core judges +// a sample by when it first arrived on Core's clock (noteDraw): a sample +// arrives after it was measured. It counts as before the reading only +// when Core saw it arrive evMeterDelay before the reading did (arrivedBy), +// and no more than one control interval before that: a fast charger may +// have applied a 0 A offer, or the car paused, since an older sample. The +// draw is the lowest of that sample and every sample since (noteDraw, each +// the lowest of the sample, raw and smoothed), up to the charger's current +// reading. So a rise sampled after the reading never counts, whatever the +// charger's clock. A held reading after a failed poll says nothing of now. +// A charger that samples less often (OCPP MeterValues every 10 s or more) counts +// only on the ticks from evMeterDelay to one control interval more after a +// sample arrives, and holds its battery's discharge between them. // // Until the latest offer lands, the car may still rise from that draw to // the offer in force. Core does not know that offer: one from before a @@ -431,7 +434,7 @@ func (s *State) evFoundDrawW(store *telemetry.Store, gridW float64, meterAt, at if skew <= 0 { skew = 2 * time.Second // config's default control_interval_s } - edge := meterAt.Add(-evClockAllowance) + edge := meterAt.Add(-evMeterDelay) from := edge.Add(-skew) var w float64 for _, c := range s.evLimit.offers { @@ -440,15 +443,24 @@ func (s *State) evFoundDrawW(store *telemetry.Store, gridW float64, meterAt, at continue } now, ok := readEVDraw(store, c.driver, at) - if !ok || now.seen.Before(from) { + if !ok { continue } - drawW, before := now.w, !now.at.After(edge) + for _, d := range c.draws { + if d.at.Equal(now.at) { + d.merge(now) + now = d + } + } + if now.seen.Before(from) { + continue + } + drawW, before := now.w, c.arrivedBy(now, edge) for _, d := range c.draws { if d.seen.Before(from) { continue } - drawW, before = math.Min(drawW, d.w), before || !d.at.After(edge) + drawW, before = math.Min(drawW, d.w), before || c.arrivedBy(d, edge) } if !before { continue @@ -462,31 +474,55 @@ func (s *State) evFoundDrawW(store *telemetry.Store, gridW float64, meterAt, at return math.Max(0, math.Min(w, consumptionW-shownW)) } -// evClockAllowance is how much earlier than the site reading's arrival a -// charger's sample must be stamped to count as in that reading -// (evFoundDrawW). It covers a charger clock running behind Core's, a stamp -// cut to the whole second, and the meter's own delay from measurement to -// arrival, together. -const evClockAllowance = 5 * time.Second +// evMeterDelay is how much earlier than the site reading a charger's +// sample must arrive to count as in that reading (evFoundDrawW): the site +// meter's own delay from measurement to arrival. +const evMeterDelay = time.Second -// evDraw is one charger sample: when the charger measured it (its own -// clock), when it last vouched for it, and the lowest of the sample, raw -// and smoothed. +// evDraw is one charger sample: its stamp on the charger's own clock, +// which only tells samples apart; when it first arrived on Core's clock; +// when the charger last vouched for it, on Core's clock (its arrival, or a +// later confirmed reading); and the lowest of the sample, raw and smoothed. type evDraw struct { - at, seen time.Time - w float64 + at, got, seen time.Time + confirmed bool + w float64 +} + +// merge folds a repeat of the same sample into e: the lowest draw, the +// first arrival, and a later receipt only where the charger confirms it. +func (e *evDraw) merge(d evDraw) { + e.w = math.Min(e.w, d.w) + if d.got.Before(e.got) { + e.got = d.got + } + if d.confirmed && d.seen.After(e.seen) { + e.seen, e.confirmed = d.seen, true + } } // readEVDraw is the charger's current sample, while its telemetry is live, -// its last poll succeeded and the sample passes qualifiedFuseObservation. +// its last poll succeeded and the sample passes qualifiedFuseObservation, +// taken as arriving with the charger's current reading. func readEVDraw(store *telemetry.Store, driver string, at time.Time) (evDraw, bool) { lowerW, live := store.OnlineLowerW(driver, telemetry.DerEV) if !live { return evDraw{}, false } - p, ok := qualifiedFuseObservation(store.Get(driver, telemetry.DerEV), at) + r := store.Get(driver, telemetry.DerEV) + p, ok := qualifiedFuseObservation(r, at) + if !ok { + return evDraw{}, false + } w := math.Min(p.PowerW, lowerW) - return evDraw{at: p.At, seen: p.Seen(), w: w}, ok && finiteFuseValue(w) + return evDraw{at: p.At, got: r.UpdatedAt, seen: r.UpdatedAt, confirmed: !p.ConfirmedAt.IsZero(), w: w}, finiteFuseValue(w) +} + +// arrivedBy reports whether Core saw sample d arrive by edge. A sample +// already there when Core began to watch the charger arrived at a time +// Core does not know, so it never counts as arrived. +func (c chargerOffers) arrivedBy(d evDraw, edge time.Time) bool { + return !c.watchFrom.IsZero() && d.got.After(c.watchFrom) && !d.got.After(edge) } // foundOpen is true while the charger has no order of this run that has @@ -496,22 +532,22 @@ func (c chargerOffers) foundOpen(at time.Time) bool { } // noteDraw keeps the charger's samples while foundOpen, for evFoundDrawW, -// over telemetry.ControlWindowDuration. +// over telemetry.ControlWindowDuration, each with its first arrival. func (c *chargerOffers) noteDraw(store *telemetry.Store, at time.Time) { if !c.foundOpen(at) || c.driver == "" { - c.draws = nil + c.draws, c.watchFrom = nil, time.Time{} return } d, ok := readEVDraw(store, c.driver, at) if !ok { return } + if c.watchFrom.IsZero() { + c.watchFrom = d.got + } if n := len(c.draws); n > 0 && !d.at.After(c.draws[n-1].at) { if last := &c.draws[n-1]; d.at.Equal(last.at) { - last.w = math.Min(last.w, d.w) - if d.seen.After(last.seen) { - last.seen = d.seen - } + last.merge(d) } return } From 2b30933be9428de8f332e825e00c7782b820a4b4 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 10:03:20 +0100 Subject: [PATCH 67/68] test(site): judge overages at the fuse rating, not fuse - 1 A At margin 0 the car in s8-60-25 settles at the rating, as the owner's rule says, and the rig's old 1 A hidden margin failed it: 271 s above 24 A against 67 s allowed, with no second over 25 A. siterig/full has the same threshold in overage() (s9, s10, s11), the random invariants and s15bat. Port #1907's judge hunks: s3, s8, s9-s11, s15bat and the invariants now count time over the fuse rating. TestS8JudgesAtTheFuse and #1907's TestInvariantsJudgeAtTheFuse fail on the old judges. Co-Authored-By: Claude Opus 5.5 --- go/test/site/README.md | 2 +- go/test/site/evaluate_test.go | 3 +- go/test/site/random_test.go | 6 +-- go/test/site/rig_unit_test.go | 76 +++++++++++++++++++++++++++++++++- go/test/site/scenarios_test.go | 8 ++-- go/test/site/verdicts_test.go | 35 +++++++--------- 6 files changed, 99 insertions(+), 31 deletions(-) diff --git a/go/test/site/README.md b/go/test/site/README.md index c09718fcf..c5e600b07 100644 --- a/go/test/site/README.md +++ b/go/test/site/README.md @@ -73,7 +73,7 @@ its sources (`provenance` in [catalog_test.go](catalog_test.go)). ## Scenarios -"Over the limit" is the worst phase above the fuse − 1 A, measured through +"Over the limit" is the worst phase above the fuse rating, measured through the fuse. A device's response time counts as 2 s, the meter and control tick as 2 s more. diff --git a/go/test/site/evaluate_test.go b/go/test/site/evaluate_test.go index 1e3caaee4..9a2e95a13 100644 --- a/go/test/site/evaluate_test.go +++ b/go/test/site/evaluate_test.go @@ -650,8 +650,7 @@ func le(p *float64, limit float64) bool { return p != nil && *p <= limit } func (d *runData) overage(t0, t1, fuse float64) metrics { w := d.window(t0, t1) m := metrics{"max_i": round(maxOf(w, maxAbsI), 2)} - m["over_limit_longest_s"], m["over_limit_total_s"] = d.runsOver(t0, t1, fuse-1) - m["over_fuse_longest_s"], _ = d.runsOver(t0, t1, fuse) + m["over_limit_longest_s"], m["over_limit_total_s"] = d.runsOver(t0, t1, fuse) m["fuse_damage_max"] = round(maxOf(w, damage), 4) m["fuse_blown"] = anyBlown(w) return m diff --git a/go/test/site/random_test.go b/go/test/site/random_test.go index aeaa2b10d..a0c7f3377 100644 --- a/go/test/site/random_test.go +++ b/go/test/site/random_test.go @@ -217,7 +217,6 @@ type eventWindow struct{ from, to float64 } func judgeInvariants(d *runData) (metrics, []criterion) { fuse := d.metaF("fuse") - limit := fuse - 1 h := d.timing() t0, t1 := d.marks["start"], d.marks["end"] run := d.window(t0, t1) @@ -269,7 +268,7 @@ func judgeInvariants(d *runData) (metrics, []criterion) { var firstBad float64 var start *sample for i, r := range run { - over := maxAbsI(r) > limit + over := maxAbsI(r) > fuse if over && start == nil { start = r } @@ -367,7 +366,8 @@ func judgeInvariants(d *runData) (metrics, []criterion) { for _, hw := range holds { run4 = 0 for i, r := range d.window(hw.from+grace, hw.to) { - roomA := limit - (maxAbsI(r) - carW(r, 0)/(3*volt)) + // Room below fuse - 1 A, the car's line in Core. + roomA := fuse - 1 - (maxAbsI(r) - carW(r, 0)/(3*volt)) bad := carW(r, 0) < 0.5*1380 && roomA >= 7 && !inFault(r.T) && !nearRestart(r.T) if bad && i > 0 { run4++ diff --git a/go/test/site/rig_unit_test.go b/go/test/site/rig_unit_test.go index 021c82cd2..5afd0dc0b 100644 --- a/go/test/site/rig_unit_test.go +++ b/go/test/site/rig_unit_test.go @@ -4,6 +4,8 @@ package site import ( "encoding/json" + "slices" + "strings" "testing" ) @@ -113,7 +115,7 @@ func TestInvariantsTellStepsFromOwnRaises(t *testing.T) { for i := 0; i <= 100; i++ { a := 10.0 if i >= 50 && i < 56 { - a = 26 // 6 s over the 24 A limit + a = 26 // 6 s over the 25 A fuse } d.samples = append(d.samples, &sample{T: float64(i), PhaseA: [3]float64{a, a, a}, Bat: plantDevice{SoCPct: 50}}) } @@ -175,3 +177,75 @@ func TestS18OwnCommandsSkipTheHouseStep(t *testing.T) { } } } + +// s8 at margin 0: the car settles at the fuse rating, as the owner's rule +// says. A phase at exactly the fuse for the whole run passes; 0.1 A above +// it for longer than the charger's delay + 7 s fails. Before, the judge +// counted every second above fuse - 1 A, and s8-60-25 failed at 25 A. +func TestS8JudgesAtTheFuse(t *testing.T) { + const over = "no longer than the charger's delay + 7 s" + ok := func(a float64) bool { + d := &runData{marks: map[string]float64{"charge_now": 0, "end": 300}, meta: map[string]any{"fuse": 25.0, "charger_delay_s": 60.0}} + for i := 0; i <= 300; i++ { + d.samples = append(d.samples, &sample{T: float64(i), PhaseA: [3]float64{a, 15, 15}}) + } + _, cs := judgeS8(d) + for _, c := range cs { + if strings.HasSuffix(c.Name, over) { + return c.OK + } + } + t.Fatalf("no criterion ending %q", over) + return false + } + if !ok(25) { + t.Error("a phase at exactly the 25 A fuse failed") + } + if ok(25.1) { + t.Error("a phase 0.1 A over the 25 A fuse for 300 s passed") + } +} + +// The limit is the fuse rating: a phase may sit at exactly the fuse until +// the end of the run, and 0.1 A above it fails once the time budget is up. +func TestInvariantsJudgeAtTheFuse(t *testing.T) { + const fuse = 25.0 + const own = "over the limit at most 3 s after FTW's own raise" + const step = "over the limit no longer than an outside step allows" + for _, c := range []struct { + name string + a float64 + to int // the level holds from 50 s until this second + withStep bool + want []string + }{ + {"at the fuse", fuse, 101, false, nil}, + {"at the fuse after a step", fuse, 101, true, nil}, + // 20 s is past the 3 s for FTW's own raise, and past the + // 2 + 2 + 3 s a step allows while the battery can answer. + {"0.1 A over", fuse + 0.1, 70, false, []string{own}}, + {"0.1 A over after a step", fuse + 0.1, 70, true, []string{step}}, + } { + d := &runData{marks: map[string]float64{"start": 0, "end": 100}, meta: map[string]any{"fuse": fuse}} + for i := 0; i <= 100; i++ { + a := 10.0 + if i >= 50 && i < c.to { + a = c.a + } + d.samples = append(d.samples, &sample{T: float64(i), PhaseA: [3]float64{a, a, a}, Bat: plantDevice{SoCPct: 50}}) + } + if c.withStep { + d.events = append(d.events, houseEventLine{T: 49.5, Event: houseEvent{Do: "loads"}}) + } + var failed []string + _, cs := judgeInvariants(d) + for _, x := range cs { + if !x.OK { + failed = append(failed, x.Name) + } + } + if !slices.Equal(failed, c.want) { + t.Errorf("%s: failed %v, want %v", c.name, failed, c.want) + } + } +} diff --git a/go/test/site/scenarios_test.go b/go/test/site/scenarios_test.go index c1cb69f9d..294124cca 100644 --- a/go/test/site/scenarios_test.go +++ b/go/test/site/scenarios_test.go @@ -1010,7 +1010,7 @@ func judgeS15bat(d *runData) (metrics, []criterion) { start := d.firstT(t0, func(r *sample) bool { return carW(r, 0) >= 0.95*1380 }) over, longest := 0.0, 0.0 for _, r := range d.window(t0, t1) { - if maxAbsI(r) > fuse-1 { + if maxAbsI(r) > fuse { over++ longest = math.Max(longest, over) } else { @@ -1018,13 +1018,13 @@ func judgeS15bat(d *runData) (metrics, []criterion) { } } m := metrics{"battery_rise_w_20s_before": math.Round(rise), "car_start_s": roundp(start, 1), - "car_w_last60": math.Round(meanOf(d.window(t1-60, t1), func(r *sample) float64 { return carW(r, 0) })), - "over_fuse_minus1_longest_s": longest, "max_abs_i": round(maxOf(d.window(t0, t1), maxAbsI), 1)} + "car_w_last60": math.Round(meanOf(d.window(t1-60, t1), func(r *sample) float64 { return carW(r, 0) })), + "over_fuse_longest_s": longest, "max_abs_i": round(maxOf(d.window(t0, t1), maxAbsI), 1)} return m, []criterion{ crit("the battery order rose over 1 150 W in the 20 s before Charge now", rise > 1150), // the setup crit("car charging within 10 s of Charge now", le(start, 10)), crit("fuse holds", !anyBlown(d.window(t0, t1))), - crit("over fuse - 1 A at most 3 s", longest <= 3), + crit("over the fuse at most 3 s", longest <= 3), } } diff --git a/go/test/site/verdicts_test.go b/go/test/site/verdicts_test.go index 9cb180db0..cfc2c678f 100644 --- a/go/test/site/verdicts_test.go +++ b/go/test/site/verdicts_test.go @@ -85,11 +85,10 @@ func judgeS3(d *runData) (metrics, []criterion) { "pre_step_max_i": round(maxOf(pre, maxAbsI), 2), } m["post_step_max_i"] = round(maxOf(d.window(tStep, tBack), maxAbsI), 2) - m["over_fuse_longest_s"], m["over_fuse_total_s"] = d.runsOver(tStep, tBack, fuse) - overLongest, overTotal := d.runsOver(tStep, tBack, fuse-1) - m["over_fuse_minus1_longest_s"], m["over_fuse_minus1_total_s"] = overLongest, overTotal - m["i2_over_fuse_minus1_s"], m["i2_peak_a"] = d.i2Over(tCN, t1, fuse-1) - m["back_under_fuse_minus1_s"] = roundp(d.firstT(tStep, func(r *sample) bool { return maxAbsI(r) <= fuse-1 && r.T > tStep+1 }), 1) + overLongest, overTotal := d.runsOver(tStep, tBack, fuse) + m["over_fuse_longest_s"], m["over_fuse_total_s"] = overLongest, overTotal + m["i2_over_fuse_s"], m["i2_peak_a"] = d.i2Over(tCN, t1, fuse) + m["back_under_fuse_s"] = roundp(d.firstT(tStep, func(r *sample) bool { return maxAbsI(r) <= fuse && r.T > tStep+1 }), 1) last := d.window(tBack-60, tBack) m["post_step_car_w_last60"] = math.Round(meanOf(last, func(r *sample) float64 { return carW(r, 0) })) m["post_step_bat_w_last60"] = math.Round(meanOf(last, batSigned)) @@ -105,15 +104,12 @@ func judgeS3(d *runData) (metrics, []criterion) { // Device response + meter and tick (2 + 2 s) + 3 s. allowed := d.metaF("charger_delay_s") + 2 + 2 + 3 m["allowed_over_s"] = allowed - m["run_over_fuse_minus1_longest_s"], _ = d.runsOver(tCN, t1, fuse-1) + m["run_over_fuse_longest_s"], _ = d.runsOver(tCN, t1, fuse) m["run_max_i"] = round(maxOf(after, maxAbsI), 2) - // Before the step, layers with different margins may hold a phase - // between fuse - 1 A and fuse - 0.5 A; reported, not judged. - m["pre_step_over_fuse_minus1_longest_s"], _ = d.runsOver(tCN, tStep, fuse-1) - m["pre_step_over_fuse_minus_half_longest_s"], _ = d.runsOver(tCN, tStep, fuse-0.5) + m["pre_step_over_fuse_longest_s"], _ = d.runsOver(tCN, tStep, fuse) return m, []criterion{ crit("fuse holds", !isBlown), - crit("over fuse - 1 A no longer than the response time + 3 s after the step", overLongest <= allowed), + crit("over the fuse no longer than the response time + 3 s after the step", overLongest <= allowed), } } @@ -412,10 +408,9 @@ func judgeS8(d *runData) (metrics, []criterion) { fuse := d.metaF("fuse") t0, t1 := d.marks["charge_now"], d.marks["end"] m := d.carSummary(t0, t1, maxW) - m["over_fuse_longest_s"], m["over_fuse_total_s"] = d.runsOver(t0, t1, fuse) - overLongest, overTotal := d.runsOver(t0, t1, fuse-1) - m["over_fuse_minus1_longest_s"], m["over_fuse_minus1_total_s"] = overLongest, overTotal - m["i2_over_fuse_minus1_s"], m["i2_peak_a"] = d.i2Over(t0, t1, fuse-1) + overLongest, overTotal := d.runsOver(t0, t1, fuse) + m["over_fuse_longest_s"], m["over_fuse_total_s"] = overLongest, overTotal + m["i2_over_fuse_s"], m["i2_peak_a"] = d.i2Over(t0, t1, fuse) var prs [][2]float64 for i, p := range connector1(profiles(d.frames, t0, t1)) { if i >= 20 { @@ -433,7 +428,7 @@ func judgeS8(d *runData) (metrics, []criterion) { } return m, []criterion{ crit("fuse holds", !m["fuse_blown"].(bool)), - crit("over fuse - 1 A no longer than the charger's delay + 7 s", overLongest <= allowed), + crit("over the fuse no longer than the charger's delay + 7 s", overLongest <= allowed), } } @@ -459,8 +454,8 @@ func judgeS9(d *runData) (metrics, []criterion) { m["profiles_after_switch"] = seq return m, []criterion{ crit("fuse holds", !before["fuse_blown"].(bool) && !after["fuse_blown"].(bool)), - crit("over fuse - 1 A at most 3 s on 3p", before["over_limit_longest_s"].(float64) <= 3), - crit("over fuse - 1 A at most 3 s after the switch to 1p", after["over_limit_longest_s"].(float64) <= 3), + crit("over the fuse at most 3 s on 3p", before["over_limit_longest_s"].(float64) <= 3), + crit("over the fuse at most 3 s after the switch to 1p", after["over_limit_longest_s"].(float64) <= 3), } } @@ -500,7 +495,7 @@ func judgeS10(d *runData) (metrics, []criterion) { } return m, []criterion{ crit("fuse holds", !before["fuse_blown"].(bool) && !after["fuse_blown"].(bool)), - crit("over fuse - 1 A at most 3 s after the step", after["over_limit_longest_s"].(float64) <= 3), + crit("over the fuse at most 3 s after the step", after["over_limit_longest_s"].(float64) <= 3), } } @@ -547,7 +542,7 @@ func judgeS11(d *runData) (metrics, []criterion) { } return m, []criterion{ crit("an offer within 60 s of the restart", le(firstPosS, 60)), - crit("over fuse - 1 A at most 3 s", run["over_limit_longest_s"].(float64) <= 3), + crit("over the fuse at most 3 s", run["over_limit_longest_s"].(float64) <= 3), crit("fuse holds", !run["fuse_blown"].(bool)), } } From 959cae3d8be40eafa447bc0c35895204c6db1f43 Mon Sep 17 00:00:00 2001 From: Fredrik Ahlgren Date: Wed, 28 Oct 2026 10:15:29 +0100 Subject: [PATCH 68/68] test(site): cap a stretch's events by the fuse heat; a car cut into export is FTW's own Owner decisions of 28 Oct 2026 for the random judge: - A car cut FTW sends that pushes export over the fuse is FTW's own, as a battery move toward export already was: after a step's meter delay and before the stretch, or while the stretch is over the fuse. - What events add to a stretch (R2 growth) stops at the fuse's heat budget: once a phase's 60 s heat passes the fuse, Core's cut gets its lever's time and no further event extends the stretch. A window that opens after the allowance ran out, with the current under the fuse since, is a new step and its cap runs from it. This closes E3 (small real rises chaining a stretch's allowance). Co-Authored-By: Claude Opus 5.5 --- go/test/site/random_test.go | 49 ++++++++++++----- go/test/site/random_unit_test.go | 93 ++++++++++++++++++++++++++++++++ 2 files changed, 130 insertions(+), 12 deletions(-) diff --git a/go/test/site/random_test.go b/go/test/site/random_test.go index 7cfc0aed1..e2855ab73 100644 --- a/go/test/site/random_test.go +++ b/go/test/site/random_test.go @@ -385,6 +385,9 @@ func judgeInvariants(d *runData) (metrics, []criterion) { } } m["car_starts_ftw_did_not_order"] = carStarts + // In time order, so a new step after a stretch's allowance is told + // from a window inside it (judgeStretch). + sort.SliceStable(windows, func(i, j int) bool { return windows[i].from < windows[j].from }) // chargerLever is how long the charger takes to answer from t: its own // time, after the rest of any outage it is in. @@ -441,15 +444,16 @@ func judgeInvariants(d *runData) (metrics, []criterion) { // starts when the heat passes the fuse, as Core's cut does. A stretch // runs on across dips under the fuse while the heat stays over it. blownAny := anyBlown(run) - // raisedIn is whether FTW sent the car a higher order in (a, b]; with - // over, only one sent while the meter showed the fuse passed. - raisedIn := func(a, b float64, over bool) bool { + // carMovedIn is whether FTW sent the car a higher order (dir +1, toward + // import) or a lower one (dir -1, toward export) in (a, b]; with over, + // only one sent while the meter showed the fuse passed. + carMovedIn := func(a, b float64, over bool, dir float64) bool { prev, ok := 0.0, false for _, p := range orders { if p.T > b { break } - if ok && p.T > a && p.offerW() > prev+1 && (!over || maxAbsI(d.at(p.T)) > fuse) { + if ok && p.T > a && dir*(p.offerW()-prev) > 1 && (!over || maxAbsI(d.at(p.T)) > fuse) { return true } prev, ok = p.offerW(), true @@ -483,16 +487,18 @@ func judgeInvariants(d *runData) (metrics, []criterion) { return false } // ownRaise is whether FTW pushed a stretch from s to end over the fuse - // itself: it moved the battery toward the stretch's direction in - // (a, s], or moved it, or raised the car on import, while the stretch - // was over the fuse. On import a car raise in (a, s] counts too. On - // export, raising the car is the right answer. + // itself: it moved the car or the battery toward the stretch's + // direction in (a, s], or while the stretch was over the fuse. On + // import that is a car raise; on export a car cut (owner, 28 Oct 2026), + // as a battery move toward export already was. Raising the car on + // export is the right answer. ownRaise := func(a, s, end float64, export bool) bool { + dir := 1.0 if export { - return batMovedIn(a, s, false, -1) || batMovedIn(s, end, true, -1) + dir = -1 } - return raisedIn(a, s, false) || batMovedIn(a, s, false, 1) || - raisedIn(s, end, true) || batMovedIn(s, end, true, 1) + return carMovedIn(a, s, false, dir) || batMovedIn(a, s, false, dir) || + carMovedIn(s, end, true, dir) || batMovedIn(s, end, true, dir) } // raisedAt is whether the worst phase rose 0.5 A or more in the 3 s // from t. @@ -563,11 +569,27 @@ func judgeInvariants(d *runData) (metrics, []criterion) { } return math.Inf(1) } + // heatCap is the most that windows opening from t on may add: once + // a phase's 60 s heat is over the fuse, Core's cut has its lever's + // time, and no further event extends the stretch (owner, 28 Oct + // 2026). Unbounded while the heat stays under the fuse. + heatCap := func(t float64) float64 { + for _, r := range stretch { + if r.T >= t && max(r.HeatA[0], r.HeatA[1], r.HeatA[2]) > fuse { + return r.T + lever(r.T, overA, export) + 2 + 3 + } + } + return math.Inf(1) + } // A window that opens inside the stretch before it broke its // allowance extends it: a second step, an outage or a Core restart. // A plain house event counts only if it raised the current. Inside // FTW's own raise a window counts only once the raise is answered: // after its 3 s, with the current under the fuse until the window. + // What windows add stops at the heat's cap, however many there are. + // A window that opens once the allowance has run out, with the + // current under the fuse since, is a new step: its cap runs from it. + capT := heatCap(s) for grown := true; grown; { grown = false for _, w := range windows { @@ -577,7 +599,10 @@ func judgeInvariants(d *runData) (metrics, []criterion) { if w.plain && !raisedAt(w.from) { continue } - if x := until(w, w.from, overA, export); x > to { + if w.from > to { + capT = math.Max(capT, heatCap(w.from)) + } + if x := math.Min(until(w, w.from, overA, export), capT); x > to { to, grown, own = x, true, false } } diff --git a/go/test/site/random_unit_test.go b/go/test/site/random_unit_test.go index 72626ed23..70b0766ef 100644 --- a/go/test/site/random_unit_test.go +++ b/go/test/site/random_unit_test.go @@ -964,3 +964,96 @@ func TestInvariantsARaiseBetweenFuseAndInstantIsOwn(t *testing.T) { t.Errorf("a raise sent at 1.1 x In passed; judged %v", m["over_limit_judged"]) } } + +// Owner, 28 Oct 2026: what events add to a stretch stops at the fuse's +// heat budget. Once L1's 60 s heat passes the fuse, Core's cut has its +// lever's time (here the 5 s charger: the battery is at its floor), and +// no further event extends the stretch, however many come. 16 A fuse, +// 8 A on each phase, a load step at 10 s puts L1 at 20 A (1.25 x In) +// from 11 s; a load event every 8 s from 18 s raises it 0.5 A from a +// 1 s dip (the third review's E3). L1's heat passes the fuse at 62 s, so +// the cap is 62 + 5 + 2 + 3 = 72 s. A Core restart at 15 s, which would +// excuse a minute, is capped too: with no dips the heat passes at 61 s. +func TestInvariantsHeatCapsWhatEventsAdd(t *testing.T) { + for _, c := range []struct { + name string + to int // L1 over the fuse until here + restartAt float64 // a Core restart instead of the load events; 0: none + want bool + }{ + {"events end before the heat passes the fuse", 55, 0, true}, + {"events end inside Core's cut time", 72, 0, true}, + {"events past the heat's cap", 76, 0, false}, + {"events chained 280 s", 290, 0, false}, + {"a Core restart past the heat's cap", 74, 15, false}, + {"a Core restart before the heat passes the fuse", 55, 15, true}, + } { + d := randomRun(301, 16, 8, func(i int, r *sample) { + r.Bat.SoCPct = 6 + if i >= 11 && i < c.to { + r.PhaseA[0] = 20 + if c.restartAt == 0 && i >= 17 && (i-17)%8 == 0 { + r.PhaseA[0] = 19.5 + } + } + }) + withCharger(t, d, 5, 0) + d.events = []houseEventLine{{T: 10, Event: houseEvent{Do: "loads"}}} + if c.restartAt > 0 { + d.allMarks = []markLine{{T: c.restartAt, Label: "ftw:restart"}, {T: c.restartAt + 9, Label: "ftw:up"}} + } else { + for at := 18.0; at < float64(c.to); at += 8 { + d.events = append(d.events, houseEventLine{T: at, Event: houseEvent{Do: "loads"}}) + } + } + d.warm() + if h := d.at(61).HeatA[0]; c.restartAt == 0 && h > 16 { + t.Fatalf("%s: heat %.2f A at 61 s, want under the fuse", c.name, h) + } + if h := d.at(62).HeatA[0]; c.to > 62 && h <= 16 { + t.Fatalf("%s: heat %.2f A at 62 s, want over the fuse", c.name, h) + } + m, _ := judgeInvariants(d) + if got := judged(d)[limitStep]; got != c.want { + t.Errorf("%s: %q = %v, want %v; judged %v", c.name, limitStep, got, c.want, m["over_limit_judged"]) + } + } +} + +// Owner, 28 Oct 2026: a car cut FTW sends that pushes export over the +// fuse is FTW's own, as a battery move toward export is: after a step's +// 2 s meter delay and before the stretch, or while the stretch is over +// the fuse. A cut the meter cannot have shown the step for yet is part +// of the step. 16 A fuse, 12 A export per phase, the battery charging at +// its maximum, so the 40 s charger is the lever; PV steps at 10 s and +// L1 exports 22 A from `from` to 45 s, inside the step's 55 s. +func TestInvariantsACarCutIntoExportIsFTWsOwn(t *testing.T) { + for _, c := range []struct { + name string + from int + frames []frame + want bool // both limit criteria hold + }{ + {"no cut", 11, []frame{profileAt(1, 16)}, true}, + {"16 -> 0 A while export is over the fuse", 11, []frame{profileAt(1, 16), profileAt(20, 0)}, false}, + {"16 -> 6 A after the meter shows the step, before the stretch", 20, []frame{profileAt(1, 16), profileAt(15, 6)}, false}, + {"16 -> 6 A before the meter shows the step", 20, []frame{profileAt(1, 16), profileAt(11, 6)}, true}, + {"6 -> 16 A while export is over the fuse", 11, []frame{profileAt(1, 6), profileAt(20, 16)}, true}, + } { + d := randomRun(121, 16, -12, func(i int, r *sample) { + r.BatW = rigBatteryMaxW + r.Status = &ftwStatus{Dispatch: []ftwDispatch{{Driver: "sungrow", TargetW: rigBatteryMaxW}}} + if i >= c.from && i < 45 { + r.PhaseA[0] = -22 + } + }) + withCharger(t, d, 40, 0) + d.frames = c.frames + d.events = []houseEventLine{{T: 10, Event: houseEvent{Do: "pv", Device: "inverter"}}} + m, _ := judgeInvariants(d) + v := judged(d) + if got := v[limitStep] && v[limitOwn]; got != c.want { + t.Errorf("%s: step %v, own %v; want both %v; judged %v", c.name, v[limitStep], v[limitOwn], c.want, m["over_limit_judged"]) + } + } +}