Skip to content

07 — Mapping — Subsystem Test Map

The mapping subsystem turns map images into room data: an image-segmentation stack (segment_primitives, segmenter_engines), a room tracker (tracker) that fires room_completed off the device's native current-room, and the service orchestrator (mapping_services). A second authoring path lets a human draw rooms directly: segment_primitives rasterises composer shapes into polygons, and mapping_services holds many named custom layouts per map alongside the CV store, selected by a segmentation_mode pointer flip.

Covered by 651 tests across 19 files (regenerated by scripts/update_test_docs.py). A third path skips authoring entirely: the map_state_source reader (map_source, map_source_runtime, map_source_coordinator) normalizes the provider's OWN segmentation + live pose into VA-owned room data (bbox/name, dock/robot anchors, area, current room, overlay layers), so rooms are auto-derived from the device's authoritative map rather than learned from drifting samples or hand-drawn. The image primitives are near-fully covered; the tracker and the service orchestrator have both their pure helpers (unit) and hass-bound bodies (integration) covered; and the real detect_room_segments CV pipeline runs end to end against a synthetic image.

Mapping split. The run-derived inference lineage — the trace_capture → trace_store → trace_segmentation → trace_review pipeline, room-boundary derivation, and image-segment suggestion — was retired, and MappingManager and the learned bounding-box store room_bounds.py (RoomBoundsStore) were removed; room tracking now reads the device's native current-room. The module table below is re-stamped by scripts/update_test_docs.py and is current; the hand-written Known gaps breakdown further down is not re-stamped by that tool and has fallen behind — see the note there.

Source: custom_components/eufy_vacuum/mapping/ Architecture reference: 11 — A Map’s Stored State through 15 — The Stall Capture Image


Coverage map

Source module Stmts Cov Test file Layer Mocking
boundary.py 15 100% tests/unit/test_mapping_boundary.py + via zone_membership in tests/integration/test_mapping_services.py (only point_in_polygon survives) unit + integration (pure geometry) clean
segment_primitives.py 277 96% tests/unit/test_mapping_segment_primitives.py unit (pure + numpy/scipy) clean
segmenter_engines.py 137 100% tests/unit/test_mapping_segmenter_engines.py unit (pure) clean
tracker.py 247 97% test_mapping_tracker.py + test_mapping_tracker_events.py unit + integration bare x2 in 2 files
mapping_services.py 1347 95% test_mapping_services_helpers.py + test_mapping_services.py + test_mapping_services_handlers.py unit + integration clean
map_source.py 434 95% tests/unit/test_map_source.py unit (pure) clean
map_source_runtime.py 972 95% tests/unit/test_map_source_runtime.py + tests/unit/test_map_source_collectors.py + tests/unit/test_dreame_mapdata_decode.py unit (pure) clean
map_source_coordinator.py 350 97% test_manager_compare_sources.py + test_manager_live_pose.py + test_manager_map_source_refresh.py + tests/unit/test_live_pose_backends.py integration + unit clean
roborock_raw_map.py 145 98% tests/unit/test_roborock_raw_map.py unit (pure) clean
stall_capture_render.py 191 98% tests/unit/test_stall_capture_render.py unit (pure) clean
live_map_image.py 52 100% tests/integration/test_manager_lifecycle_status.py ([LS-12]/[LS-13]) integration clean

What's tested

The zone/room boundary test

  • boundary.point_in_polygon (BND, unit, test_mapping_boundary.py) — the ray-casting membership test map_source.zone_membership uses to decide which rooms a drawn zone overlaps. BND-1 is the ordinary case (so the refusals mean something: without it every assertion here is satisfied by a function that always returns False), and BND-2 uses an L-shape whose notch lies inside the bounding box and outside the polygon — a bounding-box implementation passes BND-1 and fails BND-2, which is the only reason BND-1 is not the whole test.

⚠ if n < 3: return False is NOT the no-op it looks like, and BND-3 is the input that proves it. The guard had been classified as subsumed with an empty red set — a 2-point "polygon" has no interior, so surely the loop returns False anyway. It does not. For n == 2 the loop runs twice over the same pair of vertices in opposite order and computes the x-intersection two ways (x0 + (x1-x0)*(py-y0)/(y1-y0) against x1 + (x0-x1)*(py-y1)/(y0-y1)): algebraically identical, not bit-identical in IEEE 754. On the values in BND-3 they differ by 1.1368683772161603e-13, so a px placed exactly at the lower one satisfies px < higher but not px < lower, inside toggles exactly once, and the loop returns True.

The input was found by directed search (4000 random segments, py at the midpoint so both edges cross the ray, px at the smaller intersection), not copied; three disagreeing parameter sets turned up and the first is in the test. It is deterministic — IEEE 754 arithmetic, not sampling — so it reproduces exactly. What the guard buys: zone_membership passes user-drawn zone geometry here, so a zone reduced to two points by a bad drag would, without it, report overlapping whichever rooms landed on the wrong side of a rounding error — a zone clean dispatched at rooms the user never selected, decided by the last bit of a division.

