feat(robust): graceful degradation - player-lost hold, heartbeat stall-detect, crash handling (wave 8b; todo 17 done)
ci / Linux C++ core (cmake + ctest) (push) Canceled after 0s
ci / Python root tests (pytest, no tracker deps) (push) Canceled after 0s
ci / Python tracker (pytest, tracker/.venv) (push) Canceled after 0s

This commit is contained in:
kinect-bot committed 2026-11-25 05:56:51 -05:00
1 parent 30f550e489
commit 3eb8c07e4c
4 files changed
+376 -6

No files matched your search

+1 -1
View File
@@ -280,7 +280,7 @@ Your next move: run the default-on high-accuracy review (in progress), then exec
Commit: Y | feat(tools): record/replay harness + mock nui host
Recommended task executor category: unspecified-high - test infrastructure across both deliverables.
- [ ] 17. Robustness / graceful degradation
- [x] 17. Robustness / graceful degradation
What to do / Must NOT do: Harden the tracker+synth path for IS-8: player leaves frame (publish player-lost, hold last good briefly, recover), poor lighting / low-visibility joints (mark INFERRED, hold), mask fragmentation/flicker (largest-component + temporal hold already in 7 - verify under stress), tracker process crash (emitter keeps serving last frame or a safe no-player frame; heartbeat-driven). Must NOT: add fixed-delay reconnection - use event/heartbeat-driven recovery; no silent exception swallowing.
Closes: IS-8
Parallelization: Wave 8 | Blocked by: 5,7,10 | Blocks: 18
+237
View File
@@ -0,0 +1,237 @@
"""Fault-injection tests for IS-8 graceful degradation (plan todo 17).
Exercises the tracker publish loop against four fault classes, each required
to produce the specified safe behavior without crashing the host app and
without any fixed-delay reconnection or silently-swallowed exception:
* subject-exits-then-returns: the tracker holds the last tracked pose
briefly, then recovers immediately once the subject reappears.
* all-low-visibility frame: joints are marked INFERRED/NOT_TRACKED (never
snapped to the origin) without raising.
* fragmented/speckled mask: still produces a usable, non-crashing publish
(the single-stable-blob guarantee itself is proven at the C++ level in
tests/test_synth.cpp, since core/synth is where the morphological
close + largest-component + temporal hold actually run).
* tracker-stall/crash: the consumer sees a safe no-player frame (driven by
the inference worker's update heartbeat), not a frozen stale frame or a
crash, and the failure is logged rather than swallowed.
"""
from __future__ import annotations
import ctypes
import os
import sys
import time
import numpy as np
import pytest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
from tracker import contract as c # noqa: E402
from tracker.fake_pose import FakeFrameSource, make_fake_pose # noqa: E402
from tracker.publisher import FrameContractPublisher # noqa: E402
from tracker.tracker import Tracker # noqa: E402
class ScriptedPoseProvider:
"""Replays a fixed sequence of (pose | None) results, one per `process`
call, so a test can precisely script "subject present/absent/present"
without relying on timing. Raises `RuntimeError` for a scripted `"crash"`
entry (fault injection for the tracker-crash case)."""
def __init__(self, script: list) -> None:
self.script = script
self.calls = 0
def process(self, frame_bgr, timestamp_ms=None):
step = self.script[min(self.calls, len(self.script) - 1)]
self.calls += 1
if step == "crash":
raise RuntimeError("injected pose-inference crash")
return step
@pytest.fixture
def publisher():
pub = FrameContractPublisher(depth_size=(80, 60), color_size=(80, 60))
try:
yield pub
finally:
pub.close()
def _tracked_joint_count(frame) -> int:
return sum(
1
for j in range(c.JOINT_COUNT)
if frame.skeleton.joints[j].tracking_state == c.JointTrackingState.TRACKED
)
def test_subject_exits_then_returns_holds_then_recovers(publisher):
"""Subject present -> exits (several frames, within the hold window) ->
returns. The tracker must hold the last-good pose through the exit (no
instant flap to no-body) and recover immediately (the very next tick)
once the subject reappears.
Drives `Tracker._resolve_publish_frame` directly (one simulated worker
update per call) instead of racing the real background thread: the
threaded path (`FakeFrameSource` + `ScriptedPoseProvider` with no
injected delay) runs the whole script faster than a single publish tick,
so it cannot observe the intermediate hold state - only this deterministic
drive can. The thread-crash and thread-stall paths are exercised for
real in `test_tracker_crash_yields_safe_no_player_not_garbage` below.
"""
present = make_fake_pose(frame_index=0, image_width=80, image_height=60)
returned = make_fake_pose(frame_index=5, image_width=80, image_height=60)
source = FakeFrameSource(n_frames=1, width=80, height=60)
provider = ScriptedPoseProvider([present])
tracker = Tracker(source, provider, publisher, target_fps=200.0, player_lost_hold_frames=2)
try:
for _ in range(3):
tracker._latest_pose = present
tracker._update_count += 1
pose, _ = tracker._resolve_publish_frame()
assert pose is present
for _ in range(2): # within the 2-frame hold window
tracker._latest_pose = None
tracker._update_count += 1
pose, _ = tracker._resolve_publish_frame()
assert pose is present, "a brief exit within the hold window must keep serving the held pose"
tracker._latest_pose = None # hold exhausted
tracker._update_count += 1
pose, _ = tracker._resolve_publish_frame()
assert pose is None
tracker._latest_pose = returned # subject reappears
tracker._update_count += 1
pose, frame = tracker._resolve_publish_frame()
assert pose is returned, "recovery on return must be immediate, not delayed"
publisher.publish(pose, frame)
published_frame = publisher.read_latest_frame()
assert published_frame.skeleton.skeleton_tracking_id != 0
assert _tracked_joint_count(published_frame) > 0
finally:
source.release()
def test_player_lost_hold_eventually_falls_through_to_no_body(publisher):
"""If the subject stays gone longer than the hold window, the tracker must
fall through to a genuine no-body frame (never hold forever)."""
present = make_fake_pose(frame_index=0, image_width=80, image_height=60)
script = [present] + [None] * 40
source = FakeFrameSource(n_frames=len(script), width=80, height=60)
provider = ScriptedPoseProvider(script)
tracker = Tracker(source, provider, publisher, target_fps=200.0, player_lost_hold_frames=3)
try:
tracker.run(max_frames=len(script) + 5, max_seconds=5.0)
frame = publisher.read_latest_frame()
assert frame.skeleton.skeleton_tracking_id == 0
for j in range(c.JOINT_COUNT):
joint = frame.skeleton.joints[j]
assert joint.tracking_state == c.JointTrackingState.NOT_TRACKED
finally:
source.release()
def test_all_low_visibility_frame_marks_inferred_not_crash_no_origin_snap(publisher):
"""Poor lighting / low-visibility joints: every joint's visibility is near
zero. Must not crash, and no joint position is left at the hard-coded
(0,0,0) sentinel used only for the explicit no-body frame - a low- but
nonzero-visibility pose still carries a real placed position."""
pose = make_fake_pose(image_width=80, image_height=60, visibility=0.2)
# Must not raise.
publisher.publish(pose, None)
frame = publisher.read_latest_frame()
assert frame is not None
for j in range(c.JOINT_COUNT):
joint = frame.skeleton.joints[j]
assert joint.tracking_state in (
c.JointTrackingState.INFERRED,
c.JointTrackingState.NOT_TRACKED,
)
assert joint.tracking_state != c.JointTrackingState.TRACKED
if joint.tracking_state == c.JointTrackingState.INFERRED:
# Held/placed position, not the no-body origin sentinel.
assert not (joint.position.x == 0.0 and joint.position.y == 0.0 and joint.position.z == 0.0)
def test_fragmented_speckled_mask_publishes_without_crash(publisher):
"""A fragmented/speckled segmentation mask (the per-frame raw MediaPipe
output before core/synth's largest-component+morph-close+temporal-hold
cleanup runs downstream) must still publish a valid frame rather than
raising. The single-stable-blob guarantee itself is proven at the C++
layer (tests/test_synth.cpp StabilizerSurvivesHeavySpeckleNoiseAndMultiFrameFlicker)."""
pose = make_fake_pose(image_width=80, image_height=60)
rng = np.random.default_rng(1234)
speckle = rng.random((60, 80)).astype(np.float32) > 0.5
pose.mask = np.logical_or(pose.mask > 0.5, speckle).astype(np.float32)
publisher.publish(pose, None) # must not raise
frame = publisher.read_latest_frame()
assert frame is not None
depth = publisher.read_depth(publisher.latest_slot_index())
assert np.count_nonzero(depth) > 0 # some body pixels were written
assert int(depth.max()) > 0
assert int(depth[0, 0]) <= depth.max() # sanity: depth buffer is well-formed
def test_tracker_crash_yields_safe_no_player_not_garbage(publisher):
"""The inference worker crashes (unhandled exception in pose inference).
The publish loop must not propagate/crash and the consumer must see a
safe no-player frame, not whatever stale data was cached - and the
failure must be observable (not silently swallowed): the crash flag is
set and the published frame reflects the degraded state."""
present = make_fake_pose(frame_index=0, image_width=80, image_height=60)
script = [present, present, "crash"]
source = FakeFrameSource(n_frames=100, width=80, height=60) # outlives the crash
provider = ScriptedPoseProvider(script)
tracker = Tracker(source, provider, publisher, target_fps=200.0)
try:
published = tracker.run(max_frames=60, max_seconds=3.0)
assert published > 0
# The worker is observably dead (not silently stuck "running").
assert tracker._worker_crashed.is_set()
frame = publisher.read_latest_frame()
assert frame.skeleton.skeleton_tracking_id == 0
for j in range(c.JOINT_COUNT):
assert frame.skeleton.joints[j].tracking_state == c.JointTrackingState.NOT_TRACKED
finally:
source.release()
def test_tracker_stall_yields_safe_no_player_after_heartbeat_timeout(publisher):
"""The inference worker hangs (stops producing updates, e.g. a stuck
MediaPipe call) without crashing. Once the liveness window derived from
the configured cadence elapses without a new worker heartbeat, the
publish loop must stop serving the frozen last-good pose and switch to a
safe no-player frame - driven by the worker's own update heartbeat, not a
fixed reconnect delay. The elapsed real time is the exact liveness window
under test here, so sleeping past it (not a generic pacing sleep) is the
correct way to exercise it."""
present = make_fake_pose(frame_index=0, image_width=80, image_height=60)
source = FakeFrameSource(n_frames=1, width=80, height=60)
provider = ScriptedPoseProvider([present])
tracker = Tracker(source, provider, publisher, target_fps=100.0)
try:
tracker._latest_pose = present
tracker._update_count = 1
pose, _ = tracker._resolve_publish_frame()
assert pose is present
time.sleep(tracker._stall_timeout + 0.05)
# update_count unchanged since the last tick: the worker produced no
# new heartbeat for longer than the liveness window => stalled.
pose, _ = tracker._resolve_publish_frame()
assert pose is None, "a stalled worker must not keep serving the frozen last-good pose forever"
finally:
source.release()
+66
View File
@@ -13,7 +13,9 @@ namespace {
using nui::contract::SkeletonFrame;
using nui::synth::BinaryMask;
using nui::synth::has_body;
using nui::synth::ImageSize;
using nui::synth::MaskStabilizer;
using nui::synth::SegmentationMask;
SkeletonFrame fixture_pose(ImageSize size) {
@@ -146,6 +148,70 @@ TEST(synth, CleanupKeepsOneBlobAndTemporallyHoldsIt) {
EXPECT_NE(held.pixels[static_cast<std::size_t>(6) * size.width + 7], 0);
}
TEST(synth, StabilizerSurvivesHeavySpeckleNoiseAndMultiFrameFlicker) {
// Stress case for IS-8 (mask fragmentation/flicker under harsher conditions
// than CleanupKeepsOneBlobAndTemporallyHoldsIt): a body silhouette peppered
// with scattered single-pixel salt noise (its own tiny components, must not
// merge into / enlarge the body's largest component) plus internal pepper
// holes (must be closed), followed by TWO consecutive fully-empty frames
// within the temporal hold window (must still hold the last stable blob),
// then a hold-exhausting gap (must correctly fall through to background).
const ImageSize size{20, 16};
const std::size_t total = static_cast<std::size_t>(size.width) * size.height;
SegmentationMask speckled{size, std::vector<float>(total, 0.0f)};
for (uint32_t y = 2; y < 14; ++y) {
for (uint32_t x = 3; x < 17; ++x) {
speckled.confidence[static_cast<std::size_t>(y) * size.width + x] = 1.0f;
}
}
// Pepper: punch isolated holes inside the body.
const std::array<std::pair<uint32_t, uint32_t>, 4> holes{{
{5, 4}, {9, 7}, {12, 10}, {15, 12}}};
for (const auto& [hx, hy] : holes) {
speckled.confidence[static_cast<std::size_t>(hy) * size.width + hx] = 0.0f;
}
// Salt: scattered single-pixel noise well outside the body, each isolated
// (no two salt pixels touching, so each forms its own tiny component).
const std::array<std::pair<uint32_t, uint32_t>, 6> salt{{
{0, 0}, {19, 0}, {0, 15}, {19, 15}, {1, 15}, {18, 0}}};
for (const auto& [sx, sy] : salt) {
speckled.confidence[static_cast<std::size_t>(sy) * size.width + sx] = 1.0f;
}
MaskStabilizer stabilizer(/*temporal_hold_frames=*/2);
const BinaryMask cleaned = stabilizer.update(speckled, size);
// The pepper holes are filled (morphological close) and the body stays one
// component; the salt noise is discarded because largest-component keeps
// only the (much larger) body blob.
EXPECT_EQ(count_components(cleaned), 1u);
for (const auto& [hx, hy] : holes) {
EXPECT_NE(cleaned.pixels[static_cast<std::size_t>(hy) * size.width + hx], 0)
<< "pepper hole at (" << hx << "," << hy << ") should be closed";
}
for (const auto& [sx, sy] : salt) {
EXPECT_EQ(cleaned.pixels[static_cast<std::size_t>(sy) * size.width + sx], 0)
<< "salt speckle at (" << sx << "," << sy << ") should not survive largest-component";
}
ASSERT_TRUE(has_body(cleaned));
const SegmentationMask empty{size, std::vector<float>(total, 0.0f)};
const BinaryMask held_frame1 = stabilizer.update(empty, size);
const BinaryMask held_frame2 = stabilizer.update(empty, size);
const BinaryMask fallen_through = stabilizer.update(empty, size);
// Two consecutive empty frames stay within the 2-frame hold: the stable
// blob keeps being served, not a flicker to background.
EXPECT_TRUE(has_body(held_frame1));
EXPECT_EQ(held_frame1.pixels, cleaned.pixels);
EXPECT_TRUE(has_body(held_frame2));
EXPECT_EQ(held_frame2.pixels, cleaned.pixels);
// The third consecutive empty frame exhausts the hold: falls through to a
// safe, empty (no-player) background rather than holding forever.
EXPECT_FALSE(has_body(fallen_through));
}
TEST(synth, BackgroundRemainsZeroAndColorAndInfraredResize) {
// The depth body sits two pixels in from every edge so morphological
// closing's zero-padded boundary cannot erode it away; the corner pixel
+72 -5
View File
@@ -18,6 +18,7 @@ pipeline (`FakePoseProvider` + `FakeFrameSource`) share this loop through the
from __future__ import annotations
import argparse
import logging
import threading
import time
from typing import Optional, Protocol
@@ -26,6 +27,8 @@ from .control import ControlPlaneServer
from .pose import PoseProvider, PoseResult
from .publisher import FrameContractPublisher
logger = logging.getLogger(__name__)
class FrameSource(Protocol):
def read(self): ...
@@ -58,12 +61,23 @@ class Tracker:
publisher: FrameContractPublisher,
control: Optional[ControlPlaneServer] = None,
target_fps: float = 30.0,
player_lost_hold_frames: int = 15,
) -> None:
self.source = source
self.provider = provider
self.publisher = publisher
self.control = control
self.target_fps = target_fps
# IS-8: when the subject leaves frame (provider yields no pose), hold the
# last tracked pose for a short number of publish ticks before falling
# through to a no-body frame, so a brief occlusion/exit doesn't flap the
# player-lost state. Recovery on return is immediate (first fresh pose
# wins), never delayed.
self.player_lost_hold_frames = player_lost_hold_frames
# Liveness bound derived from the configured cadence (not a sleep/
# delay): if the worker's heartbeat (_update_count) hasn't moved for
# this long, it is stalled, independent of whether it later recovers.
self._stall_timeout = max(5.0 / target_fps, 0.25)
self._lock = threading.Lock()
self._latest_pose: Optional[PoseResult] = None
@@ -71,19 +85,74 @@ class Tracker:
self._stop = threading.Event()
self._source_done = threading.Event()
self._worker: Optional[threading.Thread] = None
# Heartbeat from the inference worker: bumped on every completed read+
# infer cycle (whether or not a pose was found), so the publish loop can
# tell "no person in frame" (update_count keeps moving, pose is None)
# apart from "the worker stalled/crashed" (update_count stops moving).
self._update_count = 0
self._worker_crashed = threading.Event()
self._hold_pose: Optional[PoseResult] = None
self._hold_remaining = 0
self._last_update_count = -1
self._last_update_time = time.monotonic()
def _inference_worker(self) -> None:
t0 = time.monotonic()
while not self._stop.is_set():
frame = self.source.read()
try:
frame = self.source.read()
except Exception:
logger.exception("frame source read failed; marking worker crashed")
self._worker_crashed.set()
return
if frame is None:
self._source_done.set()
return
ts_ms = int((time.monotonic() - t0) * 1000)
pose = self.provider.process(frame, timestamp_ms=ts_ms)
try:
pose = self.provider.process(frame, timestamp_ms=ts_ms)
except Exception:
logger.exception("pose inference failed; marking worker crashed")
self._worker_crashed.set()
return
with self._lock:
self._latest_frame = frame
self._latest_pose = pose
self._update_count += 1
def _resolve_publish_frame(self):
"""One publish tick's fault-handling decision (IS-8): the fresh pose,
a briefly held last-good pose across a player-exit, or a safe
no-player state once the hold expires or the worker is stalled/
crashed. Pure state transition over `self`'s latched fields, so tests
can drive it deterministically without racing the inference thread.
"""
with self._lock:
pose = self._latest_pose
frame = self._latest_frame
update_count = self._update_count
now = time.monotonic()
if update_count != self._last_update_count:
self._last_update_count = update_count
self._last_update_time = now
worker_stalled = (
self._worker_crashed.is_set() or (now - self._last_update_time) > self._stall_timeout
)
if worker_stalled:
# Crashed or stalled tracker: never keep serving a frozen stale
# frame - the consumer must see a safe no-player state instead.
pose = None
self._hold_pose = None
self._hold_remaining = 0
elif pose is not None:
self._hold_pose = pose
self._hold_remaining = self.player_lost_hold_frames
elif self._hold_remaining > 0:
pose = self._hold_pose
self._hold_remaining -= 1
return pose, frame
def run(self, max_frames: Optional[int] = None, max_seconds: Optional[float] = None) -> int:
self._worker = threading.Thread(target=self._inference_worker, name="inference", daemon=True)
@@ -99,9 +168,7 @@ class Tracker:
self._stop.wait(deadline - now)
if self._stop.is_set():
break
with self._lock:
pose = self._latest_pose
frame = self._latest_frame
pose, frame = self._resolve_publish_frame()
seq = self.publisher.publish(pose, frame)
if self.control is not None:
self.control.send_heartbeat(seq)