Skip to content

fix(nc-ocr-flow): make job ids collision-free across restarts; fix dead mtime-based venv guard - #57

Merged
Likivik merged 2 commits into
mainfrom
feat/nc-ocr-jobseq-collision
Oct 15, 2026
Merged

Likivik merged 2 commits into
mainfrom
feat/nc-ocr-jobseq-collision

Conversation

@Likivik

@Likivik Likivik commented Oct 15, 2026

Copy link
Copy Markdown
Owner

Fixes the immediate blocker for the user's goal of re-OCR'ing the corpus on poweredge, plus a sibling dead venv-rebuild guard.

Bug 1 (PRIMARY) — every service restart silently broke the queue

webhook_server assigned ids from itertools.count(1) (process-local; restarts at 1 on every boot) while jobstore.record_enqueue used INSERT OR IGNORE against the persistent jobs SQLite table. After a restart, the first batch of new enqueues collided with persisted ids, the conflict was silently discarded, and the durable queue never grew — the symptom on poweredge (journal: scan-all: enqueued=10 and no worker: job N start lines; files.status = 'queued').

Fix: SQLite is now the sole source of truth for the row sequence. record_enqueue either accepts an explicit id (raising RuntimeError on collision — never silent no-op), or omits the column and reads back lastrowid. The in-memory _job_seq counter is gone, the import itertools is gone with it.

Bug 2 — dead mtime-based venv-rebuild guard

The nc-ocr-webhook start script checked [ ".installed" -ot "<nix store source>" ] before reinstalling the venv. Every file in /nix/store carries a synthetic 1970-01-01 mtime, so the test was always false — the deployed venv has been frozen at 2026-09-27.

Fix: the marker file /var/lib/nc-ocr/venv-v4/.installed is now a content-hash manifest (one <store-path>=<sha256> line per tracked source). On start we compute the current sha256 of each source and compare; any mismatch or missing line triggers a reinstall. No reinstall happens unless a source file actually changed.

Added pkgs.coreutils, pkgs.gawk, pkgs.gnused, pkgs.gnugrep to the systemd ExecStart path so the new shell helpers (sha256sum, awk, sed, grep) resolve under NixOS's minimal systemd PATH.

Regression tests

tests/test_jobstore.py::test_record_enqueue_no_silent_collision_after_restart simulates a service restart (drop module from sys.modules, reimport, init): inserts 50 rows in "process A", then 20 more in "process B" without pre-setting id (the production contract). It asserts the new ids exceed A's high-water mark, all 70 rows survive, the worker can claim all 20 newly-enqueued rows, and an explicit-id collision raises loudly.

tests/test_jobstore.py::test_no_in_memory_job_mirror extended with assert not hasattr(ws, "_job_seq") so a future reintroduction of the counter is caught immediately.

Local verification

PYTHONPATH=src NC_OCR_ORIENTATION_MODEL=… .venv-test/bin/python -m pytest tests/:

162 passed in 163s (1 more than baseline — the new regression).

Nix: nix eval --impure … nixosConfigurations.poweredge.config.systemd.services."nc-ocr-webhook".script returns a derivation whose nix-instantiate --parse evaluates cleanly. nix build --dry-run … #poweredge.config.system.build.toplevel completes with only benign warnings (Nextcloud pre-26.11 notice; preexisting). I did NOT run a full Nix build (cache-fetched closures take 10–30 min on this host) and did NOT deploy per the "do not deploy" constraint.

Out of scope (mentioned for the reviewer)

  • modules/aspects/server/hr-bot/hr-bot.nix has the identical dead-mtime-guard bug (if … [ "${botVenv}/.installed" -ot "${botDir}/hr_bot.py" ]). The same content-hash fix applies verbatim; happy to land in a follow-up PR.
  • The production jobs table schema is id INTEGER PRIMARY KEY (no AUTOINCREMENT). Strict monotonicity across DELETE+INSERT would require AUTOINCREMENT, but that's a separate concern from collision-free ids for new rows — INTEGER PRIMARY KEY already auto-assigns the next rowid. I did not migrate the existing live schema (would touch 99 rows of history; out of scope here).

No changes to the deployed venv, /var/lib/nc-ocr/jobs.db, the OC pipeline, or any Nextcloud state.

…ad mtime-based venv guard

Bug #1 (PRIMARY): every nc-ocr-flow service restart silently broke the
job queue. ``webhook_server`` assigned ids from ``itertools.count(1)``
(a process-local counter that restarted at 1 on every boot) while
``jobstore.record_enqueue`` used ``INSERT OR IGNORE`` against the
``jobs`` SQLite table. After a restart, the first batch of new
enqueues collided with persisted ids, the conflict was silently
ignored, and the durable queue never grew — matching the symptom on
poweredge where ``POST /scan-all`` logged ``enqueued=10`` and the
worker thread logged nothing.

