move_detect/server/tests/MultiDownWatchTest.php
유창욱 4bfb7e0274
Some checks are pending
verify / edge (push) Waiting to run
verify / server (push) Waiting to run
feat: 추락 · 동시 다발 쓰러짐 · 구역 프리셋 (1.2.0)
AI CCTV 목적을 원론부터 재점검한 결과. 셋 다 새 추론 모델 없이 지금 있는
자세추정·구역·트랙 이력만으로 구현했다.

■ 추락 (fall_from_height)

잡고 있던 것은 같은 높이의 '넘어짐'이었고, 사망 1위 유형인 '떨어짐'은 못
잡았다. GhostIncidentDetector 가 트랙이 이미 위험 자세일 때만 무장하므로
(_DANGEROUS), 발판에 서 있다가 떨어지는 사람은 소실 순간 STANDING 이라
아무것도 안 걸렸다.

판정의 핵심은 bbox 중심이 아니라 하단(y2)이다. 쭈그려 앉으면 중심은
내려가도 발은 그 자리이고, 추락은 발 밑선이 통째로 내려간다 — 중심으로
재면 쭈그려 앉아 작업하는 사람이 전부 추락이 된다. 원근 접근은 y2 도
내려가므로 높이 증가 가드로 따로 막는다. Track.frames 가 90프레임을 들고
있어 별도 버퍼가 없다.

발보는 두 갈래로 나뉘되 한 사고는 한 건이다: 프레임 안에서 넘어짐이
확정되면 유형을 승격하고, 화각 밖으로 사라지면 ghost 무장을 넓혀 그쪽으로
낸다. 심각도 CRITICAL — 척추·두부 손상 주의가 통보에 실리려면 넘어짐(HIGH)과
등급이 갈라져야 한다. 고소 구역은 rules_json 의 elevated 키로 붙어 스키마
변경이 없고, 구역이 없어도 하강 신호만으로 동작한다.

■ 동시 다발 쓰러짐 (multi_down)

같은 구역에서 짧은 시간에 둘이 쓰러진 것은 넘어짐 두 건이 아니라 질식·
가스·폭발이다. 이 기능의 본체는 감지가 아니라 통보 문구다 — 밀폐공간
사망자의 상당수가 구조하러 들어간 사람이므로, 링크를 열기 전에 메일 본문에서
"공기호흡기 없이 진입하지 마십시오"가 읽혀야 한다. Channels::guidance 로
유형별 안내를 붙였고 문구를 테스트로 고정했다(문구가 사라지면 기능이 사라진
것과 같다).

서버에 둔 이유: 가스는 카메라 화각을 존중하지 않아 노드를 넘는 판단이
필요하고, 현장 즉시 대응은 첫 쓰러짐의 경광등이 이미 확보한다. 오탐 방어의
핵심은 근접성 — 넓은 공장에서 2분 안의 무관한 넘어짐 두 건은 실제로
일어나므로 같은 구역이거나 좌표가 가까워야 묶는다. 한 사람이 두 번 넘어진
것은 한 명으로 센다.

■ 구역 프리셋 6종 + max_workers:0 수정

밀폐공간 감시에 필요한 것(제한구역+2인1조+체류상한)은 이미 전부 있었는데
화면이 "최소 인원을 넣으세요"라고만 물어 아무도 그렇게 쓰지 못했다.
안전관리자는 min_workers 가 아니라 밀폐공간을 생각한다.

그 과정에서 잠복 결함 하나: max_workers:0 이 falsy 로 걸러져 "아무도 있으면
안 되는 구역"(크레인 짐 아래·굴착기 선회 반경 = 깔림 사고의 전형)이 통째로
꺼져 있었다. 운영자가 저장해 놓고도 아무 일이 안 일어났다. 감지기·입력란
(min=1)·저장 직렬화(>0)·목록 표시 네 곳에서 막혀 있었다.

■ 검증

pytest 322 passed / phpunit 263 passed. 신규 테스트 30건.
이벤트 유형 2종 추가는 test_event_type_parity 가 강제하는 5곳(엣지 enum ·
EventValidator · schema CHECK · 프런트 라벨 5파일 · 필터 옵션) 전부 동기화했고
기존 설치용 마이그레이션을 추가했다.

■ Pi 번들

1.1.0 과 달리 이번에는 edge/ 가 바뀌었으므로 Pi 번들 재빌드가 필수다.
낡은 1.0.0 번들은 dist/ 에서 제거했다 — 두면 추락 감지가 빠진 노드가 그대로
납품된다. arm64 + 네트워크 빌드 머신에서 재빌드해야 Pi 납품이 가능하다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EBjuR7DW6PNNMows4KnbYU
2026-09-05 12:21:50 +09:00

