Repository navigation
Expand file tree
/
Copy pathModelQ.php
More file actions
1570 lines (1380 loc) · 54.5 KB
/
Copy pathModelQ.php
File metadata and controls
1570 lines (1380 loc) · 54.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace ModelsLab\ModelQ;
use ModelsLab\ModelQ\Exception\RetryTaskException;
use ModelsLab\ModelQ\Exception\TaskProcessingException;
use ModelsLab\ModelQ\Exception\TaskTimeoutException;
use ModelsLab\ModelQ\Middleware\Middleware;
use ModelsLab\ModelQ\Task\Task;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Redis;
use Throwable;
/**
* ModelQ - A lightweight PHP task queue library.
*
* Alternative to traditional queue systems, optimized for ML inference workloads.
* Uses phpredis extension for fast Redis operations.
*/
class ModelQ
{
public const HEARTBEAT_INTERVAL = 30;
public const PRUNE_TIMEOUT = 300;
public const PRUNE_CHECK_INTERVAL = 60;
public const TASK_RESULT_RETENTION = 86400;
public const TASK_HISTORY_RETENTION = 86400; // 24 hours (configurable)
public const TASK_TTL = 86400; // 24 hours TTL for all tasks
public const DEFAULT_STREAM_TIMEOUT = 300; // 5 minutes default stream timeout
public const SCAN_BATCH = 500; // keys per SCAN round-trip
/**
* Connection liveness.
*
* BLPOP_TIMEOUT is what we ask the *server* to wait. READ_TIMEOUT is what
* the *client* will wait for that answer to arrive. The second must exceed
* the first, or every idle poll aborts the read before Redis has replied.
*
* phpredis defaults both connect and read timeouts to 0, meaning "wait
* forever". A silently dropped TCP connection then parks the reader
* permanently: the server-side BLPOP timeout is irrelevant because the
* reply it would have produced can never reach us.
*/
public const BLPOP_TIMEOUT = 1; // seconds Redis holds the blocking pop
public const CONNECT_TIMEOUT = 5; // seconds to establish a connection
public const READ_TIMEOUT = 10; // seconds to wait for any single reply
public const TCP_KEEPALIVE = 60; // seconds idle before the kernel probes
private Redis $redis;
private string $serverId;
private array $allowedTasks = [];
private array $taskHandlers = [];
private array $taskOptions = [];
private ?Middleware $middleware = null;
private ?string $webhookUrl = null;
private ?int $requeueThreshold = null;
private int $delaySeconds;
private int $taskHistoryRetention;
private int $taskTtl;
private LoggerInterface $logger;
private bool $running = false;
public function __construct(
?Redis $redisClient = null,
string $host = '127.0.0.1',
int $port = 6379,
int $db = 0,
?string $password = null,
?string $serverId = null,
?string $webhookUrl = null,
?int $requeueThreshold = null,
int $delaySeconds = 30,
?int $taskHistoryRetention = null,
?int $taskTtl = null,
?LoggerInterface $logger = null
) {
if ($redisClient) {
$this->redis = $redisClient;
} else {
$this->redis = new Redis();
// Bounded connect and read. Without the read timeout phpredis waits
// forever for a reply, so a half-open socket strands the caller
// instead of raising — see the constants above.
$this->redis->connect(
$host,
$port,
self::CONNECT_TIMEOUT,
null,
0,
self::READ_TIMEOUT
);
// Let the kernel notice a peer that has gone away while we are idle.
if (defined('Redis::OPT_TCP_KEEPALIVE')) {
$this->redis->setOption(Redis::OPT_TCP_KEEPALIVE, self::TCP_KEEPALIVE);
}
if ($password) {
$this->redis->auth($password);
}
$this->redis->select($db);
}
$this->serverId = $serverId ?? gethostname();
$this->webhookUrl = $webhookUrl;
$this->requeueThreshold = $requeueThreshold;
$this->delaySeconds = $delaySeconds;
$this->taskHistoryRetention = $taskHistoryRetention ?? self::TASK_HISTORY_RETENTION;
$this->taskTtl = $taskTtl ?? self::TASK_TTL;
$this->logger = $logger ?? new NullLogger();
$this->registerServer();
}
/**
* Get the Redis client instance.
*/
public function getRedisClient(): Redis
{
return $this->redis;
}
/**
* Get the list of allowed task names.
*
* @return string[]
*/
public function getAllowedTasks(): array
{
return array_keys($this->allowedTasks);
}
/**
* Set a middleware instance for lifecycle hooks.
*/
public function setMiddleware(Middleware $middleware): self
{
$this->middleware = $middleware;
return $this;
}
/**
* Register this server in Redis.
*/
public function registerServer(): void
{
$serverData = [
'allowed_tasks' => array_keys($this->allowedTasks),
'status' => 'idle',
'last_heartbeat' => microtime(true),
];
$this->redis->hSet('servers', $this->serverId, json_encode($serverData));
}
/**
* Register a task handler.
*
* @param string $taskName The name of the task
* @param callable $handler The task handler function
* @param array $options Task options (timeout, stream, retries)
*/
public function task(string $taskName, callable $handler, array $options = []): self
{
$this->allowedTasks[$taskName] = true;
$this->taskHandlers[$taskName] = $handler;
$this->taskOptions[$taskName] = array_merge([
'timeout' => null,
'stream' => false,
'retries' => 0,
], $options);
$this->registerServer();
return $this;
}
/**
* Enqueue a task for processing.
*
* @param string $taskName The name of the task to run
* @param array $data The data to pass to the task
* @param string|null $taskId Optional custom task ID (uses UUID if not provided)
* @param array|null $additionalParams Optional additional parameters to include in task response
* @return Task The queued task instance
*/
public function enqueue(string $taskName, array $data = [], ?string $taskId = null, ?array $additionalParams = null): Task
{
$options = $this->taskOptions[$taskName] ?? [];
$payload = [
'data' => [
"args" => [$data],
],
'timeout' => $options['timeout'] ?? null,
'stream' => $options['stream'] ?? false,
'retries' => $options['retries'] ?? 0,
];
$task = new Task(
taskName: $taskName,
payload: $payload,
taskId: $taskId,
additionalParams: $additionalParams
);
if ($options['stream'] ?? false) {
$task->stream = true;
}
$taskDict = $task->toArray();
$now = microtime(true);
$taskDict['created_at'] = $now;
$taskDict['queued_at'] = $now;
$this->enqueueTask($taskDict, $payload);
return $task;
}
/**
* Push a task into the queue.
*
* All five writes go out as one pipeline. They used to be five separate
* commands, each waiting for its own reply before the next was sent, which
* costs five network round trips on the caller's request path -- 1.36s
* measured from a producer in us-east4 against the Redis in Mumbai, on
* every generation request. Redis still executes them in order; only the
* waiting is removed.
*
* Order is also corrected while we are here: the task's own state is
* written before the id is advertised on `ml_tasks`, so a worker can no
* longer pop a task whose `task:{id}` key does not exist yet.
*/
private function enqueueTask(array $taskData, array $payload): void
{
$taskData['status'] = 'queued';
$this->checkMiddleware('before_enqueue');
if (!isset($taskData['queued_at'])) {
$taskData['queued_at'] = microtime(true);
}
$taskId = $taskData['task_id'];
$encoded = json_encode($taskData);
$historyScore = $taskData['created_at'] ?? $taskData['queued_at'];
$this->redis->multi(Redis::PIPELINE)
->setex("task:{$taskId}", self::TASK_TTL, $encoded)
->zAdd('task_history', $historyScore, $taskId)
->setex(
"task_history:{$taskId}",
self::TASK_HISTORY_RETENTION,
json_encode($this->withoutPayload($taskData))
)
->rPush('ml_tasks', $encoded)
->zAdd('queued_requests', $taskData['queued_at'], $taskId)
->exec();
$this->checkMiddleware('after_enqueue');
}
/**
* Enqueue a delayed task.
*/
public function enqueueDelayedTask(array $taskDict, int $delaySeconds): void
{
$runAt = microtime(true) + $delaySeconds;
$taskJson = json_encode($taskDict);
$this->redis->zAdd('delayed_tasks', $runAt, $taskJson);
$this->logger->info("Delayed task {$taskDict['task_id']} by {$delaySeconds} seconds.");
}
/**
* Start worker processes.
*
* @param int $workers Number of workers (for PHP single-threaded, this affects logging only)
*/
public function startWorkers(int $workers = 1): void
{
$this->running = true;
$this->checkMiddleware('before_worker_boot');
$this->checkMiddleware('after_worker_boot');
$lastHeartbeat = 0.0;
$lastPrune = 0.0;
$lastDelayedCheck = 0.0;
$this->logger->info("ModelQ workers started. Registered tasks: " . implode(', ', array_keys($this->allowedTasks)));
while ($this->running) {
$now = microtime(true);
// Heartbeat
if ($now - $lastHeartbeat >= self::HEARTBEAT_INTERVAL) {
$this->heartbeat();
$lastHeartbeat = $now;
}
// Pruning
if ($now - $lastPrune >= self::PRUNE_CHECK_INTERVAL) {
$this->pruneInactiveServers();
$this->requeueStuckProcessingTasks();
// pruneOldTaskResults() is deliberately NOT called here. Every
// task_result key is written with a TTL, so Redis expires it on
// its own; running the scan every PRUNE_CHECK_INTERVAL only
// re-read the whole keyspace. Measured on a production shard
// over 26 days: 196.7M SCAN + 228.8M GET to issue 2 DELs.
$lastPrune = $now;
}
// Check delayed tasks
if ($now - $lastDelayedCheck >= 1) {
$this->requeueDelayedTasks();
$lastDelayedCheck = $now;
}
// Process tasks
$this->updateServerStatus('idle');
$taskData = $this->redis->blPop(['ml_tasks'], self::BLPOP_TIMEOUT);
if (!$taskData) {
continue;
}
$this->updateServerStatus('busy');
$taskJson = $taskData[1];
$taskDict = json_decode($taskJson, true);
$task = Task::fromArray($taskDict);
$added = $this->redis->sAdd('processing_tasks', $task->taskId);
if ($added === 0) {
$this->logger->warning("Task {$task->taskId} is already being processed. Skipping duplicate.");
continue;
}
$now = microtime(true);
$task->status = 'processing';
$task->startedAt = $now;
$taskDict['status'] = 'processing';
$taskDict['started_at'] = $now;
$this->redis->setex("task:{$task->taskId}", 86400, json_encode($taskDict));
if (isset($this->allowedTasks[$task->taskName])) {
try {
$this->logger->info("Started processing: {$task->taskName}");
$startTime = microtime(true);
$this->processTask($task);
$endTime = microtime(true);
$this->logger->info(sprintf(
"Finished %s in %.2f seconds",
$task->taskName,
$endTime - $startTime
));
} catch (TaskProcessingException $e) {
$this->logger->error("TaskProcessingError: " . $e->getMessage());
$this->handleRetry($task, $taskDict);
} catch (Throwable $e) {
$this->logger->error("Unexpected error: " . $e->getMessage());
$this->handleRetry($task, $taskDict);
}
} else {
$this->logger->warning("Cannot process task {$task->taskName}, re-queueing...");
$this->redis->rPush('ml_tasks', $taskJson);
}
}
$this->checkMiddleware('before_worker_shutdown');
$this->checkMiddleware('after_worker_shutdown');
}
/**
* Stop the worker loop.
*/
public function stop(): void
{
$this->running = false;
}
/**
* Handle task retry logic.
*/
private function handleRetry(Task $task, array $taskDict): void
{
$retries = $task->payload['retries'] ?? 0;
if ($retries > 0) {
$newTaskDict = $task->toArray();
$newTaskDict['payload'] = $task->originalPayload;
$newTaskDict['payload']['retries'] = $retries - 1;
$this->enqueueDelayedTask($newTaskDict, $this->delaySeconds);
}
}
/**
* Process a task.
*/
private function processTask(Task $task): void
{
try {
if (!isset($this->allowedTasks[$task->taskName])) {
$task->status = 'failed';
$task->result = 'Task not allowed on this server.';
$this->storeFinalTaskState($task, false);
$this->logger->error("Task {$task->taskName} is not allowed on this server.");
throw new TaskProcessingException($task->taskName, 'Task not allowed');
}
$handler = $this->taskHandlers[$task->taskName] ?? null;
if (!$handler) {
$task->status = 'failed';
$task->result = 'Task handler not found';
$this->storeFinalTaskState($task, false);
$this->logger->error("Task {$task->taskName} failed - handler not found.");
throw new TaskProcessingException($task->taskName, 'Task handler not found');
}
$data = $task->payload['data'] ?? [];
$timeout = $task->payload['timeout'] ?? null;
$stream = $task->payload['stream'] ?? false;
$this->logger->info("Processing task: {$task->taskName} with data: " . json_encode($data));
if ($stream) {
// Stream results using Redis Streams
$generator = $handler($data);
if ($generator instanceof \Generator) {
foreach ($generator as $result) {
$task->status = 'in_progress';
$this->redis->xAdd(
"task_stream:{$task->taskId}",
'*',
['result' => json_encode($result)]
);
}
}
$task->status = 'completed';
$this->redis->expire("task_stream:{$task->taskId}", 3600);
$this->storeFinalTaskState($task, true);
} else {
// Standard execution
if ($timeout) {
$result = $this->runWithTimeout($handler, $timeout, $data);
} else {
$result = $handler($data);
}
$task->result = $result;
$task->status = 'completed';
$this->storeFinalTaskState($task, true);
}
$this->logger->info("Task {$task->taskName} completed successfully.");
} catch (RetryTaskException $e) {
$this->logger->warning("Task {$task->taskName} requested retry: " . $e->getMessage());
$newTaskDict = $task->toArray();
$newTaskDict['payload'] = $task->originalPayload;
$this->enqueueDelayedTask($newTaskDict, $this->delaySeconds);
} catch (Throwable $e) {
$task->status = 'failed';
$task->result = $e->getMessage();
$this->storeFinalTaskState($task, false, $e);
$this->logTaskErrorToFile($task, $e);
$this->checkMiddleware('on_error', $task, $e);
$this->postErrorToWebhook($task, $e);
$this->logger->error("Task {$task->taskName} failed with error: " . $e->getMessage());
throw new TaskProcessingException($task->taskName, $e->getMessage(), 0, $e);
} finally {
$this->redis->sRem('processing_tasks', $task->taskId);
}
}
/**
* Run a handler with a timeout.
*/
private function runWithTimeout(callable $handler, int $timeout, array $data): mixed
{
$startTime = microtime(true);
// Set alarm if pcntl is available
if (function_exists('pcntl_alarm')) {
pcntl_alarm($timeout);
try {
$result = $handler($data);
pcntl_alarm(0);
return $result;
} catch (\Throwable $e) {
pcntl_alarm(0);
throw $e;
}
}
// Fallback: just run and check time after
$result = $handler($data);
$elapsed = microtime(true) - $startTime;
if ($elapsed > $timeout) {
throw new TaskTimeoutException(
'timeout',
"Task exceeded timeout of {$timeout} seconds"
);
}
return $result;
}
/**
* Store the final state of a task in Redis.
*/
private function storeFinalTaskState(Task $task, bool $success, ?Throwable $error = null): void
{
$taskDict = $task->toArray();
$taskDict['finished_at'] = microtime(true);
// Add error details if failed
if (!$success && $error) {
$taskDict['error'] = [
'message' => $error->getMessage(),
'type' => get_class($error),
'file' => $error->getFile(),
'line' => $error->getLine(),
'trace' => $error->getTraceAsString(),
];
}
$this->redis->setex("task_result:{$task->taskId}", 3600, json_encode($taskDict));
$this->redis->setex("task:{$task->taskId}", 86400, json_encode($taskDict));
$this->redis->zRem('queued_requests', $task->taskId);
// Update task history
$this->updateTaskHistory($task->taskId, $taskDict);
}
/**
* Update server heartbeat.
*/
private function heartbeat(): void
{
$rawData = $this->redis->hGet('servers', $this->serverId);
if (!$rawData) {
$this->registerServer();
return;
}
$data = json_decode($rawData, true);
$data['last_heartbeat'] = microtime(true);
$this->redis->hSet('servers', $this->serverId, json_encode($data));
}
/**
* Update server status in Redis.
*/
private function updateServerStatus(string $status): void
{
$rawData = $this->redis->hGet('servers', $this->serverId);
if (!$rawData) {
$this->registerServer();
return;
}
$serverData = json_decode($rawData, true);
$serverData['status'] = $status;
$serverData['last_heartbeat'] = microtime(true);
$this->redis->hSet('servers', $this->serverId, json_encode($serverData));
}
/**
* Check and execute middleware.
*/
private function checkMiddleware(string $event, ?Task $task = null, ?Throwable $error = null): void
{
if ($this->middleware) {
$this->middleware->execute($event, $task, $error);
}
}
/**
* Get registered server IDs.
*
* @return string[]
*/
public function getRegisteredServerIds(): array
{
$keys = $this->redis->hKeys('servers');
return $keys ?: [];
}
/**
* Get all registered workers with their system info.
*
* Returns worker details including:
* - worker_id: Unique worker identifier
* - status: Current status (idle, busy)
* - allowed_tasks: List of tasks this worker handles
* - last_heartbeat: Unix timestamp of last heartbeat
* - system_info: CPU, RAM, GPU information (if provided by worker)
*
* @return array<string, array> Map of worker_id => worker data
*/
public function getWorkers(): array
{
$workers = [];
$allServers = $this->redis->hGetAll('servers');
foreach ($allServers as $serverId => $dataJson) {
try {
$data = json_decode($dataJson, true);
$workers[$serverId] = [
'worker_id' => $serverId,
'status' => $data['status'] ?? 'unknown',
'allowed_tasks' => $data['allowed_tasks'] ?? [],
'last_heartbeat' => array_key_exists('last_heartbeat', $data) ? $data['last_heartbeat'] : null,
'system_info' => array_key_exists('system_info', $data) ? $data['system_info'] : null,
'hostname' => array_key_exists('hostname', $data) ? $data['hostname'] : null,
'os' => array_key_exists('os', $data) ? $data['os'] : null,
'python_version' => array_key_exists('python_version', $data) ? $data['python_version'] : null,
'php_version' => array_key_exists('php_version', $data) ? $data['php_version'] : null,
];
} catch (Throwable $e) {
$this->logger->warning("Could not parse worker data for {$serverId}: " . $e->getMessage());
}
}
return $workers;
}
/**
* Get a specific worker's info by ID.
*
* @param string $workerId The worker ID to look up
* @return array|null Worker data or null if not found
*/
public function getWorker(string $workerId): ?array
{
$dataJson = $this->redis->hGet('servers', $workerId);
if (!$dataJson) {
return null;
}
try {
$data = json_decode($dataJson, true);
return [
'worker_id' => $workerId,
'status' => $data['status'] ?? 'unknown',
'allowed_tasks' => $data['allowed_tasks'] ?? [],
'last_heartbeat' => array_key_exists('last_heartbeat', $data) ? $data['last_heartbeat'] : null,
'system_info' => array_key_exists('system_info', $data) ? $data['system_info'] : null,
'hostname' => array_key_exists('hostname', $data) ? $data['hostname'] : null,
'os' => array_key_exists('os', $data) ? $data['os'] : null,
'python_version' => array_key_exists('python_version', $data) ? $data['python_version'] : null,
'php_version' => array_key_exists('php_version', $data) ? $data['php_version'] : null,
];
} catch (Throwable $e) {
$this->logger->warning("Could not parse worker data for {$workerId}: " . $e->getMessage());
return null;
}
}
/**
* Get all queued tasks.
*/
public function getAllQueuedTasks(): array
{
$queuedTasks = [];
$tasksInList = $this->redis->lRange('ml_tasks', 0, -1);
foreach ($tasksInList as $taskJson) {
try {
$taskDict = json_decode($taskJson, true);
if (($taskDict['status'] ?? '') === 'queued') {
$queuedTasks[] = $taskDict;
}
} catch (Throwable $e) {
$this->logger->error("Error deserializing task from ml_tasks: " . $e->getMessage());
}
}
return $queuedTasks;
}
/**
* Get the number of tasks waiting in the queue.
*
* O(1) LLEN on `ml_tasks`. This is the fast path for queue-depth checks and
* autoscaling: unlike getAllQueuedTasks(), it does NOT LRANGE and deserialize
* every entry, so it stays cheap even when task payloads are large (which
* otherwise blocks Redis's single thread and can surface as client read
* timeouts under load).
*/
public function getQueuedTaskCount(): int
{
return (int) $this->redis->lLen('ml_tasks');
}
/**
* Get task status by ID.
*/
public function getTaskStatus(string $taskId): ?string
{
$taskData = $this->redis->get("task:{$taskId}");
if ($taskData) {
$data = json_decode($taskData, true);
return $data['status'] ?? null;
}
return null;
}
// ========================================
// Task History Methods
// ========================================
/**
* Strip the request payload before a task is written to history.
*
* Enqueueing already stores the payload twice — once in the `ml_tasks` list
* for the worker to pop, and once under `task:{id}` because
* requeueStuckProcessingTasks() rebuilds a stuck job from that key. History
* was a third copy, held for TASK_HISTORY_RETENTION, and nothing reads it:
* getTaskHistory() and getTaskStats() only look at `status` and `task_name`,
* and getTaskDetails() reads `task:{id}`, never history.
*
* That third copy is what makes a large request expensive. A generation
* carrying an inline base64 image can push a multi-megabyte payload, so a
* single request could pin three times its own size in Redis for a day —
* enough for one caller to exhaust a database that many queues share.
*
* CAUTION for future changes: callers do read output links back out of the
* payload — the frontend resolves a finished generation via
* `payload.data.args.0.output` on whatever getTaskDetails() returns. That is
* safe only because getTaskDetails() reads `task:{id}`, which keeps its
* payload. If getTaskDetails() is ever given a `task_history:{id}` fallback
* (tests/Integration/ModelQTest.php::testTaskHistoryWithErrorDetails already
* expects one), a stripped history would resolve those links to an empty
* array and report finished work as producing no output. Restore the payload
* here, or keep the output slice, before adding that fallback.
*
* @param array<string, mixed> $taskData
* @return array<string, mixed>
*/
private function withoutPayload(array $taskData): array
{
unset($taskData['payload']);
return $taskData;
}
/**
* Update task in history.
*/
private function updateTaskHistory(string $taskId, array $taskData): void
{
$this->redis->setex(
"task_history:{$taskId}",
self::TASK_HISTORY_RETENTION,
json_encode($this->withoutPayload($taskData))
);
}
/**
* Get full task details including error information.
*
* @return array|null Task data with error details if failed
*/
public function getTaskDetails(string $taskId): ?array
{
// First try task_history (longer retention)
$taskData = $this->redis->get("task:{$taskId}");
if ($taskData) {
return json_decode($taskData, true);
}
return null;
}
/**
* Get task history with optional filters.
*
* @param int $limit Maximum number of tasks to return
* @param int $offset Number of tasks to skip
* @param string|null $status Filter by status (queued, processing, completed, failed)
* @param string|null $taskName Filter by task name
* @return array List of tasks with their details
*/
public function getTaskHistory(
int $limit = 50,
int $offset = 0,
?string $status = null,
?string $taskName = null
): array {
// Get task IDs from sorted set (newest first)
$taskIds = $this->redis->zRevRange('task_history', $offset, $offset + $limit - 1);
$tasks = [];
foreach ($taskIds as $taskId) {
$taskData = $this->redis->get("task_history:{$taskId}");
if ($taskData) {
$task = json_decode($taskData, true);
// Apply filters
if ($status !== null && ($task['status'] ?? '') !== $status) {
continue;
}
if ($taskName !== null && ($task['task_name'] ?? '') !== $taskName) {
continue;
}
$tasks[] = $task;
}
}
return $tasks;
}
/**
* Get failed tasks with error details.
*
* @param int $limit Maximum number of tasks to return
* @return array List of failed tasks with error information
*/
public function getFailedTasks(int $limit = 50): array
{
return $this->getTaskHistory(limit: $limit, status: 'failed');
}
/**
* Get completed tasks.
*
* @param int $limit Maximum number of tasks to return
* @return array List of completed tasks
*/
public function getCompletedTasks(int $limit = 50): array
{
return $this->getTaskHistory(limit: $limit, status: 'completed');
}
/**
* Get tasks by task name.
*
* @param string $taskName The task name to filter by
* @param int $limit Maximum number of tasks to return
* @return array List of tasks matching the name
*/
public function getTasksByName(string $taskName, int $limit = 50): array
{
return $this->getTaskHistory(limit: $limit, taskName: $taskName);
}
/**
* Get task statistics.
*
* @return array Statistics about tasks in history
*/
public function getTaskStats(): array
{
$taskIds = $this->redis->zRange('task_history', 0, -1);
$stats = [
'total' => count($taskIds),
'by_status' => [
'queued' => 0,
'processing' => 0,
'completed' => 0,
'failed' => 0,
],
'by_task_name' => [],
'failed_tasks' => [],
];
foreach ($taskIds as $taskId) {
$taskData = $this->redis->get("task_history:{$taskId}");
if ($taskData) {
$task = json_decode($taskData, true);
$status = $task['status'] ?? 'unknown';
$taskName = $task['task_name'] ?? 'unknown';
// Count by status
if (isset($stats['by_status'][$status])) {
$stats['by_status'][$status]++;
}
// Count by task name
if (!isset($stats['by_task_name'][$taskName])) {
$stats['by_task_name'][$taskName] = ['total' => 0, 'completed' => 0, 'failed' => 0];
}
$stats['by_task_name'][$taskName]['total']++;
if ($status === 'completed') {
$stats['by_task_name'][$taskName]['completed']++;
} elseif ($status === 'failed') {
$stats['by_task_name'][$taskName]['failed']++;
// Add to failed tasks list (limit to 10 most recent)
if (count($stats['failed_tasks']) < 10) {
$stats['failed_tasks'][] = [
'task_id' => $task['task_id'],
'task_name' => $taskName,
'error' => $task['error']['message'] ?? $task['result'] ?? 'Unknown error',
'finished_at' => $task['finished_at'] ?? null,
];
}
}
}
}
return $stats;
}
/**
* Clear old task history.
*
* @param int $olderThanSeconds Remove tasks older than this many seconds
* @return int Number of tasks removed
*/
public function clearTaskHistory(int $olderThanSeconds = 604800): int
{
$cutoff = microtime(true) - $olderThanSeconds;
// Get old task IDs
$oldTaskIds = $this->redis->zRangeByScore('task_history', '-inf', (string) $cutoff);
$removed = 0;
foreach ($oldTaskIds as $taskId) {
$this->redis->zRem('task_history', $taskId);
$this->redis->del("task_history:{$taskId}");
$removed++;
}
return $removed;
}
/**
* Get task count in history.
*/
public function getTaskHistoryCount(): int
{
return $this->redis->zCard('task_history') ?: 0;
}
/**
* Delete the entire queue.
*/
public function deleteQueue(): void
{
$this->redis->lTrim('ml_tasks', 1, 0);
}
/**
* Remove a task from the queue.
*/
public function removeTaskFromQueue(string $taskId): bool
{
// Always drop the queue index and processing marker so a cancelled task
// is neither counted (queue_num / queue_time) nor picked up again — even
// if it has already left ml_tasks.
$this->redis->zRem('queued_requests', $taskId);
$this->redis->sRem('processing_tasks', $taskId);
$tasks = $this->redis->lRange('ml_tasks', 0, -1);
$removed = false;
foreach ($tasks as $taskJson) {
try {
$taskDict = json_decode($taskJson, true);
if (($taskDict['task_id'] ?? '') === $taskId) {
$this->redis->lRem('ml_tasks', $taskJson, 1);
$removed = true;
$this->logger->info("Removed task {$taskId} from queue.");
break;
}
} catch (Throwable $e) {
$this->logger->error("Failed to process task while trying to remove: " . $e->getMessage());
}
}
return $removed;
}
/**
* Prune inactive servers.
*/
private function pruneInactiveServers(?int $timeoutSeconds = null): void
{
$timeoutSeconds = $timeoutSeconds ?? self::PRUNE_TIMEOUT;
$allServers = $this->redis->hGetAll('servers');
$now = microtime(true);
$removedCount = 0;
foreach ($allServers as $serverId => $dataJson) {
try {
$data = json_decode($dataJson, true);
$lastHeartbeat = $data['last_heartbeat'] ?? 0;
if (($now - $lastHeartbeat) > $timeoutSeconds) {
$this->redis->hDel('servers', $serverId);
$removedCount++;
$this->logger->info("[Prune] Removed stale server: {$serverId}");
}
} catch (Throwable $e) {
$this->logger->warning("[Prune] Could not parse server data for {$serverId}: " . $e->getMessage());
}
}