The image stack

  • segment_primitives (SP) — pure geometry (rdp, polygon_area, compactness, aspect_ratio, …), the numpy/scipy mask primitives (mask_to_polygon, mask_iou, transforms, mask_edge_band, estimate_alignment, normalized_color_features), and rasterize_primitives — the composer rasteriser that turns rect/circle/polygon shapes into a mask (fill + ordered subtract ops) for custom segments.
  • segmenter_engines (SE) — the engine registry, tuning validation, and the no-image/noop unavailable paths. The CV pipeline body (detect_room_segments) is exercised only through its failure paths.

The stall capture renderer

  • stall_capture_render (SC) — the one-room capture drawn for a stall notification: a flat silhouette from the room-id raster, the pose trail, a position dot, and a black-on-white name pill. Pure — bytes in, PNG bytes out, no hass and no adapter — which is what lets the maintainer dev card fire it repeatedly and what keeps it testable without a fixture.

Every interesting target here is an ABSENCE case, because this sits on a job-lifecycle path and consumes values that are legitimately missing. A docked robot has no anchor (the pose sampler nulls it by design), a held map source nulls it too, an unsegmented room has no pixels, and Pillow is an optional dependency the install matrix expects absent. SC-3/SC-4/SC-5/SC-6 pin that each degrades to a smaller picture or to None — never an exception, and never a fabricated coordinate. SC-4 compares renders byte-for-byte with and without an anchor, so a None silently coerced to (0, 0) fails rather than drawing a dot in the corner.

SC-2 is the one to read for the RASTER half. It calls _to_rendered directly and pins that room cells are offset by ro_dx/ro_dy and, when flip_y is set, mirrored about canvas_height (raw row 0 is the image bottom) — flip_y describes the RASTER only.

⚠ This paragraph used to end "the anchor and trail arrive already normalized in the rendered frame, so they must NOT be flipped" and sold that as something SC-2 pins. The RULE is true — render_room_capture puts anchor and trail through _norm_to_px only, never _to_rendered, because they arrive already normalized 0–1 against the canvas — but SC-2 does not pin it: SC-2 never calls render_room_capture at all, and no test in tests/unit/test_stall_capture_render.py passes ro_dx, ro_dy or flip_y into it. The two sides of that seam are exercised separately and never through it. Getting the rule wrong renders a plausible image of the wrong part of the map, which is the failure most likely to pass a glance — and today nothing but review catches it.

SC-10 is an evidence rule, not a threshold. Below four DISTINCT points no trail is drawn at all. A line between two samples asserts the robot travelled straight between them; Eufy declares interval_s 2.0 so a ±30 s window is a real trace, but Roborock's pose comes from the map backdrop at ~30 s, so the same window yields two or three. Joining those would fabricate a route in the one artifact whose job is to show what actually happened. Identical consecutive anchors also collapse to one point — a wedged robot repeats its pose, and it must not read as movement.

SC-11 rotates to the user's map orientation, negating the angle because the card rotates with CSS transform: rotate(Ndeg) (clockwise) and PIL rotates counter-clockwise. Applied after the vector layer and before the label, so the room turns and the text stays level. Pinned with a 40×10 room becoming 10×40, so a wrong angle cannot pass on symmetry.

The tracker

  • tracker (MT, unit) — the pure _RoomConfidenceState machine (reset_room, movement increment / saturate, reset_job).
  • tracker (MTE, integration) — the job lifecycle: register/unregister, start_job/end_job (seed / reset the confidence state), pause/resume sampling, _handle_position_update (per-tick confidence advance when a job is active, else the passive dock-drift JSONL log), the native current-room resolution (_detect_current_room / _get_raw_position), and the confidence-threshold room-exit firing eufy_vacuum_room_completed.

The service orchestrator

  • mapping_services (MS, unit) — _apply_segment_adjustments, _build_segments_response, and the module-local geometry helpers. MSH, integration — the service handlers via async_register_mapping_services: get_map_segments, adjust_map_segment, set_segment_room_link (set/clear/1:1), set_companion_anchor, delete_map_image.

Custom & multi-layout segmentation