138 lines
5.9 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Tests;
use App\Alert\MultiDownWatch;
use App\Tests\Support\InMemoryEventRepository;
use PHPUnit\Framework\TestCase;
/**
* 같은 자리에서 짧은 시간에 둘이 쓰러지면 그것은 넘어짐 두 건이 아니라 질식·가스·폭발이다.
*
* 이 테스트가 지키는 두 가지: (1) 진짜 무리를 놓치지 않는다, (2) 무관한 넘어짐을 묶지 않는다.
* 넓은 공장에서 2분 안의 무관한 넘어짐 두 건은 실제로 일어나므로 (2)가 (1)만큼 중요하다.
*/
final class MultiDownWatchTest extends TestCase
{
private const NOW = 1_700_000_000;
private function ev(InMemoryEventRepository $repo, array $over = []): int
{
return $repo->insert($over + [
'event_uuid' => bin2hex(random_bytes(16)),
'device_id' => 'pi-01', 'site' => 'site-a', 'camera_id' => 'cam-01',
'event_type' => 'fall', 'severity' => 'high', 'track_id' => 1,
'zone_id' => null, 'occurred_at' => (float)(self::NOW - 60),
'duration_s' => 0.0, 'metrics' => [],
'spatial_x' => 0.50, 'spatial_y' => 0.50,
]);
}
public function testTwoPeopleDownInTheSameSpotFilesOneCriticalEvent(): void
{
$repo = new InMemoryEventRepository();
$this->ev($repo, ['track_id' => 1, 'spatial_x' => 0.50, 'spatial_y' => 0.50]);
$this->ev($repo, ['track_id' => 2, 'spatial_x' => 0.55, 'spatial_y' => 0.52,
'occurred_at' => (float)(self::NOW - 30)]);
$filed = (new MultiDownWatch($repo))->run(self::NOW);
self::assertCount(1, $filed);
self::assertSame(2, $filed[0]['people']);
$row = $repo->find($filed[0]['event_id']);
self::assertSame('multi_down', $row['event_type']);
self::assertSame('critical', $row['severity']);
self::assertCount(2, $row['metrics']['origin_event_ids']);
}
public function testOnePersonFallingTwiceIsNotAGroup(): void
{
// 넘어졌다 회복했다 다시 넘어진 것은 한 명이다.
$repo = new InMemoryEventRepository();
$this->ev($repo, ['track_id' => 7]);
$this->ev($repo, ['track_id' => 7, 'occurred_at' => (float)(self::NOW - 20)]);
self::assertSame([], (new MultiDownWatch($repo))->run(self::NOW));
}
public function testFarApartFallsAreNotAGroup(): void
{
// 같은 카메라라도 화면 반대편은 다른 사건이다.
$repo = new InMemoryEventRepository();
$this->ev($repo, ['track_id' => 1, 'spatial_x' => 0.05, 'spatial_y' => 0.05]);
$this->ev($repo, ['track_id' => 2, 'spatial_x' => 0.95, 'spatial_y' => 0.95,
'occurred_at' => (float)(self::NOW - 30)]);
self::assertSame([], (new MultiDownWatch($repo))->run(self::NOW, ['radius' => 0.35]));
}
public function testFallsOutsideTheWindowAreNotAGroup(): void
{
$repo = new InMemoryEventRepository();
$this->ev($repo, ['track_id' => 1, 'occurred_at' => (float)(self::NOW - 1000)]);
$this->ev($repo, ['track_id' => 2, 'occurred_at' => (float)(self::NOW - 10)]);
self::assertSame([], (new MultiDownWatch($repo))->run(self::NOW, ['window_s' => 120]));
}
public function testSameZoneGroupsEvenWithoutSpatialProximity(): void
{
// 운영자가 "여기가 한 공간"이라고 선언한 것이 좌표 거리보다 정확하다.
$repo = new InMemoryEventRepository();
$this->ev($repo, ['track_id' => 1, 'zone_id' => 'z-tank', 'spatial_x' => 0.05, 'spatial_y' => 0.05]);
$this->ev($repo, ['track_id' => 2, 'zone_id' => 'z-tank', 'spatial_x' => 0.95, 'spatial_y' => 0.95,
'occurred_at' => (float)(self::NOW - 20)]);
$filed = (new MultiDownWatch($repo))->run(self::NOW);
self::assertCount(1, $filed);
self::assertSame('zone:z-tank', $filed[0]['scope']);
}
public function testRepeatedRunsDoNotDuplicate(): void
{
$repo = new InMemoryEventRepository();
$this->ev($repo, ['track_id' => 1]);
$this->ev($repo, ['track_id' => 2, 'occurred_at' => (float)(self::NOW - 30)]);
$w = new MultiDownWatch($repo);
self::assertCount(1, $w->run(self::NOW));
self::assertSame([], $w->run(self::NOW + 60));
self::assertSame([], $w->run(self::NOW + 90));
}
public function testAThirdPersonRaisesItAgain(): void
{
// 사람이 늘어난 것은 상황이 악화된 것이다 — 한 번 더 올라와야 한다.
$repo = new InMemoryEventRepository();
$this->ev($repo, ['track_id' => 1]);
$this->ev($repo, ['track_id' => 2, 'occurred_at' => (float)(self::NOW - 30)]);
$w = new MultiDownWatch($repo);
self::assertCount(1, $w->run(self::NOW));
$this->ev($repo, ['track_id' => 3, 'occurred_at' => (float)(self::NOW - 10)]);
$again = $w->run(self::NOW + 5);
self::assertCount(1, $again);
self::assertSame(3, $again[0]['people']);
}
public function testNonDownTypesAreIgnored(): void
{
// 니어미스·자세부담은 사람이 쓰러진 것이 아니다.
$repo = new InMemoryEventRepository();
$this->ev($repo, ['track_id' => 1, 'event_type' => 'near_fall']);
$this->ev($repo, ['track_id' => 2, 'event_type' => 'ergo_report',
'occurred_at' => (float)(self::NOW - 30)]);
self::assertSame([], (new MultiDownWatch($repo))->run(self::NOW));
}
public function testFallFromHeightCountsAsDown(): void
{
$repo = new InMemoryEventRepository();
$this->ev($repo, ['track_id' => 1, 'event_type' => 'fall_from_height']);
$this->ev($repo, ['track_id' => 2, 'event_type' => 'no_motion',
'occurred_at' => (float)(self::NOW - 30)]);
self::assertCount(1, (new MultiDownWatch($repo))->run(self::NOW));
}
}