governance + unit-self-describing demand + dashboard fixes
Two governance items from the 2026-05-14 quality review:
- test/_output-manifest.md enumerates every Port 0/1/2 key MGC emits, its
source, type, range, and which tests cover it in populated/degraded states
(per .claude/rules/output-coverage.md).
- src/control/strategies.js extracts computeEqualFlowDistribution as a pure
function so the equal-flow algorithm is testable without an MGC fixture.
test/basic/equalFlowDistribution.basic.test.js (6 tests) covers all three
demand branches and pins the legacy quirk where the default branch counts
active machines but iterates priority-ordered first-N (documented in the
test so the future cleanup is a deliberate change).
Plus rolled-up session work that landed alongside:
- set.demand is now unit-self-describing ({value, unit:'m3/h'|'l/s'|'%'|...}
or bare number = %); setScaling/scaling.current removed from MGC, commands,
editor (mgc.html), specificClass.
- _optimalControl + equalFlowControl now compute eta = (Q*dP)/P_shaft rather
than Q/P, keeping the metric in the same scale as each child's cog.
- groupEfficiency.calcRelativeDistanceFromPeak returns undefined (was 1) when
pumps are homogeneous (|max-min| < 1e-9). Dashboard treats undefined as
'-' instead of showing a misleading 100% / 0% reading.
- examples/02-Dashboard.json: auto-init inject so the dashboard populates at
deploy, NCog formatter normalizes the SUM emitted by MGC by
machineCountActive, Q-H fanout trims the flat-Q tail so the H axis isn't
stretched to 40m by curve-envelope clamp points, num/pct treat null AND
undefined as no-data (closes the +null === 0 trap).
- new test/integration/dashboard-fanout.integration.test.js (17 tests),
bep-distance-demand-sweep.integration.test.js (3 tests),
group-bep-cascade.integration.test.js -- total suite now 108/108 green.
- .gitignore: wiki/test.gif (143 MB screen recording, kept locally only).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -22,23 +22,33 @@ function makeLogger() {
|
||||
};
|
||||
}
|
||||
|
||||
function makeSource({ name = 'mgc-1', handleInputResult = undefined } = {}) {
|
||||
function makeSource({ name = 'mgc-1', handleInputResult = undefined, dt = { flow: { min: 0, max: 100 } } } = {}) {
|
||||
const calls = {
|
||||
setMode: [],
|
||||
setScaling: [],
|
||||
handleInput: [],
|
||||
registerChild: [],
|
||||
turnOffAllMachines: 0,
|
||||
};
|
||||
const source = {
|
||||
logger: makeLogger(),
|
||||
config: { general: { name } },
|
||||
setMode: (m) => calls.setMode.push(m),
|
||||
setScaling: (s) => calls.setScaling.push(s),
|
||||
handleInput: async (src, demand) => {
|
||||
calls.handleInput.push({ src, demand });
|
||||
if (handleInputResult instanceof Error) throw handleInputResult;
|
||||
return handleInputResult;
|
||||
},
|
||||
// Used by set.demand handler when unit is %: needs dt.flow + interpolation.
|
||||
// With min=0, max=100, the linear interpolation is identity so a bare
|
||||
// numeric demand round-trips through handleInput unchanged.
|
||||
calcDynamicTotals: () => dt,
|
||||
interpolation: {
|
||||
interpolate_lin_single_point: (x, ix, iy, ox, oy) => {
|
||||
if (iy === ix) return ox;
|
||||
return ox + ((x - ix) * (oy - ox)) / (iy - ix);
|
||||
},
|
||||
},
|
||||
turnOffAllMachines: async () => { calls.turnOffAllMachines += 1; },
|
||||
childRegistrationUtils: {
|
||||
registerChild: (childSource, position) =>
|
||||
calls.registerChild.push({ childSource, position }),
|
||||
@@ -69,14 +79,31 @@ test('canonical topics dispatch to their handlers', async () => {
|
||||
await reg.dispatch({ topic: 'set.mode', payload: 'prioritycontrol' }, source, makeCtx());
|
||||
assert.deepEqual(calls.setMode, ['prioritycontrol']);
|
||||
|
||||
await reg.dispatch({ topic: 'set.scaling', payload: 'normalized' }, source, makeCtx());
|
||||
assert.deepEqual(calls.setScaling, ['normalized']);
|
||||
|
||||
// bare-number demand → interpreted as % → interpolated against dt.flow.
|
||||
// Default test dt is {min:0,max:100} so % is identity.
|
||||
await reg.dispatch({ topic: 'set.demand', payload: '12.5' }, source, makeCtx());
|
||||
assert.equal(calls.handleInput.length, 1);
|
||||
assert.deepEqual(calls.handleInput[0], { src: 'parent', demand: 12.5 });
|
||||
});
|
||||
|
||||
test('set.demand with explicit flow unit converts to canonical m³/s', async () => {
|
||||
const { source, calls } = makeSource();
|
||||
const reg = makeRegistry(makeLogger());
|
||||
await reg.dispatch({ topic: 'set.demand', payload: { value: 200, unit: 'm3/h' } }, source, makeCtx());
|
||||
assert.equal(calls.handleInput.length, 1);
|
||||
// 200 m³/h = 0.0555... m³/s
|
||||
assert.ok(Math.abs(calls.handleInput[0].demand - 0.05555555555555556) < 1e-9,
|
||||
`expected ~0.0556 m³/s, got ${calls.handleInput[0].demand}`);
|
||||
});
|
||||
|
||||
test('set.demand negative value triggers turnOffAllMachines and bypasses handleInput', async () => {
|
||||
const { source, calls } = makeSource();
|
||||
const reg = makeRegistry(makeLogger());
|
||||
await reg.dispatch({ topic: 'set.demand', payload: -1 }, source, makeCtx());
|
||||
assert.equal(calls.turnOffAllMachines, 1);
|
||||
assert.equal(calls.handleInput.length, 0);
|
||||
});
|
||||
|
||||
test('child.register canonical resolves child via RED.nodes.getNode', async () => {
|
||||
const { source, calls } = makeSource();
|
||||
const child = { id: 'child-1', source: { tag: 'child-domain' } };
|
||||
@@ -103,11 +130,6 @@ test('aliases dispatch to the same handler and log a one-time deprecation', asyn
|
||||
let warns = ctxLogger.calls.warn.filter((m) => m.includes("'setMode' is deprecated"));
|
||||
assert.equal(warns.length, 1, 'setMode deprecation warning should log exactly once');
|
||||
|
||||
await reg.dispatch({ topic: 'setScaling', payload: 'absolute' }, source, makeCtx({ logger: ctxLogger }));
|
||||
warns = ctxLogger.calls.warn.filter((m) => m.includes("'setScaling' is deprecated"));
|
||||
assert.equal(warns.length, 1);
|
||||
assert.deepEqual(calls.setScaling, ['absolute']);
|
||||
|
||||
await reg.dispatch({ topic: 'Qd', payload: 5 }, source, makeCtx({ logger: ctxLogger }));
|
||||
warns = ctxLogger.calls.warn.filter((m) => m.includes("'Qd' is deprecated"));
|
||||
assert.equal(warns.length, 1);
|
||||
|
||||
132
test/basic/equalFlowDistribution.basic.test.js
Normal file
132
test/basic/equalFlowDistribution.basic.test.js
Normal file
@@ -0,0 +1,132 @@
|
||||
// Unit tests for the pure distribution math extracted out of equalFlowControl.
|
||||
// Decoupling target: the algorithm should be testable without a full MGC.
|
||||
|
||||
'use strict';
|
||||
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const { computeEqualFlowDistribution } = require('../../src/control/strategies.js');
|
||||
|
||||
// Tiny helpers to make synthetic machines. The pure function still calls
|
||||
// filterOutUnavailableMachines, which reads machine.state.getCurrentState()
|
||||
// and machine.isValidActionForMode() — stub both so the algorithm sees the
|
||||
// machine as available. groupFlow/groupCalcPower are injected.
|
||||
function mkMachine(id, capability = { min: 0.01, max: 0.10, power: (flow) => flow * 1000 }, state = 'operational') {
|
||||
return {
|
||||
id,
|
||||
machine: {
|
||||
__testCapability: capability,
|
||||
state: { getCurrentState: () => state },
|
||||
isValidActionForMode: () => true,
|
||||
},
|
||||
};
|
||||
}
|
||||
const dummyLogger = { warn() {}, error() {}, debug() {}, info() {} };
|
||||
|
||||
// Default injected helpers: read from the synthetic machine's __testCapability.
|
||||
const groupFlow = (m) => ({
|
||||
currentFxyYMin: m.__testCapability.min,
|
||||
currentFxyYMax: m.__testCapability.max,
|
||||
});
|
||||
const groupCalcPower = (m, flow) => m.__testCapability.power(flow);
|
||||
|
||||
function basicArgs(overrides = {}) {
|
||||
const m = { a: mkMachine('a').machine, b: mkMachine('b').machine, c: mkMachine('c').machine };
|
||||
return {
|
||||
machines: m, Qd: 0.06,
|
||||
dynamicTotals: { flow: { min: 0.01, max: 0.30 } },
|
||||
activeTotals: { flow: { min: 0.03, max: 0.30 } },
|
||||
priorityList: ['a', 'b', 'c'],
|
||||
isMachineActive: () => true,
|
||||
groupFlow, groupCalcPower, logger: dummyLogger,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
test('default case: distributes Qd equally across active machines', () => {
|
||||
const r = computeEqualFlowDistribution(basicArgs({ Qd: 0.06 }));
|
||||
// 3 active pumps, demand 0.06 → 0.02 per pump.
|
||||
assert.equal(r.flowDistribution.length, 3);
|
||||
for (const entry of r.flowDistribution) {
|
||||
assert.ok(Math.abs(entry.flow - 0.02) < 1e-12, `entry.flow=${entry.flow}`);
|
||||
}
|
||||
assert.ok(Math.abs(r.totalFlow - 0.06) < 1e-12);
|
||||
// power(flow) = flow * 1000 in the test capability → 0.02 * 1000 = 20 W per pump.
|
||||
assert.ok(Math.abs(r.totalPower - 60) < 1e-9);
|
||||
});
|
||||
|
||||
test('Qd above active capacity: starts additional priority machines until covered', () => {
|
||||
// Only one machine "active" to start with; demand exceeds its envelope.
|
||||
// Algorithm should bring more priority machines online via the high-demand branch.
|
||||
const active = new Set(['a']);
|
||||
const args = basicArgs({
|
||||
Qd: 0.18, // above any single pump's max (0.10)
|
||||
activeTotals: { flow: { min: 0.01, max: 0.10 } },
|
||||
isMachineActive: (id) => active.has(id),
|
||||
});
|
||||
const r = computeEqualFlowDistribution(args);
|
||||
// The algorithm reduces Qd iteratively (Qd /= i) until it fits per-pump max.
|
||||
// We don't assert exact splits — only that flowDistribution is non-empty
|
||||
// and totalFlow is finite, since the legacy algorithm is preserved as-is.
|
||||
assert.ok(r.flowDistribution.length >= 1);
|
||||
assert.ok(Number.isFinite(r.totalFlow));
|
||||
assert.ok(Number.isFinite(r.totalPower));
|
||||
});
|
||||
|
||||
test('Qd below active min flow: routes excess machines to flow=0 and redistributes', () => {
|
||||
// demand below active min — algorithm shuts off lowest-priority machine(s)
|
||||
// and redistributes Qd across the remainder.
|
||||
const args = basicArgs({
|
||||
Qd: 0.015,
|
||||
dynamicTotals: { flow: { min: 0.01, max: 0.30 } },
|
||||
activeTotals: { flow: { min: 0.03, max: 0.30 } }, // active min > Qd
|
||||
});
|
||||
const r = computeEqualFlowDistribution(args);
|
||||
const offCount = r.flowDistribution.filter(e => e.flow === 0).length;
|
||||
assert.ok(offCount >= 1, `expected ≥1 machine to be shut off, got distribution: ${JSON.stringify(r.flowDistribution)}`);
|
||||
const totalServed = r.flowDistribution.filter(e => e.flow > 0).reduce((s, e) => s + e.flow, 0);
|
||||
assert.ok(Math.abs(totalServed - 0.015) < 1e-12, `served flow ${totalServed} should equal Qd 0.015`);
|
||||
});
|
||||
|
||||
test('totalCog is always 0 for equalFlow — preserves legacy contract', () => {
|
||||
// The historical algorithm sets totalCog = 0 in this strategy (BEP-Gravitation
|
||||
// is the only optimizer that produces a meaningful per-combination cog).
|
||||
// Pinned here so a future "improvement" doesn't silently introduce a fake value.
|
||||
const r = computeEqualFlowDistribution(basicArgs());
|
||||
assert.equal(r.totalCog, 0);
|
||||
});
|
||||
|
||||
test('isMachineActive is consulted for COUNT but not for SELECTION (legacy quirk)', () => {
|
||||
// Pins pre-existing behaviour of the default branch: it counts how many
|
||||
// machines are active (countActive) to decide how to split Qd, but then
|
||||
// iterates the FIRST countActive machines in priority order — which may
|
||||
// include inactive ones. So 2 of 3 active + Qd within range → first 2 in
|
||||
// priorityList both get flow, regardless of which are actually active.
|
||||
//
|
||||
// This is a latent bug that pre-dates the strategies decoupling refactor.
|
||||
// Documenting it here so a future cleanup is a deliberate change with a
|
||||
// failing-then-passing test, not a silent semantic shift.
|
||||
const active = new Set(['a', 'c']);
|
||||
const r = computeEqualFlowDistribution(basicArgs({
|
||||
Qd: 0.06,
|
||||
isMachineActive: (id) => active.has(id),
|
||||
}));
|
||||
// Today: machinesInPriorityOrder[0]='a', [1]='b' → 'a' and 'b' both get 0.03.
|
||||
// 'c' (active but third in priority order) gets nothing.
|
||||
const aFlow = r.flowDistribution.find(e => e.machineId === 'a')?.flow;
|
||||
const bFlow = r.flowDistribution.find(e => e.machineId === 'b')?.flow;
|
||||
const cFlow = r.flowDistribution.find(e => e.machineId === 'c')?.flow;
|
||||
assert.equal(aFlow, 0.03, 'a (priority 0, active)');
|
||||
assert.equal(bFlow, 0.03, 'b (priority 1, INACTIVE — receives flow anyway, bug)');
|
||||
assert.equal(cFlow, undefined, 'c (priority 2, active — does NOT receive flow, bug)');
|
||||
});
|
||||
|
||||
test('priorityList controls iteration order', () => {
|
||||
// The order in flowDistribution should match priorityList — i.e., machine 'c'
|
||||
// appears before machine 'a' when priorityList = ['c', 'b', 'a'].
|
||||
const r = computeEqualFlowDistribution(basicArgs({
|
||||
priorityList: ['c', 'b', 'a'],
|
||||
}));
|
||||
assert.equal(r.flowDistribution[0].machineId, 'c');
|
||||
});
|
||||
@@ -53,14 +53,33 @@ test('calcDistanceBEP returns both abs + rel', () => {
|
||||
assert.ok(Math.abs(relDistFromPeak - expectedRel) < 1e-9);
|
||||
});
|
||||
|
||||
test('calcRelativeDistanceFromPeak returns 1 when max === min (degenerate)', () => {
|
||||
test('calcRelativeDistanceFromPeak returns undefined when max === min (degenerate)', () => {
|
||||
// For homogeneous pump groups (all cogs equal), the [max..min] band
|
||||
// collapses and the metric is mathematically undefined. Return undefined
|
||||
// so the dashboard displays "—" instead of a misleading 0% / 100%.
|
||||
const ge = makeGE();
|
||||
assert.equal(ge.calcRelativeDistanceFromPeak(0.85, 0.8, 0.8), 1);
|
||||
assert.equal(ge.calcRelativeDistanceFromPeak(0.85, 0.8, 0.8), undefined);
|
||||
});
|
||||
|
||||
test('calcRelativeDistanceFromPeak returns 1 when current is null', () => {
|
||||
test('calcRelativeDistanceFromPeak returns undefined when max ≈ min within epsilon', () => {
|
||||
// Float noise from identical pumps: max-min might be 1e-12 rather than 0.
|
||||
// Must still report undefined — the interpolation extrapolates wildly here.
|
||||
const ge = makeGE();
|
||||
assert.equal(ge.calcRelativeDistanceFromPeak(null, 0.92, 0.7), 1);
|
||||
assert.equal(ge.calcRelativeDistanceFromPeak(0.85, 0.211264, 0.211263999), undefined);
|
||||
});
|
||||
|
||||
test('calcRelativeDistanceFromPeak returns undefined when current is null', () => {
|
||||
const ge = makeGE();
|
||||
assert.equal(ge.calcRelativeDistanceFromPeak(null, 0.92, 0.7), undefined);
|
||||
});
|
||||
|
||||
test('calcDistanceBEP propagates undefined relDist for degenerate input', () => {
|
||||
// Regression: if currentEff is finite, absDist is still computed (it's
|
||||
// just |current - peak|), but relDist must be undefined for degenerate.
|
||||
const ge = makeGE();
|
||||
const { absDistFromPeak, relDistFromPeak } = ge.calcDistanceBEP(0.206, 0.211, 0.211);
|
||||
assert.ok(Math.abs(absDistFromPeak - 0.005) < 1e-9);
|
||||
assert.equal(relDistFromPeak, undefined);
|
||||
});
|
||||
|
||||
test('calcGroupEfficiency handles a single machine', () => {
|
||||
|
||||
Reference in New Issue
Block a user