Liking cljdoc? Tell your friends :D

Race Condition Analysis: Negative In-Progress Statistics

Summary

The in-progress statistics can become negative due to a race condition between the immediate-stats function and queue operations (take!, put!, mark-complete!).

The Root Cause

Formula for In-Progress Count (Line 419)

(defn- immediate-stats [^LinkedBlockingQueue q {:keys [enqueued retried completed]}]
  (let [cnt (.size q)
        completed (.get ^AtomicLong completed)
        enqueued (.get ^AtomicLong enqueued)]
    {:enqueued enqueued
     :retried (.get ^AtomicLong retried)
     :completed completed
     :in-progress (- (- enqueued completed) cnt)}))

The formula is: in-progress = (enqueued - completed) - cnt

Where:

  • enqueued = total tasks added (AtomicLong)
  • completed = total tasks marked complete (AtomicLong)
  • cnt = current size of LinkedBlockingQueue

The Race Condition

The problem occurs because:

  1. cnt is read first (line 413): .size q
  2. completed is read second (line 414): .get ^AtomicLong completed
  3. enqueued is read third (line 415): .get ^AtomicLong enqueued

These reads are not atomic. Between reading cnt and reading completed/enqueued, other threads can:

  • Remove items from the queue (reducing cnt)
  • Mark tasks as complete (incrementing completed)

Scenario That Causes Negative In-Progress

This race condition occurs in this sequence:

Time  Thread 1 (stats reader)        Thread 2 (task processor)
----  -------------------------        -------------------------
  1   cnt = q.size()                  [reads queue size: cnt = 5]
      
  2                                   take!(q)
                                      [removes item from queue]
                                      
  3                                   mark-complete!()
                                      completed.incrementAndGet()
                                      [now completed is higher]
  
  4   completed = completed.get()     
      enqueued = enqueued.get()
      
  5   Calculate:
      in-progress = (enqueued - completed) - cnt
      
      If between steps 1 and 3:
      - 1 item was removed from queue (cnt was 5, now 4)
      - That item was marked complete (completed went from 3 to 4)
      
      Then: in-progress = (8 - 4) - 5 = 4 - 5 = -1  ✗ NEGATIVE

Multiple Vulnerabilities

Vulnerability 1: Take Then Complete

(take! [_ q-name timeout timeout-val]
  (let [q-name (munge (name q-name))
        ^LinkedBlockingQueue q (queue q-name)]
    (try
      (if-let [t (if (zero? timeout)
                   (.poll q)        ;; <-- removes from queue
                   (.poll q timeout TimeUnit/MILLISECONDS))]
        (let [slab (:slab t)]
          ;; ...
          (status! t :in-progress)   ;; <-- marks as in-progress
          t)
        timeout-val))))

(mark-complete! [_ q-name]
  (mark-action!)
  (populate-stats! q-name)
  (let [^AtomicLong retry-counter (get-in @queue-name->stats [q-name :completed])]
    (.incrementAndGet retry-counter)))  ;; <-- increments completed

The sequence is:

  1. take! calls .poll(q) → item leaves the queue
  2. Task is processed
  3. mark-complete! increments completed counter
  4. Meanwhile, immediate-stats reads: cnt (now smaller), then completed (now larger)
  5. Result: in-progress = (enqueued - completed) - cnt can be negative

Vulnerability 2: Queue Size Check

The .size() call on LinkedBlockingQueue is not atomic and can lag behind actual queue state changes. By the time the atomic counters are read, more items may have been removed.

Code Locations

  • Formula: Line 419
  • Statistics calculation: Lines 412-419
  • Take operation: Lines 668-695
  • Mark complete: Lines 649-653
  • Enqueue: Lines 737-740

Why This Matters

Negative in-progress counts are:

  • Semantically impossible (can't have negative work in progress)
  • Indicate monitoring/metrics are unreliable
  • May trigger false alerts in monitoring systems
  • Reflect actual timing issues not captured by the statistics

Solutions

The core issue is that the three values (cnt, completed, enqueued) are read in separate, non-atomic operations. Possible fixes:

  1. Atomic Read Reordering (Weak): Read enqueued and completed BEFORE cnt

    • Still has race condition, but less likely to produce negative values in practice
  2. Thread-safe Snapshot (Better): Acquire a lock that protects all three reads together

    • Ensures cnt, completed, and enqueued form a consistent snapshot
  3. Alternative Formula (Best): Track in-progress directly instead of computing it

    • Add an in-progress AtomicLong counter
    • Increment when take! succeeds, decrement when mark-complete! or mark-retry! is called
    • This eliminates the complex formula and race window
  4. Defensive Minimum (Pragmatic): Add max(0, in-progress) to prevent negative values

    • Masks the problem but ensures valid metrics output

Can you improve this documentation?Edit on GitHub

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close