diff --git a/server/app/adminapi/logic/tcm/PrescriptionAiLogic.php b/server/app/adminapi/logic/tcm/PrescriptionAiLogic.php index 97e888d64..70e6bf5be 100755 --- a/server/app/adminapi/logic/tcm/PrescriptionAiLogic.php +++ b/server/app/adminapi/logic/tcm/PrescriptionAiLogic.php @@ -169,23 +169,30 @@ final class PrescriptionAiLogic if (!$task) { throw new DomainException('资料尚未准备完成,请查看分析状态'); } - if ($task['status'] === 'success' || in_array($task['status'], Policy::ACTIVE_TASKS, true)) { - return ['batch_id' => $batchId, 'status' => $task['status']]; - } - if ($task['status'] !== 'failed') { + $now = time(); + $newRetry = $task['status'] === 'failed'; + if ($newRetry) { + if ((int) $task['manual_retries'] >= (int) config('prescription_analysis.max_manual_retries', 2)) { + throw new DomainException('该模型已达手动重试上限,请检查失败原因'); + } + $changes = [ + 'status' => 'retry_wait', 'attempts' => 0, 'next_run_at' => $now, + 'manual_retries' => (int) $task['manual_retries'] + 1, + 'lock_token' => '', 'lock_until' => 0, 'error_code' => '', 'updated_at' => $now, + ]; + $task = array_replace($task, $changes); + } elseif ($task['status'] !== 'success' && !in_array($task['status'], Policy::ACTIVE_TASKS, true)) { throw new DomainException('该任务不能重试'); } - if ((int) $task['manual_retries'] >= (int) config('prescription_analysis.max_manual_retries', 2)) { - throw new DomainException('该模型已达手动重试上限,请检查失败原因'); + $state = self::taskStates([$task], $now)[0]; + if ($newRetry) { + // Keep audit history and the encrypted resume checkpoint across retry rounds. + $changes['next_run_at'] = $state['progress']['next_run_at']; + $changes['error_code'] = $state['error_code']; + Db::name('prescription_ai_task')->where('id', $task['id'])->update($changes); + Store::refreshBatch($batchId); } - // Attempt history and lifetime counter remain immutable across retry rounds. - Db::name('prescription_ai_task')->where('id', $task['id'])->update([ - 'status' => 'retry_wait', 'attempts' => 0, 'next_run_at' => time(), 'lock_token' => '', - 'manual_retries' => (int) $task['manual_retries'] + 1, - 'lock_until' => 0, 'error_code' => '', 'updated_at' => time(), - ]); - Store::refreshBatch($batchId); - return ['batch_id' => $batchId, 'status' => 'retry_wait']; + return ['batch_id' => $batchId, 'model_key' => $model] + $state; }); } @@ -280,12 +287,54 @@ final class PrescriptionAiLogic 'metric_label' => '药味与剂量一致度(不代表临床准确率)']; } + /** Project the retry response and polled model states from the same task, ledger and attempt history. */ + private static function taskStates(array $tasks, int $now): array + { + $budgetModels = []; + $attemptTaskIds = []; + foreach ($tasks as $task) { + if ($task['status'] !== 'retry_wait') { continue; } + if ($task['error_code'] !== 'BUDGET_PAUSED' || (int) $task['next_run_at'] <= $now) { + $budgetModels[] = $task['model_key']; + } + if ((int) $task['total_attempts'] > 0) { + $attemptTaskIds[] = $task['id']; + } + } + $exhausted = Store::exhaustedModels($budgetModels, $now); + $lastErrors = $attemptTaskIds ? Db::name('prescription_ai_attempt')->alias('a') + ->join('prescription_ai_task t', 't.id = a.task_id AND t.total_attempts = a.attempt_no') + ->whereIn('a.task_id', $attemptTaskIds)->whereIn('a.status', ['failed', 'expired']) + ->column('a.error_code', 'task_id') : []; + $maxRetries = (int) config('prescription_analysis.max_manual_retries', 2); + $states = []; + foreach ($tasks as $task) { + $code = $task['error_code']; + $lastError = $task['status'] === 'failed' ? $code : ($lastErrors[$task['id']] ?? ''); + if ($task['status'] === 'retry_wait') { + if (in_array($task['model_key'], $exhausted, true)) { + $code = 'BUDGET_PAUSED'; + $task['next_run_at'] = max((int) $task['next_run_at'], strtotime('tomorrow', $now)); + } elseif ($code === 'BUDGET_PAUSED' && (int) $task['next_run_at'] <= $now) { + $code = ''; // Yesterday's pause has expired; eligibility still awaits a real claim. + } + } + $task['error_code'] = $code; + $states[] = ['status' => $task['status'], 'error_code' => $code, + 'error_message' => $code !== '' ? Policy::errorMessage($code) : '', + 'last_error_code' => $lastError, 'last_error_message' => $lastError !== '' ? Policy::errorMessage($lastError) : '', + 'manual_retries' => (int) $task['manual_retries'], 'max_manual_retries' => $maxRetries, + 'progress' => Progress::task($task, $now)]; + } + return $states; + } + private static function models(array $batchIds, bool $full, bool $agreementVisible = true): array { if ($batchIds === []) { return []; } - $taskFields = ['batch_id', 'model_key', 'status', 'error_code', 'attempts', 'total_attempts', 'result_id', + $taskFields = ['id', 'batch_id', 'model_key', 'status', 'error_code', 'attempts', 'total_attempts', 'manual_retries', 'result_id', 'started_at', 'finished_at', 'updated_at', 'next_run_at']; if (Store::supportsProgress()) { $taskFields[] = 'progress_json'; @@ -298,14 +347,11 @@ final class PrescriptionAiLogic } $results = Db::name('prescription_ai_result')->whereIn('batch_id', $batchIds)->field($fields)->select()->toArray(); $map = []; - foreach ($tasks as $task) { - $map[(int) $task['batch_id']][$task['model_key']] = [ - 'status' => $task['status'], 'score' => null, 'herb_score' => null, - 'error_code' => $task['error_code'], 'error_message' => $task['error_code'] !== '' ? Policy::errorMessage($task['error_code']) : '', - 'reason' => $task['error_code'] !== '' ? Policy::errorMessage($task['error_code']) : '', - 'report_id' => (int) $task['result_id'], - 'progress' => Progress::task($task), - ]; + $taskStates = self::taskStates($tasks, time()); + foreach ($tasks as $index => $task) { + $state = $taskStates[$index]; + $map[(int) $task['batch_id']][$task['model_key']] = $state + ['score' => null, 'herb_score' => null, + 'reason' => $state['error_message'], 'report_id' => (int) $task['result_id']]; } foreach ($results as $result) { $body = $full ? (new Cipher())->decrypt($result['body_cipher'], 'result:' . $result['batch_id'] . ':' . $result['model_key']) : []; diff --git a/server/app/command/PrescriptionAiDispatch.php b/server/app/command/PrescriptionAiDispatch.php new file mode 100644 index 000000000..af623dd81 --- /dev/null +++ b/server/app/command/PrescriptionAiDispatch.php @@ -0,0 +1,71 @@ +setName('prescription-ai:dispatch')->setDescription('巡检处方 AI 消费者,对缺失的队列派发一轮处理') + ->addOption('check', null, Option::VALUE_NONE, '只输出巡检状态'); + } + + protected function execute(Input $input, Output $output): int + { + $enabled = PrescriptionAiStore::enabled(); + $checkOnly = (bool) $input->getOption('check'); + if (!$enabled && !$checkOnly) { + $output->writeln('PRESCRIPTION_AI_DISPATCH {"enabled":false}'); + return 0; + } + $root = $this->app->getRootPath(); + $think = $root . 'think'; + if (PHP_SAPI !== 'cli' || !is_readable($think)) { + throw new RuntimeException('处方 AI 巡检需要 PHP CLI 和可读的 think 入口'); + } + $present = PHP_OS_FAMILY === 'Linux' ? PrescriptionAiLaneGuard::linuxWorkers($think) : []; + $null = PHP_OS_FAMILY === 'Windows' ? 'NUL' : '/dev/null'; + $streams = [['file', $null, 'r'], ['file', $null, 'w'], ['file', $null, 'w']]; + $states = []; + foreach (PrescriptionAiLaneGuard::LANES as $lane) { + if (isset($present[$lane])) { + $states[$lane] = $present[$lane]; + continue; + } + if ($checkOnly) { + $states[$lane] = PrescriptionAiLaneGuard::busy($this->app->getRuntimePath(), $lane) ? 'busy' : 'missing'; + continue; + } + // Surface runtime permission errors in the admin schedule before detaching the worker. + $probe = PrescriptionAiLaneGuard::acquire($this->app->getRuntimePath(), $lane, LOCK_EX | LOCK_NB); + if ($probe === null) { + $states[$lane] = 'busy'; + continue; + } + fclose($probe); + if (!function_exists('proc_open')) { + throw new RuntimeException('处方 AI 单轮接管需要启用 proc_open'); + } + $process = proc_open([PHP_BINARY, $think, 'prescription-ai:work', '--lane=' . $lane, '--once', '--scheduled'], + $streams, $pipes, $root); + if (!is_resource($process)) { + throw new RuntimeException('无法启动处方 AI 消费者 ' . $lane); + } + // proc_close waits for the model. Releasing a pipe-free handle lets the cron runner continue immediately. + unset($process); + $states[$lane] = 'dispatched'; + } + $output->writeln('PRESCRIPTION_AI_DISPATCH ' . json_encode(['enabled' => $enabled, 'lanes' => $states])); + return 0; + } +} diff --git a/server/app/command/PrescriptionAiWork.php b/server/app/command/PrescriptionAiWork.php index a55206399..4600a0613 100755 --- a/server/app/command/PrescriptionAiWork.php +++ b/server/app/command/PrescriptionAiWork.php @@ -4,11 +4,13 @@ declare(strict_types=1); namespace app\command; +use app\common\service\prescriptionai\PrescriptionAiLaneGuard; use app\common\service\prescriptionai\PrescriptionAiStore; use app\common\service\prescriptionai\PrescriptionAiWorker; use think\console\Command; use think\facade\Config; use think\facade\Db; +use think\facade\Log; use think\console\Input; use think\console\input\Option; use think\console\Output; @@ -19,16 +21,26 @@ final class PrescriptionAiWork extends Command { $this->setName('prescription-ai:work')->setDescription('处方AI独立后台任务;分别运行prepare/qwen/openai') ->addOption('lane', null, Option::VALUE_REQUIRED, 'prepare、qwen、openai', 'prepare') - ->addOption('once', null, Option::VALUE_NONE, '只处理一轮'); + ->addOption('once', null, Option::VALUE_NONE, '只处理一轮') + ->addOption('scheduled', null, Option::VALUE_NONE, '定时任务单轮接管,当前队列已占用时跳过'); } protected function execute(Input $input, Output $output): int { $lane = (string) $input->getOption('lane'); - if (!in_array($lane, ['prepare', 'qwen', 'openai'], true)) { + if (!in_array($lane, PrescriptionAiLaneGuard::LANES, true)) { $output->writeln('Invalid lane'); return 1; } + $scheduled = $input->getOption('scheduled'); + if ($scheduled && !$input->getOption('once')) { + $output->writeln('--scheduled requires --once'); + return 1; + } + // This handle stays open until execute() returns. Process exit also releases it after a crash. + $laneLock = PrescriptionAiLaneGuard::acquire($this->app->getRuntimePath(), $lane, + $scheduled ? LOCK_EX | LOCK_NB : LOCK_SH); + if ($laneLock === null) { return 0; } $running = true; if (function_exists('pcntl_async_signals')) { pcntl_async_signals(true); @@ -48,6 +60,11 @@ final class PrescriptionAiWork extends Command $sweepAt = 0; $sourceCursor = 0; $rxCursor = 0; + if ($scheduled && $lane === 'prepare') { + $saved = json_decode((string) stream_get_contents($laneLock), true); + $sourceCursor = (int) ($saved['source'] ?? 0); + $rxCursor = (int) ($saved['prescription'] ?? 0); + } do { $worked = false; try { @@ -60,6 +77,12 @@ final class PrescriptionAiWork extends Command $sourceCursor = $sweep['selected'] > 0 ? $sweep['last_id'] : 0; $rx = $worker->reconcile($rxCursor); $rxCursor = $rx['selected'] > 0 ? $rx['last_id'] : 0; + if ($scheduled) { + rewind($laneLock); + ftruncate($laneLock, 0); + fwrite($laneLock, json_encode(['source' => $sourceCursor, 'prescription' => $rxCursor])); + fflush($laneLock); + } $sweepAt = time() + 60; } } @@ -73,6 +96,9 @@ final class PrescriptionAiWork extends Command $detail .= ' ' . $sqlState[0]; } $output->writeln('PRESCRIPTION_AI storage_or_configuration_error ' . $detail); + if ($scheduled) { + Log::write('PRESCRIPTION_AI ' . $lane . ' storage_or_configuration_error ' . $detail, 'error'); + } // Drop a possibly dead connection so the next round reconnects instead of looping. try { Db::connect()->close(); diff --git a/server/app/common/service/prescriptionai/PrescriptionAiLaneGuard.php b/server/app/common/service/prescriptionai/PrescriptionAiLaneGuard.php new file mode 100644 index 000000000..bb604a133 --- /dev/null +++ b/server/app/common/service/prescriptionai/PrescriptionAiLaneGuard.php @@ -0,0 +1,106 @@ + $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; + } +} diff --git a/server/app/common/service/prescriptionai/PrescriptionAiProgress.php b/server/app/common/service/prescriptionai/PrescriptionAiProgress.php index 067035a84..867145838 100755 --- a/server/app/common/service/prescriptionai/PrescriptionAiProgress.php +++ b/server/app/common/service/prescriptionai/PrescriptionAiProgress.php @@ -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)) { diff --git a/server/app/common/service/prescriptionai/PrescriptionAiStore.php b/server/app/common/service/prescriptionai/PrescriptionAiStore.php index af806266a..d2617a885 100755 --- a/server/app/common/service/prescriptionai/PrescriptionAiStore.php +++ b/server/app/common/service/prescriptionai/PrescriptionAiStore.php @@ -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, diff --git a/server/config/console.php b/server/config/console.php index a0c22d588..c0b1c475e 100755 --- a/server/config/console.php +++ b/server/config/console.php @@ -19,6 +19,7 @@ return [ 'followup-audio:probe' => 'app\\command\\FollowupAudioProbe', 'followup-audio:cleanup' => 'app\\command\\FollowupAudioCleanup', 'prescription-ai:work' => 'app\\command\\PrescriptionAiWork', + 'prescription-ai:dispatch' => 'app\\command\\PrescriptionAiDispatch', 'prescription-ai:backfill' => 'app\\command\\PrescriptionAiBackfill', // 定时任务 'crontab' => 'app\common\command\Crontab', diff --git a/server/config/prescription_analysis.php b/server/config/prescription_analysis.php index d2e1e70a8..0f53cf800 100755 --- a/server/config/prescription_analysis.php +++ b/server/config/prescription_analysis.php @@ -10,7 +10,7 @@ return [ 'lease_seconds' => 600, 'max_attempts' => 3, 'max_manual_retries' => 2, - 'daily_model_tasks' => (int) env('prescription_analysis.DAILY_MODEL_TASKS', 200), + 'daily_model_tasks' => (int) env('prescription_analysis.DAILY_MODEL_TASKS', 5000), // Analyses of one prescription per day. Regenerating after each change is the normal way to // review a case, so this is a budget guard, not a correctness limit. 'daily_patient_batches' => (int) env('prescription_analysis.DAILY_PATIENT_BATCHES', 20), diff --git a/server/config/project.php b/server/config/project.php index 920bfbb9f..6bb852c44 100755 --- a/server/config/project.php +++ b/server/config/project.php @@ -113,10 +113,10 @@ return [ 'order_edit_all_roles' => [0, 3, 4, 9, 6], // 处方库:以下角色ID + 超级管理员(root) 可查看/编辑/删除全部;他人仅可管理自己创建的,公开处方对他人只读 - 'prescription_library_manage_all_roles' => [0, 3, 4, 9, 6], + 'prescription_library_manage_all_roles' => [0, 3, 4, 9, 6, 13], // 消费者处方单:以下角色 + root 可对「待审核」处方进行通过/驳回(驳回即作废处方) - 'prescription_audit_roles' => [0, 3, 4, 9, 6], + 'prescription_audit_roles' => [0, 3, 4, 9, 6, 13], // 处方业务订单 internal_cost 等财务字段:以下角色 ID + root 可见 'prescription_order_finance_roles' => [0, 3, 4, 9, 6], diff --git a/server/database/migrations/2026_12_02_prescription_ai_crontab.sql b/server/database/migrations/2026_12_02_prescription_ai_crontab.sql new file mode 100644 index 000000000..ce46baa15 --- /dev/null +++ b/server/database/migrations/2026_12_02_prescription_ai_crontab.sql @@ -0,0 +1,4 @@ +-- 非默认表前缀需替换 zyt_。保留管理员已有的暂停状态和运行周期。 +INSERT INTO `zyt_dev_crontab` (`name`, `type`, `system`, `remark`, `command`, `params`, `status`, `expression`, `last_time`, `create_time`, `update_time`) +SELECT '处方 AI 分析队列', 1, 0, '每分钟巡检资料准备、通义千问和 OpenAI 消费者,只对缺失的队列派发单轮处理', 'prescription-ai:dispatch', '', 1, '* * * * *', UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), UNIX_TIMESTAMP() +WHERE NOT EXISTS (SELECT 1 FROM `zyt_dev_crontab` WHERE `command` = 'prescription-ai:dispatch' AND `delete_time` IS NULL);