diff --git a/src/miniapps/waterwatch/corroboration.test.ts b/src/miniapps/waterwatch/corroboration.test.ts index aeec58b..af674dc 100644 --- a/src/miniapps/waterwatch/corroboration.test.ts +++ b/src/miniapps/waterwatch/corroboration.test.ts @@ -9,6 +9,7 @@ import { extractWaterReadingReports, } from "./corroboration.ts"; import { createChannelCusumGate } from "./cusum.ts"; +import { DEFAULT_PIPE_NETWORK } from "./waterNetwork.ts"; beforeEach(async () => { indexedDB.deleteDatabase(db.name); @@ -185,6 +186,125 @@ describe("corroboration gate (adversarial robustness - non-finite readings)", () }); }); +describe("multi-sensor corroboration gate (topology-proximity gating - coherence-audit GAP-FOUND fix)", () => { + it( + "does NOT promote to alert when two known sensors on DISTANT topology branches " + + "(kiosk-1 East wing vs kiosk-3 West wing) report the same CUSUM side within the window", + async () => { + const gate = createCorroborationGate({ + windowMs: 5 * 60_000, + network: DEFAULT_PIPE_NETWORK, + }); + + await warmUp(gate, "kiosk-1", "pH", 7.0, 60); + await warmUp(gate, "kiosk-3", "pH", 7.0, 60); + + const candidate = gate.ingest({ + sensorId: "kiosk-1", + channel: "pH", + timestamp: T0 + 60 * 60_000, + value: 9.5, + }); + expect(candidate.state).toBe("corroborating"); + + // kiosk-3 is on the West wing, kiosk-1 on the East wing - their only + // common ancestor is the far-upstream main line. Before this fix this + // falsely promoted to "alert" and credited ma-fairshare's water pool; + // now it must stay non-alert (the prior false-corroboration regression + // this fix closes). + const falseCorroboration = gate.ingest({ + sensorId: "kiosk-3", + channel: "pH", + timestamp: T0 + 60 * 60_000 + 60_000, + value: 9.4, + }); + expect(falseCorroboration.state).not.toBe("alert"); + expect(falseCorroboration.state).toBe("corroborating"); + + const effect = await applyCorroboratedReadingToFairshare(falseCorroboration, append); + expect(effect).toBeUndefined(); + + const entries = await readAll(); + const waterSeedEvents = entries.filter( + (entry) => + typeof entry.payload === "object" && + entry.payload !== null && + (entry.payload as Record).type === "seed.resource.water", + ); + expect(waterSeedEvents).toHaveLength(0); + }, + ); + + it( + "still promotes to alert when two known sensors on the SAME topology branch " + + "(kiosk-1 and kiosk-2, both East wing) report the same CUSUM side within the window", + async () => { + const gate = createCorroborationGate({ + windowMs: 5 * 60_000, + network: DEFAULT_PIPE_NETWORK, + }); + + await warmUp(gate, "kiosk-1", "pH", 7.0, 60); + await warmUp(gate, "kiosk-2", "pH", 7.0, 60); + + const candidate = gate.ingest({ + sensorId: "kiosk-1", + channel: "pH", + timestamp: T0 + 60 * 60_000, + value: 9.5, + }); + expect(candidate.state).toBe("corroborating"); + + // kiosk-2 shares the East wing junction with kiosk-1 - a legitimate + // nearby corroboration that must keep working after the fix. + const corroborated = gate.ingest({ + sensorId: "kiosk-2", + channel: "pH", + timestamp: T0 + 60 * 60_000 + 60_000, + value: 9.4, + }); + expect(corroborated.state).toBe("alert"); + expect(corroborated.corroboratedWith).toEqual(candidate.reading); + + const effect = await applyCorroboratedReadingToFairshare(corroborated, append); + expect(effect).toBeDefined(); + }, + ); + + it( + "falls back to the original distinct-sensorId + timing-only check (still promotes) when " + + "one sensorId is unknown to the topology", + async () => { + const gate = createCorroborationGate({ + windowMs: 5 * 60_000, + network: DEFAULT_PIPE_NETWORK, + }); + + await warmUp(gate, "kiosk-1", "pH", 7.0, 60); + await warmUp(gate, "resident-phone-7", "pH", 7.0, 60); + + const candidate = gate.ingest({ + sensorId: "kiosk-1", + channel: "pH", + timestamp: T0 + 60 * 60_000, + value: 9.5, + }); + expect(candidate.state).toBe("corroborating"); + + // "resident-phone-7" is free text, unknown to DEFAULT_PIPE_NETWORK - the + // gate must not block corroboration outright just because one side is + // unmapped; it falls back to the pre-fix distinct-id + timing check. + const corroborated = gate.ingest({ + sensorId: "resident-phone-7", + channel: "pH", + timestamp: T0 + 60 * 60_000 + 60_000, + value: 9.4, + }); + expect(corroborated.state).toBe("alert"); + }, + ); +}); + describe("two-sided CUSUM mechanism sensitivity (synthetic property test, NOT GECCO validation data)", () => { it("fires when a sustained synthetic drift is injected into an otherwise-stable channel", () => { const gate = createChannelCusumGate(); diff --git a/src/miniapps/waterwatch/corroboration.ts b/src/miniapps/waterwatch/corroboration.ts index 837bf22..81864f3 100644 --- a/src/miniapps/waterwatch/corroboration.ts +++ b/src/miniapps/waterwatch/corroboration.ts @@ -17,6 +17,7 @@ import { computeFairshareAllocation } from "../../lib/fairshare.ts"; import { sortForReplay } from "../../lib/ledger.ts"; import type { RobustBaselineOptions } from "./ewma.ts"; import { createChannelCusumGate, type ChannelCusumGateOptions, type CusumOptions, type CusumSide } from "./cusum.ts"; +import { buildIndex, topologyDistance, type PipeIndex, type PipeNetwork } from "./waterNetwork.ts"; export type GateState = "clean" | "corroborating" | "alert"; @@ -125,7 +126,6 @@ export function extractWaterReadingReports( }; }); } - export interface CorroborationGateOptions { /** Max gap between two independent sensors' candidate alerts to count as corroboration, in ms. Default 5 minutes. */ windowMs?: number; @@ -143,6 +143,31 @@ export interface CorroborationGateOptions { * touches the GECCO-validated default used for automated sensor feeds. */ gate?: ChannelCusumGateOptions; + /** + * The pipe-graph topology (`waterNetwork.ts`'s `DEFAULT_PIPE_NETWORK` or + * an equivalent) used to require physical proximity before promoting a + * pending candidate to "alert". Optional and additive: when omitted, the + * gate falls back to the original distinct-sensorId + timing-only check + * for every reading, exactly as before this option existed. When + * supplied, a pair of readings whose sensorIds BOTH resolve to a known + * node is also required to be within `maxTopologyDistance` of each other; + * a reading from a sensorId the topology doesn't recognize (a free-text + * device id typed into `ReportReadingForm`) still falls back to the + * timing-only check rather than being blocked outright. + */ + network?: PipeNetwork; + /** + * Max topological distance (edges through the pair's lowest common + * ancestor - see `waterNetwork.ts`'s `topologyDistance`) between two + * known sensors for their candidates to corroborate. Default 2: on + * `DEFAULT_PIPE_NETWORK`'s demo topology every tap sits exactly one hop + * below its wing junction, so two taps under the *same* wing (e.g. + * kiosk-1/kiosk-2, both East) are distance 2 apart - the tightest + * meaningful "same local branch" relationship short of an identical + * sensor - while two taps on different wings (e.g. kiosk-1 East / + * kiosk-3 West) are distance 4, correctly rejected. + */ + maxTopologyDistance?: number; } interface PendingCandidate { @@ -163,6 +188,31 @@ export function createCorroborationGate(options: CorroborationGateOptions = {}) const windowMs = options.windowMs ?? DEFAULT_WINDOW_MS; const detectorsBySensorChannel = new Map>(); const pendingByChannel = new Map(); + const topologyIndex: PipeIndex | undefined = options.network ? buildIndex(options.network) : undefined; + const maxTopologyDistance = options.maxTopologyDistance ?? 2; + + // Two readings "corroborate" each other iff they're both physically + // plausible reports of the SAME event, not just two differently-named + // sensors reacting to unrelated local causes within the same window. + // When both sensorIds resolve to a known node in the supplied pipe + // topology, require them to be within `maxTopologyDistance` of each + // other (reusing `waterNetwork.ts`'s `topologyDistance`/ + // `lowestCommonAncestor` - the same topology reasoning + // `waterWatchController.ts`'s `localizeAnomaly` already does for + // display, now consulted before the gating decision instead of only + // after it). An unrecognized sensorId (free-text device id typed into + // `ReportReadingForm`, not present in the demo network) falls back to + // the original distinct-sensorId + timing-only check rather than being + // blocked outright - this is additive, never a regression for sensors + // the topology doesn't know about. + function isTopologicallyPlausible(sensorIdA: string, sensorIdB: string): boolean { + if (!topologyIndex) return true; + const nodeA = topologyIndex.sensorToNode.get(sensorIdA); + const nodeB = topologyIndex.sensorToNode.get(sensorIdB); + if (nodeA === undefined || nodeB === undefined) return true; + const distance = topologyDistance(topologyIndex, nodeA, nodeB); + return distance !== null && distance <= maxTopologyDistance; + } function detectorFor(sensorId: string, channel: string) { const key = `${sensorId}\u0000${channel}`; @@ -195,7 +245,8 @@ export function createCorroborationGate(options: CorroborationGateOptions = {}) pending !== undefined && pending.sensorId !== reading.sensorId && pending.side === fired && - Math.abs(reading.timestamp - pending.reading.timestamp) <= windowMs; + Math.abs(reading.timestamp - pending.reading.timestamp) <= windowMs && + isTopologicallyPlausible(pending.sensorId, reading.sensorId); if (corroborates) { pendingByChannel.delete(reading.channel); diff --git a/src/miniapps/waterwatch/waterNetwork.ts b/src/miniapps/waterwatch/waterNetwork.ts index ea2a843..39b7663 100644 --- a/src/miniapps/waterwatch/waterNetwork.ts +++ b/src/miniapps/waterwatch/waterNetwork.ts @@ -129,3 +129,59 @@ export function buildIndex(net: PipeNetwork): PipeIndex { return { nodesById, sensorToNode, parent, children, depth, edgeFlowSeconds }; } + +/** Climbs `nodeId` up `index.parent` until it reaches `targetDepth` (never below it). */ +export function climbToDepth(index: PipeIndex, nodeId: string, targetDepth: number): string { + let current = nodeId; + while ((index.depth.get(current) ?? 0) > targetDepth) { + const parentId = index.parent.get(current); + if (parentId === null || parentId === undefined) break; + current = parentId; + } + return current; +} + +/** + * Lowest common ancestor of two nodes in `index`'s tree, found by lifting + * the deeper node up to the shallower one's depth, then climbing both in + * lockstep until they meet. Returns null only when either node is absent + * from the index entirely (an inconsistent caller, not an expected input). + * + * Shared by `waterWatchController.ts`'s post-hoc leak localization and + * `corroboration.ts`'s pre-alert topology-proximity check - one graph + * algorithm, two callers, never two representations of the same tree. + */ +export function lowestCommonAncestor(index: PipeIndex, a: string, b: string): string | null { + const depthA = index.depth.get(a); + const depthB = index.depth.get(b); + if (depthA === undefined || depthB === undefined) return null; + + const meetDepth = Math.min(depthA, depthB); + let x = climbToDepth(index, a, meetDepth); + let y = climbToDepth(index, b, meetDepth); + while (x !== y) { + const nextX = index.parent.get(x); + const nextY = index.parent.get(y); + if (nextX === null || nextX === undefined || nextY === null || nextY === undefined) return null; + x = nextX; + y = nextY; + } + return x; +} + +/** + * Topological distance between two nodes: the number of edges on the path + * between them through their lowest common ancestor (sum of each node's + * depth above the LCA). Two sibling taps under the same junction are + * distance 2 apart (one hop up, one hop down); taps on unrelated branches + * are farther. Returns null when either node is unknown to `index` or no + * common ancestor exists (should not happen on a well-formed tree). + */ +export function topologyDistance(index: PipeIndex, a: string, b: string): number | null { + const depthA = index.depth.get(a); + const depthB = index.depth.get(b); + const lca = lowestCommonAncestor(index, a, b); + if (depthA === undefined || depthB === undefined || lca === null) return null; + const lcaDepth = index.depth.get(lca) ?? 0; + return (depthA - lcaDepth) + (depthB - lcaDepth); +} diff --git a/src/miniapps/waterwatch/waterWatchController.ts b/src/miniapps/waterwatch/waterWatchController.ts index 60c75f0..fcd9052 100644 --- a/src/miniapps/waterwatch/waterWatchController.ts +++ b/src/miniapps/waterwatch/waterWatchController.ts @@ -16,7 +16,7 @@ import { type GateEvent, type WaterReading, } from "./corroboration.ts"; -import { buildIndex, type PipeIndex, type PipeNetwork } from "./waterNetwork.ts"; +import { buildIndex, lowestCommonAncestor, type PipeIndex, type PipeNetwork } from "./waterNetwork.ts"; /** How many recent readings to keep per channel for the "live feed" list. */ const FEED_HISTORY_LIMIT = 8; @@ -80,41 +80,6 @@ export interface WaterWatchController { getChannelStatuses(): ChannelStatus[]; } -/** Climbs `nodeId` up `index.parent` until it reaches `targetDepth` (never below it). */ -function climbToDepth(index: PipeIndex, nodeId: string, targetDepth: number): string { - let current = nodeId; - while ((index.depth.get(current) ?? 0) > targetDepth) { - const parentId = index.parent.get(current); - if (parentId === null || parentId === undefined) break; - current = parentId; - } - return current; -} - -/** - * Lowest common ancestor of two nodes in `index`'s tree, found by lifting - * the deeper node up to the shallower one's depth, then climbing both in - * lockstep until they meet. Returns null only when either node is absent - * from the index entirely (an inconsistent caller, not an expected input). - */ -function lowestCommonAncestor(index: PipeIndex, a: string, b: string): string | null { - const depthA = index.depth.get(a); - const depthB = index.depth.get(b); - if (depthA === undefined || depthB === undefined) return null; - - const meetDepth = Math.min(depthA, depthB); - let x = climbToDepth(index, a, meetDepth); - let y = climbToDepth(index, b, meetDepth); - while (x !== y) { - const nextX = index.parent.get(x); - const nextY = index.parent.get(y); - if (nextX === null || nextX === undefined || nextY === null || nextY === undefined) return null; - x = nextX; - y = nextY; - } - return x; -} - /** * Localizes a contaminant's origin over `net`'s flow tree from the * sensorIds that independently detected it. A single detecting sensor can