同步线上直接修改的代码:处方 AI 队列派发与重试额度、角色 13 处方权限

以下改动此前只在生产服务器上直接修改,未进仓库,现按线上文件原样收回:
- 处方 AI:新增 prescription-ai:dispatch 每分钟派发单轮队列(PrescriptionAiDispatch、
  PrescriptionAiLaneGuard 队列锁),work 命令支持 --scheduled;重试接口返回与轮询一致的
  任务状态,额度用尽时提示最早可重试时间;每日模型任务默认额度 200 → 5000
- 定时任务 SQL:database/migrations/2026_12_02_prescription_ai_crontab.sql(线上已执行)
- project.php:prescription_library_manage_all_roles / prescription_audit_roles 加入角色 13

Co-Authored-By: Claude Opus 5 <[EMAIL]>
This commit is contained in:
Your Name
2026-12-05 10:27:47 +08:00
co-authored by Claude Opus 5
parent 580444731b
commit 5ea3417e4c
10 changed files with 310 additions and 32 deletions
@@ -0,0 +1,106 @@
<?php
declare(strict_types=1);
namespace app\common\service\prescriptionai;
use RuntimeException;
final class PrescriptionAiLaneGuard
{
public const LANES = ['prepare', 'qwen', 'openai'];
/** Shared locks allow several supervised workers. A scheduled fallback needs the lane exclusively. */
public static function acquire(string $runtime, string $lane, int $operation)
{
if (!in_array($lane, self::LANES, true)) {
throw new RuntimeException('未知处方 AI 队列');
}
$directory = $runtime . 'lock';
if (!is_dir($directory) && !@mkdir($directory, 0775, true) && !is_dir($directory)) {
throw new RuntimeException('无法创建处方 AI 队列锁目录');
}
return self::lock($directory . '/prescription_ai_' . $lane . '.lock', 'c+', $operation);
}
public static function busy(string $runtime, string $lane): bool
{
$path = $runtime . 'lock/prescription_ai_' . $lane . '.lock';
if (!is_file($path)) { return false; }
$probe = self::lock($path, 'r', LOCK_EX | LOCK_NB);
if ($probe === null) { return true; }
fclose($probe);
return false;
}
private static function lock(string $path, string $mode, int $operation)
{
$handle = @fopen($path, $mode);
if ($handle === false) {
throw new RuntimeException('无法打开处方 AI 队列锁');
}
if (flock($handle, $operation, $wouldBlock)) {
return $handle;
}
fclose($handle);
if ($wouldBlock) {
return null;
}
throw new RuntimeException('无法锁定处方 AI 队列');
}
/** Detect workers started before lane locks were introduced, without requiring a service restart. */
public static function linuxWorkers(string $think, string $proc = '/proc'): array
{
$target = realpath($think);
$processFiles = glob($proc . '/[0-9]*/comm');
if (!$target || !is_readable($proc . '/self/cmdline') || $processFiles === false) {
throw new RuntimeException('处方 AI 巡检无法读取 Linux 进程信息');
}
$found = [];
foreach ($processFiles as $file) {
$name = trim((string) @file_get_contents($file));
if (!preg_match('/^php(?:-?cli|[0-9.]+)?$/iD', $name) && $name !== basename(PHP_BINARY)) {
continue;
}
$pid = dirname($file);
$arguments = explode("\0", rtrim((string) @file_get_contents($pid . '/cmdline'), "\0"));
$index = array_search('prescription-ai:work', $arguments, true);
if ($index === false || $index < 2) {
continue;
}
$script = $arguments[$index - 1];
if (basename($script) !== 'think') {
continue;
}
if ($script[0] !== '/') {
$cwd = realpath($pid . '/cwd');
if ($cwd === false) {
if (!is_dir($pid)) { continue; } // A short-lived worker can exit during inspection.
throw new RuntimeException('无法核对处方 AI 消费者的工作目录,请使用消费者的系统账号运行巡检');
}
$script = $cwd . '/' . $script;
}
if (realpath($script) !== $target) {
continue;
}
$lane = 'prepare';
foreach (array_slice($arguments, $index + 1) as $offset => $argument) {
if (str_starts_with($argument, '--lane=')) {
$lane = substr($argument, 7);
} elseif ($argument === '--lane') {
$lane = $arguments[$index + $offset + 2] ?? '';
}
}
if (in_array($lane, self::LANES, true)) {
if (!in_array('--once', $arguments, true)) {
$found[$lane] = 'resident';
} elseif (!isset($found[$lane])) {
$found[$lane] = 'single_run';
}
if (count(array_keys($found, 'resident', true)) === count(self::LANES)) { break; }
}
}
return $found;
}
}
@@ -70,9 +70,15 @@ final class PrescriptionAiProgress
$result = self::present($meta, $now, self::number($task['started_at'] ?? null), $end);
$result['attempt'] = self::number($task['total_attempts'] ?? $task['attempts'] ?? null, 1000000) ?? 0;
if ($status === 'retry_wait') {
$result['wait_remaining_seconds'] = self::remaining($task['next_run_at'] ?? null, $now);
$result['notice'] = ($task['error_code'] ?? '') === 'BUDGET_PAUSED'
? '今日模型任务额度已用完,到时间后自动继续。' : '本次未完成,已安排自动重试。';
$result['next_run_at'] = self::number($task['next_run_at'] ?? null);
$result['wait_remaining_seconds'] = self::remaining($result['next_run_at'], $now);
if ($result['wait_remaining_seconds'] === 0) {
$result['notice'] = '已到可重试时间,等待后台领取任务。';
} elseif (($task['error_code'] ?? '') === 'BUDGET_PAUSED' && $result['next_run_at'] > 0) {
$result['notice'] = '今日模型任务额度已用完,最早可于 ' . date('Y-m-d H:i:s', $result['next_run_at']) . '(服务器时间)领取重试。';
} else {
$result['notice'] = '本次未完成,已安排自动重试。';
}
}
if (in_array($status, ['failed', 'retry_wait'], true)
&& in_array($lastStage, ['text', 'files', 'reduce', 'final', 'validating', 'comparing'], true)) {
@@ -234,6 +234,24 @@ final class PrescriptionAiStore
]);
}
/** Read-only snapshot for retry scheduling. Only a successful claim reserves a daily slot. */
public static function exhaustedModels(array $models, int $now): array
{
if (!$models) { return []; }
$keys = [];
foreach ($models as $model) {
$keys[date('Y-m-d', $now) . ':' . $model] = $model;
}
$exhausted = Db::name('prescription_ai_limit')->whereIn('limit_key', array_keys($keys))
->where('used_count', '>=', self::dailyModelTaskLimit())->column('limit_key');
return array_map(static fn ($key): string => $keys[$key], $exhausted);
}
private static function dailyModelTaskLimit(): int
{
return max(1, (int) config('prescription_analysis.daily_model_tasks', 200));
}
public static function claimTask(string $model): ?array
{
if (!in_array($model, PrescriptionAiPolicy::MODELS, true)) {
@@ -272,7 +290,7 @@ final class PrescriptionAiStore
self::refreshBatch((int) $row['batch_id']);
return null;
}
if ((int) $budget['used_count'] >= max(1, (int) config('prescription_analysis.daily_model_tasks', 200))) {
if ((int) $budget['used_count'] >= self::dailyModelTaskLimit()) {
Db::name('prescription_ai_task')->where('id', $id)->update([
'status' => 'retry_wait', 'error_code' => 'BUDGET_PAUSED',
'next_run_at' => strtotime('tomorrow', $now), 'updated_at' => $now,