Files
kinect/tests/test_robustness.py
T
kinect-bot b4397e6151
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
fix(qa): conftest root-venv ignore + calibration doc honesty + deterministic player-lost test (final-wave 22/23/24; F1-F4 pass, F5 [~])
2026-11-25 06:25:25 -05:00

265 lines
12 KiB
Python

"""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).
Drives `Tracker._resolve_publish_frame` directly (the same deterministic
seam `test_subject_exits_then_returns_holds_then_recovers` above uses)
instead of racing `tracker.run()`'s background inference thread against
its own wall-clock-paced publish loop: in that threaded form, whether the
hold has finished counting down to a no-body frame by the time the loop's
tick/time budget runs out depends on how far the background thread got
scheduling real time, which is exactly the timing-luck race test
discipline forbids. Advancing the hold counter by an exact tick count
removes the race.
"""
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])
hold_frames = 3
tracker = Tracker(source, provider, publisher, target_fps=200.0, player_lost_hold_frames=hold_frames)
try:
tracker._latest_pose = present
tracker._update_count += 1
pose, _ = tracker._resolve_publish_frame()
assert pose is present
for _ in range(hold_frames): # still within the hold window
tracker._latest_pose = None
tracker._update_count += 1
pose, _ = tracker._resolve_publish_frame()
assert pose is present, "must keep holding while the hold window has not elapsed"
tracker._latest_pose = None # one tick past the hold window: must fall through
tracker._update_count += 1
pose, frame = tracker._resolve_publish_frame()
assert pose is None, "hold window exceeded must fall through to no-body, never hold forever"
publisher.publish(pose, frame)
published_frame = publisher.read_latest_frame()
assert published_frame.skeleton.skeleton_tracking_id == 0
for j in range(c.JOINT_COUNT):
joint = published_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()