The human-authored alternative to CV, exercised end to end through the services.

  • Authoring (test_mapping_services.py) — set_custom_segments rasterises composer primitives into room polygons (replace-all; refuses with no_custom_backdrop until a backdrop image exists), and a custom room link survives a re-save. set_segmentation_mode is a pure pointer flip that never re-runs the segmenter and losslessly switches the served store (cv ↔ custom).
  • Named layouts (LAYOUT-*, test_mapping_services.py) — the custom_layouts collection lifecycle: a legacy single custom_segments store migrates into one default layout (custom-resolved links/anchors move onto the layout, CV's stay on the map bucket); create / rename / set-active / delete (create flips to custom and activates, delete-active reassigns, delete-last flips back to CV); and set-active with zero layouts auto-creates one.
  • Per-layout isolation — the same segment id may link to different rooms on two layouts (test_per_layout_segment_isolation), and companion anchors including the reserved dock spot are per-layout (LAYOUT-6) — neither bleeds across.
  • Furnished render (FURN-*, test_mapping_furnished_render.py) — the per-layout furnished-art contract end to end: set_furnished_art_placement (home/room scope, 4dp round-trip, scale clamp to [0.05, 20], clear-on-all-null, missing-room-id guard), set_furnished_render_mode (layout vs per-room, blank room_id → layout level), set_room_viewport, the upload_map_image art_scope variant routing (custom_<id>_home_art / _room_<rid> onto home_art/rooms, never the backdrop), the resolve_furnished_render projection, the delete_custom_layout art sweep, and per-layout isolation — all through the real service registry.

The map_state_source reader

The brand-agnostic read of the provider's own segmentation + live pose into VA-owned room data (architecture: docs/dev/map-state-source.md). The pure extraction/normalization is unit-tested without Home Assistant; the manager-facing seams (delegators into MapSourceCoordinator) are integration-tested.

  • map_source (MS-*, unit, test_map_source.py) — the pure core: rooms_from_room_pixels (per-room bbox+name, Y-flip, catch-all rid 32 filtered, malformed/short buffers degrade to []; the rid gate itself is pinned by MS-21, because two guards in learning/external_run.py::_room_footprints are documented DEAD on the strength of it — widening it reddens three tests across both layers), normalize_rendered clamp+flip, anchors_from_storage (dock/robot normalize, non-numeric coords skipped), per-room area (pixel_count × (res_cm/100)² — rounded to 1dp, so at the default resolution 5 a room needs 20 cells to come out non-zero; 19 → 0.0, 20 → 0.1, measured, and learning/external_run.py::_room_footprints relies on that to drop specks), and build_map_source_result's presence gate (absent-with-reason vs populated, with extra overlay layers merged in). (rooms_from_parsed_map, a dead second Roborock-parser room extractor with a disputed coordinate frame, was removed -- #11:A3-EXT-5.)
  • map_source_runtime (MSR-* + MSC-*, unit, test_map_source_runtime.py + test_map_source_collectors.py) — the HA-aware glue tested with injected plain data: eufy_result_from_store (the #136 version guard, presence gate, extraction, degradation), the Roborock find_mapdata / find_roomlike_collection defensive introspector (duck-typing, cycle-safety, attr denylist), the dreame_coordinator device→config-entry hop (MSC-4/MSC-4b, ISSUE #69 — run with two dreame coordinators loaded so the single-coordinator fallback declines and route 1 has to do the work; MSC-4b spies on _report_deprecated_config_entries_property because the returned coordinator is identical either way and only the report distinguishes the deprecated path), and the candidate collectors (eufy_inmem_candidates, roborock_candidates, image_entity_object) that gather roots from hass.data[domain] / per-entry runtime_data / the image entity, each degrading cleanly when a source is absent.
  • the Store + device-registry readers (MSR-6..MSR-7c, MSC-6..MSC-6g, unit) — the group that answers "where is this vacuum's Store file", from the public device registry plus the adapter's declaration. load_store_json is the one function here that touches disk, and its except (OSError, ValueError) is one clause over two unrelated producers, so an absent file and a truncated one are separate rows: proving one leaves the other half unproven, which is the shape where a guard that exists reads as complete.

⚠ device_identifier_value's fixture must give the identifier and the serial DIFFERENT values. It scans device.identifiers for the asked-for domain and falls back to device.serial_number. On a real Eufy device those are the same string — the fork keys its Store by the serial, which is the (robovac_mqtt, <serial>) identifier — so a fixture copied from the real device cannot tell the scan from the fallback: delete the whole scan loop and the test still passes. Measured on exactly that shape, both routes return the same value. MSC-6/MSC-6b use a distinct serial, which is the only arrangement in which the two arms are distinguishable.

MSR-7/MSR-7b close the last two __slots__ arms, the siblings of RB-7: __slots__ = "rooms" is legal Python meaning ONE slot, and iterating that string character-wise yields ['r','o','m','s'] so the object dead-ends exactly as it did before RB-7 for a different reason; and a slot that is declared but never assigned raises on getattr, which the walk must step over because the data may be in the next slot. - the Dreame render's DEGRADATION arms (DMD-11..DMD-24b, unit) — DMD-1..DMD-10 establish the happy path on a real frame; these are what the render does when ONE piece of the device's map is unusable, which was nine statements and eight partial branches of dreame_render_from_mapdata plus most of dreame_render_data_from_mapdata and all of _dreame_raster_flip's give-up arms. Each arm decides which FIELD goes missing, and the card draws what it is given — so a room with no area_m2 still draws, a room whose corners would not project must not draw at a garbage bbox, and an unplaceable anchor must be absent rather than pinned at the frame origin. The assertions are on the surviving shape, never on the absence of an exception.

Three worth knowing: - DMD-11 asserts a malformed map_frame_offset_mm yields a payload equal to the unshifted render, which pins the fallback at (0, 0) rather than merely "present". Its fourth row was dropped on measurement: a dict declaration raises KeyError, which is a LookupError but not an IndexError, so it escapes the handler. Left alone — the key is in no schema, its only producer is a hardcoded list literal, and the second copy of that read in dispatch/manager.py (the replica pair in 00c-replicas.md) carries the identical except tuple, so this is a uniform limit rather than the copies having drifted. - DMD-21 proves both raster orientations decode to byte-identical room_pixels, which is the [x][y] vs [y][x] question the fixture header makes a point of. - DMD-24 injects its own proj stub and hand-computes the centroids (rows 8–9 of 10 → raster_cy 0.85 against a projection at 0.0, so 0.85 > 0.15 → flip). That is deliberate: deriving the expected rows from _dreame_projector — the transform under test — would be a shared oracle whose assertion could never fail. DMD-24b's four give-up rows all assert False, which only means something because DMD-24 proves True is reachable.

⚠ Four of dreame_render_from_mapdata's None guards are SUBSUMED, found by ablating each and seeing nothing go red: None in (x0, y0, x1, y1) by not c0 or not c1; cx is not None and cy is not None by if centre:; ra is not None by the except (TypeError, ValueError); and dx is not None and dy is not None by if p:. In each case _n() reaches float(None), raises, and returns None, so the downstream check already skips the field. The guards are harmless belt-and-braces costing two wasted _n calls apiece — and no test proves them, so their red sets are declared empty in the test file. Written down because the obvious next move, "add a test for that guard", cannot succeed. - dreame_mapdata_candidates (MSC-5..MSC-5h, unit) — the locator for a Dreame user's map, whose entire body was uncovered while three call sites in map_source_coordinator.py consumed it. What it costs when it answers absent while a map exists is specific: the coordinator falls through to the camera-attribute bbox fallback, and the Dreame adapter deliberately declares map_pixel_size: None, so that fallback yields raw pixel coordinates instead of 0..1 — rooms land in the wrong frame.

The fixtures' vocabulary is read from the installed custom_components/dreame_vacuum v2.0.3, not assumed: hass.data["dreame_vacuum"][entry_id] is the coordinator object (not a dict, and not the Eufy fork's {"coordinators": [...]} shape); dreame/types.py declares self.pixel_type: Optional[Any] = None inside MapData while MapDataPartial declares no pixel_type at all, so MSC-5f carries both real shapes of "decoded but no raster yet"; and the camera attributes are the component's own ATTR_ROBOT_POSITION = "vacuum_position" / ATTR_CHARGER = "charger_position", assigned the raw position object rather than a dict — which is why MSC-5g asserts by identity. A fixture using dicts, or the plausible-looking robot_position, would pass a shape check and read nothing the producer emits.

⚠ MSC-5c must RECORD the fallback call, never make it raise. The production fallback sits under except Exception, so a raising get_map stub is swallowed and a preference-order test built on one passes with the preference inverted — the same shape as the LP-3 note below. The index literal matters too: MSC-5d pins get_map(0) because index 0 is status.current_map (live) and index 1 is the saved map, so an off-by-one hands the user their other floor. And MSC-5b is the row that proves the adapter's identifier_domain is read rather than defaulted — core holds no brand word, so a locator that found the coordinator regardless of the declaration would be a defect in its own right. - _structure_tree's bounds (MSR-5..MSR-5f, unit) — the diagnostic shape dump, which is the one piece of this module whose output no user ever sees and whose bounds are still worth pinning. Both call sites run on the FAILURE path (reason="no_parsed_map", reason="no_pose") and write diag["structure"], whose job is to SHOW where a parsed map or Room geometry lives when the duck-typed search misses — on hardware nobody here owns, so the dump is the bug report. The arms tested are the limits that keep it usable: the depth and width caps (a live SDK graph reaches hass, the bus and back); the empty-sequence guard, without which the list arm indexes obj[0] and an empty rooms list raises — and because one call site wraps the dump in a blanket except that degrades it to {"error": "structure dump failed"}, a raise there costs the diagnostic silently rather than loudly; and show_skipped, asserted in both directions, since a denylisted attr like api must be invisible by default and visible as a "<type> (skipped)" leaf when asked for — the data may sit behind exactly the attr the walk refuses to traverse.

⚠ MSR-5c is RB-7 one function over. MSR-3e pins the __slots__ lesson in _walk; _structure_tree carries its own copy of that fallback and had no test, so the dump could have dead-ended on precisely the object a __slots__-using parser hands over, reporting "_Slotted" and no attributes — which reads exactly like an object with nothing in it. Same question answered twice, fenced once.

One asymmetry to know before reading a dump: an empty list renders as the string "list[0]", an empty dict as {"dict[0]": {}}. The bare-string form belongs to the list/tuple arm alone. - the live-pose backend seam (LP-*, unit, test_live_pose_backends.py) — async_get_map_live_pose's brand dispatch, plus robot_pose_from_mapdata / mapdata_live_pose_from_candidates in MSR-2k. The bug they pin is a DECLARATION gap, not a geometry one: the accessor was the eufy-clean reader wearing a generic name, so it keyed off a live_pose block merely existing and answered not_configured for a brand that could not describe itself in fork terms. Roborock's position was live on its parsed MapData the whole time — the card drew it while the stall capture drew rooms with no dot and the pose ring banked rows with no anchors. Covered: the declared backend selects the reader; no backend is a default (an undeclared one says so rather than falling through to a brand); the pixel-override path is gated on the pixel backend so a parsed-map brand can never drive the fork's attr walk; and the card's overlay payload and the pose accessor are asserted to read the SAME extractor, so the two cannot silently disagree about whether a map has a robot on it again.

Note the LP-3 test records the call rather than raising from the stub. _apply_inmem_pose_to_result swallows Exception by design, so a raising probe is eaten and the test passes with the gate removed — it did, until ablation caught it. - the native current-room HIGHLIGHT source (CRR-*, unit, tests/unit/test_current_room_resolve.py; MSD-14/MSD-15, integration, test_manager_map_source_refresh.py) — the SAME sibling-drift as the live-pose seam, one layer over. The render frame's current_room (what the card's current-room layer fills) is supplied per brand: Eufy by pixel lookup, Roborock by vacuum_room. Dreame's decoded map leaves vacuum_room null, so the camera_attrs render carried no current_room and the highlight stayed dark — even though the brand answers the question directly via its native active_cleaning_target NAME entity (already consumed for attribution). rooms/current_room.py::resolve_native_current_room_id is the ONE resolver both consumers share (name → slug → managed room id; None for the dock / a transit room / an unmatched name); a THIRD, deliberately different variant on ActiveJobTracker matches the job QUEUE and is not unified. MSD-14 is the declaration-proving gate: a native_current_room brand whose decode omits current_room gets it injected from the NAME entity, and it goes red (KeyError: current_room) with the injection removed — ablation-confirmed. MSD-15 holds the None case (an unmatched name draws nothing rather than a wrong room).

