Repository navigation
fix(nc-ocr-flow): create the retry index after the ALTERs (jobstore init was dead on existing DBs) - #68
Merged
Conversation
… schema script The C6 retry migration put `CREATE INDEX idx_jobs_next_run ON jobs(next_run_at)` in _SCHEMA_SQL, which runs BEFORE _migrate_add_retry_columns. On any database created before those columns existed the index statement raised 'no such column: next_run_at', which aborted init() and left jobstore permanently in its no-op state: no job history, no file index, empty /stats and /states — while the database itself was intact. First production rollout hit exactly this (ready: False, 0 files reported against a 58-row table). Move the index creation into _migrate_add_retry_columns, after its ALTERs, and add tests/test_jobstore_migration.py: it builds the pre-C6 schema by hand and runs the real init(), so a fresh-DB-only test suite can no longer miss this.
Likivik
added a commit
that referenced
this pull request
Oct 17, 2026
…68 (#69) * fix(nc-ocr-flow): A1-A3 per-page strip, real page indices, pixel dims A1 _strip_existing_text now has an optional page_idx parameter; callers passing one strip only that page, callers passing None (or omitting it) keep the old whole-doc behaviour. _finalize uses the per-page form so a page whose engine returned no blocks retains its pre-existing text layer. A2 google_engine._aggregate_json_results returns list[tuple[int, OcrResult]] with REAL 0-indexed source page indices and warns on duplicate pageNumber; vlm_pages is no longer list(range(n)). A3 google_engine._page_dims local-PDF fallback renders at the new _PAGE_DIMS_FALLBACK_DPI = 200 and returns PIXELS, not PDF points. * fix(nc-ocr-flow): combine A1-A3 engine/text fixes and B1-B6 webhook/jobstore/orientation fixes A1 per-page text strip in _finalize: pages whose engine result has no blocks keep their pre-existing text layer; _strip_existing_text gained an optional page_idx=None parameter (None = old whole-doc behaviour). A2 google_engine._aggregate_json_results returns list[tuple[int, OcrResult]] with REAL 0-indexed source page indices and warns on duplicate pageNumber, so vlm_pages is no longer list(range(n)). A3 google_engine._page_dims local-PDF fallback now renders at a new _PAGE_DIMS_FALLBACK_DPI = 200 and returns PIXELS, not PDF points. B1 force=True no longer bypasses the per-path in-flight gate in _enqueue. Two concurrent force callers collapse to ONE jobs row, returning status 'already_running' naming the existing job. Added jobstore.in_flight_job_for_path. B2 retry counters no longer double-count and /stats now spreads retries_total + retries_queued into the payload the NC app reads. B3 _webdav_exists treats HTTP 410 Gone like 404. B4 jobstore._prune skips rows waiting on a backoff (COALESCE(next_run_at,0) <= now). B5 _ENQUEUE_LOCKS got a bounded 1h idle TTL sweep. B6 the expensive orientation precheck was REMOVED: preorient_pages_safe calls preorient_pdf exactly once; _detect_all_pages_orientations does not exist; a regression-guard test asserts its absence. Conflicts resolved: - jobstore.py:6 conflicts around the C6 retry migration and the stats() retry counters. Kept main's _migrate_add_retry_columns helper (PR #68 ordering fix) and main's typed-docstring style for attempts_i/next_run_at_f. Reconciled the schema column defs and the inline ALTER loop into one migration path with the index AFTER the ALTERs (PR #68 invariant). - webhook_server.py:2 conflicts. Adopted main's _webdav_exists structure (with timeout parameter) and B3's 410-as-gone behaviour (now uses requests.request("HEAD", ...) so the standard test monkeypatching ws.requests.request intercepts the call). Adopted main's jobstore.stats() call site in /stats and added the B2 retries_total/retries_queued spread from the same js handle. - test_webhook_api.py:1 conflict. Both sides added disjoint test blocks (main's C1-C6 and B's B1-B6); kept both, stripped the conflict markers. - orientation.py: removed the precheck call and the _detect_all_pages_orientations function (B6). Main's docstring already described the regression; preserved the audit contract. Kept the A-side 0.3.0 -> 0.4.0 uv.lock version bump (package version was already bumped in A; no further change).
Likivik
added a commit
that referenced
this pull request
Oct 17, 2026
…ters (#73) G1: stamp-skip now compares live WebDAV (size, etag) against the stored fingerprint before trusting the stamp. Match → skip as today; mismatch → log a WARNING naming BOTH fingerprints and re-OCR the file. Stored fingerprint NULL (row ended in error/gone or never recorded) → fall back to stamp-only skip at debug level. G2: per-path counter (foreign_rewrites column, idempotent migration following the C6 / PR #68 pattern) bounds the loop. After FOREIGN_REWRITE_LIMIT=3 consecutive foreign rewrites the guard stops auto-re-OCRing and records reason='foreign_rewrite' so the operator knows the competing writer has won. ERROR logged exactly once on the crossing; subsequent mismatches at the cap are silent. G3: /stats.foreign_rewrites (sum across rows) added so the NC panel can surface the cumulative count. Also a one-line INFO at startup so an operator can confirm the guard is compiled in. G4: tests/test_fingerprint_guard.py pins every behaviour: (a) stamp + mismatch → re-OCR, WARNING names stored+live, (b) stamp + match → skipped, counter reset, (c) NULL stored fingerprint → skipped as today, PROPFIND skipped, (d) 3 mismatches → reason='foreign_rewrite', cap stops the bump, (e) /stats.foreign_rewrites == SUM of per-path counters, (f) self-test that a no-op guard reverts to silent skip.
Likivik
added a commit
that referenced
this pull request
Oct 17, 2026
Two concurrent `force=True` callers for the same path used to slip between the in-flight check and the durable insert and produce two `jobs` rows for one file — the Nextcloud app's "Re-OCR anyway" button double-clicked, or /rescan racing a /webhook, each double-billed Vision. CI's timing exposed the race even when local runs serialised the threads favourably. In-process fix: single critical section --------------------------------------- The previous `_enqueue` held TWO separate critical sections: `with _enqueue_path_lock(...):` did the `in_flight_job_for_path` check and returned `status='already_running'` if a queued/running row existed, but released the lock before any insert; then `with _enqueue_lock_for(...):` did the `file_put` + `record_enqueue` with a re-check (`if _path_in_flight(...) and not force`) that `force=True` skipped altogether. Two threads could each pass the in-flight check, then both insert. This commit collapses both sections into ONE `with _enqueue_path_lock` that spans the in-flight check AND the durable writes, so any second caller arriving on the same path blocks on the lock and, once admitted, sees the row the first caller just inserted (returning `status='already_running'`). `force` still does NOT bypass the in-flight gate (that was the whole point of the lock), but continues to bypass the born-digital / stamp / recently-processed-TTL guards downstream in `_process_file` — those semantics are unchanged. The duplicate lock machinery is also collapsed: `_enqueue_lock_for` and its companion `_ENQUEUE_LOCKS_GUARD` were redundant — the B5 helper `_enqueue_path_lock` is the sole `_ENQUEUE_LOCKS` mutator, with the same TTL-sweep behaviour kept. Cross-process fix: DB unique partial index ------------------------------------------ The in-process lock only protects threads within ONE process. Two workers in separate processes (one uvicorn × N workers) can still both pass the in-flight check and both insert. The DB is the only thing they share, so the invariant has to live there too. * `_migrate_inflight_unique_index` (called LAST from `init()`, after every column-add it depends on, per the PR #68 ordering lesson) creates a UNIQUE PARTIAL INDEX `jobs(path) WHERE status IN ('queued','running')`. Dedupes any pre-existing duplicate queued/running rows for the same path FIRST — running wins over queued, lowest-id wins within a status, matching `claim_next`'s ordering — otherwise CREATE UNIQUE INDEX would fail and abort `init()`. Idempotent (IF NOT EXISTS) so re-runs are safe. * `record_enqueue` now distinguishes IntegrityError causes: an explicit-id collision still raises RuntimeError (the legacy loud fail that catches service-boot counter resets); the path-collision via `uq_jobs_inflight` returns None with a clear log line. * `_enqueue` treats None from `record_enqueue` as a cross-process collision: looks up the winner via `in_flight_job_for_path` and returns it with `status='already_running'`. Same observable contract as the in-process race. * `record_retry` / `enqueue_retry` (the SECOND insert path that bypassed `_enqueue` and called `record_enqueue` directly) now log-and-skip when the path is already in flight, returning None rather than raising into the worker / retry loop. Migration safety ---------------- The retry-index migration ordering bug from PR #68 left the service in the no-op state with every counter at zero on its first rollout because the index was created before the columns. The new migration follows the same discipline: `CREATE UNIQUE INDEX` lives in a function called AFTER every ALTER, never in `_SCHEMA_SQL`. The dedupe runs inside the same migration so CREATE UNIQUE INDEX never sees a duplicate set. The CREATE statement uses IF NOT EXISTS so re-runs are no-ops. The migration function itself catches and logs on any failure without raising — the surrounding `init()` try/except ensures `_ready()` is set only on full success, so a broken migration leaves the service in a defined (no-op) state rather than a half-migrated one. Tests ----- * `test_force_inflight_gate_holds_check_and_insert_atomically` — deterministic regression. Splits the path lock into two per-caller objects (so the buggy code's two `with` blocks see independent locks), controls `in_flight_job_for_path` to make the first call signal T1 has reached the gate and the second call wait for that signal then run the real query, and sleeps `record_enqueue` for 50 ms so T2 reliably reaches its in-flight check before T1 inserts. OLD code: T2's first lock is free while T1 is mid-insert → both insert → two rows → `['queued', 'queued']`. FIX: T2's single lock resolves to the same object T1 holds → T2 blocks behind T1 → T2 sees the row → `['already_running', 'queued']`. Verified 20/20 fail on the buggy code, 20/20 pass on the fix. * `test_enqueue_cross_process_collision_returns_already_running` — the DB-backstop branch of `_enqueue`. Monkeypatches `in_flight_job_for_path` to lie on the FIRST call (so `_enqueue` proceeds past the in-lock gate) but run normally on subsequent calls (so the post-insert fallback sees the winner). The seeded row + the monkeypatched pre-check + the `uq_jobs_inflight` rejection together force the cross-process path; `_enqueue` must return `status='already_running'` from the fallback branch. * 4 migration tests in `test_jobstore_migration.py` — `test_migration_dedupes_duplicate_queued_rows_before_creating_index` builds a pre-existing DB with two queued rows for one path and asserts init() succeeds, the dedupe keeps the lowest-id queued row, and the index lands; `test_migration_dedupes_running_over_queued` proves the dedupe is status-aware (running wins over queued even at a higher id); `test_migration_creates_index_without_duplicates` pins the clean-DB shape; `test_migration_is_idempotent` proves re-running init() is a no-op. Same failure mode PR #68 caught (migration aborts → ready=False → every counter at zero) is impossible here: a DB full of duplicates still ends up with `_ready() == True` and exactly one queued row per path. * 4 in-process tests in `test_jobstore.py` — `test_record_enqueue_returns_none_on_path_collision` (the IntegrityError → None translation), `test_record_enqueue_still_raises_on_explicit_id_collision` (the legacy loud-fail path is preserved), `test_enqueue_retry_skips_when_path_already_in_flight` and `test_record_retry_skips_when_path_already_in_flight` close the retry-path hole. * `test_two_force_concurrent_enqueues_produce_one_jobs_row` still passes (it relied on the lock serialising the threads; the fix preserves that property). * `test_enqueue_lock_cache_evicts_idle_entries` still passes (B5 TTL-sweep behaviour unchanged). * Full suite: 251 passed + the 1 known local-only PP-LCNet failure (passes in CI; absent ONNX model). Before/after interleaving ------------------------- In-process, two `with` blocks (BUGGY): ``` T1: [acquire lock A] check→None [release lock A] ↓ T2 squeezes in here ↓ T2: [acquire lock A] check→None [release lock A] T1: [acquire lock A] force-bypass file_put record_enqueue(row #1) [release lock A] T2: [acquire lock A] force-bypass file_put record_enqueue(row #2) [release lock A] → 2 jobs rows, double Vision bill ``` In-process, single `with` block (FIX): ``` T1: [acquire lock] check→None file_put record_enqueue(row #1) [release lock] T2: [acquire lock — blocks until T1 releases] check→row #1 → returns already_running → 1 jobs row + 1 already_running handoff ``` Cross-process (FIX, DB backstop): ``` Process A: [acquire lock] check→None file_put record_enqueue(row #1) [release lock] Process B: [acquire lock — does NOT block on A's lock; separate process] check→None file_put record_enqueue → uq_jobs_inflight IntegrityError → None → look up winner → already_running → 1 jobs row + 1 already_running handoff ``` Out of scope ------------ The Google engine, fingerprint/foreign-rewrite guard, retry counters, and `modules/` (a different change owns the nix side) are all untouched.
Likivik
added a commit
that referenced
this pull request
Oct 17, 2026
Two concurrent `force=True` callers for the same path used to slip between the in-flight check and the durable insert and produce two `jobs` rows for one file — the Nextcloud app's "Re-OCR anyway" button double-clicked, or /rescan racing a /webhook, each double-billed Vision. CI's timing exposed the race even when local runs serialised the threads favourably. In-process fix: single critical section --------------------------------------- The previous `_enqueue` held TWO separate critical sections: `with _enqueue_path_lock(...):` did the `in_flight_job_for_path` check and returned `status='already_running'` if a queued/running row existed, but released the lock before any insert; then `with _enqueue_lock_for(...):` did the `file_put` + `record_enqueue` with a re-check (`if _path_in_flight(...) and not force`) that `force=True` skipped altogether. Two threads could each pass the in-flight check, then both insert. This commit collapses both sections into ONE `with _enqueue_path_lock` that spans the in-flight check AND the durable writes, so any second caller arriving on the same path blocks on the lock and, once admitted, sees the row the first caller just inserted (returning `status='already_running'`). `force` still does NOT bypass the in-flight gate (that was the whole point of the lock), but continues to bypass the born-digital / stamp / recently-processed-TTL guards downstream in `_process_file` — those semantics are unchanged. The duplicate lock machinery is also collapsed: `_enqueue_lock_for` and its companion `_ENQUEUE_LOCKS_GUARD` were redundant — the B5 helper `_enqueue_path_lock` is the sole `_ENQUEUE_LOCKS` mutator, with the same TTL-sweep behaviour kept. Cross-process fix: DB unique partial index ------------------------------------------ The in-process lock only protects threads within ONE process. Two workers in separate processes (one uvicorn × N workers) can still both pass the in-flight check and both insert. The DB is the only thing they share, so the invariant has to live there too. * `_migrate_inflight_unique_index` (called LAST from `init()`, after every column-add it depends on, per the PR #68 ordering lesson) creates a UNIQUE PARTIAL INDEX `jobs(path) WHERE status IN ('queued','running')`. Dedupes any pre-existing duplicate queued/running rows for the same path FIRST — running wins over queued, lowest-id wins within a status, matching `claim_next`'s ordering — otherwise CREATE UNIQUE INDEX would fail and abort `init()`. Idempotent (IF NOT EXISTS) so re-runs are safe. * `record_enqueue` now distinguishes IntegrityError causes: an explicit-id collision still raises RuntimeError (the legacy loud fail that catches service-boot counter resets); the path-collision via `uq_jobs_inflight` returns None with a clear log line. * `_enqueue` treats None from `record_enqueue` as a cross-process collision: looks up the winner via `in_flight_job_for_path` and returns it with `status='already_running'`. Same observable contract as the in-process race. * `record_retry` / `enqueue_retry` (the SECOND insert path that bypassed `_enqueue` and called `record_enqueue` directly) now log-and-skip when the path is already in flight, returning None rather than raising into the worker / retry loop. Migration safety ---------------- The retry-index migration ordering bug from PR #68 left the service in the no-op state with every counter at zero on its first rollout because the index was created before the columns. The new migration follows the same discipline: `CREATE UNIQUE INDEX` lives in a function called AFTER every ALTER, never in `_SCHEMA_SQL`. The dedupe runs inside the same migration so CREATE UNIQUE INDEX never sees a duplicate set. The CREATE statement uses IF NOT EXISTS so re-runs are no-ops. The migration function itself catches and logs on any failure without raising — the surrounding `init()` try/except ensures `_ready()` is set only on full success, so a broken migration leaves the service in a defined (no-op) state rather than a half-migrated one. Tests ----- * `test_force_inflight_gate_holds_check_and_insert_atomically` — deterministic regression. Splits the path lock into two per-caller objects (so the buggy code's two `with` blocks see independent locks), controls `in_flight_job_for_path` to make the first call signal T1 has reached the gate and the second call wait for that signal then run the real query, and sleeps `record_enqueue` for 50 ms so T2 reliably reaches its in-flight check before T1 inserts. OLD code: T2's first lock is free while T1 is mid-insert → both insert → two rows → `['queued', 'queued']`. FIX: T2's single lock resolves to the same object T1 holds → T2 blocks behind T1 → T2 sees the row → `['already_running', 'queued']`. Verified 20/20 fail on the buggy code, 20/20 pass on the fix. * `test_enqueue_cross_process_collision_returns_already_running` — the DB-backstop branch of `_enqueue`. Monkeypatches `in_flight_job_for_path` to lie on the FIRST call (so `_enqueue` proceeds past the in-lock gate) but run normally on subsequent calls (so the post-insert fallback sees the winner). The seeded row + the monkeypatched pre-check + the `uq_jobs_inflight` rejection together force the cross-process path; `_enqueue` must return `status='already_running'` from the fallback branch. * 4 migration tests in `test_jobstore_migration.py` — `test_migration_dedupes_duplicate_queued_rows_before_creating_index` builds a pre-existing DB with two queued rows for one path and asserts init() succeeds, the dedupe keeps the lowest-id queued row, and the index lands; `test_migration_dedupes_running_over_queued` proves the dedupe is status-aware (running wins over queued even at a higher id); `test_migration_creates_index_without_duplicates` pins the clean-DB shape; `test_migration_is_idempotent` proves re-running init() is a no-op. Same failure mode PR #68 caught (migration aborts → ready=False → every counter at zero) is impossible here: a DB full of duplicates still ends up with `_ready() == True` and exactly one queued row per path. * 4 in-process tests in `test_jobstore.py` — `test_record_enqueue_returns_none_on_path_collision` (the IntegrityError → None translation), `test_record_enqueue_still_raises_on_explicit_id_collision` (the legacy loud-fail path is preserved), `test_enqueue_retry_skips_when_path_already_in_flight` and `test_record_retry_skips_when_path_already_in_flight` close the retry-path hole. * `test_two_force_concurrent_enqueues_produce_one_jobs_row` still passes (it relied on the lock serialising the threads; the fix preserves that property). * `test_enqueue_lock_cache_evicts_idle_entries` still passes (B5 TTL-sweep behaviour unchanged). * Full suite: 251 passed + the 1 known local-only PP-LCNet failure (passes in CI; absent ONNX model). Before/after interleaving ------------------------- In-process, two `with` blocks (BUGGY): ``` T1: [acquire lock A] check→None [release lock A] ↓ T2 squeezes in here ↓ T2: [acquire lock A] check→None [release lock A] T1: [acquire lock A] force-bypass file_put record_enqueue(row #1) [release lock A] T2: [acquire lock A] force-bypass file_put record_enqueue(row #2) [release lock A] → 2 jobs rows, double Vision bill ``` In-process, single `with` block (FIX): ``` T1: [acquire lock] check→None file_put record_enqueue(row #1) [release lock] T2: [acquire lock — blocks until T1 releases] check→row #1 → returns already_running → 1 jobs row + 1 already_running handoff ``` Cross-process (FIX, DB backstop): ``` Process A: [acquire lock] check→None file_put record_enqueue(row #1) [release lock] Process B: [acquire lock — does NOT block on A's lock; separate process] check→None file_put record_enqueue → uq_jobs_inflight IntegrityError → None → look up winner → already_running → 1 jobs row + 1 already_running handoff ``` Out of scope ------------ The Google engine, fingerprint/foreign-rewrite guard, retry counters, and `modules/` (a different change owns the nix side) are all untouched.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Impact
The retry-column migration from #65 put
CREATE INDEX idx_jobs_next_run ON jobs(next_run_at)in_SCHEMA_SQL, which runs before_migrate_add_retry_columns. On a database created before those columns existed, the index statement raisedno such column: next_run_at,init()aborted, and jobstore stayed in its no-op state:Consequences on poweredge after deploying #65:
/statsand/statesreturned zeros against an intact 58-rowfilestable / 110-rowjobstable, and the service ran with no job history or file index at all.Every test DB was freshly created (so it already had the columns), which is why the whole suite passed while production was broken.
Fix
Create the index inside
_migrate_add_retry_columns, after itsALTER TABLEs. Plustests/test_jobstore_migration.py, which builds the pre-C6 schema by hand and runs the realinit()— verified to fail with the old ordering and pass with the new one.Verification against production data
Copied the live
jobs.dbfrom poweredge and ran the fixed jobstore against the copy:Full suite: 216 passed, 1 failed (the known local PP-LCNet model absence).