Skip to content

fix(nc-ocr-flow): harden the job pipeline (foreign users, atomic overwrite, reconcile, retries) - #65

Merged
Likivik merged 1 commit into
mainfrom
ocrfix2-pipeline
Oct 16, 2026
Merged

Likivik merged 1 commit into
mainfrom
ocrfix2-pipeline

Conversation

@Likivik

@Likivik Likivik commented Oct 16, 2026

Copy link
Copy Markdown
Owner

Second batch of OCR fixes, following the review findings in #64.

Changes

  • Foreign-user paths are refused at the boundary (reason='foreign_user', 200) instead of 401-ing against WebDAV as the service user and ending as an opaque error job. /rescan rejects them with 422.
  • Image→PDF: a failed source-image delete is no longer silent — the job records reason='image_delete_failed', keeps both files, and never deletes the PDF.
  • Atomic overwrite: the in-place PDF path now PUTs to a sibling .ocr-tmp-* object and MOVEs it onto the target (sabre MOVE is atomic), cleaning up the temp on failure. A truncated upload can no longer replace the user's file.
  • /jobs/{id} 404s now say the record was pruned and point at /states, so the app can't render it as "never OCR'd".
  • Reconcile pass (POST /reconcile, also run on startup): file rows in error/queued whose path 404s are marked gone instead of staying permanent errors. Bounded (limit/max_propfind, default 500). This is what clears the 36 phantom errors seen in production — all 36 are rows for deleted test probes.
  • Bounded retries: transient failures (5xx/408/429/timeouts/connection errors) are retried up to 2× with 60s/300s backoff via new jobs columns (attempts, next_run_at, additive migration). Permanent failures (404/gone, unsupported mime, too large, zero-block OCR, foreign user) never retry. /stats exposes retries_total/retries_queued.
  • 'gone' status contract locked by tests against /states and /stats.

Tests

cd pkgs/nc-ocr-flow && .venv/bin/python -m pytest tests/ -q → 213 passed, 1 failed. The failure is the known local-only test_orientation.py::…test_takes_pp_lcnet_when_confident (PP-LCNet model absent here; passes in CI). 17 new tests added for the items above.

Not in this PR

The parallel review of the un-audited code found a critical bug: the minimax engine never writes output_pdf, so every minimax job dies in _finalize with FileNotFoundError. Fixed separately (it touches ocr.py/minimax_engine.py, not this file).

…write, reconcile, retries)

- foreign-user paths are refused at the boundary (reason='foreign_user') instead
  of 401-ing against WebDAV and ending as an opaque error job.
- image->PDF: a failed source delete no longer passes silently — reason
  'image_delete_failed' is recorded and both files are kept.
- PDF overwrite goes through PUT-to-temp + atomic WebDAV MOVE, so a partial
  upload can no longer leave a truncated file in place of the original.
- /jobs/{id} 404 now explains that the row was pruned and points at /states.
- new bounded reconcile pass (POST /reconcile, also on startup) marks file rows
  whose path 404s as 'gone' instead of leaving them as permanent errors — this
  is what clears the 36 phantom errors seen in production.
- transient failures (5xx/408/429/timeouts/connection errors) are retried up to
  2 times with 60s/300s backoff via new jobs columns (attempts, next_run_at);
  permanent failures never retry. /stats exposes retries_total/retries_queued.
- 'gone' status contract locked by a test against /states and /stats.
Comment on lines +2964 to +2968
return reconcile_stale_files(
limit=body.limit,
max_propfind=body.max_propfind,
statuses=body.statuses,
)
@Likivik
Likivik merged commit bd92479 into main Oct 16, 2026
7 checks passed
@Likivik
Likivik deleted the ocrfix2-pipeline branch October 16, 2026 17:46
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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants