Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 36 additions & 3 deletions modelq/app/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1105,7 +1105,32 @@ def wrapper(*args, **kwargs):
return wrapper
return decorator

def start_workers(self, no_of_workers: int = 1, no_of_preprocessors: int = 4):
def _claim_bounded_preprocessor(self, inflight_key, capacity):
"""Reserve capacity and claim atomically, using existing custody lists.

Counts ready execution tasks plus preprocessing claims. No separate
semaphore survives cancellation or needs repair after process death.
This is intended for a dedicated pipeline queue.
"""
script = """
local used = redis.call('LLEN', KEYS[3])
for _, key in ipairs(redis.call('SMEMBERS', KEYS[4])) do
if string.match(key, ':preprocessor_[^:]+$') then
used = used + redis.call('LLEN', key)
end
end
if used >= tonumber(ARGV[1]) then return nil end
local blob = redis.call('LPOP', KEYS[1])
if blob then redis.call('RPUSH', KEYS[2], blob) end
return blob
"""
return self.redis_client.eval(
script, 4, self.PREPROCESSING_QUEUE, inflight_key,
"ml_tasks", self.INFLIGHT_REGISTRY, capacity,
)

def start_workers(self, no_of_workers: int = 1, no_of_preprocessors: int = 4,
max_prepared_tasks: Optional[int] = None):
"""
Start execution workers and independent preprocessing workers.
Preprocessing continues while all execution workers are occupied.
Expand All @@ -1114,6 +1139,8 @@ def start_workers(self, no_of_workers: int = 1, no_of_preprocessors: int = 4):
- a heartbeat thread
- a pruning thread
"""
if max_prepared_tasks is not None and max_prepared_tasks < 1:
raise ValueError("max_prepared_tasks must be at least 1")
if no_of_preprocessors < 1:
raise ValueError("no_of_preprocessors must be at least 1")
# Avoid restarting if workers are already running
Expand Down Expand Up @@ -1182,7 +1209,12 @@ def worker_loop(worker_id, preprocessing=False):
# a task in transit to a worker that never receives it stays in
# `inflight_key` until a sweep returns it to the queue.
if preprocessing:
task_json = self._claim_task(inflight_key, self.PREPROCESSING_QUEUE)
if max_prepared_tasks is None:
task_json = self._claim_task(inflight_key, self.PREPROCESSING_QUEUE)
else:
task_json = self._claim_bounded_preprocessor(inflight_key, max_prepared_tasks)
if not task_json:
time.sleep(self.CLAIM_POLL_INTERVAL)
else:
task_json = self._claim_task(inflight_key)
if not task_json:
Expand Down Expand Up @@ -1562,7 +1594,7 @@ def process_preprocessor(self, task: Task, inflight_key=None, claimed_blob=None)
args, kwargs = (schema(**(json.loads(data) if isinstance(data, str) else data)),), {}
else:
args, kwargs = tuple(data.get("args", ())), dict(data.get("kwargs", {}))
execution = _ProcessorExecution(getattr(function, "_mq_preprocessor", None), None)
execution = _ProcessorExecution(getattr(function, "_mq_preprocessor", None), None, task_id=task.task_id)
timeout = task.payload.get("timeout")
prepare = lambda *args, **kwargs: execution.preprocessor_result
if timeout:
Expand Down Expand Up @@ -1696,6 +1728,7 @@ def process_task(self, task: Task) -> None:
processor_execution = _ProcessorExecution(
getattr(task_function, "_mq_preprocessor", None),
getattr(task_function, "_mq_postprocessor", None),
task_id=task.task_id,
prepared=self.PREPROCESSOR_RESULT in task.payload,
result=task.payload.get(self.PREPROCESSOR_RESULT),
)
Expand Down
10 changes: 8 additions & 2 deletions modelq/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ def _context():
return context


def get_task_id():
"""Internal queue identity, available during preparation and execution."""
return _context().task_id


def get_preprocessor_result():
"""Return this task attempt's preprocessor result (None if not configured)."""
return _context().preprocessor_result
Expand Down Expand Up @@ -66,7 +71,8 @@ def _start(processor, args, kwargs):
class _ProcessorExecution:
"""One attempt's state, shared with its timeout thread but no other task."""

def __init__(self, preprocessor, postprocessor, prepared=False, result=None):
def __init__(self, preprocessor, postprocessor, prepared=False, result=None, task_id=None):
self.task_id = task_id
self.preprocessor = preprocessor
self.postprocessor = postprocessor
self.preprocessor_result = result
Expand Down Expand Up @@ -140,5 +146,5 @@ def finish(self, success=False):

__all__ = [
"Middleware", "ProcessorMiddleware", "Processor_middlware",
"Processor_middleware", "get_preprocessor_result", "send_postprocessor",
"Processor_middleware", "get_preprocessor_result", "get_task_id", "send_postprocessor",
]
39 changes: 39 additions & 0 deletions tests/test_queued_preprocessors.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import json
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from unittest.mock import Mock

import fakeredis
Expand Down Expand Up @@ -263,3 +264,41 @@ def compute():
mq.process_task(ready)
assert ready.result == 1
assert called.call_count == 1


@pytest.mark.parametrize("capacity", [1, 2, 5])
def test_capacity_edges_with_eleven_concurrent_claims(mq, capacity):

class Pre(ProcessorMiddleware):
def start(self, value):
return value
@mq.task(preprocessor=Pre)
def task(value):
return value
tasks = [task(i) for i in range(12)]
keys = [mq._inflight_key(f"preprocessor_{i}") for i in range(11)]
mq.redis_client.sadd(mq.INFLIGHT_REGISTRY, *keys)
barrier = threading.Barrier(len(keys))
def claim(key):
barrier.wait(timeout=10)
return mq._claim_bounded_preprocessor(key, capacity)
with ThreadPoolExecutor(len(keys)) as pool:
blobs = list(pool.map(claim, keys))
assert sum(bool(blob) for blob in blobs) == capacity
assert mq.redis_client.llen(mq.PREPROCESSING_QUEUE) == len(tasks) - capacity
for key, blob in zip(keys, blobs):
if blob:
mq.process_preprocessor(Task.from_dict(json.loads(blob)), key, blob)
assert mq.redis_client.llen("ml_tasks") == capacity
assert mq._claim_bounded_preprocessor(keys[0], capacity) is None
# Cancellation frees one ready place without dropping other pending jobs.
ready = json.loads(mq.redis_client.lindex("ml_tasks", 0))
mq.cancel_task(ready["task_id"])
assert mq._claim_bounded_preprocessor(keys[0], capacity) is not None


@pytest.mark.parametrize("capacity", [0, -1])
def test_invalid_capacity_fails_at_startup(mq, capacity):
with pytest.raises(ValueError, match="max_prepared_tasks must be at least 1"):
mq.start_workers(max_prepared_tasks=capacity)
assert not mq.worker_threads