current_room.py reached 100% on 2026-11-08 with CRR-7/CRR-8, and both are about the managed-room registry being STORED data — its rows come back from .storage, so they are outside data even though the producer is in this repo. CRR-7 drives a non-dict row with the real match placed AFTER it (position is the test: continue and break are indistinguishable when the bad row is last), and CRR-8 drives both arms of the int() except on a room that MATCHED — the one failure mode where the brand's live name found a managed room and the answer still has to be None, since a raw string in the frame's current_room is what the card uses as a raster room id. The cost of the missing guard is not a lost room and the two call sites differ: the map coordinator calls the resolver inside the refresh's blanket except, whose handler serves an ABSENT MARKER, so one junk registry row blanks the whole frame rather than dropping a highlight; the pose sampler loses one tick's sample to POSE-5 and retries. return vs continue inside that except is deliberately not asserted — RP-015 makes slugs unique per map, so no second room with that slug exists for a continue to reach. - res_m (RESM-*, unit, test_render_res_m.py) — one unit for the raster cell size, asserted across all three brands at once. The room_pixels_v1 payload has always carried a res field from every producer, and they do not agree on what it means: Eufy's is centimetres, Roborock's and Dreame's are millimetres. Measured 2026-11-14 — alfred 5, ivy 50, robin 50, all three physically 5 cm per cell, in a field of one name holding two units. Nothing on the card read it, so nothing was wrong; the first consumer would have been 10× out on two brands of three with no value on the wire to tell them apart. res_m is the normalised field, converted at each producer where the unit is known. Why this file is cross-brand rather than three brand tests. The defect it guards is ONE producer forgetting to convert, and a brand-scoped test is blind to exactly that — it passes on whichever brand its author had in mind. [RESM-1] therefore asserts EQUALITY across the three rather than three literals, which would invite whoever broke it to edit the matching constant. [RESM-2] doubles each device's own resolution in its own native unit: a producer returning a hardcoded 0.05 passes [RESM-1] and dies here. [RESM-3] pins that res itself is UNCHANGED. Measured 2026-11-14: nothing in shipped code reads that field — grepping src/, the three built bundles and custom_components/ finds only the producers writing it, and the pose overlays project through map_data["resolution"] and the Roborock parser's own ImageDimensions.to_img. So the reason to keep it is not internal dependence (an earlier draft of this note said three call sites trusted it, which was false) but that get_map_render_data is a public service whose response an automation may already read. Its lack of consumers is worth recording: if res is ever retired, [RESM-3] is where that is established. All three ablation-proven, including the realistic slip of swapping the two conversions. - physical sample size (MPCS-*, unit, test_material_pack_scale_contract.py) — the arithmetic that turns a declared sample_m into a raster scale, and the 2048 canvas the whole derivation stands on. scripts/material_pack_contract.py warns an author when a declared physical size will be CLAMPED rather than drawn, and it shipped with no test: the sweep was ablated once by hand, and that evidence does not survive the session. A gate nobody can show firing reads as coverage while being indistinguishable from one that cannot fail. [MPCS-1] reads all four RNTA1EGS declarations of the mask canvas out of their own files and asserts they agree — the replica note's weakness was that it fires only if someone notices, and gen_floor_masks.py is read as TEXT because importing it would pull numpy/Pillow, which are optional dependencies this suite does not declare. [MPCS-3] is the defect the pre-ship review caught: a 0.6 m sample is representable at S=4 and clamped at S=3 and S=2, so the band depends on the raster's PIXEL WIDTH and not only on how fine it is — a single-S check calls 0.6 m fine, and it is, on two of the three development vacuums. [MPCS-5] catches a raster scale value published as a sample_m: the two sit side by side in one descriptor and nothing about the number says which it is. Why [MPCS-6] asserts SILENCE. Sweeping S=1 as well once made a correct 5 ft board warn, and a warning that fires on good input teaches the author to skip the whole block, which costs the warnings that do matter. S=1 needs a raster ~1715 px wide — 86 m across, not a home. Re-adding it turns [MPCS-6] red, which is why the envelope is stated as a test rather than only as a comment. [MPCS-7] straddles _CLAMP_TOLERANCE from both sides: 1.0 m clamps by 2.4% and is NOT reported, 0.96 m clamps to the same 1.024 m by 6.7% and is — a tolerance tested on one side only cannot be shown to still reject anything. [MPCS-8] pins that the report carries the metres that will be DRAWN, since a report echoing the request back would be unactionable while looking identical in shape. Ablation-proven, 11 cases over 8 claims: eight edits to the checker and the replica sites — canvas moved, sweep narrowed to one S, S=1 re-added, tolerance set to 0 and to 0.5, upper clamp removed, drawn size replaced by the request — each naming the ids it must turn red, and every one of the eight claims goes red under at least one. One expectation in that sweep was the HARNESS's own error, not a dead claim: [MPCS-5]'s inputs miss the band by 924% and 105%, so no plausible tolerance can hide them. - floor placement (RM-FIT-*, unit, test_room_manager.py) — where a FITTED material sits in a room, as floor_rotation is for its angle. [RM-FIT-1] pins that _as_fit CLAMPS rather than refuses — safe here in a way it would not be for a size, because tx/ty are normalised to the slack that exists, so every value in range still covers the room and a refusal would protect nothing — and that non-finite is DROPPED rather than clamped, since NaN survives float() and HA's store writes it back as a bare JSON token that makes the card's whole fetch fail, taking every room's config with it. [RM-FIT-2] pins the three rules floor_material and floor_rotation already follow: absent means UNCHANGED, explicit means set, never gates approval. An explicit {} is a REAL value there — back to centred, exact cover — so the test is is None and not falsiness; getting that wrong makes a placement impossible to clear. A numeric STRING is accepted here and refused by declared_number on the drop-in side, which looks like the divergence that function exists to prevent and is not. The sides differ in who writes the value: a descriptor comes from a GENERATOR, where a stringified number means a field it could not compute, while this arrives from a service call a person may have typed in YAML, where tx: "0.5" means what it says. It follows _as_rotation, its own neighbour, rather than a helper in another module. Four ablations red: no finite guard, no clamp, the identity not dropped, and is None weakened to falsiness.

