Skip to content

fix(nc-ocr-flow): atomic in-flight gate in _enqueue under a single lock - #74

Merged
Likivik merged 1 commit into
mainfrom
fix-enqueue-inflight-race
Oct 17, 2026
Merged

Likivik merged 1 commit into
mainfrom
fix-enqueue-inflight-race

Conversation

@Likivik

@Likivik Likivik commented Oct 17, 2026 •

Copy link
Copy Markdown
Owner

What

Two concurrent force=True callers for the same NC 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
Google 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
(_enqueue and the retry helpers that bypass it).

The race (in-process)

The previous _enqueue held TWO separate critical sections:

with _enqueue_path_lock(nc_path):                  # lock A
    existing = jobstore.in_flight_job_for_path(nc_path)
    if existing is not None and existing["status"] in ("queued", "running"):
        return {**existing, "status": "already_running", ...}
# lock A released here — T2 can squeeze in

with _enqueue_lock_for(nc_path):                  # same lock, but a fresh acquire
    if _path_in_flight(nc_path) and not force:    # force=True skips this!
        return job
    file_put(...)
    record_enqueue(job)

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. Two
jobs rows → two Vision bills for one file.

The hole (retry path bypasses _enqueue)

jobstore.record_retry and jobstore.enqueue_retry build a fresh
jobs row with status='queued' for the SAME path and call
record_enqueue(new_retry) directly — they never go through
_enqueue. So a retry scheduled for a path that already has a
queued/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

with _enqueue_path_lock(nc_path):
    existing = jobstore.in_flight_job_for_path(nc_path)
    if existing is not None and existing["status"] in ("queued", "running"):
        return {**existing, "status": "already_running", ...}
    _prev = jobstore.file_get(nc_path) or {}
    jobstore.file_put({**_prev, "path": nc_path, "status": "queued",
                       "node_id": node_id})
    jobstore.record_enqueue(job)

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').

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 are gone; the B5 helper
_enqueue_path_lock is the sole _ENQUEUE_LOCKS mutator, with
the same TTL-sweep behaviour kept (_ENQUEUE_LOCKS_LAST_USED,
_ENQUEUE_LOCK_TTL_S, sweep on acquire).

Layer 2 — cross-process: uq_jobs_inflight partial unique 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 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'). Dedupes
    any 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) — 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 now log-and-skip when the
    path is already in flight, returning None rather than raising
    into the worker / retry loop. They share the IntegrityError →
    None translation that record_enqueue does 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 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

  • New test_force_inflight_gate_holds_check_and_insert_atomically —
    deterministic regression for the in-process race. Splits
    _enqueue_path_lock into two per-caller objects (so the buggy
    code's two with blocks see independent locks — the original
    buggy design intent), controls in_flight_job_for_path so the
    first call signals "T1 is at the gate" and the second call
    waits for that signal then runs the real query, and sleeps
    record_enqueue for 50 ms so T2 reliably reaches its in-flight
    check 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 the
    buggy code, 20/20 pass on the fix
    (no timing sensitivity).
  • New test_enqueue_cross_process_collision_returns_already_running —
    pins 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). Together
    with the seeded row this forces the cross-process path;
    _enqueue must return status='already_running' from the
    fallback branch.
  • New 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.
  • New 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 closes
      the retry-path hole for the worker-facing helper.
    • test_record_retry_skips_when_path_already_in_flight closes
      the retry-path hole for the legacy / low-level helper.
  • 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; the ONNX model is absent locally).

Before/after interleaving

Before (two with blocks, separate acquisitions):

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

After (one with block, single acquisition):

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 (after the DB backstop is installed):

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

Retry path (after the DB backstop is installed):

Worker: job X failed, schedules retry of /a.pdf via enqueue_retry
DB: uq_jobs_inflight rejects (path /a.pdf is queued from the
    failed job's own row? no — failed rows are status='error'
    and the partial index does not cover them; but if a retry
    lands for a path that's CURRENTLY queued/running because the
    user just triggered /rescan, the index refuses and
    enqueue_retry logs + returns None).
Worker: skips the retry; the in-flight row will OCR the file,
    and "schedule one more attempt" is best-effort, not a
    hard guarantee.
→ no duplicate jobs row

Out of scope

The Google engine, fingerprint/foreign-rewrite guard, retry
counters, and modules/ (a different change owns the nix side) are
all untouched.

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
Likivik force-pushed the fix-enqueue-inflight-race branch from e121674 to 72d0e9e Compare October 17, 2026 19:20
@Likivik
Likivik merged commit 38eef1b into main Oct 17, 2026
7 checks passed
@Likivik
Likivik deleted the fix-enqueue-inflight-race branch October 17, 2026 19:25
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