Liking cljdoc? Tell your friends :D

Implementation Plan: Issue 12 - Direct In-Progress Tracking

Overview

Instead of computing in-progress as (enqueued - completed) - queue-size, we'll track it directly with an in-progress AtomicLong counter. This eliminates the race condition entirely.

Changes Required

1. Modify initial-stats (Line 407-410)

Current:

(defn- initial-stats [^long count]
  {:enqueued (AtomicLong. count)
   :retried  (AtomicLong. 0)
   :completed (AtomicLong. 0)})

New:

(defn- initial-stats [^long count]
  {:enqueued (AtomicLong. count)
   :retried  (AtomicLong. 0)
   :completed (AtomicLong. 0)
   :in-progress (AtomicLong. 0)})

Rationale: Add a new counter to track in-progress items directly.


2. Modify immediate-stats (Line 412-419)

Current:

(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)}))

New:

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

Rationale:

  • Remove the computed formula
  • Remove queue size read (no longer needed)
  • Read the direct in-progress counter inline in the map
  • Simpler and eliminates the race window
  • No intermediate let bindings needed

3. Update take! method (Line 668-695)

Current:

(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)
                   (.poll q timeout TimeUnit/MILLISECONDS))]
        (let [slab (:slab t)]
          ;; ... slab management ...
          (status! t :in-progress)
          t)
        timeout-val)
      (catch TimeoutException _
        timeout-val))))

New:

(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)
                   (.poll q timeout TimeUnit/MILLISECONDS))]
        (let [slab (:slab t)]
          ;; ... slab management ...
          (status! t :in-progress)
          
          ;; Increment in-progress counter
          (populate-stats! q-name)
          (let [^AtomicLong counter (get-in @queue-name->stats [q-name :in-progress])]
            (.incrementAndGet counter))
          
          t)
        timeout-val)
      (catch TimeoutException _
        timeout-val))))

Rationale:

  • When an item is successfully taken from the queue, increment the in-progress counter
  • Occurs immediately after status! t :in-progress is called
  • Ensures consistency: in-progress count increases exactly when item leaves queue

4. Update mark-complete! method (Line 649-653)

Current:

(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)))

New:

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

Rationale:

  • When a task is marked complete, decrement the in-progress counter
  • Also increment completed (existing behavior)
  • Ensures in-progress count decreases when work is finished

5. Update mark-retry! method (Line 643-647)

Current:

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

New:

(mark-retry! [_ q-name]
  (mark-action!)
  (populate-stats! q-name)
  (let [^AtomicLong retry-counter (get-in @queue-name->stats [q-name :retried])
        ^AtomicLong in-progress-counter (get-in @queue-name->stats [q-name :in-progress])]
    (.incrementAndGet retry-counter)
    (.decrementAndGet in-progress-counter)))

Rationale:

  • When a task is marked for retry, it leaves in-progress state
  • Decrement the in-progress counter
  • Also increment retried (existing behavior)
  • Task will be re-added to the queue, eventually causing in-progress to increment again via take!

State Transitions

The new flow ensures proper state tracking:

Initial State (after take!):
  in-progress = 0, completed = 0, retried = 0, enqueued = N

After take! (item dequeued):
  in-progress = 1, completed = 0, retried = 0, enqueued = N
  
After mark-complete!:
  in-progress = 0, completed = 1, retried = 0, enqueued = N
  
After take! then mark-retry!:
  in-progress = 0, completed = 0, retried = 1, enqueued = N
  [task will be re-enqueued, increasing enqueued]

Testing Considerations

Unit Tests

  1. Verify in-progress starts at 0
  2. Verify in-progress increments on take!
  3. Verify in-progress decrements on mark-complete!
  4. Verify in-progress decrements on mark-retry!
  5. Test concurrent take! and mark-complete! operations
  6. Verify stats never produce negative in-progress

Stress Tests

  • Multiple concurrent threads taking and completing tasks
  • Rapid take/complete cycles
  • Verify in-progress never goes negative
  • Verify in-progress >= queue-size (invariant: items in-progress are >= items in queue)

Backward Compatibility

  • Stats structure change: The return value of stats() will now include :in-progress as a direct counter instead of computed value
  • API compatibility: No changes to public API, only internal stats representation
  • Behavior: Stats should be more accurate and consistent across reads

Potential Issues & Mitigations

Issue 1: Race between take! and mark-complete!

Problem: What if mark-complete! is called before in-progress is incremented in take!? Mitigation: Very tight timing required. take! increments immediately after poll succeeds. In practice, mark-complete! is called after user processing, which happens after take! returns. Risk Level: Very low

Issue 2: What about restart/recovery?

Problem: in-progress is lost on restart (not persisted) Current behavior: In-progress items become "incomplete" on restart anyway Solution: Initialize in-progress to 0 on startup (as done in initial-stats) Risk Level: No change from current behavior

Issue 3: Multiple queues

Problem: Each queue has its own stats map Solution: Each queue's stats independently track in-progress Risk Level: None - already handled by existing structure


Implementation Order

  1. Add :in-progress to initial-stats
  2. Update immediate-stats to read the counter
  3. Update mark-complete! to decrement in-progress
  4. Update mark-retry! to decrement in-progress
  5. Update take! to increment in-progress
  6. Run all tests
  7. Add regression tests for race condition

Success Criteria

  • [ ] in-progress is never negative
  • [ ] in-progress == number of items currently being processed
  • [ ] Stats are consistent across multiple rapid reads
  • [ ] All existing tests pass
  • [ ] New race condition tests confirm the fix
  • [ ] Stress tests with high concurrency show stable stats

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