move_detect/server/tests/DeviceHealthWatchTest.php
유창욱 9c0cfd2fea feat(alert): 아무도 발행하지 않던 device_fault·monitoring_degraded 구현
두 유형은 타입 정의(edge/events.py)·서버 검증(EventValidator)·콘솔 필터·
통보 라벨까지 전 구간에 있었으나 생성하는 코드가 어디에도 없었다. 실제로
값을 넣는 것은 seed_demo.php 뿐이었고, 소개서가 내세운 "17종"은 15종이었다.

앞서 고친 EventValidator 누락과 정확히 반대 방향의 같은 병이다. 그때는
감지기가 있는데 서버가 막았고, 이번엔 서버·UI가 열려 있는데 감지기가 없다.
어느 쪽이든 화면은 멀쩡해 보인다.

엣지가 낼 수 없는 유형이라 서버에 둔다 — 전원·회선이 끊긴 노드는 자기가
죽었다고 신고할 수 없다. 하트비트의 부재로만 관측된다.

App\Alert\DeviceHealthWatch:
- dispatch_alerts.php 1분 크론의 1단계. 에스컬레이션·통보보다 앞에 두어
  같은 실행 안에서 발행된 장치 이벤트가 곧바로 통보 대상이 되게 했다.
- 멱등은 EscalationWatch와 같은 방식(event_uuid UNIQUE 충돌)이되, 장치
  건전성은 연속 상태라 uuid 앵커를 '장애 구간의 시작'으로 잡았다.
  device_fault는 last_heartbeat_at(장애 내내 불변) → 장애당 정확히 1건.
  monitoring_degraded는 창 안의 마지막 정상 하트비트 ts. 창 전체가 저하면
  시작을 볼 수 없으므로 창 버킷으로 폴백해 시간당 1회 재고지한다 —
  의도된 리마인더이고, 매 틱 재발행하는 앵커 드리프트가 아니다.
- 성능 저하는 지속을 요구(기본 5분). 한 번 튄 값에 울리면 운영자가 이
  유형을 무시하게 되고, 그러면 감시가 멈춘 날에도 아무도 보지 않는다.
  엣지 감지기들이 쓰는 규율과 같다.
- 하트비트를 한 번도 보낸 적 없는 장치는 장애가 아니다(미설치 노드).
  새 현장 첫날이 빨간 벽이 되면 그 사이트는 이 유형을 영영 신뢰하지 않는다.
- 죽은 노드에 degraded를 겹쳐 내지 않는다 — 한 고장에 두 알람은 소음이다.
- fps NULL을 0으로 강압하지 않는다(측정 실패 ≠ 정지). PdoDeviceMetric
  Repository가 NULL을 지키는 이유와 같다.
- 억제(정비 모드)는 여기서 보지 않는다. 기록은 남기고 통보 여부는
  AlertDispatcher가 정한다 — 정비 창은 전화를 끄는 것이지 노드가 죽었던
  기록을 지우는 것이 아니다.

camera_id는 NOT NULL인데 장치 단위 이벤트에는 카메라가 없다. '__device__'
센티넬을 쓰고, 콘솔은 "장치 전체"로 표시, 구역 편집기 카메라 목록에서는
제외한다(카메라 목록은 보고된 이벤트에서 파생되므로, 두면 존재하지 않는
카메라에 구역을 그리려는 일이 생긴다).

설정 4종 추가(device_stale_seconds 180 · degraded_sustain_seconds 300 ·
degraded_fps_ratio 0.6 · target_fps 12) — 두 config 템플릿에 한국어 설명과
함께. 낮은 프레임으로 운용하는 현장이 target_fps를 안 맞추면 전 노드가
영구 저하로 보고되므로 그 경고를 템플릿에 적었다.

검증: pytest 308 passed(3 skip: 모델 미동봉·shellcheck 미설치·AF_UNIX,
기존과 동일) · phpunit 240 passed(신규 16). dist 재생성으로 패리티 회복.
2026-08-25 10:36:48 +09:00

