fix: review pass — atomic busy-guard, exact FCP mode filters, docs

- _ANALYZE_LOCK: busy-check through enqueue is atomic; overlapping
  POSTs can no longer both pass the busy guard (one-GPU contract)
- fcp.mode_models now {letter: {stem: engine_classes}} mirroring FCP
  models.modes engines[].classes exactly: B/D use v4-best truck-only
  role (not truck-detector), C filters yolo11n to box only — prevents
  sack double-count and truck-ROI divergence vs FCP batches
- CHANGELOG: document /api/analyze + stem filter fix
- handoff doc: correct precedence (fcp_mode wins over model_stems),
  correct B/D mapping note
- tests: 4 new (mode B/C/D filters, concurrent-submit race) — 195 pass
This commit is contained in:
jetson committed 2026-10-20 11:34:34 +07:00
1 parent ca0583b734
commit 371e9593d8
6 files changed
+210 -56

No files matched your search

+19
View File
@@ -6,12 +6,31 @@ version tags are cut in this repo — `main` is the release line).
## [Unreleased]
### Added
- **`POST /api/analyze` machine endpoint** (`540e1b5`): multipart video +
`fcp_mode` letter (A–D) or explicit `model_stems`; returns
**202** `{"job_id","status_url"}`; **409 busy** guard when any job is
pending/running (one GPU, atomic check+enqueue under submit lock);
optional `X-API-Key` auth iff env `RECOUNTER_API_KEY` set; all errors
JSON. For FCP → recounter clip repush (phase 1 of cross-service
recount; FCP sender still TODO, see `docs/ai-handoff-fcp-recount.md`).
- `config.yaml → fcp.mode_models`: FCP model-mode letter →
`{stem: engine_classes}`, mirroring platform `models.modes
engines[].classes` exactly (B/D use v4-best truck-only role, not
truck-detector weights).
- `docs/ai-handoff-fcp-recount.md`: AI handoff for the FCP-side phase 2.
- `ERD.md` (Mermaid ERD) + this changelog (`97507f8`).
### Fixed
- **Upload 500 on new video + start analysis**: `/upload` referenced
`video_path` in `probe_video(video_path)` before the variable was defined
(`NameError` → Flask 500). Removed the duplicate premature height-check
block; post-save `resize_video_to_max_height()` (720p) already covers it
(`app.py:120-125`, `b1dd06e`).
- **Single-model class filters silently dropped** (`src/job.py`): worker
looked filters up by `ModelConfig.filename` while UI/API store them by
`stem` — `filter_<stem>` now honored on single-model jobs (stem-first,
filename fallback for legacy callers).
### Changed
- **Counting/tracking params mirrored from platform** (`karung_counter_semarang`):
+53 -36
View File
@@ -170,31 +170,47 @@ def _save_and_queue(video, model_configs, class_filters,
def _resolve_fcp_mode(mode: str):
"""Map an FCP model-mode letter to ModelConfigs via config.yaml fcp.mode_models.
"""Map an FCP model-mode letter to (ModelConfigs, class_filters).
Returns (model_configs, error). error is None on success; model_configs
is None when the letter is unknown or a mapped stem is missing on disk.
Reads config.yaml fcp.mode_models: {letter: {stem: [engine classes]}}
mirroring FCP models.modes engines[].classes. Returns
(model_configs, class_filters, error); error is None on success,
(None, None, msg) when the letter is unknown or a stem is missing.
"""
from src.config import load_config
mode = (mode or "").strip().upper()
mapping = (load_config().get("fcp") or {}).get("mode_models") or {}
stems = mapping.get(mode)
if not stems:
return None, f"unknown fcp_mode: {mode!r} (valid: {', '.join(sorted(mapping))})"
stem_classes = mapping.get(mode)
if not stem_classes:
return None, None, (
f"unknown fcp_mode: {mode!r} (valid: {', '.join(sorted(mapping))})"
)
groups = {g.stem: g for g in scan_model_groups(MODELS_DIR)}
configs = []
for stem in stems:
class_filters: dict = {}
for stem, classes in stem_classes.items():
group = groups.get(stem)
if group is None:
return None, f"fcp_mode {mode!r} maps to stem {stem!r} not found under {MODELS_DIR}"
return None, None, (
f"fcp_mode {mode!r} maps to stem {stem!r} not found under {MODELS_DIR}"
)
configs.append(ModelConfig(
filename=os.path.basename(group.format_paths[group.default_format]),
path=group.format_paths[group.default_format],
stem=stem,
known_classes=list(group.known_classes),
))
return configs, None
if isinstance(classes, list) and classes:
class_filters[stem] = [str(c) for c in classes]
return configs, class_filters, None
# Serializes API submits: busy-check → save/transcode → enqueue is one
# atomic section so overlapping POSTs can't both pass the busy guard and
# double-book the GPU. Ponytail: per-process lock, fine with gunicorn-less
# single-threaded app.run; add a cross-process lock only if multi-worker.
_ANALYZE_LOCK = threading.Lock()
@app.route("/api/analyze", methods=["POST"])
@@ -216,35 +232,36 @@ def api_analyze():
if not safe_name or not safe_name.lower().endswith(VIDEO_EXTENSIONS):
return jsonify({"error": "Invalid video file type"}), 400
active = [
{"job_id": j.job_id, "status": j.status.name}
for j in job_queue.list_jobs()
if j.status.name in ("PENDING", "RUNNING")
]
if active:
return jsonify({"error": "busy", "active": active}), 409
fcp_mode = request.form.get("fcp_mode", "")
if fcp_mode:
model_configs, err = _resolve_fcp_mode(fcp_mode)
if err:
return jsonify({"error": err}), 400
class_filters: dict = {}
else:
model_configs, class_filters = _parse_model_configs(request.form)
if not model_configs:
return jsonify({
"error": "No models selected (send fcp_mode or model_stems)",
}), 400
job = _save_and_queue(
video, model_configs, class_filters,
request.form.get("output_height", ""),
request.form.get("zone_mode", "dynamic"),
request.form.get("zone_preset", ""),
)
return jsonify({"job_id": job.job_id,
"status_url": f"/api/jobs/{job.job_id}"}), 202
with _ANALYZE_LOCK:
active = [
{"job_id": j.job_id, "status": j.status.name}
for j in job_queue.list_jobs()
if j.status.name in ("PENDING", "RUNNING")
]
if active:
return jsonify({"error": "busy", "active": active}), 409
if fcp_mode:
model_configs, class_filters, err = _resolve_fcp_mode(fcp_mode)
if err:
return jsonify({"error": err}), 400
else:
model_configs, class_filters = _parse_model_configs(request.form)
if not model_configs:
return jsonify({
"error": "No models selected (send fcp_mode or model_stems)",
}), 400
job = _save_and_queue(
video, model_configs, class_filters,
request.form.get("output_height", ""),
request.form.get("zone_mode", "dynamic"),
request.form.get("zone_preset", ""),
)
return jsonify({"job_id": job.job_id,
"status_url": f"/api/jobs/{job.job_id}"}), 202
@app.route("/upload/reuse", methods=["POST"])
+16 -7
View File
@@ -37,11 +37,20 @@ pipeline:
preview_every_n: 5 # preview JPEG every N frames
fcp:
# FCP model-mode letter -> recounter model stems, for POST /api/analyze
# (mirrors karung_counter_semarang config.yaml models.modes semantics;
# C = platform's current active_mode).
# FCP model-mode letter -> {model stem: engine-contributed classes}, for
# POST /api/analyze. Mirrors karung_counter_semarang config.yaml
# models.modes engines[].classes exactly (v4-best serves the truck-only
# role in B/D — NOT the truck-detector weights). C = active_mode.
mode_models:
A: [v4-best]
B: [truck-detector, "yolo11n-bbox-100ep-sack+box-20260909-best"]
C: [v4-best, "yolo11n-bbox-100ep-sack+box-20260909-best"]
D: [truck-detector, best, "yolo11n-bbox-100ep-sack+box-20260909-best"]
A:
v4-best: [truck, sack]
B:
v4-best: [truck]
"yolo11n-bbox-100ep-sack+box-20260909-best": [sack, box]
C:
v4-best: [truck, sack]
"yolo11n-bbox-100ep-sack+box-20260909-best": [box]
D:
v4-best: [truck]
best: [sack]
"yolo11n-bbox-100ep-sack+box-20260909-best": [box]
+15 -6
View File
@@ -34,9 +34,17 @@ curl -X POST http://localhost:9050/api/analyze \
set on the recounter process. Unset = open (current default in
`start_dashboard.sh` — set it before exposing beyond LAN).
- **`fcp_mode`** = FCP model-mode letter `A|B|C|D`, mapped server-side via
recounter `config.yaml → fcp.mode_models` (mirrors FCP `models.modes`;
`C` = FCP's current `active_mode`). Explicit `model_stems` (multipart,
repeatable) + `format_<stem>`/`filter_<stem>` still work as override.
recounter `config.yaml → fcp.mode_models` — a mapping of
`{letter: {stem: engine_classes}}` that mirrors FCP `models.modes`
`engines[].classes` **exactly** (verified against FCP config 2026-10-20;
note FCP B/D use **v4-best in the truck-only role**, NOT the
`truck-detector` weights, and mode letters set per-stem class filters
e.g. C: `v4-best:[truck,sack]`, `yolo11n…:[box]`). `C` = FCP's current
`active_mode`.
- **Field precedence:** if both `fcp_mode` and `model_stems` are sent,
**`fcp_mode` wins and `model_stems` is ignored**. Use `model_stems`
(multipart, repeatable) + `format_<stem>`/`filter_<stem>` only when
`fcp_mode` is absent (manual/custom selection).
- **Busy policy:** 409 not a queue. Caller retries. One job at a time =
one GPU.
- **Results:** poll `status_url` → `{"status":"COMPLETED","results":[
@@ -154,9 +162,10 @@ and retry poll after a few seconds; do not auto-loop >3 retries.
| FCP mode endpoint | `GET /api/model-modes` (fresh-read active_mode) |
| Mode → engines detail | FCP `config.yaml models.modes` (C = combined v4-best + box model) |
**Model stem parity confirmed:** recounter `models/` has the same weight
stems FCP modes reference (`v4-best`, `truck-detector`, `best`,
`yolo11n-bbox-100ep-sack+box-20260909-best`).
**Model stem parity confirmed:** recounter `models/` has the weight stems
FCP mode presets use (`v4-best`, `best`, `yolo11n-bbox-100ep-sack+box-20260909-best`;
FCP defines `truck-detector` path but **no mode uses it** — B/D give
truck duty to v4-best, engine `classes` act as the per-stem filter).
## 6. Known limitations / deferred
+11 -6
View File
@@ -47,13 +47,18 @@ DEFAULTS: dict = {
"preview_every_n": 5,
},
"fcp": {
# FCP model-mode letter -> recounter model stems (mirrors
# karung_counter_semarang config.yaml models.modes semantics).
# FCP model-mode letter -> {model stem: engine-contributed classes}
# (mirrors karung_counter_semarang config.yaml models.modes
# engines[].classes exactly; C = platform's active_mode).
"mode_models": {
"A": ["v4-best"],
"B": ["truck-detector", "yolo11n-bbox-100ep-sack+box-20260909-best"],
"C": ["v4-best", "yolo11n-bbox-100ep-sack+box-20260909-best"],
"D": ["truck-detector", "best", "yolo11n-bbox-100ep-sack+box-20260909-best"],
"A": {"v4-best": ["truck", "sack"]},
"B": {"v4-best": ["truck"],
"yolo11n-bbox-100ep-sack+box-20260909-best": ["sack", "box"]},
"C": {"v4-best": ["truck", "sack"],
"yolo11n-bbox-100ep-sack+box-20260909-best": ["box"]},
"D": {"v4-best": ["truck"],
"best": ["sack"],
"yolo11n-bbox-100ep-sack+box-20260909-best": ["box"]},
},
},
}
+96 -1
View File
@@ -117,7 +117,8 @@ def test_analyze_fcp_mode_a_single_model(client, stub_queue):
assert stems == ["v4-best"]
def test_analyze_explicit_stems_override_mode(client, stub_queue):
def test_analyze_explicit_stems_alternative_to_fcp_mode(client, stub_queue):
"""model_stems path used when fcp_mode absent (fcp_mode wins if both sent)."""
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
"model_stems": ["best"],
@@ -251,3 +252,97 @@ def test_single_model_job_filter_looked_up_by_stem(monkeypatch):
job.status = JobStatus.CANCELLED # keep worker from re-running
assert captured["class_filter"] == ["sack", "box"]
# ── review fixes: per-mode class filters mirroring FCP engines ─────────
def test_fcp_mode_b_filters_mirror_fcp_engines(client, stub_queue):
"""FCP B = v4-best truck-only + yolo11n sack+box (engine classes)."""
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
"fcp_mode": "B",
})
assert resp.status_code == 202
assert stub_queue[0]["class_filters"] == {
"v4-best": ["truck"],
"yolo11n-bbox-100ep-sack+box-20260909-best": ["sack", "box"],
}
def test_fcp_mode_c_filters_mirror_fcp_engines(client, stub_queue):
"""FCP C = v4-best truck+sack, yolo11n box-only (no sack double count)."""
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
"fcp_mode": "C",
})
assert resp.status_code == 202
assert stub_queue[0]["class_filters"] == {
"v4-best": ["truck", "sack"],
"yolo11n-bbox-100ep-sack+box-20260909-best": ["box"],
}
def test_fcp_mode_d_three_engines(client, stub_queue):
resp = _post(client, data={
"video": (io.BytesIO(b"x"), "clip.mp4"),
"fcp_mode": "D",
})
assert resp.status_code == 202
stems = [c.stem for c in stub_queue[0]["model_configs"]]
assert stems == ["v4-best", "best", "yolo11n-bbox-100ep-sack+box-20260909-best"]
assert stub_queue[0]["class_filters"] == {
"v4-best": ["truck"],
"best": ["sack"],
"yolo11n-bbox-100ep-sack+box-20260909-best": ["box"],
}
# ── review fix: busy-check + enqueue must be atomic (no 202/202 race) ──
def test_concurrent_submits_second_gets_409(monkeypatch):
"""Two overlapping POSTs must not both be accepted (one-GPU guard)."""
import time
import threading
import app as app_module
from src.job import JobStatus
def slow_save(video, model_configs, class_filters,
output_height, zone_mode, zone_preset):
time.sleep(0.4) # simulate save+transcode window
job = app_module.job_queue.add_job(
video_path="/tmp/x.mp4", model_configs=[]
)
with app_module.job_queue._lock:
job.status = JobStatus.RUNNING
class _J:
job_id = job.job_id
return _J()
monkeypatch.setattr(app_module, "_save_and_queue", slow_save)
app.config["TESTING"] = True
codes = []
def post():
with app.test_client() as c:
r = c.post(
"/api/analyze",
data={"video": (io.BytesIO(b"x"), "clip.mp4"),
"fcp_mode": "C"},
content_type="multipart/form-data",
)
codes.append(r.status_code)
t1 = threading.Thread(target=post)
t2 = threading.Thread(target=post)
t1.start()
time.sleep(0.15) # t1 is now inside slow_save (before job registered? no—
# lock held from busy-check through enqueue, so t2 must wait or be refused)
t2.start()
t1.join(10)
t2.join(10)
assert sorted(codes) == [202, 409], f"got {codes}"