From dbaa87c4e8e40bfa88490c5734738b78e6ddbd2e Mon Sep 17 00:00:00 2001 From: jetson Date: Mon, 26 Oct 2026 12:07:52 +0700 Subject: [PATCH] docs: plan FCP counting-logic parity for feedmill_recounter Audit of karung_counter_semarang (FCP) vs feedmill_recounter found the counting core only partially synced: the unload-after-load gate, the counting-polygon centroid filter, the calibrated static count line, sack conf 0.30, box min_bbox_area 1000, stabilizer max_hold 10 and real batch-FSM crossing events were never ported. Plan lists 10 TDD tasks, each pinned to the FCP file:line it mirrors. FCP itself is read-only. --- .../plans/2026-10-26-fcp-counting-parity.md | 783 ++++++++++++++++++ 1 file changed, 783 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-26-fcp-counting-parity.md diff --git a/docs/superpowers/plans/2026-10-26-fcp-counting-parity.md b/docs/superpowers/plans/2026-10-26-fcp-counting-parity.md new file mode 100644 index 0000000..774ba25 --- /dev/null +++ b/docs/superpowers/plans/2026-10-26-fcp-counting-parity.md @@ -0,0 +1,783 @@ +# FCP Counting-Logic Parity Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make `feedmill_recounter` produce the same sack/box counts as the Feedmill Counting Platform (FCP = `../karung_counter_semarang`) for the same clip, by porting FCP's counting logic onto the recounter's video-file pipeline — without changing FCP. + +**Architecture:** The recounter keeps its own video-file pipeline (upload → 720p transcode → track → stabilize → count → JSON result). FCP is a live RTSP pipeline with a fixed 1280×720 calibration. Parity = (a) copy FCP's counting predicates and thresholds verbatim into the recounter, (b) make the recounter count against FCP's calibrated static zone instead of its own dynamic truck-derived ROI. Every value is pinned to a `file:line` in FCP, which is read-only. + +**Tech Stack:** Python 3.10, Flask, ultralytics (YOLO track), OpenCV, shapely (already a dependency), pytest. + +**Spec:** This plan *is* the spec. FCP is the reference implementation, quoted inline with `file:line`. Never edit `../karung_counter_semarang`. + +## Global Constraints + +- FCP (`../karung_counter_semarang`) is READ-ONLY: no edits, no commits, no service runs inside its tree. For the cross-check, copy it to `/tmp/fcp-parity/` and run there. +- The recounter stays **video-file based**. FCP's stream-only mechanisms are out of scope: `RTSPStreamReader` (`src/pipeline.py:16`), `_RtspHealth` freeze/drop monitor (`predict.py:365-427`), reconnect/backoff, `stream.resolution`, `inference_stride`. +- Counts must match FCP for the same clip. FCP's production path is `predict.py` — NOT `src/main.py` (prints DEPRECATED, `src/main.py:266-270`) and NOT `archive/`. +- FCP geometry is authored in 1920×1080 and hard-scaled to 1280×720 (`predict.py:688-689`). The recounter's `zones.json` holds the same polygons in 1920×1080 space and `src/zone_config.build_static_roi` scales them by the real frame size. **Do not re-author the calibration** — the numbers already match (see Verification). +- FCP's `counting.*` keys (`confirm_delay_sec`, `exit_confirm_delay_sec`, `debounce_frames`, `entry_overlap_threshold`, `exit_overlap_threshold`, `camera_noise_deadband`, `max_reid_transit_distance`, `circle_stay_timeout_sec`, `tolerance_missing_frames`, `max_reid_frames`, `jarak_toleransi_duplikat`, `min_valid_area`) are parsed but **never read** by FCP runtime (`src/config_loader.py:637-662` warns they are ignored). Do not port them — dead in the reference too. +- Existing suite must stay green: baseline `195 passed` (`python -m pytest tests/ -q`). +- No new dependency. +- Commit after every task; message style follows repo history (`feat:`, `fix:`, `docs:`, `test:`, `chore:`). + +## Review Focus + +Five failure modes a reasonable person would expect to be handled, each pinned to a task below: + +1. A sack first seen *below* the line never counted as loading must also never count as unloading (FCP gates unloading on a prior loading) → Task 1. +2. A sack crossing outside the calibrated counting polygon must not be counted at all → Task 3. +3. A truncated / half-written upload must not report partial counts as if the clip were complete → Task 10. +4. Two truck sessions in one clip must not carry per-track dedup state from session 1 into session 2 → Task 7. +5. A typo in `config.yaml` must not silently fall back to built-in defaults and quietly change counts → Task 9. + +## Already At Parity — Do Not Touch + +| Behaviour | FCP | Recounter | +|---|---|---| +| `cfg/tracker.yaml` | — | byte-identical (`diff` exit 0) | +| `src/stabilizer.py` | — | byte-identical (`diff` exit 0) | +| EMA alpha / height clamps / hold decay | 0.35 / 1.5 / 0.70 / ×0.85 (`predict.py:666-671`) | same | +| Counter band margin | 20 px | 20 px (`src/counting.py:47`) | +| Dedup radius / TTL | 30 px / 3.0 s | 30 px / 3.0 s | +| 3-layer dedup (state, spatial circle, track-id) | `src/counting.py:13-20` | same | +| History latch (`_has_been_above/_has_been_below`) | `src/counting.py:152-157` | same | +| Truck ROI X filter window | 400…936 (`predict.py:715-719`) | same via `build_static_roi` | +| Cross-class box-wins suppression | IoU 0.4 (`predict.py:946-948`) | same (`src/pipeline.py:476`) | + +--- + +## File Structure + +**Modify** +- `src/counting.py` — `_loaded_tracks` gate (Task 1), `reset_state()` (Task 7). +- `src/zone_config.py` — expose counting-area + truck-area polygons (Task 3, 6). +- `src/pipeline.py` — polygon filter (Task 3), real batch events (Task 6), batch-start reset hook (Task 7), truncation flag (Task 10). +- `src/batch.py` — none required; `update_sacks()` already accepts real events (`src/batch.py:199`). +- `src/config.py` — fail-fast load + validation call (Task 9). +- `src/job.py` — `JobResult.truncated` / `frames_expected` (Task 10). +- `config.yaml` — parity values (Tasks 4, 5, 8). +- `app.py` — `zone_mode` default (Task 2), truncation fields in the job response (Task 10). + +**Create** +- `src/validation.py` — `validate_config()` + `InputValidator` mirroring FCP `src/validation.py` (Task 9). +- `tests/test_counting.py` — counting-core unit tests (Tasks 1, 7). +- `tests/test_batch.py` — batch FSM unit tests (Task 6). +- `tests/test_validation.py` — config validation unit tests (Task 9). + +--- + +### Task 1: Gate unloading on a prior loading (FCP parity) + +**Files:** +- Modify: `src/counting.py:60-240` (`LineCrossCounter`) +- Test: `tests/test_counting.py` (create) + +**Interfaces:** +- Consumes: existing `LineCrossCounter(line_y, line_x_start, line_x_end, margin=20, dedup_radius=30.0)`, `.loading_count`, `.unloading_count`, `.update(detections) -> list[dict]`, `.reset()`. +- Produces: `LineCrossCounter._loaded_tracks: set[int]`. + +FCP reference: `src/counting.py:168` (`and tid in self._loaded_tracks`), `:196` (`self._loaded_tracks.add(tid)`), `:235` (cleared in `reset()`), `:68` (declaration). + +- [ ] **Step 1: Write the failing tests** — create `tests/test_counting.py`: + +```python +"""Counting core tests — FCP counting-logic parity.""" + +from src.counting import LineCrossCounter +from src.interfaces import Detection + + +def _det(tid: int, y1: int, cls: str = "sack") -> Detection: + """Detection with top edge at y1, spanning the whole counting X span.""" + return Detection(bbox=(100.0, float(y1), 200.0, float(y1 + 50)), + confidence=0.9, class_id=0, class_name=cls, track_id=tid) + + +def test_unloading_requires_prior_loading(): + """Track first seen below the line never counts as unloading.""" + c = LineCrossCounter(line_y=100, line_x_start=0, line_x_end=1000) + assert c.update([_det(7, 200)]) == [] # first seen below -> no event + assert c.update([_det(7, 10)]) == [] # now above -> still no unloading + assert c.unloading_count == 0 + assert c.loading_count == 0 + + +def test_loading_then_unloading_counts_both(): + """Above -> below counts loading; below -> above then counts unloading.""" + c = LineCrossCounter(line_y=100, line_x_start=0, line_x_end=1000) + c.update([_det(3, 10)]) + events = c.update([_det(3, 200)]) + assert [e["direction"] for e in events] == ["loading"] + assert c.loading_count == 1 + events = c.update([_det(3, 10)]) + assert [e["direction"] for e in events] == ["unloading"] + assert c.unloading_count == 1 + + +def test_reset_clears_loaded_tracks(): + """reset() clears the loaded-track registry (FCP src/counting.py:235).""" + c = LineCrossCounter(line_y=100, line_x_start=0, line_x_end=1000) + c.update([_det(1, 10)]) + c.update([_det(1, 200)]) + c.reset() + assert c._loaded_tracks == set() + c.update([_det(1, 200)]) + assert c.update([_det(1, 10)]) == [] + assert c.unloading_count == 0 +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `python -m pytest tests/test_counting.py -v` +Expected: `test_unloading_requires_prior_loading` FAILS (unloading counted without a prior loading); `test_reset_clears_loaded_tracks` FAILS (AttributeError: `_loaded_tracks`). + +- [ ] **Step 3: Implement the gate** in `src/counting.py`: + - In `LineCrossCounter.__init__`: add `self._loaded_tracks: set[int] = set()`. + - In the unloading predicate (currently `new_state == "above" and self._has_been_below.get(tid, False) and "unloading" not in counted_dirs`): add `and tid in self._loaded_tracks`. + - In the loading branch (where the `"loading"` event is appended): add `self._loaded_tracks.add(tid)`. + - In `reset()`: add `self._loaded_tracks.clear()`. + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `python -m pytest tests/test_counting.py -v` +Expected: 3 passed. + +- [ ] **Step 5: Run the full suite, then commit** + +Run: `python -m pytest tests/ -q` → expect `197 passed` (195 + 3 new − 1 counting file previously had none; exact number may differ — the point is zero failures). +```bash +git add src/counting.py tests/test_counting.py +git commit -m "fix: gate unloading on prior loading (FCP src/counting.py:168 parity)" +``` + +--- + +### Task 2: Count against the calibrated static zone by default + +**Files:** +- Modify: `app.py:128`, `app.py:260`, `app.py:284` (`request.form.get("zone_mode", "dynamic")` → `"fixed"`), `app.py:149-159` (fallback when no zone preset exists), `src/job.py:70`, `src/job.py:119` (dataclass defaults) +- Test: `tests/test_app.py` + +**Interfaces:** +- Consumes: `build_static_roi(zone, video_w, video_h) -> TruckROI`, `get_active_zone(path, preset)`. +- Produces: job field `zone_mode` now `"fixed"` by default; `zone_mode == "dynamic"` remains available as an explicit opt-in. + +FCP reference: FCP always counts against `static_roi` built from the hard-scaled calibration (`predict.py:715-724`, `:1037`, `:1066`) — there is no dynamic mode in production. + +**Why:** today the recounter defaults to `zone_mode="dynamic"`, so the count line is derived from the *detected truck bbox* (`src/pipeline.py:301-314`), i.e. a moving line. FCP counts against the calibrated line. Same clip, different geometry → different counts. + +- [ ] **Step 1: Write the failing test** — add to `tests/test_app.py`: + +```python +ZONE_JSON = { + "active_preset": "default", + "presets": {"default": { + "truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]], + "counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]], + "count_line": {"x_start": 577, "x_end": 1401, "y": 330}, + "reference_resolution": [1920, 1080], + }}, +} + + +def test_analyze_defaults_to_fixed_zone_mode(tmp_path, monkeypatch): + """POST /api/analyze without zone_mode uses the calibrated static zone.""" + import app as app_module + zones = tmp_path / "zones.json" + zones.write_text(json.dumps(ZONE_JSON)) + monkeypatch.setattr(app_module, "ZONES_PATH", str(zones)) + resp = client.post("/api/analyze", data={"fcp_mode": "C", "video": (buf, "clip.mp4")}) + assert resp.status_code == 202 + job = app_module.job_queue.get_job(resp.get_json()["job_id"]) + assert job.zone_mode == "fixed" + assert job.fixed_zone is not None + assert job.fixed_zone.fixed is True +``` + +`zones.json` shape is confirmed by `src/zone_config.get_active_zone` (`active_preset` + `presets` map, `src/zone_config.py:76-81`) and by the repo's own `zones.json`. `ZONES_PATH` is read inside the handlers at call time, so `monkeypatch.setattr(app_module, "ZONES_PATH", ...)` is enough. Reuse the `client` fixture that `tests/test_app.py` already defines. + +Add a second test asserting the documented fallback: + +```python +def test_analyze_falls_back_to_dynamic_without_zone_file(tmp_path, monkeypatch): + """No calibration on disk -> dynamic zone, job still accepted.""" + import app as app_module + monkeypatch.setattr(app_module, "ZONES_PATH", str(tmp_path / "missing.json")) + resp = client.post("/api/analyze", data={"fcp_mode": "C", "video": (buf, "clip.mp4")}) + assert resp.status_code == 202 + job = app_module.job_queue.get_job(resp.get_json()["job_id"]) + assert job.zone_mode == "dynamic" +``` + +- [ ] **Step 2: Run the test to verify it fails** + +Run: `python -m pytest tests/test_app.py -k zone_mode -v` +Expected: FAIL — current default is `"dynamic"`. + +- [ ] **Step 3: Flip the default and add the graceful fallback** + - `app.py:128`, `:260`, `:284`: `request.form.get("zone_mode", "dynamic")` → `request.form.get("zone_mode", "fixed")`. + - `src/job.py:70`, `:119`: `zone_mode: str = "dynamic"` → `zone_mode: str = "fixed"`. + - In `_save_and_queue` (`app.py:149-159`) and the reuse path (`app.py:284-296`): when `zone_mode == "fixed"` but no active zone is found, set `zone_mode = "dynamic"` so an uncalibrated deployment still runs. Add a one-line comment naming why. + +- [ ] **Step 4: Run the test to verify it passes** + +Run: `python -m pytest tests/test_app.py -v` → all pass. + +- [ ] **Step 5: Commit** + +```bash +git add app.py src/job.py tests/test_app.py +git commit -m "feat: count against calibrated static zone by default (FCP parity)" +``` + +**Note:** this changes published counts vs today (that is the point). Announce it in the PR/CHANGELOG. + +--- + +### Task 3: Filter detections by the calibrated counting polygon + +**Files:** +- Modify: `src/zone_config.py` (add `build_counting_polygon`) +- Modify: `src/pipeline.py` (apply the filter in `run_pipeline` and `run_merged_pipeline`) +- Test: `tests/test_zone_config.py`, `tests/test_pipeline.py` + +**Interfaces:** +- Produces: `build_counting_polygon(zone: dict, video_w: int, video_h: int) -> Polygon | None` — shapely `Polygon` of `zone["counting_area"]` scaled by `video_w/ref_w`, `video_h/ref_h` (same factors `build_static_roi` uses, `src/zone_config.py:34-56`); `None` when the zone has no `counting_area`. +- Pipeline parameter: `counting_polygon: Polygon | None = None` on `run_pipeline` and `run_merged_pipeline`. +- Job field: `Job.counting_polygon: Polygon | None = None` and `JobQueue.add_job(counting_polygon=...)` — the polygon is built once per job from the same zone dict as `build_static_roi` (`app.py:150-158`, `app.py:287-296`). + +FCP reference: `predict.py:939-942` (sacks) and `:931` (boxes) — keep a detection only when `detection_polygon.contains(Point(centroid))`, where centroid = `((x1+x2)/2, (y1+y3)/2)` of the bbox. + +- [ ] **Step 1: Write the failing tests** + +In `tests/test_zone_config.py`: +```python +def test_build_counting_polygon_scales_to_frame_size(): + zone = {"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]], + "reference_resolution": [1920, 1080]} + poly = build_counting_polygon(zone, 1280, 720) + assert poly is not None + assert poly.contains(Point(700, 400)) # inside after scaling + assert not poly.contains(Point(10, 10)) # outside +``` +In `tests/test_pipeline.py`: +```python +def test_pipeline_signature_accepts_counting_polygon(): + import inspect + from src.pipeline import run_pipeline, run_merged_pipeline + assert "counting_polygon" in inspect.signature(run_pipeline).parameters + assert "counting_polygon" in inspect.signature(run_merged_pipeline).parameters +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `python -m pytest tests/test_zone_config.py tests/test_pipeline.py -k polygon -v` +Expected: FAIL — `build_counting_polygon` does not exist; signature has no `counting_polygon`. + +- [ ] **Step 3: Implement** + - `src/zone_config.py`: add `build_counting_polygon(zone, video_w, video_h) -> Polygon | None` using `zone["counting_area"]` and the same `sx = video_w / ref_w`, `sy = video_h / ref_h` factors as `build_static_roi`; return `None` when the key is absent or has fewer than 3 points. + - `src/pipeline.py`: add the `counting_polygon: Polygon | None = None` parameter to both runners. In each runner, after the stabiliser/class-filter step and **before** the ROI X filter and `counter.update(...)`, drop detections whose centroid is outside the polygon: + `keep = counting_polygon.contains(Point((b[0]+b[2])/2.0, (b[1]+b[3])/2.0))` + Import `Point` from `shapely.geometry`. + - `src/job.py` / `app.py`: build the polygon from the same zone dict used for `build_static_roi` and pass it into the job (Task 2 already builds the zone dict at `app.py:150-158`). + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `python -m pytest tests/test_zone_config.py tests/test_pipeline.py -v` → all pass. + +- [ ] **Step 5: Commit** + +```bash +git add src/zone_config.py src/pipeline.py src/job.py app.py tests/test_zone_config.py tests/test_pipeline.py +git commit -m "feat: filter counts by calibrated counting polygon (FCP predict.py:939 parity)" +``` + +--- + +### Task 4: Align detection thresholds with FCP + +**Files:** +- Modify: `config.yaml` (`detection.sack_conf`, `min_bbox_area.box`) +- Test: `tests/test_config.py` + +**Interfaces:** +- Consumes: `load_config(path) -> dict` (`src/config.py:78`), `_scaled_min_areas(cfg, w, h)` (`src/pipeline.py:515`). +- Produces: no new API. + +FCP reference: `config.yaml:83-93` — `truck {conf 0.45, iou 0.7, min_bbox_area 5000}`, `sack {conf 0.30, iou 0.7, min_bbox_area 1500}`, `box {conf 0.35, iou 0.7, min_bbox_area 1000}`. The sack conf 0.30 carries the comment *"live gate used hardcode 0.50; 0.30 reduce undercounting"*. + +Note on inference conf: FCP runs the sack tracker at `dp_sack.conf = 0.30` and the box tracker at 0.35 (`predict.py:491`, `:504`). The recounter runs ONE shared tracker at `min(sack_conf, box_conf)` and then re-gates per class (`src/pipeline.py:212-214`, `:489-501`), so with `sack_conf = 0.30` the effective tracker conf becomes 0.30 and boxes are still gated at `box_conf = 0.35` — net effect matches FCP. No code change needed beyond the config value. + +- [ ] **Step 1: Write the failing test** — add to `tests/test_config.py`: + +```python +def test_detection_thresholds_match_fcp(): + cfg = load_config() + assert cfg["detection"]["sack_conf"] == 0.30 + assert cfg["detection"]["box_conf"] == 0.35 + assert cfg["detection"]["truck_conf"] == 0.45 + assert cfg["min_bbox_area"]["sack"] == 1500 + assert cfg["min_bbox_area"]["box"] == 1000 + assert cfg["min_bbox_area"]["truck"] == 5000 +``` + +- [ ] **Step 2: Run the test to verify it fails** + +Run: `python -m pytest tests/test_config.py -k fcp -v` +Expected: FAIL — `sack_conf` is 0.4 and `min_bbox_area.box` is 1500. + +- [ ] **Step 3: Edit `config.yaml`** + - `detection.sack_conf: 0.4` → `0.3` (add the FCP rationale as a trailing comment: *"FCP config.yaml:87 — reduce undercounting"*). + - `min_bbox_area.box: 1500` → `1000` (FCP `config.yaml:92`). + - Leave `sack: 1500`, `truck: 5000` unchanged. + +- [ ] **Step 4: Run the test to verify it passes** + +Run: `python -m pytest tests/test_config.py -v` → all pass. + +- [ ] **Step 5: Commit** + +```bash +git add config.yaml tests/test_config.py +git commit -m "chore: align detection thresholds with FCP (sack conf 0.30, box area 1000)" +``` + +--- + +### Task 5: Align the stabiliser hold with FCP + +**Files:** +- Modify: `config.yaml` (`stabilizer.max_hold`, and its stale comment) +- Test: `tests/test_config.py` + +**Interfaces:** none new. `src/pipeline.py:245-248` and `:627-630` already read `cfg["stabilizer"]["max_hold"]`. + +FCP reference: `predict.py:668` — `max_hold_frames=10` (the class default in `src/stabilizer.py:27` is 25; FCP overrides it to 10 at the call site). + +- [ ] **Step 1: Write the failing test** — add to `tests/test_config.py`: + +```python +def test_stabilizer_hold_matches_fcp(): + cfg = load_config() + assert cfg["stabilizer"]["ema_alpha"] == 0.35 + assert cfg["stabilizer"]["max_hold"] == 10 +``` + +- [ ] **Step 2: Run the test to verify it fails** + +Run: `python -m pytest tests/test_config.py -k stabilizer -v` +Expected: FAIL — `max_hold` is 25. + +- [ ] **Step 3: Edit `config.yaml`** + - `stabilizer.max_hold: 25` → `10`. + - Replace the comment `platform parity: 25 = ~1s @25fps` with `FCP parity: predict.py:668 (max_hold_frames=10)`. + +- [ ] **Step 4: Run the test to verify it passes** + +Run: `python -m pytest tests/test_config.py -v` → all pass. + +- [ ] **Step 5: Commit** + +```bash +git add config.yaml tests/test_config.py +git commit -m "chore: align stabilizer max_hold with FCP (10 frames)" +``` + +--- + +### Task 6: Drive the batch FSM with real crossing events + +**Files:** +- Modify: `src/pipeline.py` (both runners) +- Modify: `src/zone_config.py` (add `build_truck_polygon`) +- Test: `tests/test_batch.py` (create), `tests/test_pipeline.py` + +**Interfaces:** +- Consumes: `BatchLifecycleManager.update_sacks(has_crossing_event, sacks_in_area_count, timestamp, loading_count, unloading_count)` (`src/batch.py:199`), `update_truck(truck_detected, truck_centroid, timestamp)` (`src/batch.py:120`). +- Produces: `build_truck_polygon(zone: dict, video_w: int, video_h: int) -> Polygon | None`; `compute_sacks_in_truck_area(detections: list[Detection], truck_polygon: Polygon, cutoff_ratio: float = 0.15) -> int`. + +FCP reference: `predict.py:1064-1085` — `has_crossing = len(events) > 0`; `sacks_in_truck_area` counts stable detections whose centroid is inside the truck polygon AND `cy >= truck_polygon_top + 0.15 * truck_height` (`predict.py:946-958`); then `batch_mgr.update_sacks(has_crossing_event=has_crossing, sacks_in_area_count=sacks_in_truck_area, ...)`. + +**Why:** the recounter's legacy `batch_mgr.update(...)` (`src/batch.py:263-281`) hardcodes `has_crossing_event=False` and passes `sacks_in_area_count=1 if truck_detected else 0`. So `_last_sack_crossing_time` is never set, the 10 s idle timeout fires on wall-clock alone, and `_pending_loading/_pending_unloading` (the values written into the final batch record) freeze at the 30 s `min_batch_duration` mark (`src/batch.py:248-259`). + +- [ ] **Step 1: Write the failing tests** — create `tests/test_batch.py`: + +```python +"""Batch lifecycle tests — FCP batch-FSM parity.""" + +from src.batch import BatchLifecycleManager +from src.interfaces import Detection +from src.pipeline import compute_sacks_in_truck_area, update_batch_state +from shapely.geometry import Polygon + + +def _counting_manager() -> BatchLifecycleManager: + """Manager already in COUNTING_SACKS (stabilize_seconds=0 to skip the ramp).""" + m = BatchLifecycleManager(stabilize_seconds=0.0) + m.update_truck(True, (100.0, 100.0), 1000.0) + assert m.state == "COUNTING_SACKS" + return m + + +class _RecordingManager(BatchLifecycleManager): + """Batch manager that records the arguments it was driven with.""" + + def __init__(self) -> None: + super().__init__(stabilize_seconds=0.0) + self.sacks_calls: list[dict] = [] + + def update_sacks(self, has_crossing_event, sacks_in_area_count, timestamp, + loading_count=0, unloading_count=0): + self.sacks_calls.append({ + "has_crossing_event": has_crossing_event, + "sacks_in_area_count": sacks_in_area_count, + "loading_count": loading_count, + "unloading_count": unloading_count, + }) + super().update_sacks(has_crossing_event, sacks_in_area_count, timestamp, + loading_count, unloading_count) + + +def test_update_batch_state_passes_real_crossing_flag(): + """A crossing event reaches the manager as has_crossing_event=True.""" + m = _RecordingManager() + update_batch_state(m, events=[{"direction": "loading"}], tracked_sacks=[], + truck_polygon=None, timestamp=1000.0, + loading_count=1, unloading_count=0) + assert m.sacks_calls[-1]["has_crossing_event"] is True + + +def test_update_batch_state_counts_sacks_in_truck_area(): + """sacks_in_area_count comes from the truck polygon, not from truck presence.""" + poly = Polygon([(0, 0), (100, 0), (100, 100), (0, 100)]) + dets = [Detection(bbox=(10.0, 80.0, 20.0, 95.0), confidence=0.9, + class_id=0, class_name="sack", track_id=1)] + m = _RecordingManager() + update_batch_state(m, events=[], tracked_sacks=dets, truck_polygon=poly, + timestamp=1000.0, loading_count=0, unloading_count=0) + assert m.sacks_calls[-1]["sacks_in_area_count"] == 1 + + +def test_compute_sacks_in_truck_area_applies_bottom_cutoff(): + """Only the bottom 85% of the truck area counts (FCP predict.py:950-958).""" + poly = Polygon([(0, 0), (100, 0), (100, 100), (0, 100)]) + top = [Detection(bbox=(10.0, 5.0, 20.0, 20.0), confidence=0.9, + class_id=0, class_name="sack", track_id=1)] + bottom = [Detection(bbox=(10.0, 80.0, 20.0, 95.0), confidence=0.9, + class_id=0, class_name="sack", track_id=2)] + assert compute_sacks_in_truck_area(top, poly) == 0 + assert compute_sacks_in_truck_area(bottom, poly) == 1 + + +def test_idle_timeout_without_activity_enters_waiting(): + """No crossing and no sack in area for sack_idle_timeout -> WAITING.""" + m = _counting_manager() + m.update_sacks(False, 0, 1001.0, 1, 0) + m.update_sacks(False, 0, 1045.0, 1, 0) # 45s after batch start + assert m.state == "WAITING_FOR_ACTIVITY" + + +def test_pending_counts_follow_latest_crossing(): + """_pending_loading tracks the newest count, not a frozen snapshot.""" + m = _counting_manager() + m.update_sacks(True, 1, 1001.0, 7, 2) + assert m._pending_loading == 7 + assert m._pending_unloading == 2 +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `python -m pytest tests/test_batch.py -v` +Expected: FAIL — `src.pipeline` has no `compute_sacks_in_truck_area` / `update_batch_state` (ImportError at collection). + +- [ ] **Step 3: Implement** + - `src/zone_config.py`: add `build_truck_polygon(zone, video_w, video_h) -> Polygon | None` (same scaling as `build_static_roi`, polygon from `zone["truck_area"]`). + - `src/pipeline.py`: add + `compute_sacks_in_truck_area(detections: list[Detection], truck_polygon: Polygon, cutoff_ratio: float = 0.15) -> int` — count detections whose centroid is inside `truck_polygon` AND whose centroid Y is `>= min_y + cutoff_ratio * (max_y - min_y)` (FCP `predict.py:950-958`). + - `src/pipeline.py`: add + `update_batch_state(batch_mgr: BatchLifecycleManager, *, events: list[dict], tracked_sacks: list[Detection], truck_polygon: Polygon | None, timestamp: float, loading_count: int, unloading_count: int) -> None` — the single seam the runners call each frame. It must call `batch_mgr.update_sacks(has_crossing_event=bool(events), sacks_in_area_count=compute_sacks_in_truck_area(tracked_sacks, truck_polygon) if truck_polygon is not None else 0, timestamp=timestamp, loading_count=loading_count, unloading_count=unloading_count)` when the batch is counting or waiting, and `batch_mgr.update_truck(...)` otherwise. + - In both runners: capture the events returned by `counter.update(...)` (currently discarded at `src/pipeline.py:350` and `:756`); call `update_batch_state(...)` **every frame**; stop using the legacy `batch_mgr.update(...)` wrapper in the pipeline (`src/batch.py:263-281`). + - Wire `truck_polygon` from the job (same zone dict as Task 2/3) into both runners: add `Job.truck_polygon: Polygon | None = None` and `JobQueue.add_job(truck_polygon=...)`. + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `python -m pytest tests/test_batch.py tests/test_pipeline.py -v` → all pass. + +- [ ] **Step 5: Commit** + +```bash +git add src/pipeline.py src/zone_config.py src/job.py tests/test_batch.py tests/test_pipeline.py +git commit -m "fix: drive batch FSM with real crossing events (FCP predict.py:1064 parity)" +``` + +--- + +### Task 7: Reset per-track counting state at each batch start + +**Files:** +- Modify: `src/counting.py` (`LineCrossCounter.reset_state()`), `src/pipeline.py` (register the batch-start hook) +- Test: `tests/test_counting.py` + +**Interfaces:** +- Produces: `LineCrossCounter.reset_state() -> None` — clears `_state`, `_has_been_above`, `_has_been_below`, `_counted`, `_loaded_tracks` but **keeps** `loading_count` / `unloading_count` totals. + +FCP reference: `predict.py:1020-1032` and `:1148-1150` call `counter.reset()`, `stabilizer.reset()`, `box_stabilizer.reset()` when a batch starts. + +**Why not a plain `reset()`:** the recounter reports ONE cumulative count per clip/job. FCP writes one DB row per batch, so resetting its totals is harmless there; here it would drop the earlier truck sessions' counts. `reset_state()` gives the per-batch isolation FCP wants while keeping the clip-level total. Mark the ceiling with a `ponytail:` comment naming the upgrade path (per-batch result rows). + +- [ ] **Step 1: Write the failing test** — add to `tests/test_counting.py`: + +```python +def test_reset_state_keeps_totals_but_clears_track_state(): + """reset_state() clears dedup state but keeps the clip totals.""" + c = LineCrossCounter(line_y=100, line_x_start=0, line_x_end=1000) + c.update([_det(4, 10)]) + c.update([_det(4, 200)]) + assert c.loading_count == 1 + c.reset_state() + assert c.loading_count == 1 # totals survive + assert c.unloading_count == 0 + assert c._loaded_tracks == set() # per-track state cleared + # the same track may cross again in the next batch + assert [e["direction"] for e in c.update([_det(4, 10)])] == [] + assert [e["direction"] for e in c.update([_det(4, 200)])] == ["loading"] +``` + +- [ ] **Step 2: Run the test to verify it fails** + +Run: `python -m pytest tests/test_counting.py -k reset_state -v` +Expected: FAIL — `AttributeError: 'LineCrossCounter' object has no attribute 'reset_state'`. + +- [ ] **Step 3: Implement** + - `src/counting.py`: add `reset_state()` clearing the per-track dicts/sets only; keep `reset()` (full reset) unchanged for its existing callers. + - `src/pipeline.py`: in both runners, register `batch_mgr.on_batch_start(callback)` where the callback calls `counter.reset_state()` and `stabilizer.reset()`. + +- [ ] **Step 4: Run the test to verify it passes** + +Run: `python -m pytest tests/test_counting.py -v` → all pass. + +- [ ] **Step 5: Commit** + +```bash +git add src/counting.py src/pipeline.py tests/test_counting.py +git commit -m "fix: reset per-track counting state at batch start (FCP predict.py:1020 parity)" +``` + +--- + +### Task 8: Match FCP's truck-detection cadence + +**Files:** +- Modify: `config.yaml` (`pipeline.truck_det_interval`) +- Test: `tests/test_config.py` + +FCP reference: the separate truck model runs every 5th frame (`predict.py:882`); the recounter uses 15 (`config.yaml`, `src/pipeline.py:193`, `:305`). + +**Why:** the truck ROI (and therefore the truck-present signal that opens/closes a batch) refreshes 3× slower than FCP, which delays batch start and end. + +- [ ] **Step 1: Write the failing test** — add to `tests/test_config.py`: + +```python +def test_truck_det_interval_matches_fcp(): + assert load_config()["pipeline"]["truck_det_interval"] == 5 +``` + +- [ ] **Step 2: Run the test to verify it fails** + +Run: `python -m pytest tests/test_config.py -k truck_det -v` +Expected: FAIL — value is 15. + +- [ ] **Step 3: Edit `config.yaml`**: `pipeline.truck_det_interval: 15` → `5` (add comment *"FCP predict.py:882 — truck model every 5th frame"*). + +- [ ] **Step 4: Run the test to verify it passes** + +Run: `python -m pytest tests/test_config.py -v` → all pass. + +- [ ] **Step 5: Commit** + +```bash +git add config.yaml tests/test_config.py +git commit -m "chore: match FCP truck detection cadence (every 5 frames)" +``` + +--- + +### Task 9: Fail fast on invalid configuration + +**Files:** +- Create: `src/validation.py` +- Modify: `src/config.py:78-91` (`load_config`) +- Test: `tests/test_validation.py` (create), `tests/test_config.py` + +**Interfaces:** +- Produces: + - `class ValidationError(Exception)` + - `validate_config(cfg: dict) -> None` — raises `ValidationError` on invalid values. + - `InputValidator.validate_model_path(path: str) -> bool`, `InputValidator.validate_video_source(source: str) -> bool` — mirrors FCP `src/validation.py`. + +FCP reference: `src/config_loader.py:513-537` (`validate_config`: empty modes, `active_mode` not in modes, mode engine path missing from `models.paths`, `conf`/`iou` outside `(0, 1]`, negative `min_bbox_area`) and `src/validation.py` (`InputValidator`, `VALID_MODEL_EXTENSIONS`, `VALID_VIDEO_EXTENSIONS`, `URL_PATTERN`). + +- [ ] **Step 1: Write the failing tests** — create `tests/test_validation.py`: + +```python +"""Config / input validation — FCP src/validation.py parity.""" + +import pytest +from src.validation import ValidationError, validate_config + + +def test_validate_config_accepts_current_config(): + from src.config import load_config + validate_config(load_config()) # must not raise + + +def test_validate_config_rejects_out_of_range_conf(): + with pytest.raises(ValidationError): + validate_config({"detection": {"sack_conf": 1.5, "box_conf": 0.35, "truck_conf": 0.45}, + "iou": {"dedup": 0.5, "suppress_sack_box": 0.4, "synthetic": 0.3, "sticky_truck": 0.3}}) + + +def test_validate_config_rejects_non_positive_iou(): + with pytest.raises(ValidationError): + validate_config({"detection": {"sack_conf": 0.3, "box_conf": 0.35, "truck_conf": 0.45}, + "iou": {"dedup": 0.0, "suppress_sack_box": 0.4, "synthetic": 0.3, "sticky_truck": 0.3}}) + + +def test_validate_config_rejects_negative_min_bbox_area(): + with pytest.raises(ValidationError): + validate_config({"detection": {"sack_conf": 0.3, "box_conf": 0.35, "truck_conf": 0.45}, + "iou": {"dedup": 0.5, "suppress_sack_box": 0.4, "synthetic": 0.3, "sticky_truck": 0.3}, + "min_bbox_area": {"sack": -1}}) +``` + +Add to `tests/test_config.py`: +```python +def test_load_config_raises_on_broken_yaml(tmp_path): + bad = tmp_path / "config.yaml" + bad.write_text("detection: [unclosed\n") + with pytest.raises(Exception): + load_config(str(bad)) +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `python -m pytest tests/test_validation.py tests/test_config.py -v` +Expected: FAIL — `src.validation` does not exist; `load_config` silently returns DEFAULTS for broken YAML. + +- [ ] **Step 3: Implement** + - `src/validation.py`: create `ValidationError`, `InputValidator` (model path + video source checks mirroring FCP), and `validate_config(cfg)` checking: every `detection.*_conf` in `(0, 1]`; every `iou.*` in `(0, 1]`; every `min_bbox_area.*` `>= 0`; `detector.sack_conf`/`box_conf`/`truck_conf` present. Raise `ValidationError` with the offending key and value in the message. + - `src/config.py`: in `load_config`, a `yaml.YAMLError` must **raise** (wrap as `ValidationError`) instead of returning DEFAULTS; a missing file may still fall back to DEFAULTS (a fresh checkout has no config.yaml). After merging, call `validate_config(cfg)`. + - Keep the DEFAULTS-fallback only for the missing-file case; document it in the docstring. + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `python -m pytest tests/test_validation.py tests/test_config.py -v` → all pass. Then `python -m pytest tests/ -q` → zero failures. + +- [ ] **Step 5: Commit** + +```bash +git add src/validation.py src/config.py tests/test_validation.py tests/test_config.py +git commit -m "feat: fail fast on invalid config (FCP src/validation.py parity)" +``` + +--- + +### Task 10: Flag truncated clips instead of reporting partial counts as complete + +**Files:** +- Modify: `src/pipeline.py` (frame accounting), `src/job.py:27-42` (`JobResult`), `app.py:548-560` (job response) +- Test: `tests/test_job.py`, `tests/test_pipeline.py` + +**Interfaces:** +- Produces: + - `is_truncated(expected_frames: int, frames_read: int) -> bool` in `src/pipeline.py` — `True` when `expected_frames > 0 and frames_read < expected_frames * 0.98`. + - `JobResult.truncated: bool = False`, `JobResult.frames_expected: int = 0`. + +**Why (not FCP parity — a file-source necessity):** FCP's `_RtspHealth` freeze/drop monitor (`predict.py:365-427`) protects the live stream; FCP's *file* path has the same silent `break` on `cap.read()` failure (`predict.py:820-823`) but nobody noticed because the live path is the product. The recounter has no stream at all — every input is a file, so an upload that was cut short (bad transcode, partial copy) silently produces a count for the first N% of the clip and reports it as a complete count. FCP's own advice ("verify manual count", `predict.py:426`) becomes a machine-checkable flag here. + +- [ ] **Step 1: Write the failing tests** — add to `tests/test_pipeline.py`: + +```python +def test_is_truncated_detects_short_decode(): + from src.pipeline import is_truncated + assert is_truncated(100, 100) is False + assert is_truncated(100, 99) is False + assert is_truncated(100, 40) is True + assert is_truncated(0, 10) is False # unknown length -> not truncated +``` + +Add to `tests/test_job.py`: +```python +def test_job_result_exposes_truncation(): + r = JobResult(model_name="m", output_path="", loading_count=1, unloading_count=0, + net_count=1, batch_count=1, frame_count=40, duration_seconds=1.0, + truncated=True, frames_expected=100) + assert r.truncated is True + assert r.frames_expected == 100 +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `python -m pytest tests/test_pipeline.py tests/test_job.py -k "truncat" -v` +Expected: FAIL — `is_truncated` missing; `JobResult` has no `truncated` field. + +- [ ] **Step 3: Implement** + - `src/pipeline.py`: add `is_truncated(expected_frames: int, frames_read: int) -> bool`; in both runners read `expected = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))` right after opening the capture (before the loop), track `frames_read`, and set `truncated = is_truncated(expected, frames_read)` on the result. Propagate `frames_expected=expected` and `truncated` into `PipelineResult` / `MergedPipelineResult`. + - `src/job.py`: add the two fields to `JobResult` and pass them at both construction sites (`src/job.py:260`, `:311`). + - `app.py:548-560`: add `"truncated": r.truncated` and `"frames_expected": r.frames_expected` to each result dict. + +- [ ] **Step 4: Run the tests to verify they passes** + +Run: `python -m pytest tests/test_job.py tests/test_pipeline.py -v` → all pass. Then `python -m pytest tests/ -q` → zero failures. + +- [ ] **Step 5: Commit** + +```bash +git add src/pipeline.py src/job.py app.py tests/test_job.py tests/test_pipeline.py +git commit -m "feat: flag truncated clips in the job result" +``` + +--- + +## Out of Scope (deliberately not ported) + +| FCP feature | Why not | +|---|---| +| `RTSPStreamReader`, reconnect, `_RtspHealth` (`predict.py:365-427`, `src/pipeline.py:16-77`) | Stream-only. The recounter is file-based by design. | +| SQLite persistence, `daily_summaries`, `batch_summary.csv` (`src/persistence.py:226-374`) | Platform infrastructure, not counting logic. Counts reach the FCP database through the FCP-side recount button (see `docs/ai-handoff-fcp-recount.md`), not from this service. | +| XLSX export with `manual_sack`/`manual_box` + Accuracy % table (`counter_dashboard.py:2120-2172`, commit `0e5c70e`) | Same reason: manual-vs-AI accuracy belongs to the FCP dashboard, which owns the manual counts. | +| Delivery-Order photo upload, DO→batch attach (`src/persistence.py:337-343`) | FCP-only workflow. | +| `set_counts()` / `resume_batch()` restore-after-restart (FCP `src/counting.py` `set_counts`; this repo's `src/batch.py:350`) | The recounter is request-scoped and stateless between jobs; nothing to resume. | +| Load `.pt` before `.engine` (`predict.py:481-489`) | Speculative for us: the recounter already runs `.engine` models fine on the same Jetson. Revisit only if a TensorRT load ever fails on `.93`. | +| `counting.confirm_delay_sec` / `exit_confirm_delay_sec` / `debounce_frames` / re-ID distance keys | Dead in FCP too — parsed, never read (`src/config_loader.py:637-662`). Porting them would add config with no behaviour. | +| Cross-class IoU boundary: FCP keeps a sack when IoU `< 0.4` (`predict.py:946-948`), the recounter drops it only when IoU `> 0.4` (`src/pipeline.py:486`) | Differs at exactly IoU 0.400 — a measure-zero case with no measurable count effect. One-character fix if it ever shows up in a clip diff. | + +--- + +## Verification + +1. **Unit suite**: `python -m pytest tests/ -q` → zero failures (baseline was 195 passed; new tests added in Tasks 1, 3, 4, 5, 6, 7, 8, 9, 10). +2. **Calibration equality** (static geometry must match FCP exactly): + ```bash + python - <<'PY' + from src.zone_config import build_static_roi, build_counting_polygon + zone = {"truck_area": [[600,385],[609,1076],[1404,1078],[1381,343]], + "count_line": {"x_start":577,"x_end":1401,"y":330}, + "counting_area": [[574,50],[586,1077],[1418,1076],[1397,50]], + "reference_resolution": [1920,1080]} + roi = build_static_roi(zone, 1280, 720) + print(roi.line_y, roi.line_x_start, roi.line_x_end, roi.x1, roi.x2) + PY + ``` + Expected: `220 384 934 400 936` — identical to FCP `predict.py:701-719`. +3. **Cross-check against FCP on one real clip** (read-only w.r.t. the FCP repo): + ```bash + rm -rf /tmp/fcp-parity && cp -r ../karung_counter_semarang /tmp/fcp-parity + # run FCP on the clip (file source, not RTSP) from the copy + (cd /tmp/fcp-parity && python predict.py ...) + # run the recounter on the same clip + curl -F "fcp_mode=C" -F "video=@" http://127.0.0.1:9050/api/analyze + ``` + Expected: `loading_count` / `unloading_count` agree, or differ by at most the documented platform-only differences (FCP counts a live session per truck batch; the recounter counts the whole clip). Record the actual delta in the PR description. +4. **Manual spot check**: play the annotated output of one clip and confirm the counted sacks are exactly the ones that crossed the calibrated line inside the counting polygon.