[RM-FIT-3] (integration, test_manager_rooms.py) covers the TARGETED service, update_room_fields, which is what a placement control on the map writes through — deliberately not save_managed_rooms, which rewrites a map's whole room configuration from the caller's payload and is the most destructive in the area. A dial being dragged must not be able to take the room list with it. The _UNSET sentinel is the mechanism and is load-bearing exactly as it already is for color: an ABSENT key leaves the placement alone (an automation touching only fan_speed must not wipe it) while a PRESENT {} is a clear. Falsiness cannot tell those apart and the one it loses is the clear, which makes Centre impossible. Two ablations red: the sentinel weakened to falsiness, and _as_fit removed so an unclamped non-finite value reaches the store. - roborock_raw_map (RRD-*, unit, test_roborock_raw_map.py) — the pure Roborock v1 raw-map segment decoder, no HA/device: decode_roborock_v1_segments (a well-formed IMAGE block → resolved room-id raster + dims + ids; no-IMAGE / empty / truncated / garbage / dims-exceed-data → None, never raises), resolve_rid's per-pixel encoding (byte >> 3 only when the low 3 bits == 7; 0xFF catch-all; scan/wall/outside → 0; the 0x08 obstacle-bit collision a naive shift would mislabel as room 1), roborock_render_data wrapping a decoded raster in the shared room_pixels_v1 payload (b64 round-trip, flip_y, catch_all_rid, room_names), the ..._from_candidates introspection bridges (BFS to a MapContent, absent-marker on no match), raster_room_bboxes (per-room normalized bbox with flip_y honored so raw top rows land at the rendered bottom — the Ivy finding), and geometry_drift, the on-device decode self-validator overlaying the parser's bboxes against the raster (aligned / IoU / centre-drift, flip detection, only_parser set-diff).

