vtrr-queue 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
vtrr_queue/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .queue import VTRRQueue, VTRRTask
2
+
3
+ __all__ = ["VTRRQueue", "VTRRTask"]
vtrr_queue/py.typed ADDED
File without changes
vtrr_queue/queue.py ADDED
@@ -0,0 +1,316 @@
1
+ import json
2
+ import logging
3
+ import uuid
4
+ from pathlib import Path
5
+ from typing import Any, Callable
6
+ from celery import Task
7
+
8
+
9
+ import redis as redis_lib
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ _SCRIPTS_DIR = Path(__file__).parent / "scripts"
14
+
15
+
16
+ class VTRRTask:
17
+ def __init__(self, fn: Callable, vtrr: "VTRRQueue", celery_task: Any) -> None:
18
+ self._fn = fn
19
+ self._vtrr = vtrr
20
+ self._celery_task = celery_task
21
+ self.__name__ = fn.__name__
22
+ self.__module__ = fn.__module__
23
+ self.__doc__ = fn.__doc__
24
+
25
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
26
+ return self._fn(*args, **kwargs)
27
+
28
+ @property
29
+ def name(self) -> str:
30
+ return f"{self.__module__}.{self.__name__}"
31
+
32
+ def queue(self, partition_key: str, tasks: list[dict[str, Any]]) -> None:
33
+ """
34
+ Bulk-enqueue tasks into the VTRR queue.
35
+
36
+ Each entry in `tasks` should contain "weight" (int) "args" (list) and/or "kwargs" (dict).
37
+ Celery dequeue workers are scheduled automatically after enqueuing.
38
+
39
+ Example:
40
+ process_file.queue(
41
+ partition_key="u_123",
42
+ tasks=[
43
+ {"weight": 4, "args": ["s3://bucket/a.pdf"], "kwargs": {"force_ocr": True}},
44
+ {"weight": 10, "args": ["s3://bucket/b.pdf"]},
45
+ ],
46
+ )
47
+ """
48
+ if not partition_key:
49
+ raise ValueError("key_id is required")
50
+ if not tasks:
51
+ return
52
+
53
+ argv: list[str] = []
54
+ for task in tasks:
55
+ task_id = str(task.get("id", uuid.uuid4()))
56
+ task_weight = int(task.get("weight", 1))
57
+ payload = json.dumps(
58
+ {
59
+ "task_name": self.name,
60
+ "args": task.get("args", []),
61
+ "kwargs": task.get("kwargs", {}),
62
+ }
63
+ )
64
+ argv += [partition_key, task_id, task_weight, payload]
65
+
66
+ self._vtrr._schedule_workers(len(tasks), self._celery_task)
67
+ self._vtrr._enqueue(argv)
68
+
69
+
70
+ class _VTRRCeleryTask(Task):
71
+ """Base task for VTRR-dispatched functions.
72
+
73
+ Overriding retry() means a task can only ever re-run *itself* with its
74
+ own payload
75
+ """
76
+
77
+ def retry(self, args=None, kwargs=None, exc=None, **options):
78
+ payload = getattr(self.request, "vtrr_payload", None)
79
+ return super().retry(
80
+ args=(),
81
+ kwargs={"task_payload": payload},
82
+ exc=exc,
83
+ **options,
84
+ )
85
+
86
+
87
+ def _resolve_base(user_base: type | None) -> type:
88
+ """Weave _VTRRTask into the user's custom Task base.
89
+
90
+ _VTRRTask goes first in the MRO so its retry() normalizes the call into
91
+ the current payload before any user-defined retry runs.
92
+ """
93
+ if user_base is None or user_base is Task:
94
+ return _VTRRCeleryTask
95
+ if issubclass(user_base, _VTRRCeleryTask):
96
+ return user_base
97
+ return type(f"VTRR{user_base.__name__}", (_VTRRCeleryTask, user_base), {})
98
+
99
+
100
+ class VTRRQueue:
101
+ DEFAULT_MAX_CONCURRENCY = 4
102
+
103
+ def __init__(
104
+ self,
105
+ redis_client: redis_lib.Redis,
106
+ celery_app: Any,
107
+ *,
108
+ name: str,
109
+ celery_queue: str = "vtrr_queue",
110
+ max_concurrency: int = DEFAULT_MAX_CONCURRENCY,
111
+ ) -> None:
112
+ self._redis = redis_client
113
+ self._celery_app = celery_app
114
+ self._celery_queue = celery_queue
115
+ self._max_concurrency = max_concurrency
116
+ self._registry: dict[str, VTRRTask] = {}
117
+
118
+ prefix = f"vtrr:{name}"
119
+ self._queue_key = f"{prefix}:queue"
120
+ self._current_vt_key = f"{prefix}:current_virtual_time"
121
+ self._task_key = f"{prefix}:task"
122
+ self._partitions_vt_key = f"{prefix}:partition_virtual_time"
123
+ self._enqueue_keys = [
124
+ self._current_vt_key,
125
+ self._partitions_vt_key,
126
+ self._queue_key,
127
+ self._task_key,
128
+ ]
129
+ self._dequeue_keys = [
130
+ self._queue_key,
131
+ self._current_vt_key,
132
+ self._task_key,
133
+ self._partitions_vt_key,
134
+ ]
135
+
136
+ self._enqueue_script = self._load_script("enqueue")
137
+ self._dequeue_script = self._load_script("dequeue")
138
+ self._broker: redis_lib.Redis | None = self._connect_broker()
139
+
140
+ def task(self, fn: Callable | None = None, **task_options: Any) -> Any:
141
+ """
142
+ Decorator that registers a function as a VTRR-dispatchable Celery task.
143
+
144
+ The first argument is always `self` (the bound Celery task), then any args/kwargs from .queue():
145
+
146
+ @vtrr.task(autoretry_for=(TransientError,), max_retries=3,
147
+ retry_backoff=True)
148
+ def my_task(self, task_id, x, y): ...
149
+ """
150
+
151
+ _ALLOWED_TASK_OPTIONS = {
152
+ # execution limits
153
+ "soft_time_limit",
154
+ "time_limit",
155
+ # retry
156
+ "max_retries",
157
+ "default_retry_delay",
158
+ "autoretry_for",
159
+ "retry_backoff",
160
+ "retry_backoff_max",
161
+ "retry_jitter",
162
+ "retry_kwargs",
163
+ # base class
164
+ "base",
165
+ }
166
+
167
+ def decorator(f: Callable) -> VTRRTask:
168
+ vtrr = self
169
+ unsupported_task_options = set(task_options) - _ALLOWED_TASK_OPTIONS
170
+ if unsupported_task_options:
171
+ raise TypeError(
172
+ f"@vtrr.task does not support option(s): {', '.join(sorted(unsupported_task_options))}. "
173
+ f"Allowed: {', '.join(sorted(_ALLOWED_TASK_OPTIONS))}"
174
+ )
175
+ options = dict(task_options)
176
+ options.pop("bind", None)
177
+ base = _resolve_base(options.pop("base", None))
178
+ task_name = f"{f.__module__}.{f.__name__}"
179
+
180
+ @self._celery_app.task(name=task_name, bind=True, base=base, **options)
181
+ def celery_wrapper(
182
+ celery_task: Any,
183
+ task_payload: dict | None = None,
184
+ is_start: bool = False,
185
+ ) -> None:
186
+ dispatched = task_payload is None
187
+
188
+ if dispatched:
189
+ result = vtrr._dequeue()
190
+ if result is None:
191
+ if is_start:
192
+ # Race: worker arrived before enqueue settled — retry once after a short delay.
193
+ celery_task.apply_async(
194
+ kwargs={"is_start": False},
195
+ queue=vtrr._celery_queue,
196
+ countdown=3,
197
+ )
198
+ return # queue empty — stop draining, no reschedule
199
+ dequeued_name, args, kwargs = result
200
+ task_payload = {
201
+ "task_name": dequeued_name,
202
+ "args": args,
203
+ "kwargs": kwargs,
204
+ }
205
+ else:
206
+ dequeued_name = task_payload["task_name"]
207
+ args = task_payload["args"]
208
+ kwargs = task_payload["kwargs"]
209
+
210
+ # Per-invocation stash (safe under threaded/gevent pools);
211
+ # retry() reads this to re-run the same item.
212
+ celery_task.request.vtrr_payload = task_payload
213
+
214
+ try:
215
+ registered = vtrr._registry.get(dequeued_name)
216
+ if registered is None:
217
+ logger.error(
218
+ "vtrr_queue: unknown task %r — dropped", dequeued_name
219
+ )
220
+ return
221
+ registered._fn(celery_task, *args, **kwargs)
222
+ finally:
223
+ if dispatched:
224
+ # In case there's an exception, schedule next dequeue
225
+ vtrr._schedule_next(celery_task)
226
+
227
+ wrapped = VTRRTask(f, self, celery_wrapper)
228
+ self._registry[wrapped.name] = wrapped
229
+ return wrapped
230
+
231
+ if fn is not None:
232
+ return decorator(fn)
233
+ return decorator
234
+
235
+ # ------------------------------------------------------------------
236
+ # Internal: setup
237
+ # ------------------------------------------------------------------
238
+
239
+ def _load_script(self, name: str) -> Any:
240
+ src = (_SCRIPTS_DIR / f"{name}.lua").read_text()
241
+ return self._redis.register_script(src)
242
+
243
+ def _connect_broker(self) -> redis_lib.Redis | None:
244
+ try:
245
+ return redis_lib.from_url(self._celery_app.conf.broker_url)
246
+ except Exception as err:
247
+ logger.warning("vtrr_queue: could not connect to Celery broker: %s", err)
248
+ return None
249
+
250
+ # ------------------------------------------------------------------
251
+ # Internal: Redis operations
252
+ # ------------------------------------------------------------------
253
+
254
+ def _enqueue(self, argv: list[str]) -> None:
255
+ self._enqueue_script(keys=self._enqueue_keys, args=argv)
256
+
257
+ def _dequeue(self) -> tuple[str, str, list, dict] | None:
258
+ raw = self._dequeue_script(keys=self._dequeue_keys, args=[])
259
+ if not raw:
260
+ return None
261
+ _, payload_bytes = raw
262
+ if isinstance(payload_bytes, (bytes, bytearray)):
263
+ payload_bytes = payload_bytes.decode()
264
+ payload = json.loads(payload_bytes)
265
+ return (
266
+ payload["task_name"],
267
+ payload["args"],
268
+ payload["kwargs"],
269
+ )
270
+
271
+ # ------------------------------------------------------------------
272
+ # Internal: worker scheduling
273
+ # ------------------------------------------------------------------
274
+
275
+ def _get_workers_scheduled(self) -> int:
276
+ """
277
+ Count pending messages in the Celery broker queue.
278
+ Does NOT include workers already running; returns 0 on any error
279
+ so the caller may over-schedule slightly, which is safe.
280
+ """
281
+ if self._broker is None:
282
+ return 0
283
+ try:
284
+ q = self._celery_queue
285
+ # Celery-managed Redis priority suffixes: 0 = no suffix, 3/6/9 = :<p>
286
+ return sum(
287
+ self._broker.llen(q if p == 0 else f"{q}:{p}") for p in (0, 3, 6, 9)
288
+ )
289
+ except Exception as err:
290
+ logger.error(
291
+ "vtrr_queue: could not check broker queue length: %s",
292
+ err,
293
+ exc_info=True,
294
+ )
295
+ return 0
296
+
297
+ def _schedule_workers(self, num_tasks: int, dispatch_task: Any) -> None:
298
+ workers_scheduled = self._get_workers_scheduled()
299
+ to_schedule = min(self._max_concurrency - workers_scheduled, num_tasks)
300
+ for _ in range(to_schedule):
301
+ dispatch_task.apply_async(
302
+ kwargs={"is_start": True},
303
+ queue=self._celery_queue,
304
+ )
305
+
306
+ def _schedule_next(self, current_celery_task: Any) -> None:
307
+ """Schedule one more dequeue worker if tasks remain in the queue."""
308
+ try:
309
+ if self._redis.zcard(self._queue_key) > 0:
310
+ current_celery_task.apply_async(queue=self._celery_queue)
311
+ except Exception as err:
312
+ logger.error(
313
+ "vtrr_queue: could not schedule next dequeue worker: %s",
314
+ err,
315
+ exc_info=True,
316
+ )
@@ -0,0 +1,24 @@
1
+ -- Dequeue a task with the smallest virtual-time from the virutal time round-robin queue (vtrr:queue).
2
+ -- Task info is fetched then deleted from the vtrr:task look-up table. And vtrr:current_virtual_time is
3
+ -- updated to the virutal-time of the dequeued task.
4
+
5
+ -- KEYS: 1=vtrr:queue 2=vtrr:current_virtual_time 3=vtrr:task 4=vtrr:partition_virtual_time
6
+ local popped = redis.call('ZPOPMIN', KEYS[1])
7
+ if #popped == 0 then
8
+ return {}
9
+ end
10
+
11
+ local task_id, task_virtual_time = popped[1], popped[2]
12
+ local task = redis.call('HGET', KEYS[3], task_id)
13
+ redis.call('HDEL', KEYS[3], task_id)
14
+
15
+ if redis.call('ZCARD', KEYS[1]) == 0 then
16
+ -- reset all values when queue is drained
17
+ redis.call('SET', KEYS[2], 0)
18
+ redis.call('DEL', KEYS[3])
19
+ redis.call('DEL', KEYS[4])
20
+ else
21
+ redis.call('SET', KEYS[2], task_virtual_time)
22
+ end
23
+
24
+ return {task_id, task}
@@ -0,0 +1,26 @@
1
+ -- Bulk enqueue to the virutal time round-robin (vtrr). Each task is saved in vtrr:task look-up table, and the task_id
2
+ -- is enqueued into the vtrr:queue with a virtual-time that's based off of how many tasks the partition has enqueued so far (managed by vtrr:partition_virtual_time)
3
+ -- The vtrr:current_virtual_time is the lowest virtual-time of any task in the queue.
4
+
5
+ -- KEYS: 1=vtrr:current_virtual_time 2=vtrr:partition_virtual_time 3=vtrr:queue 4=vtrr:task
6
+ -- ARGV: flat triples of (partition_id, task_id, task_json)
7
+ local current_virtual_time = tonumber(redis.call('GET', KEYS[1]) or '0')
8
+ local partition_vt_cache = {}
9
+ local i = 1
10
+ while i <= #ARGV do
11
+ local partition_key, task_id, task_weight, task = ARGV[i], ARGV[i+1], tonumber(ARGV[i+2]), ARGV[i+3]
12
+ local partition_virtual_time = partition_vt_cache[partition_key]
13
+ if partition_virtual_time == nil then
14
+ partition_virtual_time = tonumber(redis.call('HGET', KEYS[2], partition_key) or '0')
15
+ if current_virtual_time + 1 > partition_virtual_time then partition_virtual_time = current_virtual_time + 1 end
16
+ end
17
+ redis.call('ZADD', KEYS[3], partition_virtual_time, task_id)
18
+ partition_virtual_time = partition_virtual_time + task_weight
19
+ redis.call('HSET', KEYS[4], task_id, task)
20
+ partition_vt_cache[partition_key] = partition_virtual_time
21
+ i = i + 4
22
+ end
23
+ for partition_key, uvt in pairs(partition_vt_cache) do
24
+ redis.call('HSET', KEYS[2], partition_key, uvt)
25
+ end
26
+ return redis.status_reply('OK')
@@ -0,0 +1,334 @@
1
+ Metadata-Version: 2.5
2
+ Name: vtrr-queue
3
+ Version: 0.1.0
4
+ Summary: Virtual-time round-robin fair queue on Redis
5
+ Author-email: Nicolas Johnson <nicolas.johnson@c4ads.org>
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Framework :: Celery
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Classifier: Topic :: System :: Distributed Computing
17
+ Requires-Python: >=3.12
18
+ Requires-Dist: celery>=5.0
19
+ Requires-Dist: fakeredis[lua]<3.0.0,>=2.37.0
20
+ Requires-Dist: pytest<10.0.0,>=9.1.1
21
+ Requires-Dist: redis>=4.5.4
22
+ Provides-Extra: dev
23
+ Requires-Dist: fakeredis; extra == 'dev'
24
+ Requires-Dist: pytest; extra == 'dev'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # vtrr-queue
28
+
29
+ Virtual-time round-robin (VTRR) fair queue on Redis. Tasks from different users are interleaved so that no single user can starve others, regardless of how many tasks they submit. Each user's tasks are processed in proportion to their share of the queue.
30
+
31
+ Integrates with an existing Celery + Redis setup. The library owns the dequeue loop; your code just defines tasks and enqueues them.
32
+
33
+
34
+ ## Requirements
35
+
36
+ - Python >= 3.12
37
+ - Redis (used for both the VTRR queue state and as the Celery broker)
38
+ - Celery >= 5.0
39
+
40
+
41
+ ## Installation
42
+
43
+ Install directly from GitHub until the package is published to a package registry:
44
+
45
+ ```
46
+ pip install git+https://github.com/C-Research/vtrr-queue.git
47
+ ```
48
+
49
+ Or pin a specific commit or tag for stability:
50
+
51
+ ```
52
+ pip install git+https://github.com/C-Research/vtrr-queue.git@v0.1.0
53
+ ```
54
+
55
+ Add to your `requirements.txt` or `pyproject.toml` dependencies the same way.
56
+
57
+
58
+ ## How it works
59
+
60
+ ```
61
+ User A submits 10 tasks ──┐
62
+ User B submits 2 tasks ──┼──► Redis sorted set (score = virtual time)
63
+ User C submits 5 tasks ──┘ │
64
+ ▼
65
+ Your @vtrr.task Celery worker runs,
66
+ pops the highest-priority task from Redis,
67
+ and calls your function directly
68
+ ```
69
+
70
+ When `.queue()` is called the library:
71
+ 1. Atomically writes all tasks to Redis with fair virtual-time scores (Lua script, no race conditions).
72
+ 2. Schedules `min(max_concurrency - workers_already_queued, num_tasks_just_enqueued)` Celery workers.
73
+
74
+ Each `@vtrr.task` is itself the Celery task — when a worker picks it up, it dequeues from Redis and calls your function in one hop. There is no intermediate dispatcher task.
75
+
76
+
77
+ ## Setup
78
+
79
+ ### 1. Create the VTRRQueue instance
80
+
81
+ Create a module that constructs the `VTRRQueue` instance. This module must be imported before Celery workers start (same requirement as Celery's own `@app.task` decorators).
82
+
83
+ ```python
84
+ # myapp/vtrr.py
85
+ import redis
86
+ from celery import Celery
87
+ from vtrr_queue import VTRRQueue
88
+
89
+ celery_app = Celery(...) # or import your existing app
90
+
91
+ vtrr = VTRRQueue(
92
+ redis_client=redis.from_url("redis://localhost:6379/3"),
93
+ celery_app=celery_app,
94
+ name="files", # namespaces Redis keys as vtrr:files:*
95
+ celery_queue="vtrr_queue", # name of the Celery queue workers will consume (separate from the round-robin queue)
96
+ max_concurrency=8, # cap on dequeue workers queued in the broker at once
97
+ )
98
+ ```
99
+
100
+ Use a dedicated Redis DB index for the VTRR queue so its keys don't collide with your application cache, session store, or Celery broker.
101
+ #### VTRRQueue parameters
102
+
103
+ | Parameter | Type | Default | Description |
104
+ |---|---|---|---|
105
+ | `redis_client` | `redis.Redis` | required | Redis client pointed at the VTRR database |
106
+ | `celery_app` | `Celery` | required | Your application's Celery instance |
107
+ | `name` | `str` | required | Unique name for this queue instance; namespaces all Redis keys as `vtrr:{name}:*` |
108
+ | `celery_queue` | `str` | `"vtrr_queue"` | Celery queue name for the dispatcher task |
109
+ | `max_concurrency` | `int` | `4` | Max dequeue workers held in the broker at once |
110
+
111
+
112
+ ### 2. Register a dedicated Celery worker
113
+
114
+ The VTRR dispatcher runs on its own Celery queue. Start a worker that consumes only that queue so it doesn't compete with your other task queues:
115
+
116
+ ```
117
+ celery -A myapp worker -Q vtrr_queue --concurrency=8 --loglevel=info
118
+ ```
119
+
120
+ The `--concurrency` here is the OS-level worker pool size. `max_concurrency` in `VTRRQueue` controls how many dispatcher tasks are *pre-queued* in the broker at once, which is this concurrency value multiplied by the number of worker instances you deploy.
121
+
122
+ #### One `celery_queue` per `VTRRQueue` instance
123
+
124
+ Give each `VTRRQueue` instance its own `celery_queue` name. Otherwise, if two or more instances share the same name, the library may under-schedule the celery workers.
125
+
126
+ ```python
127
+ # Good — each queue manages its own worker budget independently
128
+ files_vtrr = VTRRQueue(..., name="files", celery_queue="vtrr_files", max_concurrency=8)
129
+ search_vtrr = VTRRQueue(..., name="search", celery_queue="vtrr_search", max_concurrency=4)
130
+ ```
131
+
132
+ Start a worker per queue so you can also size the pools independently:
133
+
134
+ ```
135
+ celery -A myapp worker -Q vtrr_files --concurrency=8 --loglevel=info
136
+ celery -A myapp worker -Q vtrr_search --concurrency=4 --loglevel=info
137
+ ```
138
+
139
+ If you genuinely want both queues served by a single shared worker pool, you can point both workers at both queues (`-Q vtrr_files,vtrr_search`), but keep the queue names distinct so scheduling counts stay accurate.
140
+
141
+
142
+ ### 3. Define tasks
143
+
144
+ Import the `vtrr` instance and decorate functions with `@vtrr.task`. The decorator accepts many of the same keyword arguments as Celery's `@app.task`:
145
+
146
+ ```python
147
+ # myapp/tasks.py
148
+ from myapp.vtrr import vtrr
149
+ from myapp.celery_utils import LogErrorsTask
150
+
151
+ # No options — plain decorator
152
+ @vtrr.task(
153
+ base=LogErrorsTask,
154
+ max_retries=3,
155
+ soft_time_limit=3600,
156
+ )
157
+ def process_file(self, task_id: str, file_key: str, dataset_id: str, force_ocr: bool = False):
158
+ try:
159
+ ...
160
+ except TransientError as exc:
161
+ # Retry will requeue the specific task to the broker
162
+ raise self.retry(exc=exc, countdown=10)
163
+ ```
164
+
165
+ `self` is the bound Celery task and is always the first argument, followed by any args/kwargs passed to `.queue()`. bound is always True despite what you may set in the decorator.
166
+
167
+ Each task gets its own Celery task registration with its own retry and timeout settings.
168
+
169
+
170
+ ### 4. Enqueue tasks
171
+
172
+ Call `.queue()` from anywhere in your application to enqueue the task in the round-robin for celery to run.
173
+
174
+ ```python
175
+ from myapp.tasks import process_file
176
+
177
+ # Bulk enqueue — all tasks from one partition in a single Redis round-trip
178
+ process_file.queue(
179
+ partition_key="u_123",
180
+ tasks=[
181
+ {"weight": 4, "args": ["s3://bucket/a.pdf"], "kwargs": {"dataset_id": "d_1", "force_ocr": True}},
182
+ {"weight": 2, "args": ["s3://bucket/b.pdf"], "kwargs": {"dataset_id": "d_2"}},
183
+ {"weight": 2, "args": ["s3://bucket/c.pdf"], "kwargs": {"dataset_id": "d_3"}},
184
+ ],
185
+ )
186
+ ```
187
+
188
+ #### .queue() parameters
189
+
190
+ | Parameter | Type | Description |
191
+ |---|---|---|
192
+ | `partition_key` | `str` | Required. Identifies whose virtual-time slot to use. |
193
+ | `tasks` | `list[dict]` | Required. Each dict has optional `"weight"` (int), `"args"` (list), and `"kwargs"` (dict). |
194
+
195
+ Each task dict may also include an `"id"` key to supply a stable task ID; otherwise a UUID is generated.
196
+
197
+ `"weight"` defaults to `1`, which gives standard one-turn-per-task round-robin fairness. A weight of `N` advances the partition's virtual time by `N` after that task is enqueued, yielding up to `N` turns to other partitions before the next task in this partition is served. Use higher weights for tasks that are known to be proportionally more expensive.
198
+
199
+
200
+ ## Celery task options
201
+
202
+ `@vtrr.task` accepts an explicit subset of `@celery_app.task()` options. Passing anything outside this list raises a `TypeError` at decoration time.
203
+
204
+ | Option | Description |
205
+ |---|---|
206
+ | `base` | Custom base task class (e.g. for structured error reporting) |
207
+ | `max_retries` | Number of times to retry on exception |
208
+ | `default_retry_delay` | Seconds to wait before retrying (default: 180) |
209
+ | `autoretry_for` | Tuple of exception types to retry on automatically |
210
+ | `retry_backoff` | Enable exponential backoff between retries |
211
+ | `retry_backoff_max` | Cap on backoff delay in seconds |
212
+ | `retry_jitter` | Add random jitter to backoff delays |
213
+ | `retry_kwargs` | Dict of kwargs passed to `self.retry()`, e.g. `{"countdown": 10}` |
214
+ | `soft_time_limit` | Seconds before a `SoftTimeLimitExceeded` is raised in the worker |
215
+ | `time_limit` | Hard kill timeout in seconds |
216
+
217
+ Since each `@vtrr.task` becomes its own Celery task, different task functions can have different retry policies and time limits.
218
+
219
+
220
+ ## Django-specific setup
221
+
222
+ A complete Django project integration:
223
+
224
+ ```python
225
+ # myproject/celery.py (standard Celery Django setup)
226
+ import os
227
+ from celery import Celery
228
+
229
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
230
+ app = Celery("myproject")
231
+ app.config_from_object("django.conf:settings", namespace="CELERY")
232
+ app.autodiscover_tasks()
233
+ ```
234
+
235
+ ```python
236
+ # myproject/settings.py
237
+ CACHES = {
238
+ # ... your existing cache entries ...
239
+ "vtrr": {
240
+ "BACKEND": "django_redis.cache.RedisCache",
241
+ "LOCATION": "redis://localhost:6379",
242
+ "OPTIONS": {
243
+ "DB": 3, # dedicated database index
244
+ "CLIENT_CLASS": "django_redis.client.DefaultClient",
245
+ },
246
+ },
247
+ }
248
+
249
+ VTRR_CELERY_SCHEDULER_QUEUE = "vtrr_queue"
250
+ VTRR_MAX_CONCURRENCY = 8
251
+ ```
252
+
253
+ ```python
254
+ # myapp/vtrr.py
255
+ from django.conf import settings
256
+ from django_redis import get_redis_connection
257
+ from myproject.celery import app as celery_app
258
+ from vtrr_queue import VTRRQueue
259
+
260
+ vtrr = VTRRQueue(
261
+ redis_client=get_redis_connection("vtrr"), # uses the "vtrr" CACHES entry
262
+ celery_app=celery_app,
263
+ name="files",
264
+ celery_queue=settings.VTRR_CELERY_SCHEDULER_QUEUE,
265
+ max_concurrency=settings.VTRR_MAX_CONCURRENCY,
266
+ )
267
+ ```
268
+
269
+ `get_redis_connection` is the recommended approach over a bare `redis.from_url()` in Django projects since it integrates with Django's connection management.
270
+
271
+ ```python
272
+ # myapp/apps.py
273
+ from django.apps import AppConfig
274
+
275
+ class MyAppConfig(AppConfig):
276
+ name = "myapp"
277
+
278
+ def ready(self):
279
+ import myapp.tasks # registers @vtrr.task functions with the dispatcher if needed
280
+ ```
281
+
282
+ ```python
283
+ # myapp/tasks.py
284
+ from myapp.vtrr import vtrr
285
+ from myapp.celery_utils import LogErrorsTask
286
+
287
+ @vtrr.task(
288
+ base=LogErrorsTask,
289
+ max_retries=3,
290
+ retry_kwargs={"countdown": 10},
291
+ soft_time_limit=3600,
292
+ )
293
+ def process_upload(self, task_id: str, file_key: str, dataset_id: str):
294
+ ...
295
+ ```
296
+
297
+ ```python
298
+ # myapp/views.py
299
+ from myapp.tasks import process_upload
300
+
301
+ class UploadView(View):
302
+ def post(self, request):
303
+ files = request.FILES.getlist("files")
304
+ process_upload.queue(
305
+ partition_key=str(request.user.id),
306
+ tasks=[
307
+ {"weight": 1, "args": [f.name], "kwargs": {"dataset_id": request.POST["dataset_id"]}}
308
+ for f in files
309
+ ],
310
+ )
311
+ return JsonResponse({"queued": len(files)})
312
+ ```
313
+
314
+
315
+ ## Redis keys
316
+
317
+ Each `VTRRQueue` instance manages four keys namespaced under `vtrr:{name}:*`.
318
+
319
+ | Key | Type | Description |
320
+ |---|---|---|
321
+ | `vtrr:{name}:queue` | Sorted Set | Task IDs scored by virtual time; lowest score = highest priority |
322
+ | `vtrr:{name}:current_virtual_time` | String | Virtual time of the last dequeued task; resets to 0 when queue drains |
323
+ | `vtrr:{name}:partition_virtual_time` | Hash | Per-partition virtual time counter; deleted when queue drains |
324
+ | `vtrr:{name}:task` | Hash | `task_id → JSON payload`; deleted when queue drains |
325
+
326
+ Multiple `VTRRQueue` instances in the same application can safely share a Redis database as long as they have distinct `name` values.
327
+
328
+ All enqueue and dequeue operations are atomic Lua scripts, so concurrent writers and workers are safe.
329
+
330
+ # Development
331
+
332
+ Run `poetry install`
333
+
334
+ Tests: `poetry run pytest tests`
@@ -0,0 +1,9 @@
1
+ vtrr_queue/__init__.py,sha256=JnO3CnxRbr6Mo0vWo7qIr-a1nhHomWzwo5hoEAVhJic,76
2
+ vtrr_queue/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ vtrr_queue/queue.py,sha256=2_xWwIwJfghtwbDQFaAk-2KwxPGEenONmhIcSu1rTTQ,11325
4
+ vtrr_queue/scripts/dequeue.lua,sha256=j_3LRDrCzYfSF0pPaQ2TnpU7ZOmg_LLbQtrM6KhH2os,840
5
+ vtrr_queue/scripts/enqueue.lua,sha256=x5WA4qYhxDWQh1mB67faYD6t8srEZSsHRA0cP-b8Pmo,1471
6
+ vtrr_queue-0.1.0.dist-info/METADATA,sha256=ZBlVr9Ue130KnRUzfm3F3_g5XaiFuF_7Zor1QdEAVYs,12223
7
+ vtrr_queue-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
8
+ vtrr_queue-0.1.0.dist-info/licenses/LICENSE,sha256=GeDK5Wa9F3kdSd3u7aptMF5cn9HFpOgt_d4UfdpBnAo,11336
9
+ vtrr_queue-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 C4ADS
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.