Repository navigation
Spike/ci kvm - #1
Merged
Merged
Conversation
…sibility Move everything that scales with the number of files out of RAM and into jobs.db, so a million-file backlog costs no memory: - `jobs` is the work queue itself; workers claim a job atomically (BEGIN IMMEDIATE + UPDATE) instead of sharing an in-process Queue. - `files` replaces the in-memory OCR index and the ocrd path set (status/engine/reason/node_id/finished/size/etag per NC path). The legacy ocr_index.json is imported once and then renamed. - `processed` replaces the recently-processed guard, so dedup survives a restart instead of forgetting everything on every deploy. - `settings` holds panel-editable settings; a saved value wins over the nix default and the source is reported back (env/db/default). - `usage` counts pages and jobs per engine per day. Parallelism: NC_OCR_WORKERS (default 2) worker threads pull from the same queue, with per-engine semaphores (NC_OCR_MAX_CONCURRENT_GOOGLE / _TESSERACT / _MINIMAX) so raising the worker count cannot blow an API quota. Jobs left running by a crash are requeued at startup. Spend and limits: /stats and the panel show Vision pages and cost for the month (one unit per page - each PDF page counts as an individual image) plus the live rate-quota reading from Cloud Quotas and Cloud Monitoring, refreshed every 15 minutes. MiniMax limit codes and its token-plan endpoint are documented in minimax_engine.py; that engine no longer treats an HTTP 200 with an error code in the body as success. Also here: docs/openapi/redoc closed (404), /panel localhost-only with anti-frame headers, atomic node claims, WebDAV retries with backoff, request-body and path guards, /scan-all dedup by path, TOC preserved when pages are rotated. 99 tests green on poweredge.
…sh one bookmark - New "Session isolation (read this first)" section: one jj workspace per agent session, never the shared checkout (it belongs to likivik), with the workspace command, the deploy path to use, and the ancestry gate to run before moving a shared bookmark. - Rewrite the "jj handles parallel work via jj new" rule, which read as permission to work in the shared checkout. jj new does not isolate. - Replace `jj git push --all` with `jj git push --bookmark <name>`: --all sweeps other sessions bookmarks into the remote. - Deploy requires an explicit go-ahead for that specific deploy; approval to edit, commit, push or merge never carries over.
Likivik
force-pushed
the
spike/ci-kvm
branch
10 times, most recently
from
October 14, 2026 22:46
dc2175d to
0cb56c7
Compare
A hosted runner cannot cold-build the serenity closure: the build job was killed by its own 90-minute timeout with nix still running, while serenity builds the same VM in 5-10 minutes. A job that cannot finish is worse than no job, so the build and smoke jobs are gone and the cache plumbing with them (there is nothing left worth caching). Required checks are now exactly two, both fast: python tests (~30 s) and nix eval over every nixosConfiguration (~4 min). checks.serenity-smoke-vm stays as a buildable handle for the smoke VM - it is the output a fleet-wide binary cache would seed from if attic gets built. Also fixes what the gate caught: - test_webhook_api.py used the deleted in-memory queue/history. - traversal did not evaluate: five dms-shell options removed upstream, six dms plugins not in the official registry (so no src), chromium-gost referenced the removed gnome2.GConf. - spectacle did not evaluate: home-manager.backupFileExtension was defined twice with different values; the fleet-wide one is now mkDefault.
Likivik
marked this pull request as ready for review
October 14, 2026 22:58
Likivik
added a commit
that referenced
this pull request
Oct 15, 2026
…ad mtime-based venv guard (#57) * chore: empty intermediate * fix(nc-ocr-flow): make job ids collision-free across restarts; fix dead 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
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.
No description provided.