Skip to content

fix(nc-ocr-flow): minimax output-PDF bug, engine contract, orientation precheck, NC app 'gone' handling - #66

Merged
Likivik merged 2 commits into
mainfrom
ocrfix3-contract
Oct 16, 2026
Merged

Likivik merged 2 commits into
mainfrom
ocrfix3-contract

Conversation

@Likivik

@Likivik Likivik commented Oct 16, 2026

Copy link
Copy Markdown
Owner

Third batch, from the review of the previously unaudited code (orchestrator, engines, orientation, Nextcloud app).

Critical

Every minimax job failed end-to-end. minimax_engine.process_pdf opened the input document (fitz.open(pdf_path)) and called saveIncr(), which writes back to the path it was loaded from — so output_pdf was never created, and ocr._finalize's fitz.open(out_pdf) raised FileNotFoundError. Dormant in production only because NC_OCR_ENGINE=google; selectable, and invisible to CI because the tests only exercised ocr_page_minimax directly.

  • Fixed by seeding out_pdf the way google_engine does, and dropping the redundant in-engine embed + save (the orchestrator owns the text layer). New end-to-end test asserts the output PDF exists and carries the layer; it fails without the fix.

Orchestrator

  • _finalize no longer depends on the engine having pre-seeded out_pdf — it seeds from the orchestrator's input when needed, so a future engine that forgets cannot reproduce the minimax failure.
  • The temp upright PDF is unlinked in a finally, so an engine exception no longer leaks it into /tmp.
  • NC_OCR_DISABLE_ORIENTATION is now case-insensitive (TRUE/Yes previously did nothing) via a shared helper the test drives directly — the old test re-implemented the check inline, so it could never catch the drift.

Engines

  • tesseract: subprocess.TimeoutExpired is handled, so a timeout produces the same RuntimeError shape as other failures; the full-document _born_digital_pages scan (whose only consumer was a log line) is gone.

Orientation

  • preorient_pages_safe now does a cheap per-page precheck: an upright input returns the input path without a full page-by-page PDF rewrite + save. Previously every file paid that cost, including ones that later skip OCR as born-digital. Behaviour when rotation is needed is unchanged.
  • preorient_pdf works on a copy, so page.remove_rotation() can no longer mutate the caller's file.

Nextcloud app

  • FileStateService had no gone arm, so a file that vanished between webhook and worker rendered as "never processed" (offering OCR on a file that isn't there). Explicit arm added, state list documented, frontend comment added.
  • StatsService + the personal panel now surface errors, gone, errors_attempts, retries_total, retries_queued (missing keys from an older service render as —).
  • PollOcrStatus no longer passes the full NC-internal path (including the user id) in notification subject parameters; it was unused and a latent disclosure.

Tests

cd pkgs/nc-ocr-flow && .venv/bin/python -m pytest tests/ -q → 198 passed, 1 failed (test_takes_pp_lcnet_when_confident — the PP-LCNet ONNX model is absent locally; passes in CI, and the review confirmed the source logic is correct). Orientation suite: 56 passed + that one. All touched PHP files pass php -l.

…ne contract

- minimax_engine: process_pdf opened the INPUT document and called saveIncr(),
  so output_pdf was never created and ocr._finalize raised FileNotFoundError on
  every minimax job. Seed out_pdf from the input like google_engine does, and
  drop the redundant in-engine embed+save (the orchestrator owns the text layer).
  Add an end-to-end test (the old tests only covered ocr_page_minimax, which is
  why CI never caught this).
- ocr._finalize: no longer depends on the engine having pre-seeded out_pdf — it
  seeds from the orchestrator's input when needed.
- ocr.process_pdf: the temp upright PDF is cleaned up in a finally block, so an
  engine exception no longer leaks it into /tmp.
- NC_OCR_DISABLE_ORIENTATION is now case-insensitive (was .strip() only) via a
  shared helper the test drives directly — the old test re-implemented the check
  inline and could never catch the drift.
- tesseract_engine: handle subprocess.TimeoutExpired so a timeout produces the
  same RuntimeError shape as other failures; drop the full-PDF _born_digital_pages
  scan whose only consumer was a log line.
…each the NC app about 'gone'

- orientation.preorient_pages_safe: cheap per-page precheck first — upright input
  now returns the input path without a full page-by-page PDF rewrite + save (the
  old code paid that cost on every file, including ones that later skip OCR).
- orientation.preorient_pdf: work on a copy so page.remove_rotation() can no
  longer mutate the caller's file.
- ocrflow-ncapp: handle the service's 'gone' status (FileStateService had no arm,
  so a deleted file rendered as 'never processed'), surface the new
  errors/gone/errors_attempts/retries_* stats keys in the panel, and stop passing
  the full NC-internal path in notification parameters.
@Likivik
Likivik enabled auto-merge (squash) October 16, 2026 17:51
@Likivik
Likivik merged commit b7db322 into main Oct 16, 2026
7 checks passed
@Likivik
Likivik deleted the ocrfix3-contract branch October 16, 2026 17:55
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.

1 participant