89% → 98% (2026-11-09), and six of the eleven claims written to get there were wrong on first measurement. RRD-14..RRD-20 close the malformed-blob guards (break on an unwalkable block header; a zero-length walk step; dims the declared data_len cannot back; a data_len the BLOB cannot back), the caller-supplied version pass-through, raster_room_bboxes' two shapeless-input returns and its un-flipped arm, and geometry_drift's two malformed-row skip paths.

⚠ THE METHOD FAILURE IS THE PART WORTH KEEPING. RRD-14 was first "verified" by comparing TWO INPUTS — a blob with a bad header returns None, the same blob without it decodes — and that was read as the guard biting. It is not the ablation. Removing the guard and re-running the SAME input is the only thing that establishes it, and when that was done the sweep read 5 of 11. Four claims were guards shadowed by a LATER guard returning the identical answer. The biting input turned out to need data_len == 4, because the walker advances by data_len + (header_len & 0xFF) and only 4 + 4 == 8 lands the ablated walk cleanly on the trailing IMAGE; at data_len == 0 it steps 4, lands misaligned, and returns None either way.

Three guards are recorded SUBSUMED rather than tested, each because its successor returns the same value: pixels_exceed_data_len falls into the blob-overrun return three lines down; {} is answered by EITHER raster_room_bboxes guard alone, so neither pins it; and _bbox_iou's if inter <= 0: return 0.0 is a short-circuit, since the general formula already computes 0 / (area_a + area_b) and the union guard catches the degenerate case. All three measured DEAD.

