From af9c8b8491d8743bf4bc285cefc5e4928b205d43 Mon Sep 17 00:00:00 2001 From: RohanGudur Date: Thu, 5 Nov 2026 12:17:34 +0530 Subject: [PATCH 1/2] Add bounded preprocessing capacity and task identity --- modelq/app/base.py | 39 ++++++++++++++++++++++++++++++++++++--- modelq/middleware.py | 10 ++++++++-- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/modelq/app/base.py b/modelq/app/base.py index d86db4f..4a74cdf 100644 --- a/modelq/app/base.py +++ b/modelq/app/base.py @@ -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. @@ -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 @@ -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: @@ -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: @@ -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), ) diff --git a/modelq/middleware.py b/modelq/middleware.py index 8a2ff58..863578c 100644 --- a/modelq/middleware.py +++ b/modelq/middleware.py @@ -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 @@ -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 @@ -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", ] From 7c1d2b285ea825ca800e1a0a66be24655eb23a79 Mon Sep 17 00:00:00 2001 From: RohanGudur Date: Thu, 5 Nov 2026 13:14:20 +0530 Subject: [PATCH 2/2] Test bounded preprocessing capacity --- tests/test_queued_preprocessors.py | 39 ++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/test_queued_preprocessors.py b/tests/test_queued_preprocessors.py index 7514134..03640a4 100644 --- a/tests/test_queued_preprocessors.py +++ b/tests/test_queued_preprocessors.py @@ -3,6 +3,7 @@ import json import threading import time +from concurrent.futures import ThreadPoolExecutor from unittest.mock import Mock import fakeredis @@ -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