Repository navigation
fix(nc-ocr-flow): atomic in-flight gate in _enqueue under a single lock - #74
Merged
Merged
Conversation
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
force-pushed
the
fix-enqueue-inflight-race
branch
from
October 17, 2026 19:20
e121674 to
72d0e9e
Compare
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.
What
Two concurrent
force=Truecallers for the same NC path used to slipbetween the in-flight check and the durable insert and produce two
jobsrows for one file — the Nextcloud app's "Re-OCR anyway" buttondouble-clicked, or
/rescanracing a/webhook, each double-billedGoogle Vision. CI's timing exposed the race even when local runs
serialised the threads favourably (see the existing
test_two_force_concurrent_enqueues_produce_one_jobs_row).This PR closes the hole at two layers — in-process (lock) and
cross-process (DB unique partial index) — and on TWO insert paths
(
_enqueueand the retry helpers that bypass it).The race (in-process)
The previous
_enqueueheld TWO separate critical sections:T1 acquires lock A, sees nothing in flight, releases. T2 acquires
lock A (T1 released), sees nothing in flight (T1 hasn't inserted
yet), releases. T1 acquires lock A again, force-bypasses the
re-check,
file_put+record_enqueue. T2 acquires lock A,force-bypasses the re-check,
file_put+record_enqueue. Twojobsrows → two Vision bills for one file.The hole (retry path bypasses
_enqueue)jobstore.record_retryandjobstore.enqueue_retrybuild a freshjobsrow withstatus='queued'for the SAME path and callrecord_enqueue(new_retry)directly — they never go through_enqueue. So a retry scheduled for a path that already has aqueued/running job yields two queued rows for one path = two Vision
runs = the same double-billing bug. The in-process lock alone does
not cover this hole.
Layer 1 — in-process: single critical section
A second caller arriving on the same path blocks on the per-path
lock and, once admitted, sees the row the first caller just
inserted (returning
status='already_running').forcestill does NOT bypass the in-flight gate (that was thewhole 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_forand its companion
_ENQUEUE_LOCKS_GUARDare gone; the B5 helper_enqueue_path_lockis the sole_ENQUEUE_LOCKSmutator, withthe same TTL-sweep behaviour kept (
_ENQUEUE_LOCKS_LAST_USED,_ENQUEUE_LOCK_TTL_S, sweep on acquire).Layer 2 — cross-process:
uq_jobs_inflightpartial unique indexThe 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 frominit(),after every column-add it depends on, per the PR fix(nc-ocr-flow): create the retry index after the ALTERs (jobstore init was dead on existing DBs) #68 ordering
lesson) creates
CREATE UNIQUE INDEX uq_jobs_inflight ON jobs(path) WHERE status IN ('queued','running'). Dedupesany pre-existing duplicate queued/running rows for the same
path FIRST — running wins over queued (so a worker mid-flight
is not orphaned), lowest-id wins within a status (matching
claim_next's ordering) — otherwiseCREATE UNIQUE INDEXwould fail and abort
init(). Idempotent (IF NOT EXISTS) sore-runs are safe.
record_enqueuenow distinguishes IntegrityError causes: anexplicit-id collision still raises RuntimeError (the legacy loud
fail that catches service-boot counter resets); the
path-collision via
uq_jobs_inflightreturnsNonewith aclear log line.
_enqueuetreatsNonefromrecord_enqueueas across-process collision: looks up the winner via
in_flight_job_for_pathand returns it withstatus='already_running'. Same observable contract as thein-process race.
record_retry/enqueue_retrynow log-and-skip when thepath is already in flight, returning
Nonerather than raisinginto the worker / retry loop. They share the IntegrityError →
Nonetranslation thatrecord_enqueuedoes for them.The retry path was the easier hole to miss but the more dangerous
one — a transient failure on a freshly-OCR'd file would have
crashed the worker when the retry collided with a queued duplicate.
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 INDEXlives in afunction called AFTER every ALTER, never in
_SCHEMA_SQL. Thededupe runs inside the same migration so
CREATE UNIQUE INDEXnever sees a duplicate set. The CREATE statement uses
IF NOT EXISTSso re-runs are no-ops. The migration function itselfcatches and logs on any failure without raising — the surrounding
init()try/except ensures_ready()is set only on fullsuccess, 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 for the in-process race. Splits
_enqueue_path_lockinto two per-caller objects (so the buggycode's two
withblocks see independent locks — the originalbuggy design intent), controls
in_flight_job_for_pathso thefirst call signals "T1 is at the gate" and the second call
waits for that signal then runs the real query, and sleeps
record_enqueuefor 50 ms so T2 reliably reaches its in-flightcheck before T1 inserts. With the bug: T2's first lock is free
while T1 is mid-insert → both insert →
['queued', 'queued']→two rows. With the 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 thebuggy code, 20/20 pass on the fix (no timing sensitivity).
test_enqueue_cross_process_collision_returns_already_running—pins the DB-backstop branch of
_enqueue. Monkeypatchesin_flight_job_for_pathto lie on the FIRST call (so_enqueueproceeds past the in-lock gate) but run normally on subsequent
calls (so the post-insert fallback sees the winner). Together
with the seeded row this forces the cross-process path;
_enqueuemust returnstatus='already_running'from thefallback branch.
test_jobstore_migration.py:test_migration_dedupes_duplicate_queued_rows_before_creating_indexbuilds 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_queuedproves thededupe is status-aware (running wins over queued even at a
higher id).
test_migration_creates_index_without_duplicatespins theclean-DB shape.
test_migration_is_idempotentproves re-running init() is ano-op.
test_jobstore.py:test_record_enqueue_returns_none_on_path_collision(theIntegrityError →
Nonetranslation).test_record_enqueue_still_raises_on_explicit_id_collision(the legacy loud-fail path is preserved).
test_enqueue_retry_skips_when_path_already_in_flightclosesthe retry-path hole for the worker-facing helper.
test_record_retry_skips_when_path_already_in_flightclosesthe retry-path hole for the legacy / low-level helper.
test_two_force_concurrent_enqueues_produce_one_jobs_rowstillpasses — it relied on the lock serialising the threads; the fix
preserves that property.
test_enqueue_lock_cache_evicts_idle_entriesstill passes (B5TTL-sweep behaviour unchanged).
(passes in CI; the ONNX model is absent locally).
Before/after interleaving
Before (two
withblocks, separate acquisitions):After (one
withblock, single acquisition):Cross-process (after the DB backstop is installed):
Retry path (after the DB backstop is installed):
Out of scope
The Google engine, fingerprint/foreign-rewrite guard, retry
counters, and
modules/(a different change owns the nix side) areall untouched.