Two units stay uncovered, both unreachable, so 98.03 % (199/203) is the honest ceiling. The except (IndexError, ValueError) net has no constructible input: n >= 4 bounds the header read, the loop's pos + 8 <= n bounds all three block reads, and header_len >= 24 with pos + header_len <= n bounds the dims quad — every index is guarded. (It DOES catch something once the header break is ablated, which is how the overrun variant of RRD-14 turned out subsumed.) And raster_room_bboxes' y-minimum update is unreachable by construction: the scan is enumerate(rp) in index order, so y = i // w never decreases and y < b[1] cannot hold after a room's first pixel. Its x twin IS reachable, because x cycles — which is why only one of the pair was ever uncovered.

RRD-15 is deliberately outside the ablation sweep. Its red input is NON-TERMINATION: with the step <= 0 break removed, pos += 0 forever. A harness that waits on an exit code would stall rather than report it, so that claim is verified out of band with a bounded timeout and the test says so. A guard whose only alternative is a hang cannot be proven by the usual instrument. - dreame_render_from_mapdata (DMD-*, unit, test_dreame_mapdata_decode.py) — the pure Dreame raster decoder over the base integration's decoded MapData (no HA/device; a SimpleNamespace fake shaped from the live ground-truth probe on vacuum.robin): TRUE per-room area_m2 from the pixel_type grid (a segment's pixels are value ∈ {id, 100+id, 200+id} × grid_size² — DMD-2 bites the border 100+id term, DMD-3 the grid_size term), bbox projection via the base's own dimensions transform (normalized 0..1), user-placed furniture as a neutral-slug overlay (+ room + size), robot/dock anchors, and the no-dimensions → absent-marker degrade. dreame_render_data_from_mapdata builds the shared room_pixels_v1 raster (pixel_type → resolved rids {id,100+id,200+id}, transposed to row-major ry*width+rx, flip_y auto-detected by matching a room's raster centroid to its projected centroid) — DMD-6/7/8 pin the format contract, rid mapping, and row-major order on a non-square fake so [x][y] vs [y][x] can't hide. The device-side readers (dreame_coordinator via the public coordinator.device, dreame_mapdata_candidates) are validated live, not unit-tested. - map_source_coordinator (CMP-* + LP-*, integration, test_manager_compare_sources.py + test_manager_live_pose.py) — the manager delegators into MapSourceCoordinator: async_compare_map_sources (the verify probe — not_configured / memory_not_configured guards, flags-only when only one source is present, compare_map_data reached when both are, diagnostics breadcrumb passthrough) and the live-pose seam async_get_map_live_pose / _apply_inmem_pose_to_result (robot/dock/heading/trail overlaid on present pose, base overlays preserved when pose is absent or its read raises, no_geom reason when geometry is missing). - map_source_coordinator dispatcher + backends (MSD-* / GLM-* / RND-* / RIP-* / LPG-*, integration, test_manager_map_source_refresh.py) — the pre-warm async_refresh_map_state_source routing (storage / memory-primary / memory / unknown-backend / error-degrade, plus the live-image presence gate), the storage backend's mtime-cache hit + version-mismatch warn + no-device marker, the memory-primary scan with its content-version cache and the three .storage fallbacks (memory miss / convert-None / present-False), get_live_mapdata_obj (the zone-dispatch object locator across both backends, None on absence/raise), async_get_map_render_data (memory-primary vs .storage vs unknown-format, plus the Roborock roborock_raw_map_v1 format dispatching to the raw-map render bridge with room names from the manager's stored rooms), and the live-pose read layer (_read_inmem_pose, _load_live_pose_geom read + mtime cache + no-map-data). The _msr parsers stay unit-tested; these pin the coordinator's own dispatch / cache / fallback branching, each fallback asserted via an assert-not-called guard so the intended branch is proven, not just non-crashing.


How it's tested

Four patterns, same as elsewhere in the suite:

  1. Pure import (Recipe C) — the geometry, engine registry, and the service helpers. No fixtures.
  2. tmp_path filesystem — the tracker file helpers (the dock-drift JSONL) get an isolated config dir. The hass is a MagicMock with config.config_dir = str(tmp_path):
    hass = MagicMock(); hass.config.config_dir = str(tmp_path)
    tracker = MappingTracker(hass)
    
  3. numpy/scipy arrays — the segment_primitives mask tests build real arrays. numpy ships transitively via HA core; scipy and Pillow are explicit test deps (see requirements_test.txt). Scipy-only paths still guard with pytest.importorskip("scipy.ndimage") so the file degrades gracefully if the stack is ever absent.

Image/CV pipeline (IMG, integration — brand-agnostic)

The framework's segment plumbing (analyze_map_image, get_map_segments) is tested against a registered fake segmenter engine that returns a canned SegmentationResult — not a concrete brand engine. This proves the framework drives any adapter's CV pipeline without coupling to Eufy's. The real Eufy CV segmentor (detect_room_segments, HSV masks, EufyCVSegmenter) is tested solo in tests/adapters/eufy/test_segmentor.py (prefix ECV), where brand code belongs. Framework-level tests stay engine-agnostic; brand CV tests live with the brand code.

Non-segment service handlers (MSV, integration)

The surviving read/display handlers — delete_map_image, set_live_map_rotation, set_map_overlay_visibility, and get_map_render_data — exercised through async_register_mapping_services. (The room-bounds-snapshot, boundary-trace, dock, trace-capture, mapping-package, and trace-review handlers were retired with the mapping split.)

Known gaps

The module table above is current (regenerated against this revision by scripts/update_test_docs.py); the itemized breakdown below is not — tracker.py (84%, down from a described 93%) and mapping_services.py (88%, down from a described 91%) have grown real new coverage gaps this campaign that are not yet itemized here (134 missed lines in mapping_services.py alone; run --cov-report=term-missing on both modules for the current line list before treating either bullet below as exhaustive). The other three modules' bullets below still track close to what they described:

  • mapping_services.py (88%) — the _handle_analyze_map_image tuning-override / light-assist wiring (the tuning dict + assist_image_path block inside that handler) was deferred: a robust test fights the filesystem-probing image store plus phac's shared config dir — not worth a fragile test. Beyond that previously-described defensive tail (the OSError delete branch in _handle_delete_map_image, non-dict guards, the tracker-absent else, the schema-unreachable coerce guards in _build_segments_response), the module now carries substantially more uncovered surface than before — not yet re-triaged.
  • tracker.py (84%) — previously-described gaps: # pragma: no cover capabilities-read / dock-drift JSONL I/O except-blocks, malformed-line resilience, and trivial early-return guards; the transition-room skip in _detect_current_room is a redundant defensive short-circuit (its normal path is covered by test_room_completed_event), deliberately left. The module has grown a further ~9 points of gap this campaign not yet itemized.
  • segment_primitives.py (93%) — empty-mask divide-by-zero returns, optional-dependency guards, and unreachable malformed-edge artifacts.
  • map_source_coordinator.py (90%) — _stat_mtime's real os.stat (monkeypatched in the dispatch tests), the except OSError stat-failure guard, the memory-backend diagnostics-log branch, and a few -> partials in the candidate loop / render / geom-cache edges. Defensive guards + real-IO; the dispatch, cache, and fallback behaviour is fully covered.

Extending

  1. A new geometry/engine behavior? Pure unit test — add a target to the matching file. Use tmp_path if it touches disk.
  2. A scipy/numpy image path? Build real arrays; gate scipy-only code with pytest.importorskip.
  3. A service handler? That's the integration pass — register via async_register_mapping_services with a real hass + tmp_path config dir.
  4. Re-measure across all mapping test files together for the true per-module number.

[MSR-4] The Dreame camera-attribute fallback

map_source_coordinator falls back to dreame_camera_candidates + dreame_result_from_candidates whenever the MapData read does not yield a present result. That is live code on every Dreame install whose decoded map is unavailable, and it shipped with 82 statements and zero tests -- the largest single block of untested live behaviour the coverage audit found.

Fixtures derive from the real producer. robin's own transform, from the 2026-08-09 field report: px = 682 + x*0.08, py = 845 - y*0.08, image 936x992, dock verified at vacuum {-553, 132}. The affine test fits three calibration pairs and then checks a FOURTH point -- the dock -- so a Cramer coefficient that is off by a term is caught by a position the fit never saw. An invented affine would have encoded an assumption about the frame instead of the device's.

Two things the tests pin that nothing else states:

  • The saved-map merge is one key wide. Room geometry comes from <entity>_1 because the live camera omits rooms, but vacuum_position must still come from the LIVE entity -- the saved map's copy is wherever the robot was when that map was stored. Merging saved wholesale draws the robot at a position from another session.
  • Production runs the unnormalised branch. The Dreame adapter declares map_pixel_size: None on purpose, so this fallback returns RAW PIXEL coordinates, not 0..1. That is deliberate and documented at the declaration, but it means this backend reports a different frame than the MapData path. [MSR-4m] pins it so a future change to the default is a decision with a red test rather than a silent reframing.

Ablated: nine substitutions across the three functions; eight redden exactly their own test. The ninth is reported rather than hidden -- removing the None in (x0,y0,x1,y1) bbox guard reddens nothing, because _norm's except (TypeError, ValueError) already drops the room. That guard is redundant, and [MSR-4n]'s docstring says so.