# Sentinel-AI — Fix Log **Source of truth for defects:** `SENTINEL_AUDIT_FINDINGS.md` **Source of truth for fixes and evidence:** this file. **Environment:** Windows 11, PowerShell, Python 3.11.5, CUDA 12.x on an RTX 3050 Laptop (6 GB), `faiss-cpu 1.15.1`, `torch 2.x`, `cascadeflow 1.1.0`, `google-genai 0.8.0`, `cohere 7.3.1`, `groq 0.9+`, Node/Vite frontend. **Dataset:** 202,599 CelebA images, `list_attr_celeba.csv`, `list_landmarks_align_celeba.csv`. **Method:** adapted from `WARDRESS_PARANOID_FIX_PROTOCOL.md`. Every finding was re-verified against running code, fixed at the root cause, covered by an automated test where possible, and then exercised end to end against the real 202k-vector index and live model stack. Because this project is not a git repository, there are no per-phase commits; the modified-file list is recorded at the end instead. --- ## Progress Tracker | ID | Severity | Area | Status | |----|----------|------|--------| | S-01 | Critical | Windows console startup | Fixed / verified | | S-02 | Critical | Face detector | Fixed / verified | | S-03 | Critical | Index/query preprocessing | Fixed / verified | | S-04 | Critical | Similarity semantics | Fixed / verified | | S-05 | High | Match threshold | Fixed / verified | | S-06 | High | Upload validation | Fixed / verified | | S-07 | High | Image-serving traversal | Fixed / verified | | S-08 | High | Fabricated frontend telemetry | Fixed / verified | | S-09 | Medium | Keyword fallback | Fixed / verified | | S-10 | Medium | Cohere blocking / `None` text | Fixed / verified | | S-11 | Medium | Packaging | Fixed / verified | | S-12 | Medium | CWD-relative paths | Fixed / verified | | S-13 | Medium | Index builder | Fixed / verified | | S-14 | Medium | Health telemetry | Fixed / verified | | S-15 | Medium | Corrupted `.gitignore`, secrets | Fixed; key rotation still required | | S-16 | Low | Test-suite false positives | Fixed / verified | | S-17 | Low | Frontend resource leaks | Fixed / verified | | S-18 | Low | CORS | Fixed / verified | | S-19 | Low | `.env.example` paths | Fixed / verified | | S-20 | Low | Generated uploads path | Fixed / verified | | S-21 | High | Alert truncated mid-sentence | Fixed / verified | | S-22 | High | "Woman" search returned men; negated keywords inverted | Fixed / verified | | S-23 | Medium | Groq fallback model decommissioned / empty reasoning output | Fixed / verified | | S-24 | Medium | Generated-file collision and raw error leakage | Fixed / verified | | S-25 | Low | `NaN`/`Infinity` env values silently accepted | Fixed / verified | | S-26 | Medium | Cost chart mislabeled; exclusions invisible in UI | Fixed / verified | | S-27 | High | Partial index build could overwrite production artifacts | Fixed / verified | S-21–S-27 were discovered during fix verification; they are recorded here rather than rewriting the original audit. --- ## Fix entries ### [FIXED] S-01 — Windows console crash at startup - **Files changed:** `backend/main.py`, `backend/core/models.py`, `backend/build_index.py`, `backend/api/routes/analyze.py`, `backend/core/gemini_agent.py` - **Root cause:** operational logs printed `✓`, `✗`, `…`, `✅`, which raise `UnicodeEncodeError` on a default `cp1252` console. - **Fix applied:** all runtime logs use ASCII (`[OK]`, `[FAIL]`). UTF-8 remains only in docstrings/API content. - **Verification:** server starts from `backend/` with the default console and logs `[OK] MTCNN`, `[OK] AdaFace`, `[OK] FAISS index (202,599 vectors)`, `[OK] Gemini client initialised`. ### [FIXED] S-02 — Wrong face detector - **Files changed:** `backend/core/models.py` - **Root cause:** `RFDETRSmall` is a COCO detector with no face class, and `optimize_for_inference` does not exist in RF-DETR 1.11. - **Fix applied:** default detector is the MTCNN implementation vendored with AdaFace. RF-DETR remains an explicit optional path supporting both APIs. - **Verification:** `/health` reports `detector_ready: true`; CelebA and non-CelebA photos produce one detected face with landmarks. RF-DETR is not loaded by default. ### [FIXED] S-03 — Index/query preprocessing mismatch - **Files changed:** `backend/build_index.py`, `backend/core/models.py`, `backend/api/routes/analyze.py` - **Root cause:** the persisted index embedded whole portraits; queries embedded tight MTCNN crops. Different framing produced incomparable embeddings (unrelated faces scored above genuine self-matches). - **Fix applied:** the index is rebuilt from `list_landmarks_align_celeba.csv`, warped with the same `warp_and_crop_face` + `get_reference_facial_points(default_square=True)` template used at query time via `MTCNN.align`. The query path falls back to a context crop only if the warp fails. - **Verification:** full build produced `celeb_index.faiss` with **202,599** vectors, 512-D, `IndexFlatL2`, plus `celeb_index.order.json` (202,599) and `celeb_index.preprocessing.json` (`aligned: true`). Calibration in the section below. ### [FIXED] S-04 — Inverted similarity - **Files changed:** `backend/core/faiss_store.py` - **Root cause:** squared-L2 distance was returned in a field named `similarity`; for unit vectors exact matches scored ≈0 and poor matches scored higher. - **Fix applied:** `cosine = clamp(1 - d/2, -1, 1)`, query vectors are L2-normalised before search, and the index is built from unit vectors. - **Verification:** `tests/test_faiss_store.py` (`0→1.0`, `2→0.0`, `4→-1.0`); live `000001.jpg` returns `match_confidence: 0.983`. ### [FIXED] S-05 — No match threshold - **Files changed:** `backend/api/routes/analyze.py` - **Root cause:** every query returned its nearest neighbour as a match. - **Fix applied:** `MATCH_SIMILARITY_THRESHOLD` (default `0.50`). Below it the response is `no_match_found`, `match_confidence: null`, no attributes. - **Verification:** `face-2.jpg` (unrelated) → `no_match_found` at 0.24; `000001.jpg` → `success` at 0.983; RDJ cross-photo → `success` at 0.739. ### [FIXED] S-06 — Upload handling - **Files changed:** `backend/api/routes/analyze.py` - **Root cause:** unbounded read, no decode validation, raw exceptions. - **Fix applied:** read at most `MAX_UPLOAD_BYTES + 1` (default 10 MiB); 413 when over, 422 for empty/undecodable input; pipeline errors sanitised to `"Inference pipeline error."`. - **Verification:** empty → 422, text file → 422, 11 MiB file → 413. ### [FIXED] S-07 — Path traversal in image serving - **Files changed:** `backend/api/routes/search.py` - **Root cause:** user input was joined directly onto `IMAGES_DIR`; numeric IDs guessed `faiss_id + 1`. - **Fix applied:** only `^\d{6}\.jpg$`; numeric IDs map through the cached FAISS order; resolved path must be inside `IMAGES_DIR`. - **Verification:** live and unit tests: `../.env`, `..%2F.env`, `..%5C.env`, `%00`, alternate extensions, and `abc` are rejected with 400/404; valid filename and FAISS IDs 0/202598 return 200. ### [FIXED] S-08 — Fabricated frontend telemetry - **Files changed:** `frontend/src/routes/index.tsx`, `frontend/src/lib/api.ts` - **Root cause:** hard-coded `200k`/`178ms`/`99.98%`, invented match cards, hard-coded latency/attribute arrays, and Unsplash stock photos presented as database results. - **Fix applied:** live `/health` polling every 15 s; real `index_vectors`, detector/embedder readiness, latency/cost from actual responses, attribute distribution from actual results, real `/api/v1/images/{id}` gallery, and explicit empty states. Decorative hero images are separate and labelled "Sample imagery". - **Verification:** frontend type-checks and builds; the page's values now come only from `/health` and API responses. ### [FIXED] S-09 — Broken keyword fallback - **Files changed:** `backend/core/gemini_agent.py` - **Root cause:** the fallback was unreachable; the map mapped female→`Male`, old→`Young`, and beard→`No_Beard` (the inverse label). - **Fix applied:** the fallback runs whenever providers fail or return no usable attributes; word-boundary matching; female terms add no `Male`; old terms add no `Young`; "beard" maps to nothing; explicit "no beard"/ "beardless" adds `No_Beard`. - **Verification:** `tests/test_gemini_fallback.py`; live queries return `["Smiling","Blond_Hair"]`, `["Young","Male","Wavy_Hair","Eyeglasses"]`, and no attributes for an alien description. ### [FIXED] S-10 — Cohere blocked the loop / `None` text - **Files changed:** `backend/core/gemini_agent.py` - **Root cause:** synchronous `cohere.ClientV2` was called from async code; `response.text.strip()` crashed when Gemini returned no text. - **Fix applied:** `cohere.AsyncClientV2` with `await .chat(...)`; every provider response passes through `_safe_text` / `_cohere_text`; empty output is treated as failure so the next provider is tried. - **Verification:** live Cohere fallback generated a complete 441-character alert while Gemini returned HTTP 429. ### [FIXED] S-11 — Packaging - **Files changed:** `requirements.txt`, `.env.example`, `README.md` - **Fix applied:** added `groq` and `cohere`; pinned `cascadeflow>=1.1.0,<1.2.0`; RF-DETR is optional/commented. - **Verification:** all imports load under Python 3.11.5; `cascadeflow 1.1.0` initialises in `enforce` mode. ### [FIXED] S-12 — CWD-relative paths - **Files changed:** `backend/core/paths.py`, `backend/core/models.py`, `backend/core/faiss_store.py`, `backend/build_index.py`, `backend/api/routes/search.py`, `backend/api/routes/generate.py` - **Fix applied:** relative env paths resolve against CWD first (backwards compatible), then the backend package, then the project root. Both `.env` locations are loaded in a defined order. - **Verification:** `tests/test_paths.py`; server and indexer run from `backend/`; paths work from other CWDs. ### [FIXED] S-13 — Index builder - **Files changed:** `backend/build_index.py` - **Root cause:** unconditional `StandardGpuResources()` crashed under `faiss-cpu`; vectors were not normalised; deprecated `torch.cuda.amp`. - **Fix applied:** GPU API detection with CPU fallback; per-batch L2-normalisation; `torch.amp.autocast(device_type=...)`; landmark support; explicit `.order.json` and `.preprocessing.json` artifacts. - **Verification:** full 202,599-vector build on `faiss-cpu`; self-match calibration below. ### [FIXED] S-14 — Weak health endpoint - **Files changed:** `backend/main.py`, `backend/api/schemas.py` - **Fix applied:** returns real `index_vectors`, `detector_ready`, `embedder_ready`, and the configured Gemini model. - **Verification:** live `/health` returns `{"index_ready":true,"index_vectors":202599,"detector_ready":true, "embedder_ready":true,"model":"gemini-2.5-flash"}`. ### [FIXED] S-15 — Corrupted ignore file and exposed secrets - **Files changed:** `.gitignore` - **Fix applied:** rewrote the NUL-corrupted file; secrets, caches, weights, index artifacts, `Data/`, and `node_modules` are ignored. `.env` is ignored at both locations. - **Residual action:** **rotate every API key present in the original archive.** The keys were not printed during this work, but exposure cannot be undone by `.gitignore`. ### [FIXED] S-16 — Test-suite false positives - **Files changed:** `test_semantic_search.py` - **Root cause:** the summary counted function objects (always truthy) and called health twice. - **Fix applied:** explicit boolean results, per-query assertions, and a non-zero exit code on failure. The female-query assertion now checks both `excluded_attrs == ["Male"]` and that no returned match carries `Male`. - **Verification:** live suite reports `4/4` and exits 0. ### [FIXED] S-17 — Frontend resource leaks - **Files changed:** `frontend/src/routes/index.tsx`, `frontend/src/lib/api.ts` - **Fix applied:** abort timers cleared in `finally`; health/progress intervals cleaned up on unmount; object URLs revoked on change/unmount; API base configurable through `VITE_API_BASE_URL`. - **Verification:** `npx tsc --noEmit` clean; `npm run build` succeeds. ### [FIXED] S-18 — CORS - **Files changed:** `backend/main.py` - **Fix applied:** `CORS_ORIGINS` (default local Vite/3000 origins), limited to GET/POST/OPTIONS and Content-Type/Authorization headers. - **Verification:** startup uses the configured list; wildcard requires an explicit `CORS_ORIGINS=*`. ### [FIXED] S-19 — Example paths - **Files changed:** `.env.example` - **Fix applied:** `CELEBA_IMAGES_DIR` points at `../Data/img_align_celeba`, matching the actual layout. - **Verification:** indexer and API resolve the dataset without overrides. ### [FIXED] S-20 — Generated uploads path - **Files changed:** `backend/api/routes/generate.py` - **Fix applied:** output directory resolves through `resolve_path` and is created on demand. ### [FIXED] S-21 — Alert truncated mid-sentence - **Files changed:** `backend/core/gemini_agent.py:408`, `backend/core/gemini_agent.py:522` - **Re-verification:** live `analyze-frame` responses ended with `"...identified a"` and `"...verify the individual's"` — no final punctuation, clearly incomplete. - **Root cause:** Gemini 2.5 counts hidden thinking tokens against `max_output_tokens`. The alert call allowed 256 and extraction allowed 128, leaving too little for the visible answer. - **Fix applied:** alert budget `256 → 1024`; extraction budget `128 → 512`; Groq budgets likewise raised for reasoning models. - **Verification:** alerts now complete at 280–497 characters and end with punctuation; Groq and Cohere fallbacks also return complete text. ### [FIXED] S-22 — "Woman" search returned men; negated keywords inverted - **Files changed:** `backend/core/gemini_agent.py:214-311`, `backend/core/faiss_store.py:190-229`, `backend/api/routes/search.py:68-108`, `backend/api/schemas.py:73`, `frontend/src/routes/index.tsx:172-1018`, `frontend/src/lib/api.ts:58` - **Re-verification:** `"smiling woman with blond hair"` returned `000013.jpg` (attributes include `Male`) as rank 1. `"man with no glasses"` would have required `Eyeglasses` because the keyword matcher saw the substring "glasses". - **Root cause:** CelebA encodes gender/age as single bits (`Male`, `Young`); there is no positive `Female`/`Old` column, so a positive-only filter cannot represent the query. Keyword matching also ignored negation. - **Fix applied:** - `_keyword_filter()` returns `(required, excluded)`. - Female terms → exclude `Male`; old terms → exclude `Young`. - Negated keywords ("no glasses", "without a hat", "not wearing makeup") become exclusions, not requirements. - "clean-shaven" requires `No_Beard` and excludes `Mustache`, `Goatee`, `5_o_Clock_Shadow`. - `search_by_attributes()` accepts `excluded_attrs`; the route supports exclusion-only queries (e.g. `"a woman"`) and returns `excluded_attrs`. - The UI displays excluded chips (`not Male`) alongside required chips. - **Verification:** live `"smiling woman with blond hair"` → `excluded_attrs: ["Male"]` and all five results are non-male; `"a woman"` → 200 with non-male results; `"man with no glasses"` → `excluded_attrs: ["Eyeglasses"]`; `"clean-shaven man"` → required `Male`,`No_Beard` and excluded facial-hair labels. Unit and route tests added. ### [FIXED] S-23 — Groq fallback model decommissioned / empty reasoning output - **Files changed:** `backend/core/gemini_agent.py:47,430-434,549-552`, `.env`, `backend/.env`, `.env.example` - **Re-verification:** server logs showed Groq 404: ``The model `llama-3.3-70b-versatile` does not exist or you do not have access to it.`` The account's model list exposes `openai/gpt-oss-120b`, `openai/gpt-oss-20b`, `qwen/qwen3.8-27b`, etc. - **Root cause:** the pinned model had been retired; additionally reasoning-capable models spend part of `max_tokens` on hidden reasoning, so the old 128/256-token budgets could yield empty content. - **Fix applied:** default and `.env` value changed to `openai/gpt-oss-120b`; Groq alert budget `1024`, extraction `512`. - **Verification:** direct Groq completion returned `OK`; forcing Gemini to fail produced `[Groq Engine]` alerts (365 characters) and correct attribute extraction through the API. ### [FIXED] S-24 — Generated-file collision and raw error leakage - **Files changed:** `backend/api/routes/generate.py:57-70,138,160-170` - **Re-verification / root cause:** filenames used `int(time.time())`, so two requests in the same second overwrote each other. `str(exception)` was returned to clients, exposing provider/SDK internals. - **Fix applied:** `generated_{uuid4().hex}.jpg`; client-visible errors are now `"Image generation failed."`, with full details logged server-side. - **Verification:** `tests/test_api_routes.py` — 200 generated names are unique; a simulated provider failure returns the sanitised message and does not include the injected secret. ### [FIXED] S-25 — `NaN`/`Infinity` env values silently accepted - **Files changed:** `backend/core/paths.py:59-68`, `backend/tests/test_paths.py` - **Root cause:** `float("nan")` succeeds; a NaN threshold makes every comparison false and silently disables matching. - **Fix applied:** `env_float` rejects non-finite values and falls back to the default. - **Verification:** tests for `nan`, `inf`, and `-inf` pass. ### [FIXED] S-26 — Cost chart mislabeled; exclusions invisible in UI - **Files changed:** `frontend/src/routes/index.tsx` - **Re-verification:** the cost line plotted `cost * 100000` while the legend said `Cost ($)`; a $0.00003 call appeared as `3` on the axis. Search exclusions were not displayed, and one suggestion ("man with beard…") could not be expressed by CelebA labels. - **Fix applied:** dedicated right-hand cost axis plotted in dollars (`$0.0000` ticks); exclusion chips rendered in the attribute panel; the unexpressible suggestion replaced with "man with a mustache wearing a necktie"; search input gained an `aria-label`. - **Verification:** `npx tsc --noEmit` clean; `npm run build` succeeds. ### [FIXED] S-27 — Partial index build could overwrite production - **Files changed:** `backend/build_index.py:246-290,404-413`, `backend/tests/test_build_index.py`, `README.md` - **Re-verification / root cause:** `python build_index.py --limit 3000` wrote to the default `index_artifacts/` paths. This had already replaced the production index with a 3,000-image one during earlier work, leaving the metadata/index inconsistent. - **Fix applied:** `_guard_partial_overwrite()` refuses any `--limit` build smaller than the dataset unless `--force` is passed or scratch `FAISS_INDEX_PATH`/`METADATA_PATH` values are set. The README now shows the scratch-path procedure and the explicit `--force` escape hatch. - **Verification:** tests assert partial builds raise, forced builds pass, and full builds pass. The production 202,599-vector index remains intact. --- ## Full-index calibration Run against the real `celeb_index.faiss` (202,599 vectors, 512-D), sampling 200 random CelebA images plus 11 non-CelebA face photos. | Metric | Result | |---|---| | MTCNN detected a face | 198/200 | | Rank-1 exact self-match | 198/198 | | Self cosine — min | 0.8735 | | Self cosine — p5 | 0.9576 | | Self cosine — median | 0.9864 | | Self cosine — mean / max | 0.9827 / 0.9980 | | Unrelated faces — min / max | 0.2426 / 0.4318 | | Genuine non-CelebA matches | 0.5265 / 0.6831 / 0.7391 | | Threshold | 0.50 | The three above-threshold "negatives" were manually inspected and are genuine matches: - `img1.jpeg` and `img2.jpeg` (both Robert Downey Jr.) → CelebA `183084.jpg` (Robert Downey Jr.). - `office4.jpg` (The Office cast) → CelebA `107763.jpg` (Jenna Fischer). So the threshold separates unrelated faces (≤0.432) from genuine cross-domain matches (≥0.527). The margin is narrower on cross-domain photos than on CelebA self-matches (≥0.874), so the threshold should be re-validated on the operator's own footage before deployment. --- ## End-to-end verification ### Automated ``` cd backend && python -m pytest -q 55 passed, 3 warnings in 15.17s cd frontend && npx tsc --noEmit (no output — 0 errors) cd frontend && npm run build ✓ client built, ✓ SSR built, ✓ Nitro output generated (non-blocking warning: chunks >500 kB) python test_semantic_search.py Tests passed: 4/4 — ALL TESTS PASSED ``` ### Live API ``` GET /health {"status":"ok","index_ready":true,"index_vectors":202599, "detector_ready":true,"embedder_ready":true,"model":"gemini-2.5-flash"} POST /api/v1/analyze-frame 000001.jpg 200 success, confidence 0.983, 1 face, complete alert POST /api/v1/analyze-frame img2.jpeg (RDJ) 200 success, confidence 0.7391 POST /api/v1/analyze-frame face-2.jpg (unrelated) 200 no_match_found, confidence null POST /api/v1/analyze-frame blank.png 200 no_face_detected, faces_detected 0 POST /api/v1/analyze-frame empty / text / 11 MiB 422 / 422 / 413 POST /api/v1/semantic-search "smiling woman with blond hair" 200 success, excluded_attrs ["Male"], all returned matches non-male POST /api/v1/semantic-search "a woman" 200 success, exclusion-only query works POST /api/v1/semantic-search "man with no glasses" 200 success, excluded_attrs ["Eyeglasses"] POST /api/v1/semantic-search "alien with three eyes" 200 no_attributes_extracted POST /api/v1/semantic-search "" / top_k 0 / top_k 101 / 999999 / invalid JSON 422 in every case GET /api/v1/images/{0, 000001.jpg, 202598} 200 image/jpeg GET /api/v1/images/{202599, ../.env, ..%2F.env, ..%5C.env, %00, .png, abc} 404 / 404 / 404 / 400 / 400 / 400 / 400 ``` ### Concurrency Five simultaneous `analyze-frame` requests (three CelebA images, RDJ, and an unrelated face) all returned HTTP 200 with the same confidences as their sequential runs (0.983, 0.9825, 0.9237, 0.7391, `no_match_found`). No model corruption, index inconsistency, or cross-request leakage was observed. ### Provider fallback With Gemini forced to an invalid model: - Groq fallback produced a complete 365-character alert and the correct attribute list. - Cohere fallback produced a complete 441-character alert during a real Gemini 429 event. - All providers failing produces the deterministic offline alert and keyword extraction rather than a 5xx. --- ## Modified files Backend: ``` backend/core/paths.py backend/core/models.py backend/core/faiss_store.py backend/core/gemini_agent.py backend/api/schemas.py backend/api/routes/analyze.py backend/api/routes/search.py backend/api/routes/generate.py backend/main.py backend/build_index.py backend/tests/conftest.py backend/tests/test_paths.py backend/tests/test_faiss_store.py backend/tests/test_gemini_fallback.py backend/tests/test_api_routes.py backend/tests/test_build_index.py backend/tests/test_health.py ``` Frontend: ``` frontend/src/lib/api.ts frontend/src/routes/index.tsx ``` Project root: ``` requirements.txt .env.example .gitignore README.md test_semantic_search.py SENTINEL_AUDIT_FINDINGS.md SENTINEL_FIX_LOG.md ``` Generated artifacts (gitignored): ``` backend/index_artifacts/celeb_index.faiss (414,922,797 bytes) backend/index_artifacts/metadata.json (27,836,228 bytes) backend/index_artifacts/celeb_index.order.json (2,633,788 bytes) backend/index_artifacts/celeb_index.preprocessing.json backend/index_artifacts/backup_fullimage/ (old index backup) ``` --- ## Rollback There is no git history in this workspace, so rollback is file-based. 1. **Index only:** stop the server, restore the old artifacts from `backend/index_artifacts/backup_fullimage/` into `backend/index_artifacts/`, delete `celeb_index.order.json` and `celeb_index.preprocessing.json`, and restart. - **Do not do this without also reverting the query pipeline.** The backup is a full-image index; aligned queries are incompatible with it, which is exactly S-03. It is a historical reference, not a supported fallback. 2. **Code:** the modified-file list above is complete. Because there is no VCS baseline, re-create the previous versions from your archive/deployment copy. For future changes, initialise git and commit before editing. 3. **Configuration:** `.env` and `backend/.env` had `GROQ_MODEL` changed from the retired `llama-3.3-70b-versatile` to `openai/gpt-oss-120b`. Reverting that value restores a non-working fallback; only do so if you pin a different working Groq model. --- ## Residual risks - **No authentication or rate limiting.** The API is for a local demo; do not expose it publicly as-is. - **Gemini free-tier quota** was exhausted during testing (20 requests/day). The fallback chain works, but production traffic needs a paid quota or a deliberate provider policy. Fallback calls report `cost_usd: 0.0` because Groq/Cohere free-tier cost is not tracked. - **MTCNN recall:** 2/200 CelebA samples and stylized frontend assets were not detected. Those requests return `no_face_detected` rather than guessing. - **Threshold margin:** unrelated faces reached 0.432 and genuine cross-domain matches started at 0.527. A different camera domain may shift this; validate on target footage and tune `MATCH_SIMILARITY_THRESHOLD`. - **Provider model drift:** Groq already retired the previous default. `COHERE_MODEL=command-r-plus-08-2024` may also be retired eventually; both are env-configurable. - **Generated files** are written to `backend/uploads/` and are never pruned. - **Frontend lint:** `npm run lint` still reports pre-existing Prettier errors in untouched files (≈616). Type-check and production build are clean. - **Frontend deployment preset** is `cloudflare-module`; the build succeeds but no live deployment was performed as part of this work. - **Biometric privacy/legal compliance** remains the operator's responsibility. --- ## Immediate operator actions 1. **Rotate every API key** that was present in the project archive (`GEMINI_API_KEY`, `GROQ_API_KEY`, `COHERE_API_KEY`, any others). 2. Keep `.env` out of version control; the rewritten `.gitignore` covers it. 3. If exposing the API beyond localhost, put authentication and rate limiting in front of it. --- ## Follow-up hardening — 2026-11-10 A second review found that the local demo worked end to end but several medium/low issues remained. This section records the follow-up fixes and supersedes the corresponding residual risks above. | ID | Severity | Issue | Status | |----|----------|-------|--------| | R-01 | High | LLM latency budget was advisory only | Fixed / verified | | R-02 | High | Rare semantic filter blocked the event loop | Fixed / verified | | R-03 | Medium | `build_index.py` ignored scratch paths | Fixed / verified | | R-04 | Medium | No isolated environment / lockfile | Fixed | | R-05 | Medium | Stale Imagen 3 `/generate-person` | Fixed / tested with mocks | | R-06 | Medium | No auth / rate limits / TLS guidance | Fixed | | R-07 | Low | Dev-only TanStack hydration warning | Fixed | | R-08 | Low | Dead legacy modules | Removed | | R-09 | Low | `.gitignore` missed order/preprocessing files | Fixed | | R-10 | Low | MTCNN missed ~1% of faces | Mitigated / tested | | R-11 | Low | Biometric privacy/legal guidance absent | Documented | ### R-01 — Enforced LLM deadline - **Files:** `backend/core/gemini_agent.py`, `backend/main.py`, `.env.example`, `backend/tests/test_llm_deadline.py`. - **Root cause:** cascadeflow records `max_latency_ms` but does not cancel a slow provider; live Gemini calls took ~2–5 s. - **Fix:** `_await_with_deadline()` races each provider against `LLM_PROVIDER_TIMEOUT_MS` (default 1200 ms) inside a whole-chain `LLM_HARD_TIMEOUT_MS` (default 2000 ms). On expiry it cancels the task and returns without waiting for SDK cleanup (`wait_for` let wall time reach ~2.9 s). Provider clients are warmed during lifespan so first-request auth setup does not consume the budget. - **Evidence:** live alerts after warm-up 1.75–1.85 s of LLM time; first call 2.0 s and fell back to offline; semantic-search extraction 1.70 s. Full analyze (CV + LLM) 2.75 s. Gemini free-tier daily quota was exhausted during testing, which exercised the Groq/offline path. ### R-02 — Vectorised attribute filter - **Files:** `backend/core/faiss_store.py`, `backend/api/routes/search.py`, `backend/tests/test_faiss_store.py`. - **Root cause:** `search_by_attributes()` iterated 202,599 metadata entries and rebuilt a Python set per entry on every request inside an async route. - **Fix:** cache a boolean `(202599, 40)` NumPy matrix, discover columns from metadata, apply required/excluded masks with boolean ops, and call the function through `asyncio.to_thread()`. The matrix is built during lifespan. - **Evidence:** build 1.12 s once; rare filter (`Smiling + Blond_Hair`, exclude `Male`) 2.64 ms vs ~778 ms before; common `Male` filter 1.15 ms. Live semantic-search request 2.0 s total (LLM extraction dominates). ### R-03 — Scratch-path-aware build guard - **Files:** `backend/build_index.py`, `backend/tests/test_build_index.py`. - **Root cause:** `_guard_partial_overwrite()` ignored the configured paths and refused every partial build without `--force`, contradicting the README. - **Fix:** compare the resolved index and metadata paths against canonical production locations. A partial build is allowed only when **both** are redirected; otherwise it still raises. `build_index()` passes the active paths explicitly. ### R-04 — Environment isolation - **Files:** `requirements.txt`, `requirements.lock`, `.python-version`, `scripts/bootstrap.ps1`, `scripts/generate_lock.py`. - **Fix:** removed unused `pydantic-settings` / `pytest-asyncio`, documented Python 3.11 + CUDA 12.6, generated an exact dependency closure, and added a bootstrap script that creates `.venv`, installs the lock, and checks secrets. - **Not executed:** a full clean-venv install (torch download size). The lock matches the tested environment; `cascadeflow==1.1.0` is pinned because the installed 1.2.0 metadata actually exposes the 1.1.x API. ### R-05 — `/generate-person` migration - **Files:** `backend/api/routes/generate.py`, `backend/api/schemas.py`, `.env.example`, `backend/tests/test_api_routes.py`. - **Root cause:** Imagen 4 was retired on 17 Aug 2026; the route still called `imagen-3.0-generate-001` / `generate_images`, hard-coded `$0.04`, and caught `HTTPException` as a 200 error. - **Fix:** use `gemini-3.1-flash-image` through `generate_content(response_modalities=["TEXT", "IMAGE"])`, extract `inline_data`, make the model/cost env-configurable (`IMAGE_MODEL`, `IMAGE_COST_USD=0.067`), and re-raise `HTTPException`. Mock tests cover the new response shape, no-image 502, and status preservation. - **Not executed:** a paid live generation. SDK shape was verified against the installed `google-genai 0.8.0`. ### R-06 — Auth, rate limits, TLS - **Files:** `backend/core/security.py`, `backend/main.py`, `frontend/src/lib/api.ts`, `frontend/.env.example`, `.env.example`, `backend/tests/test_security.py`, `deploy/nginx.conf.example`, `SECURITY.md`. - **Fix:** optional Bearer / `X-API-Key` auth (`SENTINEL_API_KEY`), per-client token bucket (`RATE_LIMIT_PER_MINUTE`, `RATE_LIMIT_BURST`), security headers, `X-Forwarded-For` support behind a trusted proxy, and a TLS/rate-limit nginx example. CORS remains outermost so preflight OPTIONS bypasses auth. The dashboard sends `VITE_API_KEY` when configured. Local demo stays open when no key is set. - **Note:** the limiter is per-process; use the proxy limit for multi-worker deployments. ### R-07–R-11 — Low-severity items - **Hydration:** `suppressHydrationWarning` on ``/`` in `frontend/src/routes/__root.tsx` silences the dev-only `data-tsd-source` mismatch without hiding real mismatches elsewhere. - **Dead code:** removed `backend/agent_interface.py`, `backend/api_routes.py`, `backend/computer_vision_logic.py`, and `backend/fastapi_entrypoint.py` (confirmed unreferenced). - **Gitignore:** added `backend/index_artifacts/*.order.json`, `*.preprocessing.json`, `backend/backup_fullimage/`, and frontend build/dev caches. - **MTCNN recall:** `detect_faces()` retries once with `MTCNN_RETRY_MIN_FACE_SIZE=12` / `MTCNN_RETRY_CONFIDENCE=0.45`. The cosine threshold still governs identity matching. Unit tests cover retry, no-retry, double-failure, and non-permissive settings. - **Privacy/legal:** `PRIVACY.md` covers GDPR/BIPA/CCPA considerations, consent, retention, access control, human review, generated faces, incident response, and open legal questions. ### Verification (follow-up) - `python -m pytest -q`: **83 passed** (14–15 s). - `npx tsc --noEmit`: clean. - `npm run build`: succeeds (client + SSR + Cloudflare/Nitro output). - Live API: `/health` reports 202,599 vectors and all models ready; CORS preflight returns 200 with `X-API-Key` allowed; semantic search returns `000018.jpg`; self-match analyze returns 0.983 confidence. - `python scripts/check_secrets.py`: clean; both `.env` files are gitignored. ### Remaining operator actions 1. **Rotate Gemini, Groq, and Cohere keys** in their consoles; the files were exposed historically and this cannot be done from code. 2. Run `.\scripts\bootstrap.ps1` on a clean machine to validate the lock (a full clean install was not executed here). 3. Set `SENTINEL_API_KEY` and `VITE_API_KEY` before any shared deployment; terminate TLS with the provided nginx example. 4. Review `PRIVACY.md` with counsel and re-tune `MATCH_SIMILARITY_THRESHOLD` on your own camera footage. 5. **VCS:** this workspace is still not a Git repository. Initialisation was deliberately skipped because the frontend is linked to Lovable; create a repository and baseline commit before further production work. ### Follow-up files changed ``` README.md SECURITY.md PRIVACY.md requirements.txt requirements.lock .python-version .env.example .gitignore test_semantic_search.py deploy/nginx.conf.example scripts/bootstrap.ps1 scripts/check_secrets.py scripts/generate_lock.py frontend/.env.example frontend/src/lib/api.ts frontend/src/routes/__root.tsx backend/main.py backend/build_index.py backend/api/schemas.py backend/api/routes/generate.py backend/api/routes/search.py backend/core/faiss_store.py backend/core/gemini_agent.py backend/core/models.py backend/core/security.py backend/tests/test_api_routes.py backend/tests/test_build_index.py backend/tests/test_faiss_store.py backend/tests/test_llm_deadline.py backend/tests/test_models_detection.py backend/tests/test_security.py ``` Removed: `backend/agent_interface.py`, `backend/api_routes.py`, `backend/computer_vision_logic.py`, `backend/fastapi_entrypoint.py`.