fix: workspace pre_chunks dedup — stop 19GB re-dispatch bloat (A1) + charade analysis

This commit is contained in:
Accusys
2026-08-16 08:44:29 +08:00
parent 5e6a7b7d51
commit 0533248f2c
2 changed files with 194 additions and 1 deletions
@@ -0,0 +1,155 @@
# Charade Large-File Deep Scan — Diagnosis & Fix (Round 1: Space / Idle-Time)
> Date: 2026-08-16 · Scope: Core (`~/momentry_core`) · Status: Fix implemented (Round 1)
> File under analysis: `c36f35685177c981aa139b66bbbccc5b` (Charade_YouTube_24fps.mp4, 252 MB, 114 min, 162,696 frames @ 24fps)
---
## 1. Problem Statement (from user)
1. **Deep Scan uses a huge amount of disk space but with a high error rate — no benefit.**
2. **Deep Scan takes too long.**
---
## 2. Measured Timeline (actual file timestamps + pipeline log)
```
15:05:33 job dispatched (face/asr/cut/ocr in parallel)
15:08 ocr done
15:18 asr done
15:35 cut done ← light processors finish within ~30 min
⛔ 15:35 → 23:05 (~7.5 h) face NOT running; job re-dispatched every ~11 s
23:05 SwiftFace finally starts (816.8 s detection over 43,103 sampled frames)
23:35 face.json written
23:41 pose.json done (6 min)
⛔ 23:41 → 02:42 (~3 h) face_traced stage (Python IoU tracking)
02:42 asrx.json
02:43 face_traced.json
02:45 face_cluster.json
02:46 pipeline log last write → DONE (≈ 11.7 hours total)
```
**Key insight:** the 11.7 h is not "slow processing" — it is **~7.5 h of idle re-dispatch spinning** + **~3 h of one heavy stage (face_traced)**. The actual face detection work was only ~14 min.
---
## 3. Root Cause (single bug → both symptoms)
The worker's `poll_and_process` (`src/worker/job_worker.rs:259-326`) re-dispatches a
**running** job every poll cycle (~11 s) whenever any processor is still
pending/deferred (`has_unstarted || has_deferred` → `process_job`).
For Charade, `pose` / `asrx` / `face_cluster` are dependency-blocked (waiting on
`face`), so the job stayed "deferred" for hours and was re-processed ~250–300 times
per light processor. Each re-dispatch walks the **skip path** (`job_worker.rs:675+`:
"output file exists, marking completed and skipping") which **re-appends ALL
pre_chunks for every already-finished processor**.
`WorkspaceDb::store_pre_chunk` (`src/core/db/workspace_sqlite.rs:214`) was a **bare
`INSERT`** — no `UNIQUE` constraint, no `ON CONFLICT`, no dedup. So every cycle
duplicated the full pre_chunk set again.
### Measured duplication (Charade `workspace.sqlite`)
| processor | total rows | unique rows | duplication |
|-----------|-----------:|------------:|------------:|
| face | 8,189,570 | 43,103 | **190×** |
| asr | 446,529 | 1,779 | **251×** |
| ocr | 64,824 | 219 | **296×** |
| cut | 570,416 | ~1,852 | **~308×** |
| pose | 8,191 | 8,191 | 1× (no dup) |
| asrx | 5,721 | — | (NULL start_frame) |
| **TOTAL** | **~9.28 M** | — | → **19 GB** |
> The same re-dispatch loop is responsible for BOTH the 19 GB space blow-up AND the
> ~7.5 h idle spinning. Fixing it addresses symptoms 1 & 2 simultaneously.
---
## 4. Fix Implemented (Round 1 = Plan A: A1 dedup + A3 write-guard)
### A1 — workspace dedup (root fix)
File: `src/core/db/workspace_sqlite.rs`
- Added an **expression UNIQUE index** created in `init_tables()`:
```sql
CREATE UNIQUE INDEX IF NOT EXISTS idx_pre_chunks_dedup ON pre_chunks(
file_uuid, processor_type, chunk_type,
COALESCE(start_frame,-1), COALESCE(end_frame,-1), COALESCE(start_time,-1))
```
`COALESCE` ensures NULL `start_frame`/`end_frame`/`start_time` (e.g. asrx rows,
which all have NULL start_frame) still participate in uniqueness.
On legacy DBs that already contain duplicates the index creation **fails → log a
warning and continue** (never crash); new duplicates are still blocked by
`INSERT OR IGNORE`.
- `store_pre_chunk` changed `INSERT` → **`INSERT OR IGNORE`** (duplicates silently skipped).
### A3 — skip-path write-guard (avoid pointless I/O)
File: `src/worker/job_worker.rs`
- New helper `WorkspaceDb::has_pre_chunks(processor_type)` (`SELECT 1 ... LIMIT 1`).
- In the skip path, computed `ws_skip_append`; each processor's append loop is wrapped
in `if !ws_skip_append { ... }`. Covers asr / asrx (+speaker batch) / cut / yolo /
ocr / face (+face_detections batch) / pose.
### Defence in depth
A1 (`INSERT OR IGNORE` + unique index) is the real guard; A3 avoids even attempting
the redundant writes. Either alone stops the blow-up; together they also stop the
wasted I/O.
---
## 5. Impact / Safety Analysis (no existing behaviour broken)
| Consumer | Usage | Impact |
|----------|-------|--------|
| `core/checkin.rs:32` | `get_all_pre_chunks()` (SELECT only) | cleaner data, no code change ✅ |
| `bin/fix_chunks.rs` | SELECT only | same ✅ |
| `playground.rs` | different `store_pre_chunk` (PG-side, different signature) | untouched ✅ |
| PG `chunk` table | `UNIQUE(file_uuid,chunk_id)` + `ON CONFLICT` | already safe, unaffected ✅ |
| `main.rs.backup` | not compiled | ignored ✅ |
| detector / tracking algorithms | none changed | deferred to Round 2 ✅ |
| PG schema / any API | none changed | ✅ |
| production (3002) / wordpress / n8n | not touched | ✅ |
---
## 6. Verification
- `cargo check --lib` — OK (only pre-existing warnings).
- `cargo clippy --lib` — OK (no new warnings from changed lines).
- `cargo test --lib` — **250 passed, 0 failed**.
- Standalone dedup behaviour test (temp SQLite): 5 duplicate face rows → 1 kept;
3 NULL-start_frame asrx rows → 1 kept; distinct-frame rows unaffected. ✅
No server was started (playground 3003 suspended; production 3002 untouched).
---
## 7. Deferred to Round 2 (NOT done here)
- **B. face_traced 3 h optimization** — `scripts/utils/face_tracker.py` is
`iou_only`. Options: sample / parallelize, or embedding-based association reusing
the existing Qdrant `_faces` embeddings. Must keep trace_id output format
(downstream: assign_pose_trace, face_clustering, extract_face_crops).
- **C. Face quality / error rate** — Apple Vision flags text/logos (e.g. "ACCUSYS")
as faces (0% false-positive rejection per
`2026-08-09_mediapipe_vs_apple_vision_comparison.md`); 2,877 / 4,834 traces are ≤5
points (noise); 14,345 faces conf<0.7. Plan: opt-in filters (min_trace_len,
confidence threshold, OCR-overlap / MediaPipe cross-check) behind flags so default
behaviour is unchanged.
---
## 8. Data Cleanup (requires explicit user approval — pending)
Charade's existing ~9.28 M duplicate rows are NOT yet removed. Proposed (only after
user confirms): `DELETE` keeping one row per group + `VACUUM` to reclaim the 19 GB.
**Will ask before any deletion.**
---
## Version History
| Version | Date | Author | Change |
|---------|------|--------|--------|
| 1.0 | 2026-08-16 | Core team | Initial diagnosis + Round 1 fix (A1 dedup + A3 write-guard) |