314 lines
12 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Tests;
use App\Alert\DeviceHealthWatch;
use App\Tests\Support\{InMemoryEventRepository, InMemoryDeviceRepository, InMemoryDeviceMetricRepository};
use PHPUnit\Framework\TestCase;
/**
* The two events nobody produced.
*
* These tests pin the behaviour that makes them trustworthy rather than noisy: a fault must be
* filed ONCE per outage (not once per cron tick), a slow node must be degraded for a sustained
* period before it counts, and a node that has never been installed must stay silent.
*/
final class DeviceHealthWatchTest extends TestCase
{
private const NOW = 1_700_000_000;
private function devices(array $rows): InMemoryDeviceRepository
{
return new InMemoryDeviceRepository([], [], [], $rows);
}
private function device(string $id, ?int $heartbeat, ?string $site = 'site-a'): array
{
return ['device_id' => $id, 'name' => $id, 'site' => $site,
'last_fps' => null, 'last_temp' => null, 'last_throttle' => null,
'config_version' => 1, 'reported_config_version' => 1,
'last_heartbeat_at' => $heartbeat];
}
/** @param array<int,array> $points [tsOffsetFromNow => metric fields] */
private function metrics(string $deviceId, array $points): InMemoryDeviceMetricRepository
{
$repo = new InMemoryDeviceMetricRepository();
foreach ($points as $offset => $fields) {
$repo->append($deviceId, $fields, self::NOW - $offset);
}
return $repo;
}
// --- device_fault ---------------------------------------------------------------------
public function testSilentDeviceFilesDeviceFault(): void
{
$events = new InMemoryEventRepository();
$watch = new DeviceHealthWatch(
$events,
$this->devices([$this->device('pi-01', self::NOW - 600)]),
new InMemoryDeviceMetricRepository()
);
$filed = $watch->run(self::NOW);
self::assertCount(1, $filed);
self::assertSame('device_fault', $filed[0]['event_type']);
$row = $events->find($filed[0]['event_id']);
self::assertSame('warning', $row['severity']);
self::assertSame(DeviceHealthWatch::DEVICE_CAMERA, $row['camera_id']);
self::assertSame('site-a', $row['site']);
self::assertSame(600, $row['metrics']['silent_s']);
}
public function testHealthyHeartbeatFilesNothing(): void
{
$events = new InMemoryEventRepository();
$watch = new DeviceHealthWatch(
$events,
$this->devices([$this->device('pi-01', self::NOW - 20)]),
$this->metrics('pi-01', [20 => ['fps' => 12.0, 'cameras_erroring' => 0]])
);
self::assertSame([], $watch->run(self::NOW));
}
public function testOutageFilesOnceAcrossRepeatedRuns(): void
{
// The cron runs every minute. An hour-long outage must leave ONE event, not sixty.
$events = new InMemoryEventRepository();
$devices = $this->devices([$this->device('pi-01', self::NOW - 600)]);
$watch = new DeviceHealthWatch($events, $devices, new InMemoryDeviceMetricRepository());
$first = $watch->run(self::NOW);
$second = $watch->run(self::NOW + 60);
$third = $watch->run(self::NOW + 120);
self::assertCount(1, $first);
self::assertSame([], $second);
self::assertSame([], $third);
}
public function testRecoveredThenFailedAgainIsASecondEvent(): void
{
$events = new InMemoryEventRepository();
$devices = $this->devices([$this->device('pi-01', self::NOW - 600)]);
$watch = new DeviceHealthWatch($events, $devices, new InMemoryDeviceMetricRepository());
self::assertCount(1, $watch->run(self::NOW));
// The node came back (new heartbeat) and then went silent again.
$devices->statusRows = [$this->device('pi-01', self::NOW + 1000)];
self::assertCount(1, $watch->run(self::NOW + 2000));
}
public function testNeverInstalledDeviceIsNotAFault(): void
{
// A provisioned row that has never reported is an uninstalled node. Alarming here would
// make every new site's first day a wall of red.
$events = new InMemoryEventRepository();
$watch = new DeviceHealthWatch(
$events,
$this->devices([$this->device('pi-new', null), $this->device('pi-zero', 0)]),
new InMemoryDeviceMetricRepository()
);
self::assertSame([], $watch->run(self::NOW));
}
public function testSilentDeviceDoesNotAlsoFileDegraded(): void
{
// A node that is gone must not be reported twice for one failure.
$events = new InMemoryEventRepository();
$watch = new DeviceHealthWatch(
$events,
$this->devices([$this->device('pi-01', self::NOW - 600)]),
$this->metrics('pi-01', [900 => ['fps' => 1.0], 700 => ['fps' => 1.0]])
);
$filed = $watch->run(self::NOW);
self::assertCount(1, $filed);
self::assertSame('device_fault', $filed[0]['event_type']);
}
// --- monitoring_degraded --------------------------------------------------------------
public function testSustainedLowFpsFilesDegraded(): void
{
$events = new InMemoryEventRepository();
$watch = new DeviceHealthWatch(
$events,
$this->devices([$this->device('pi-01', self::NOW - 10)]),
$this->metrics('pi-01', [
800 => ['fps' => 12.0], // healthy anchor
600 => ['fps' => 3.0],
300 => ['fps' => 3.0],
10 => ['fps' => 3.0],
])
);
$filed = $watch->run(self::NOW);
self::assertCount(1, $filed);
self::assertSame('monitoring_degraded', $filed[0]['event_type']);
$row = $events->find($filed[0]['event_id']);
self::assertSame(['low_fps'], $row['metrics']['reasons']);
self::assertSame(590, $row['metrics']['degraded_s']);
}
public function testBriefDipDoesNotFileDegraded(): void
{
// One slow heartbeat is a hiccup. Requiring a sustained run is what separates this event
// from noise the operator learns to ignore.
$events = new InMemoryEventRepository();
$watch = new DeviceHealthWatch(
$events,
$this->devices([$this->device('pi-01', self::NOW - 10)]),
$this->metrics('pi-01', [
200 => ['fps' => 12.0],
100 => ['fps' => 12.0],
10 => ['fps' => 3.0],
])
);
self::assertSame([], $watch->run(self::NOW));
}
public function testRecoveredFpsFilesNothingEvenAfterALongBadRun(): void
{
// The latest heartbeat is what decides. A node that already recovered must not alarm.
$events = new InMemoryEventRepository();
$watch = new DeviceHealthWatch(
$events,
$this->devices([$this->device('pi-01', self::NOW - 10)]),
$this->metrics('pi-01', [
900 => ['fps' => 2.0],
600 => ['fps' => 2.0],
10 => ['fps' => 12.0],
])
);
self::assertSame([], $watch->run(self::NOW));
}
public function testErroringCameraIsDegradedEvenAtFullFps(): void
{
$events = new InMemoryEventRepository();
$watch = new DeviceHealthWatch(
$events,
$this->devices([$this->device('pi-01', self::NOW - 10)]),
$this->metrics('pi-01', [
800 => ['fps' => 12.0, 'cameras_total' => 2, 'cameras_erroring' => 0],
600 => ['fps' => 12.0, 'cameras_total' => 2, 'cameras_erroring' => 1],
10 => ['fps' => 12.0, 'cameras_total' => 2, 'cameras_erroring' => 1],
])
);
$filed = $watch->run(self::NOW);
self::assertCount(1, $filed);
$row = $events->find($filed[0]['event_id']);
self::assertSame(['cameras_erroring'], $row['metrics']['reasons']);
self::assertSame(1, $row['metrics']['cameras_erroring']);
}
public function testThermalThrottleCountsAsDegraded(): void
{
$events = new InMemoryEventRepository();
$watch = new DeviceHealthWatch(
$events,
$this->devices([$this->device('pi-01', self::NOW - 10)]),
$this->metrics('pi-01', [
800 => ['fps' => 12.0, 'throttle' => 0],
600 => ['fps' => 12.0, 'throttle' => 1],
10 => ['fps' => 12.0, 'throttle' => 1],
])
);
$filed = $watch->run(self::NOW);
self::assertCount(1, $filed);
self::assertSame(['thermal_throttle'],
$events->find($filed[0]['event_id'])['metrics']['reasons']);
}
public function testOngoingDegradationFilesOncePerRunNotPerTick(): void
{
$events = new InMemoryEventRepository();
$watch = new DeviceHealthWatch(
$events,
$this->devices([$this->device('pi-01', self::NOW - 10)]),
$this->metrics('pi-01', [
800 => ['fps' => 12.0],
600 => ['fps' => 3.0],
10 => ['fps' => 3.0],
])
);
self::assertCount(1, $watch->run(self::NOW));
self::assertSame([], $watch->run(self::NOW + 60));
self::assertSame([], $watch->run(self::NOW + 120));
}
public function testMissingFpsIsNotTreatedAsZero(): void
{
// A node that cannot read a metric reports NULL. Coercing that to 0 would invent an
// outage out of a missing reading.
$events = new InMemoryEventRepository();
$watch = new DeviceHealthWatch(
$events,
$this->devices([$this->device('pi-01', self::NOW - 10)]),
$this->metrics('pi-01', [
600 => ['fps' => null, 'cameras_erroring' => 0],
10 => ['fps' => null, 'cameras_erroring' => 0],
])
);
self::assertSame([], $watch->run(self::NOW));
}
public function testNoHeartbeatSeriesFilesNothingWhileDeviceIsFresh(): void
{
// Fresh heartbeat but no metric rows yet (just installed): nothing to judge.
$events = new InMemoryEventRepository();
$watch = new DeviceHealthWatch(
$events,
$this->devices([$this->device('pi-01', self::NOW - 5)]),
new InMemoryDeviceMetricRepository()
);
self::assertSame([], $watch->run(self::NOW));
}
public function testEachDeviceIsJudgedIndependently(): void
{
$events = new InMemoryEventRepository();
$metrics = new InMemoryDeviceMetricRepository();
$metrics->append('pi-ok', ['fps' => 12.0], self::NOW - 10);
$metrics->append('pi-slow', ['fps' => 12.0], self::NOW - 800);
$metrics->append('pi-slow', ['fps' => 2.0], self::NOW - 600);
$metrics->append('pi-slow', ['fps' => 2.0], self::NOW - 10);
$watch = new DeviceHealthWatch($events, $this->devices([
$this->device('pi-ok', self::NOW - 10),
$this->device('pi-slow', self::NOW - 10),
$this->device('pi-dead', self::NOW - 3600),
]), $metrics);
$filed = $watch->run(self::NOW);
$byDevice = [];
foreach ($filed as $f) $byDevice[$f['device_id']] = $f['event_type'];
self::assertSame(['pi-slow' => 'monitoring_degraded', 'pi-dead' => 'device_fault'], $byDevice);
}
public function testUuidIsStableAndDistinctPerKindAndDevice(): void
{
$a = DeviceHealthWatch::uuidFor('device_fault', 'pi-01', 100);
self::assertSame($a, DeviceHealthWatch::uuidFor('device_fault', 'pi-01', 100));
self::assertSame(32, strlen($a));
self::assertNotSame($a, DeviceHealthWatch::uuidFor('monitoring_degraded', 'pi-01', 100));
self::assertNotSame($a, DeviceHealthWatch::uuidFor('device_fault', 'pi-02', 100));
self::assertNotSame($a, DeviceHealthWatch::uuidFor('device_fault', 'pi-01', 101));
}
}