ReviewOS

also looking at this

stacks/drone

feat: model VTOL electrical consumption and battery authority

#81
Merged chris wants to merge codex/owned-vtol-electrical-energy into main
15 files +605 -28
tests/unit/vtol-energy.test.tsadded+342-0
Changes to tests/unit/vtol-energy.test.ts
@@ -0,0 +1,342 @@
1import { expect, test } from 'bun:test'
2import { createVtolPlant } from '../../resources/functions/drone/vehicles/vtol/plant'
3import { createVtolHoverProfile } from '../../resources/functions/drone/vehicles/vtol'
4import { createVtolTransitionProfile } from '../../resources/functions/drone/vehicles/vtol/transition-profile'
5import { runVehicleSimulation } from '../../resources/functions/drone/vehicles/runtime'
6import { replayVehicleMission, validateVehicleMission } from '../../resources/functions/drone/missions/vehicle'
7import { vtolElectricalMaximumW } from '../../resources/functions/drone/vehicles/vtol/power'
8import type { VehicleControllerContext } from '../../resources/functions/drone/vehicles/types'
9
10const environment = { windMps: [0, 0, 0] as [number, number, number], currentMps: [0, 0, 0] as [number, number, number] }
11
12// Public plant/sensor/runtime seams. Fictional electrical coefficients do not qualify hardware endurance.
13test('simultaneous lift and pusher demand includes source loss and integrates chemical energy', () => {
14 const plant = createVtolPlant({ electricalCapacityWh: 1, rotorsN: [4, 4, 4, 4], pusherThrustN: 4 })
15 const initial = plant.snapshot().details
16 // Independent decimal oracle: 128 W lift + 40 W pusher + 12 W auxiliaries,
17 // 24 V source and 0.04 ohm series resistance. Source power includes I squared R.
18 expect(initial.batteryLoadPowerW).toBeCloseTo(180, 10)
19 expect(initial.batteryCurrentA).toBeCloseTo(7.596169655731083, 10)
20 expect(initial.batteryTerminalV).toBeCloseTo(23.696153213770757, 10)
21 expect(initial.batterySourcePowerW).toBeCloseTo(182.308071737546, 10)
22 expect(initial.batteryEnergyUsedWh).toBe(0)
23 const state = plant.step([4, 4, 4, 4, 4 / 14, 0, 0, 0], 0.004, environment)
24 expect(state.details.batteryEnergyUsedWh).toBeCloseTo(0.00020256452415282887, 12)
25 expect(state.details.batteryRemainingWh).toBeCloseTo(0.9997974354758472, 12)
26 expect(state.details.batteryCutoff).toBe(false)
27})
28
29test('electrical demand retains independent rotor loading instead of using only total thrust', () => {
30 const level = createVtolPlant({ electricalCapacityWh: 1, rotorsN: [4, 4, 4, 4] }).snapshot()
31 const unequal = createVtolPlant({ electricalCapacityWh: 1, rotorsN: [8, 8, 0, 0] }).snapshot()
32 expect(level.details.rotorThrustN).toBe(16)
33 expect(unequal.details.rotorThrustN).toBe(16)
34 expect(level.details.batteryLoadPowerW).toBeCloseTo(140, 10)
35 expect(unequal.details.batteryLoadPowerW).toBeGreaterThan(190)
36 expect(unequal.details.batterySourcePowerW).toBeGreaterThan(level.details.batterySourcePowerW as number)
37})
38
39test('invalid initial electrical state cannot silently become an unmetered plant', () => {
40 for (const electricalCapacityWh of [null, 0, -1, NaN, Infinity]) expect(() => createVtolPlant({ electricalCapacityWh } as never)).toThrow()
41 for (const energyUsedWh of [-1, 2, NaN, Infinity]) expect(() => createVtolPlant({ electricalCapacityWh: 1, energyUsedWh } as never)).toThrow()
42 expect(() => createVtolPlant({ energyUsedWh: 0 } as never)).toThrow()
43})
44
45test('the simultaneous electrical ceiling includes every motor, surface and worst supply loss', () => {
46 // Independent decimal oracle: peak load 948.023527181 W, source 1060.486739686 W at20V.
47 expect(vtolElectricalMaximumW(12, 14)).toBe(1061)
48 const plant = createVtolPlant({ electricalCapacityWh: 1, energyUsedWh: 0.99, rotorsN: [12, 12, 12, 12], pusherThrustN: 14 })
49 const state = plant.step([12, 12, 12, 12, 1, 0.4, 0.4, 0.4], 0.004, environment)
50 expect(state.details.batteryCutoff).toBe(false)
51 expect(state.details.batteryLoadPowerW).toBeCloseTo(948.0235271806248, 8)
52 expect(state.details.batterySourcePowerW).toBeGreaterThan(1050)
53 expect(state.details.batterySourcePowerW).toBeLessThan(1061)
54})
55
56test('an electrical profile refuses an underfunded peak before creating a vehicle session', () => {
57 const profile = createVtolTransitionProfile({ electrical: true })
58 profile.mission.power.maxW = 1000
59 let created = 0
60 const factory = profile.createSession
61 profile.createSession = () => { created++; return factory() }
62 expect(() => { runVehicleSimulation(profile, { seconds: 2 }) }).toThrow('modeled source envelope')
63 expect(created).toBe(0)
64})
65
66test('mission capacity must match the captured electrical plant before session allocation', () => {
67 const profile = createVtolTransitionProfile({ electrical: true })
68 profile.mission.power.availableWh = 101
69 let created = 0
70 const factory = profile.createSession
71 profile.createSession = () => { created++; return factory() }
72 expect(() => { runVehicleSimulation(profile, { seconds: 2 }) }).toThrow('modeled battery capacity')
73 expect(created).toBe(0)
74})
75
76test('owned hover delivers delayed quantified energy to existing authority and mission observations', () => {
77 const report = runVehicleSimulation(createVtolHoverProfile('hover', { electrical: true }), { seconds: 60 })
78 expect(report.status).toBe('completed')
79 expect(report).toHaveProperty('energy.evidence', 'modeled-vehicle-battery-v1')
80 const first = report.path[0]!.measurement!
81 expect(first.values.batteryCapacityWh).toBe(50)
82 const last = report.path.at(-1)!.measurement!
83 expect(last.values.batteryEnergyUsedWh).toBeGreaterThan(0)
84 expect(last.values.batteryEnergyUsedWh).toBeLessThan(10)
85 expect(last.capturedAtMs).toBeLessThan(report.path.at(-1)!.atMs)
86 expect(report.trace.rows.at(-1)!.observation.batteryPercent).toBeGreaterThan(80)
87 expect(replayVehicleMission(report.trace).snapshot()).toEqual(report.mission)
88 expect(report.board.actuators).toEqual([0, 0, 0, 0, 0, 0, 0, 0])
89})
90
91test('a captured supply cutoff withdraws authority even when chemical capacity remains', () => {
92 const profile = createVtolHoverProfile('hover', { electrical: true }), factory = profile.createSession
93 profile.createSession = () => {
94 const session = factory(), render = session.renderMeasurement
95 return { ...session, renderMeasurement(state, atMs, reference) {
96 const packet = render(state, atMs, reference)
97 if (atMs >= 3000) packet.values.batteryCutoff = true
98 return packet
99 } }
100 }
101 const report = runVehicleSimulation(profile, { seconds: 60 })
102 expect(report.status).toBe('blocked')
103 expect(report.fault).toBe('modeled-battery-supply-cutoff')
104 expect(report.energy!.lastObservation!.cutoff).toBe(true)
105 expect(report.energy!.lastObservation!.remainingPercentLowerBound).toBeGreaterThan(90)
106 expect(report.board.actuators).toEqual([0, 0, 0, 0, 0, 0, 0, 0])
107 expect(report.board.expiresAtMs).toBeNull()
108})
109
110test('electrical integration remains atomic when the rigid-body step is refused', () => {
111 const initial = { electricalCapacityWh: 1, positionM: [0, 0, -20] as [number, number, number], rotorsN: [4, 4, 4, 4] as [number, number, number, number], pusherThrustN: 4 }
112 const plant = createVtolPlant(initial), reference = createVtolPlant(initial), before = plant.snapshot(), command = [4, 4, 4, 4, 4 / 14, 0, 0, 0]
113 expect(() => plant.step(command, 0.004, { windMps: [1000000, 1000000, 0], currentMps: [0, 0, 0] })).toThrow()
114 expect(plant.snapshot()).toEqual(before)
115 expect(plant.step(command, 0.004, environment)).toEqual(reference.step(command, 0.004, environment))
116})
117
118test('an exhausted modeled source latches propulsion cutoff while retained rotor response coasts', () => {
119 const plant = createVtolPlant({ electricalCapacityWh: 0.0001, rotorsN: [4, 4, 4, 4] }), demand = [12, 12, 12, 12, 1, 0.4, 0.4, 0.4]
120 const first = plant.step(demand, 0.004, environment)
121 expect(first.details.batteryCutoff).toBe(true)
122 expect(first.details.rotorThrustN).toBeGreaterThan(0)
123 expect(first.details.rotorThrustN).toBeLessThan(16)
124 expect(first.details.pusherThrustN).toBe(0)
125 let final = first
126 for (let i = 0; i < 400; i++) final = plant.step(demand, 0.004, environment)
127 expect(final.details.batteryEnergyUsedWh).toBe(0.0001)
128 expect(final.details.batteryRemainingWh).toBe(0)
129 expect(final.details.batterySourcePowerW).toBe(0)
130 expect(final.details.batteryCurrentA).toBe(0)
131 expect(final.details.batteryCutoff).toBe(true)
132 expect(final.details.rotorThrustN).toBeLessThan(1e-8)
133 expect(final.details.pusherThrustN).toBe(0)
134})
135
136test('default and explicitly disabled electrical profiles retain exact legacy reports', () => {
137 const legacy = runVehicleSimulation(createVtolHoverProfile(), { seconds: 30 })
138 const disabled = runVehicleSimulation(createVtolHoverProfile('hover', { electrical: false }), { seconds: 30 })
139 expect(disabled).toEqual(legacy)
140 expect(Object.hasOwn(legacy, 'energy')).toBe(false)
141 expect(legacy.path.every(row => !Object.hasOwn(row.measurement!.values, 'batteryEnergyUsedWh'))).toBe(true)
142})
143
144test('the complete electrical route charges all phases without feeding plant truth into controls', () => {
145 const profile = createVtolTransitionProfile({ electrical: true }), factory = profile.createSession
146 let truthInput = false, controllerSamples = 0
147 profile.createSession = () => {
148 const session = factory(), controller = session.createController()
149 return { ...session, createController: () => ({ step(context: VehicleControllerContext) {
150 controllerSamples++
151 if (Object.hasOwn(context, 'truthPositionM') || Object.hasOwn(context, 'details') || Object.hasOwn(context, 'energyUsedWh')) truthInput = true
152 return controller.step(context)
153 } }) }
154 }
155 const report = runVehicleSimulation(profile, { seconds: 150 })
156 expect(report.status).toBe('completed')
157 expect(controllerSamples).toBeGreaterThan(100)
158 expect(truthInput).toBe(false)
159 const rows = report.path.map(row => ({ row, used: row.measurement!.values.batteryEnergyUsedWh as number, source: row.measurement!.values.batterySourcePowerW as number }))
160 expect(rows.every((r, i) => i === 0 || r.used >= rows[i - 1]!.used)).toBe(true)
161 expect(rows.every(r => r.source <= 1061)).toBe(true)
162 for (const task of ['depart', 'front', 'cruise-leg', 'back', 'land']) {
163 const phase = rows.filter(r => r.row.mission.taskId === task)
164 expect(phase.length).toBeGreaterThan(10)
165 expect(phase.at(-1)!.used).toBeGreaterThan(phase[0]!.used)
166 }
167 const front = rows.filter(r => r.row.mission.taskId === 'front')
168 // Independent lower bound: four rotors totaling10N require at least63.245553W,
169 // a5N pusher55.901699W, and auxiliaries12W, before supply losses.
170 expect(front.some(r => r.source > 131.147 && (r.row.measurement!.values.rotorThrustN as number) > 10 && (r.row.measurement!.values.pusherThrustN as number) > 5)).toBe(true)
171 expect(report.budget).toEqual({ worstCaseMs: 131520, requiredWh: 43.84 })
172 expect(report.energy!.lastObservation!.energyUsedWh).toBeGreaterThan(0)
173 expect(report.energy!.lastObservation!.energyUsedWh).toBeLessThan(report.budget.requiredWh)
174 expect(replayVehicleMission(report.trace).snapshot()).toEqual(report.mission)
175})
176
177for (const mutation of ['missing-energy', 'changed-capacity', 'energy-reset', 'over-envelope', 'impossible-current', 'reserve'] as const) test(`captured electrical ${mutation} revokes rather than substituting a full battery`, () => {
178 const profile = createVtolHoverProfile('hover', { electrical: true }), factory = profile.createSession
179 profile.createSession = () => {
180 const session = factory(), render = session.renderMeasurement
181 return { ...session, renderMeasurement(state, atMs, reference) {
182 const packet = render(state, atMs, reference)
183 if (atMs >= 3000) {
184 if (mutation === 'missing-energy') delete packet.values.batteryEnergyUsedWh
185 if (mutation === 'changed-capacity') packet.values.batteryCapacityWh = 100
186 if (mutation === 'energy-reset') packet.values.batteryEnergyUsedWh = 0
187 if (mutation === 'over-envelope') packet.values.batterySourcePowerW = 1062
188 if (mutation === 'impossible-current') packet.values.batteryCurrentA = 100
189 if (mutation === 'reserve') packet.values.batteryEnergyUsedWh = 35
190 }
191 return packet
192 } }
193 }
194 const report = runVehicleSimulation(profile, { seconds: 30 })
195 expect(report.status).toBe('blocked')
196 expect(report.path.at(-1)!.atMs).toBeLessThanOrEqual(3200)
197 expect(report.fault).toContain('battery')
198 expect(report.board.actuators).toEqual([0, 0, 0, 0, 0, 0, 0, 0])
199 expect(report.board.expiresAtMs).toBeNull()
200 expect(replayVehicleMission(report.trace).snapshot()).toEqual(report.mission)
201})
202
203test('host loss keeps the last qualified battery separate from continuing independent consumption', () => {
204 const profile = createVtolHoverProfile('host-loss', { electrical: true }), factory = profile.createSession
205 let independentEnergyWh = 0, independentAtMs = 0
206 profile.createSession = () => {
207 const session = factory()
208 return { ...session, observeIndependent(state, atMs) { independentEnergyWh = state.details.batteryEnergyUsedWh as number; independentAtMs = atMs } }
209 }
210 const report = runVehicleSimulation(profile, { seconds: 30, neutralTailMs: 1000 })
211 expect(report.status).toBe('host-lost')
212 expect(report.energy!.lastObservation!.observedAtMs).toBe(2980)
213 expect(report.energy!.lastObservation!.capturedAtMs).toBeLessThan(2980)
214 expect(independentAtMs).toBe(4100)
215 expect(independentEnergyWh).toBeGreaterThan(report.energy!.lastObservation!.energyUsedWh)
216 expect(report.board.fault).toBe('output-lease-expired')
217 expect(report.board.actuators).toEqual([0, 0, 0, 0, 0, 0, 0, 0])
218})
219
220test('modeled energy keeps advancing while an actual hover mission is paused', () => {
221 const report = runVehicleSimulation(createVtolHoverProfile('hover', { electrical: true }), { seconds: 60, missionActions: [{ atMs: 3000, action: 'pause' }, { atMs: 10000, action: 'resume' }] })
222 expect(report.status).toBe('completed')
223 const paused = report.path.filter(row => row.mission.state === 'paused')
224 expect(paused.length).toBeGreaterThan(100)
225 expect(paused.at(-1)!.measurement!.values.batteryEnergyUsedWh).toBeGreaterThan(paused[0]!.measurement!.values.batteryEnergyUsedWh as number)
226 expect(paused.at(-1)!.mission.taskId).toBe(paused[0]!.mission.taskId)
227 expect(replayVehicleMission(report.trace).snapshot()).toEqual(report.mission)
228})
229
230function electricalRecovery(sourceId: 'initial-hover' | 'front' | 'back') {
231 const profile = createVtolTransitionProfile({ electrical: true }), source = profile.mission.tasks.find(task => task.id === sourceId)!
232 if (source.kind !== 'vtol-mode') throw new Error('Expected mode task')
233 source.onFailure = 'energy-hover'
234 profile.mission.tasks.push(
235 { id: 'energy-hover', kind: 'vtol-mode', mode: 'hover', headingRad: 0, timeoutMs: sourceId === 'back' ? 40000 : 45000, next: 'energy-land' },
236 { id: 'energy-land', kind: 'land', positionM: [sourceId === 'back' ? 180 : 0, 0, 0], acceptanceM: 0.3, maxArrivalSpeedMps: 0.2, settleMs: 200, timeoutMs: sourceId === 'back' ? 30000 : 35000 },
237 )
238 return profile
239}
240
241// Front failure is116520ms, below the131520ms normal route. Back failure is176520ms.
242for (const [source, atMs, expectedMs, expectedWh] of [['initial-hover', 700, 131520, 43.84], ['front', 13000, 131520, 43.84], ['back', 30000, 176520, 58.84]] as const) test(`electrical ${source} abort accounts for the complete declared hover and landing route`, () => {
243 const report = runVehicleSimulation(electricalRecovery(source), { seconds: 180, missionActions: [{ atMs, action: 'abort' }] })
244 expect(report.mission.state).toBe('aborted')
245 expect(report.mission.reason).toBe('vtol-abort-landed')
246 expect(report.budget.worstCaseMs).toBe(expectedMs)
247 expect(report.budget.requiredWh).toBeCloseTo(expectedWh, 10)
248 expect(report.energy!.model.maximumSourceW).toBe(1061)
249 expect(report.energy!.lastObservation!.energyUsedWh).toBeGreaterThan(0)
250 expect(report.energy!.lastObservation!.energyUsedWh).toBeLessThan(expectedWh)
251 expect(report.path.at(-1)!.measurement!.values.onSurface).toBe(true)
252 expect(report.finalTruthPositionM[2]).toBe(0)
253 expect(report.path.filter(row => row.mission.taskId === 'energy-land').some(row => (row.measurement!.values.batteryEnergyUsedWh as number) > 0)).toBe(true)
254 expect(replayVehicleMission(report.trace).snapshot()).toEqual(report.mission)
255})
256
257test('energy preflight includes recovery landing even when the nominal route alone is affordable', () => {
258 const normal = createVtolTransitionProfile({ electrical: true })
259 normal.mission.power.reservePercent = 50
260 expect(validateVehicleMission(normal.mission).requiredWh).toBe(43.84)
261 const profile = electricalRecovery('back')
262 profile.mission.power.reservePercent = 50
263 let created = 0
264 const factory = profile.createSession
265 profile.createSession = () => { created++; return factory() }
266 expect(() => { runVehicleSimulation(profile, { seconds: 180 }) }).toThrow('preserve energy reserve')
267 expect(created).toBe(0)
268})
269
270test('malformed battery envelopes and accessors are refused before session creation', () => {
271 let getterCalls = 0
272 const accessor = { evidence: 'modeled-vehicle-battery-v1', get capacityWh() { getterCalls++; return 100 }, maximumSourceW: 1061 }
273 for (const input of [null, {}, [], accessor, { evidence: 'physical', capacityWh: 100, maximumSourceW: 1061 }, { evidence: 'modeled-vehicle-battery-v1', capacityWh: '100', maximumSourceW: 1061 }, { evidence: 'modeled-vehicle-battery-v1', capacityWh: 100, maximumSourceW: Infinity }, { evidence: 'modeled-vehicle-battery-v1', capacityWh: 100, maximumSourceW: 0 }, { evidence: 'modeled-vehicle-battery-v1', capacityWh: 100, maximumSourceW: 1061, extra: true }]) {
274 const profile = createVtolTransitionProfile({ electrical: true }), factory = profile.createSession
275 let created = 0
276 profile.batteryModel = input as never
277 profile.createSession = () => { created++; return factory() }
278 expect(() => { runVehicleSimulation(profile, { seconds: 2 }) }).toThrow('modeled vehicle battery envelope')
279 expect(created).toBe(0)
280 }
281 expect(getterCalls).toBe(0)
282})
283
284test('electrical sessions and returned energy views cannot mutate another run', () => {
285 const profile = createVtolHoverProfile('hover', { electrical: true }), first = profile.createSession().createPlant(), second = profile.createSession().createPlant()
286 const before = second.snapshot()
287 first.step([6, 6, 6, 6, 0, 0, 0, 0], 0.004, environment)
288 expect(first.snapshot().details.batteryEnergyUsedWh).toBeGreaterThan(0)
289 expect(second.snapshot()).toEqual(before)
290 const exposed = first.snapshot()
291 exposed.details.batteryEnergyUsedWh = -100
292 expect(first.snapshot().details.batteryEnergyUsedWh).toBeGreaterThan(0)
293 expect(() => { profile.batteryModel!.capacityWh = 1 }).toThrow()
294})
295
296test('recovery hover and landing retain measured consumption across an explicit held resume', () => {
297 const report = runVehicleSimulation(electricalRecovery('back'), { seconds: 180, missionActions: [{ atMs: 30000, action: 'recover' }, { atMs: 80000, action: 'resume' }] })
298 expect(report.mission.state).toBe('completed')
299 expect(report.mission.reason).toBe('vtol-recovery-landed')
300 const held = report.path.filter(row => row.mission.state === 'paused')
301 expect(held.length).toBeGreaterThan(100)
302 expect(held.at(-1)!.measurement!.values.batteryEnergyUsedWh).toBeGreaterThan(held[0]!.measurement!.values.batteryEnergyUsedWh as number)
303 expect(report.energy!.lastObservation!.energyUsedWh).toBeGreaterThan(held.at(-1)!.measurement!.values.batteryEnergyUsedWh as number)
304 expect(report.finalTruthPositionM[2]).toBe(0)
305 expect(replayVehicleMission(report.trace).snapshot()).toEqual(report.mission)
306})
307
308test('electrical recovery holds cannot pause global endurance or claim a landing on expiry', () => {
309 const report = runVehicleSimulation(electricalRecovery('back'), { seconds: 180, missionActions: [{ atMs: 30000, action: 'pause' }] })
310 expect(report.mission.state).toBe('blocked')
311 expect(report.mission.reason).toBe('mission-endurance-exhausted')
312 expect(report.path.at(-1)!.measurement!.values.onSurface).toBe(false)
313 expect(report.energy!.lastObservation!.energyUsedWh).toBeGreaterThan(1)
314 expect(report.energy!.lastObservation!.energyUsedWh).toBeLessThan(report.budget.requiredWh)
315 expect(report.board.actuators).toEqual([0, 0, 0, 0, 0, 0, 0, 0])
316 expect(replayVehicleMission(report.trace).snapshot()).toEqual(report.mission)
317})
318
319test('an open-circuit modeled pusher times out into electrically accounted hover and landing', () => {
320 const profile = electricalRecovery('front'), factory = profile.createSession
321 profile.createSession = () => {
322 const session = factory(), createPlant = session.createPlant
323 return { ...session, createPlant() {
324 const plant = createPlant()
325 return { snapshot: plant.snapshot, step(input, dtS, world) {
326 const commanded = [...input]
327 commanded[4] = 0
328 return plant.step(commanded, dtS, world)
329 } }
330 } }
331 }
332 const report = runVehicleSimulation(profile, { seconds: 150 })
333 expect(report.mission.state).toBe('completed')
334 expect(report.mission.reason).toBe('vtol-recovery-landed')
335 expect(report.mission.recovery!.cause).toBe('timeout')
336 expect(report.path.some(row => row.mission.taskId === 'cruise-leg')).toBe(false)
337 expect(report.path.every(row => row.measurement!.values.pusherThrustN === 0)).toBe(true)
338 expect(report.energy!.lastObservation!.energyUsedWh).toBeGreaterThan(0)
339 expect(report.energy!.lastObservation!.energyUsedWh).toBeLessThan(report.budget.requiredWh)
340 expect(report.finalTruthPositionM[2]).toBe(0)
341 expect(replayVehicleMission(report.trace).snapshot()).toEqual(report.mission)
342})