Fix: SQLite is now the sole source of truth for the row sequence.
``record_enqueue`` either accepts an explicit ``id`` (raising
``RuntimeError`` on collision — never silent), or omits the column and
reads back ``lastrowid``. The in-memory ``_job_seq`` counter in
``webhook_server`` is gone, and the ``itertools`` import is gone with
it. A regression test simulates a service restart (module reload),
asserts that newly-assigned ids exceed the previous process's
high-water mark, and that an explicit-id collision raises loudly.

Bug #2: the ``nc-ocr-webhook`` start script compared the venv marker
mtime against the source files in ``/nix/store``. Every file there
carries a synthetic 1970-01-01 mtime, so the ``-ot`` test was always
false and the venv has been frozen at the 2026-09-27 install. Fix:
write a content-hash manifest (``<path>=<sha256>``) into the marker
file at install time, and on start compare each entry against the
current sha256 of the source. Any mismatch triggers a reinstall. The
change is fully opt-in on restart; no venv rebuild happens unless a
source file actually changed.

Local CI run: 162 passed (1 more than baseline — the new
``test_record_enqueue_no_silent_collision_after_restart`` regression).
Nix evaluation: ``nix eval .#nixosConfigurations.poweredge.config``
succeeds and the rebuilt ``nc-ocr-webhook-start`` derivation evaluates
to a content-based install + manifest write. I did not run a full Nix
build or a live-host integration test (per the "do not deploy"
constraint).

Notes (out of scope, surface in PR): ``hr-bot/hr-bot.nix`` has the
identical mtime-based dead-guard bug — copy-paste of the same fix
applies, but I limited this PR to the OCR flow per the brief.
@Likivik
Likivik merged commit 112ab0e into main Oct 15, 2026
7 checks passed
@Likivik
Likivik deleted the feat/nc-ocr-jobseq-collision branch October 15, 2026 20:55
Likivik added a commit that referenced this pull request Nov 12, 2026
* deploy(poweredge): bump ocrflow to ebaf690 (engine policy, scoped status API, claim guard)

* deploy(poweredge): ocrflow 5559437 — one engine option, readable Google key

* deploy(poweredge): ocrflow 1fba10e — seeding unit names the real nextcloud user

* deploy(poweredge): ocrflow 937db35 — Google batch project id

* poweredge(ocr): point google-ocr at the ocr-project-tmp bucket, not a bucket it may create

* poweredge(ocr): worker moves bytes over the app API, not WebDAV

* deploy(poweredge): ocrflow api-transport fixes (byte fetch + enqueue id)

* deploy(poweredge): ocrflow pages/chars reporting

* feat(nc-rag): enable cross-encoder reranking in nextcloud-mcp

SEARCH_RERANK_URL points at serenity's llama-reranker (:8082/v1/rerank)
via the direct Cohere-protocol path, so no gateway M2M token is needed.
Also opens 8082 on tailscale0 explicitly instead of relying on the port
happening to be reachable.

* fix(nc-rag): rerank top-50 with a 120s timeout

The upstream 30s default times out when 200 chunks of up to 2000 chars are
scored on the 1660, and nc-mcp degrades silently to retrieval order — so
reranking was on paper only. Measured ~0.09s/doc; 50 candidates keeps
latency ~8s and 120s absorbs a cold GPU.

* deploy(poweredge): four OCR failure-class fixes

* deploy(poweredge): real failure sites (#57)

* deploy(poweredge): pdfio, reason codes, empty-source skip, readiness, retry

* deploy(poweredge): reason codes, stage events, 422 classification (#64-#69)

* feat(hermes): bump to v0.23.1 with a local patchelf gate

v0.23.1's nix/pm-packages.nix backports NixOS/patchelf#672 onto patchelf
unconditionally. That patch is written for 0.19 and rejects 4/6 hunks
against the 0.15.2 that nixpkgs reverted to (61a15beb37, 2026-10-30,
tracking #577387), so nothing built.

- apply upstream PR NousResearch/hermes-agent#152542 (gates the backport
  to 0.19.0-0.19.2) over the flake source and callPackage from it
- use hermes-agent's OWN uv2nix/pyproject stack: its python.nix passes
  default-groups, which our older uv2nix rejects
- pin nix/pnpm-deps-hash to the store hash fetchPnpmDeps produces on our
  nixpkgs; upstream's was made with 02c087f

Drop both patches once a released tag carries the gate and we bump nixpkgs.

* test(smoke): read the expected hermes version from /etc

The probe hardcoded *v0.21.7*, so the 0.23.1 build reported HERMES_VERSION_BAD
and the gate failed on a stale literal rather than on the system.

The aspect now writes /etc/hermes-expected-version from the same hermesVersion
that builds the package; the probe compares against it and keeps a literal only
as a loud fallback.

VM smoke: PASS (28 running / 68 loaded services, both ZFS pool imports
allowlisted as guest-impossible).

---------

Co-authored-by: Likivik <[email protected]>
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