feat(anpr): read every frame, settle every plate, debounce per plate
Build & push images / images (push) Successful in 3m9s

Measured on park-2 (i5-9500): a main-stream pull is ~0.1s and /analyze
~0.25s while the host sat under 3% CPU; the loop's fixed 1s sleep was the
limit (one frame per ~1.35s). The camera's picture endpoint is single-
threaded (4 parallel GETs -> two 503s) and the vision service serialises
inference, so no threads: pulls are back-to-back and serial per camera,
~3 fps. ANPR_POLL_MS is now a floor (default 0).

The loop no longer breaks on the first confident plate, and the 12s
camera-level debounce is gone: 40 of 57 plate-driven opens at park-2 had a
push dropped in that blind window, so a tailgating car was never looked at.
Each confident plate is settled once per loop (emit / anpr-skip / decline)
and the loop runs on while the camera keeps pushing, so a second car is
read by the same loop. Debounce is keyed deviceId:plate only; the card/QR
mid-poll guard is per subscriber instead of aborting the loop; the pass
sample is one per plated car. ANPR_POLL_WINDOW_MS=0 is honoured (it used to
fall back to 8s silently).

The camera event model was re-confirmed from 2780 pushes: every push is an
independent VMD/active with activePostCount=1, ~1.2s apart while a car
moves, never inactive. Nothing is held for 30s on the camera side.
This commit is contained in:
2026-10-11 18:17:25 +02:00
parent 7b29331f52
commit d93089a491
5 changed files with 337 additions and 154 deletions
+92 -18
View File
@@ -43,9 +43,10 @@ beforeEach(() => {
normalizedBoxes.mockResolvedValue({ vehicleBox: null, plateBox: null });
delete process.env.VISION_ENTRY_MIN_CONFIDENCE;
delete process.env.ANPR_DEBOUNCE_MS;
// Poll-until-confident loop: keep the window + interval tiny so a below-floor / no-plate
// case gives up in ~one tick instead of the 8s production window (tests stay fast). Each
// bridge reads these in its constructor, so set them before `new AnprBridge`.
// Read-every-frame loop: keep the window tiny so a loop ends in a few ticks instead of the
// 8s production window (tests stay fast); the 1ms floor keeps a mocked loop from spinning
// thousands of frames. Each bridge reads these in its constructor, so set them before
// `new AnprBridge`.
process.env.ANPR_POLL_MS = "1";
process.env.ANPR_POLL_WINDOW_MS = "5";
});
@@ -107,19 +108,35 @@ function fakeVision(opts: { enabled?: boolean; plate?: string; confidence?: numb
/** A fake SubscriptionFlow: only `match()` is called by the bridge. */
function fakeSubFlow(
match: SubscriptionMatch | null,
// A fixed answer, or a matcher by plate (several subscribers in one loop).
match: SubscriptionMatch | null | ((plate: string) => SubscriptionMatch | null),
// openOccurrenceCount: a constant, or a sequence consumed per call (to simulate a
// credential closing an occurrence mid-poll → count changes).
openCounts: number | number[] = 1,
): SubscriptionFlow {
const seq = Array.isArray(openCounts) ? [...openCounts] : null;
return {
match: vi.fn(() => match),
match: vi.fn((e: DeviceReadEvent) => (typeof match === "function" ? match(e.value) : match)),
openOccurrenceCount: vi.fn(() => (seq ? (seq.length > 1 ? seq.shift()! : seq[0]) : (openCounts as number))),
} as unknown as SubscriptionFlow;
}
const SUB_MATCH: SubscriptionMatch = { subscriptionId: "sub-1", carKey: "AA111BB", via: "plate" };
const SUB_MATCH_2: SubscriptionMatch = { subscriptionId: "sub-2", carKey: "CC333DD", via: "plate" };
/** A VisionClient whose analyze() walks a sequence of (plate, confidence) frames, holding the
* last one — the way a car's read evolves as it approaches and settles, or as one car gives
* way to the next. `vehicle` (optional) rides every frame. */
function sequenceVision(frames: { plate: string; confidence: number }[], vehicle: VisionVehicle | null = null): VisionClient {
let i = 0;
return {
enabled: true,
analyze: vi.fn(async () => {
const f = frames[Math.min(i++, frames.length - 1)]!;
return { plate: { text: f.plate, confidence: f.confidence }, plates: [], lowConfidence: false, vehicle, modelVersion: "test", tookMs: 1 };
}),
} as unknown as VisionClient;
}
/** Capture read events emitted during `fn` (async). */
async function captureReads(fn: () => Promise<void>): Promise<DeviceReadEvent[]> {
@@ -165,7 +182,7 @@ describe("AnprBridge pass sample — every detected car, ticket or not", () => {
expect(row).toMatchObject({ direction: "entry", deviceId: cam, identity: read.identity, contentType: "image/jpeg" });
});
it("is ONE sample per detection even when the loop polls several frames, and rides along a subscriber emit", async () => {
it("is ONE sample per car even when the loop polls several frames, and rides along a subscriber emit", async () => {
normalizedBoxes.mockResolvedValue({ vehicleBox: BOX, plateBox: { x1: 0.3, y1: 0.4, x2: 0.4, y2: 0.45 } });
const cam = seedCamera({ anpr: true });
const bridge = new AnprBridge(db, fakeVision({ plate: "AA111BB", confidence: 0.97, vehicle: VEHICLE }), fakeSubFlow(SUB_MATCH), silentLogger());
@@ -179,6 +196,23 @@ describe("AnprBridge pass sample — every detected car, ticket or not", () => {
expect(db.select().from(snapshots).all()).toHaveLength(1);
});
it("samples EACH plated car of a loop once — two cars back to back → two samples", async () => {
normalizedBoxes.mockResolvedValue({ vehicleBox: BOX, plateBox: null });
const cam = seedCamera({ anpr: true });
// Car A (3 frames) then car B, both framed; a non-subscriber lot (match null) — the
// sample is about the reviewer's stream, not about admission.
const vision = sequenceVision(
[{ plate: "AA111BB", confidence: 0.97 }, { plate: "AA111BB", confidence: 0.98 }, { plate: "AA111BB", confidence: 0.97 }, { plate: "CC333DD", confidence: 0.96 }],
VEHICLE,
);
process.env.ANPR_POLL_WINDOW_MS = "200";
const bridge = new AnprBridge(db, vision, fakeSubFlow(null), silentLogger());
const got = await captureVehicleReads(() => bridge.onVehicleDetected(cam), 2);
expect(got).toHaveLength(2);
expect(db.select().from(snapshots).all()).toHaveLength(2);
});
it("records nothing without a vehicle box (nothing to crop) — a bare class is not a sample", async () => {
const cam = seedCamera({ anpr: true });
const bridge = new AnprBridge(db, fakeVision({ vehicle: { bodyType: "car", confidence: 0.9 } }), fakeSubFlow(null), silentLogger());
@@ -251,9 +285,10 @@ describe("AnprBridge", () => {
})),
} as unknown as VisionClient;
// Generous window so all 3 escalation attempts run deterministically under suite load
// (the global beforeEach sets a tiny 5ms window for the give-up cases).
// (the global beforeEach sets a tiny 5ms window for the give-up cases). The loop keeps
// reading until the window ends — the same plate must still be emitted exactly once.
process.env.ANPR_POLL_MS = "1";
process.env.ANPR_POLL_WINDOW_MS = "2000";
process.env.ANPR_POLL_WINDOW_MS = "150";
const bridge = new AnprBridge(db, vision, fakeSubFlow(SUB_MATCH), silentLogger());
const reads = await captureReads(() => bridge.onVehicleDetected(cam));
@@ -299,18 +334,40 @@ describe("AnprBridge", () => {
expect(reads[0]).toMatchObject({ value: "AA111BB" });
});
it("ABORTS if the subscriber transacts by another credential mid-poll (no double-act)", async () => {
// The car's plate is read (identity known) but stays below the floor; meanwhile the
// subscriber scans their card → openOccurrenceCount drops. The bridge must abort and NOT
// emit (which would exit the NEXT open occurrence — a phantom double-exit, esp. fleet).
it("does NOT emit if the subscriber transacts by another credential mid-poll (no double-act)", async () => {
// The car's plate is read (identity known) while still below the floor; meanwhile the
// subscriber scans their card → openOccurrenceCount drops. When the plate finally reads
// confidently the bridge must NOT emit (it would exit the NEXT open occurrence — a
// phantom double-exit, esp. fleet).
const cam = seedCamera({ anpr: true });
const vision = fakeVision({ plate: "AA111BB", confidence: 0.5 }); // never clears the floor
// openOccurrenceCount: 1 at baseline, then 0 (the card exit closed it) on the next check.
const vision = sequenceVision([{ plate: "AA111BB", confidence: 0.5 }, { plate: "AA111BB", confidence: 0.97 }]);
// openOccurrenceCount: 1 at first sighting, then 0 (the card exit closed it) at settle time.
const sub = fakeSubFlow(SUB_MATCH, [1, 0]);
process.env.ANPR_POLL_WINDOW_MS = "200";
const bridge = new AnprBridge(db, vision, sub, silentLogger());
const reads = await captureReads(() => bridge.onVehicleDetected(cam));
expect(reads).toEqual([]); // aborted — the credential already handled it
expect(reads).toEqual([]); // declined — the credential already handled it
expect(vision.analyze).toHaveBeenCalledTimes; // (the loop itself kept going)
});
it("KEEPS READING after a confident plate: a second car in the same loop is emitted too", async () => {
// Car A reads confidently on frames 1-3, then car B pulls into the zone (frames 4+).
// Before 2026-10-11 the loop broke on A's first read and the camera-level debounce then
// dropped every push for 12s — B was invisible. Now A is settled once and the loop goes
// on; B is read by the same loop. Each plate exactly once, however many frames repeat.
const cam = seedCamera({ anpr: true });
const vision = sequenceVision([
{ plate: "AA111BB", confidence: 0.97 }, { plate: "AA111BB", confidence: 0.98 }, { plate: "AA111BB", confidence: 0.97 },
{ plate: "CC333DD", confidence: 0.96 },
]);
const sub = fakeSubFlow((plate) => (plate === "AA111BB" ? SUB_MATCH : plate === "CC333DD" ? SUB_MATCH_2 : null));
process.env.ANPR_POLL_WINDOW_MS = "200";
const bridge = new AnprBridge(db, vision, sub, silentLogger());
const reads = await captureReads(() => bridge.onVehicleDetected(cam));
expect(reads.map((r) => r.value)).toEqual(["AA111BB", "CC333DD"]);
expect(captureSnapshot.mock.calls.length).toBeGreaterThan(4); // it did not stop at A
});
it("does NOT emit for a plate matching no subscription — records an advisory anpr-skip", async () => {
@@ -342,17 +399,34 @@ describe("AnprBridge", () => {
expect(skips).toHaveLength(1);
});
it("debounces: two vehicle events within the window analyze/emit at most once", async () => {
it("debounces PER PLATE: the same car re-detected within the window is emitted once", async () => {
const cam = seedCamera({ anpr: true });
const vision = fakeVision({ plate: "AA111BB", confidence: 0.97 });
const bridge = new AnprBridge(db, vision, fakeSubFlow(SUB_MATCH), silentLogger());
const reads = await captureReads(async () => {
await bridge.onVehicleDetected(cam);
await bridge.onVehicleDetected(cam); // within the 12s window → suppressed
await bridge.onVehicleDetected(cam); // a second loop — the same plate within 12s → suppressed
});
expect(reads).toHaveLength(1);
expect(captureSnapshot).toHaveBeenCalledTimes(1); // 2nd was gated before the snapshot
expect(captureSnapshot.mock.calls.length).toBeGreaterThanOrEqual(2); // the 2nd loop DID look
});
it("is NOT blind after a read: a different car detected right after is emitted", async () => {
// The old camera-level debounce dropped every push for 12s after a success. A car behind
// the first, arriving after the first loop ended, must get its own loop and its own read.
const cam = seedCamera({ anpr: true });
const frames = [{ plate: "AA111BB", confidence: 0.97 }];
const vision = sequenceVision(frames);
const sub = fakeSubFlow((plate) => (plate === "AA111BB" ? SUB_MATCH : plate === "CC333DD" ? SUB_MATCH_2 : null));
const bridge = new AnprBridge(db, vision, sub, silentLogger());
const reads = await captureReads(async () => {
await bridge.onVehicleDetected(cam); // car A
frames[0] = { plate: "CC333DD", confidence: 0.96 }; // car B now in the zone
await bridge.onVehicleDetected(cam); // its push starts a new loop
});
expect(reads.map((r) => r.value)).toEqual(["AA111BB", "CC333DD"]);
});
it("is a no-op (no throw) when vision is disabled or reads nothing", async () => {