更新
This commit is contained in:
@@ -885,8 +885,8 @@ class PrescriptionOrderLists extends BaseAdminDataLists implements ListsSearchIn
|
||||
'export_supply_mode' => '供货方式',
|
||||
'export_gancao_prescription_cost' => '处方成本',
|
||||
'export_first_visit_assistant' => '初诊医助',
|
||||
'export_rx_audit_time' => '审核时间',
|
||||
'export_rx_auditor' => '审核人',
|
||||
'export_payment_audit_time' => '审核时间',
|
||||
'export_payment_auditor' => '审核人',
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ use app\common\service\prescriptionai\PrescriptionAiStore as Store;
|
||||
use app\common\service\prescriptionai\PrescriptionAiVisibility as Visibility;
|
||||
use DomainException;
|
||||
use think\facade\Db;
|
||||
use think\facade\Log;
|
||||
|
||||
final class PrescriptionAiLogic
|
||||
{
|
||||
@@ -169,23 +170,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 +288,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 +348,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']) : [];
|
||||
@@ -387,7 +434,17 @@ final class PrescriptionAiLogic
|
||||
if (!Access::sourceIds($ids, $actor, $info) || empty($batch['access_cipher'])) {
|
||||
return false;
|
||||
}
|
||||
$access = (new Cipher())->decrypt($batch['access_cipher'], 'access:' . $batch['id']);
|
||||
try {
|
||||
$access = (new Cipher())->decrypt($batch['access_cipher'], 'access:' . $batch['id']);
|
||||
} catch (\RuntimeException $e) {
|
||||
if ($e->getMessage() !== Cipher::INVALID_PAYLOAD) {
|
||||
throw $e;
|
||||
}
|
||||
// An unreadable authorization snapshot cannot establish access to this batch.
|
||||
Log::warning('Unreadable prescription AI access snapshot: {code} (batch_id={batch_id})',
|
||||
['code' => Cipher::INVALID_PAYLOAD, 'batch_id' => (int) $batch['id']]);
|
||||
return false;
|
||||
}
|
||||
return \app\common\service\prescriptionai\PrescriptionAiContext::assertSnapshotAccess($access, $actor, $info);
|
||||
}
|
||||
|
||||
|
||||
@@ -3015,7 +3015,8 @@ class PrescriptionOrderLogic
|
||||
|
||||
$logSummary = $summary;
|
||||
if ($changeParts !== []) {
|
||||
$logSummary .= '(' . implode(';', $changeParts) . ')';
|
||||
$changeSummary = '(' . implode(';', $changeParts) . ')';
|
||||
$logSummary = mb_substr($summary, 0, 500 - mb_strlen($changeSummary)) . $changeSummary;
|
||||
}
|
||||
self::writeLog($id, $adminId, $adminInfo, 'manual_log', $logSummary);
|
||||
|
||||
@@ -4482,26 +4483,30 @@ class PrescriptionOrderLogic
|
||||
}
|
||||
}
|
||||
|
||||
$paymentAuditActions = ['audit_pay_approve', 'audit_pay_reject'];
|
||||
$paymentAuditResetActions = [
|
||||
'revoke_pay_audit', 'audit_rx_reject', 'revoke_rx_audit', 'add_pay_order', 'link_pay_order', 'completion_request',
|
||||
];
|
||||
$logRows = PrescriptionOrderLog::whereIn('prescription_order_id', $poIds)
|
||||
->whereIn('action', ['audit_rx_approve', 'audit_rx_reject', 'revoke_rx_audit'])
|
||||
->field(['prescription_order_id', 'id', 'action', 'admin_name', 'create_time'])
|
||||
->whereIn('action', [...$paymentAuditActions, ...$paymentAuditResetActions, 'manual_log'])
|
||||
->field(['prescription_order_id', 'action', 'admin_name', 'create_time', 'summary'])
|
||||
->order('id', 'asc')
|
||||
->select()
|
||||
->toArray();
|
||||
$auditEffectiveByPo = [];
|
||||
$paymentAuditByPo = [];
|
||||
foreach ($logRows as $lg) {
|
||||
$pid = (int) ($lg['prescription_order_id'] ?? 0);
|
||||
if ($pid <= 0) {
|
||||
$pid = (int) $lg['prescription_order_id'];
|
||||
$action = $lg['action'];
|
||||
if (in_array($action, $paymentAuditActions, true)) {
|
||||
$paymentAuditByPo[$pid] = $lg;
|
||||
continue;
|
||||
}
|
||||
$act = (string) ($lg['action'] ?? '');
|
||||
if ($act === 'revoke_rx_audit') {
|
||||
$auditEffectiveByPo[$pid] = null;
|
||||
// 手工调整支付审核状态会追加固定格式的变更说明,普通备注不影响已有审核记录。
|
||||
if ($action === 'manual_log'
|
||||
&& !preg_match('/[(;]支付单审核:(待审核|已通过|已驳回) → (待审核|已通过|已驳回))$/u', (string) $lg['summary'])) {
|
||||
continue;
|
||||
}
|
||||
if ($act === 'audit_rx_approve' || $act === 'audit_rx_reject') {
|
||||
$auditEffectiveByPo[$pid] = $lg;
|
||||
}
|
||||
unset($paymentAuditByPo[$pid]);
|
||||
}
|
||||
|
||||
// 服务套餐字典:与前端 formatServicePackage 同口径(dict_data type_value=server_order;只取启用项做兜底取原值)
|
||||
@@ -4703,16 +4708,18 @@ class PrescriptionOrderLogic
|
||||
$item['export_center_label'] = '一中心';
|
||||
}
|
||||
|
||||
$paSt = (int) ($item['prescription_audit_status'] ?? 0);
|
||||
$aud = $auditEffectiveByPo[$poId] ?? null;
|
||||
if (($paSt === 1 || $paSt === 2) && \is_array($aud)) {
|
||||
$at = (int) ($aud['create_time'] ?? 0);
|
||||
$item['export_rx_audit_time'] = $at > 0 ? date('Y-m-d H:i:s', $at) : '';
|
||||
$item['export_rx_auditor'] = (string) ($aud['admin_name'] ?? '');
|
||||
} else {
|
||||
$item['export_rx_audit_time'] = '';
|
||||
$item['export_rx_auditor'] = '';
|
||||
$paymentAudit = $paymentAuditByPo[$poId] ?? [];
|
||||
$expectedAction = match ((int) ($item['payment_slip_audit_status'] ?? 0)) {
|
||||
1 => 'audit_pay_approve',
|
||||
2 => 'audit_pay_reject',
|
||||
default => null,
|
||||
};
|
||||
if ($expectedAction === null || ($paymentAudit['action'] ?? null) !== $expectedAction) {
|
||||
$paymentAudit = [];
|
||||
}
|
||||
$auditTime = (int) ($paymentAudit['create_time'] ?? 0);
|
||||
$item['export_payment_audit_time'] = $auditTime > 0 ? date('Y-m-d H:i:s', $auditTime) : '';
|
||||
$item['export_payment_auditor'] = (string) ($paymentAudit['admin_name'] ?? '');
|
||||
}
|
||||
unset($item);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use app\common\service\prescriptionai\PrescriptionAiLaneGuard;
|
||||
use app\common\service\prescriptionai\PrescriptionAiStore;
|
||||
use RuntimeException;
|
||||
use think\console\Command;
|
||||
use think\console\Input;
|
||||
use think\console\input\Option;
|
||||
use think\console\Output;
|
||||
|
||||
final class PrescriptionAiDispatch extends Command
|
||||
{
|
||||
protected function configure(): void
|
||||
{
|
||||
$this->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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -9,6 +9,8 @@ use RuntimeException;
|
||||
/** Authenticated at-rest encryption; key is never stored in the database. */
|
||||
final class PrescriptionAiCipher
|
||||
{
|
||||
public const INVALID_PAYLOAD = 'AI_ANALYSIS_CIPHER_INVALID';
|
||||
|
||||
private ?string $secret;
|
||||
|
||||
public function __construct(?string $secret = null)
|
||||
@@ -32,16 +34,20 @@ final class PrescriptionAiCipher
|
||||
{
|
||||
$bytes = str_starts_with($value, 'v1:') ? base64_decode(substr($value, 3), true) : false;
|
||||
if ($bytes === false || strlen($bytes) < 30) {
|
||||
throw new RuntimeException('AI_ANALYSIS_CIPHER_INVALID');
|
||||
throw new RuntimeException(self::INVALID_PAYLOAD);
|
||||
}
|
||||
$plain = openssl_decrypt(substr($bytes, 28), 'aes-256-gcm', $this->key(), OPENSSL_RAW_DATA,
|
||||
substr($bytes, 0, 12), substr($bytes, 12, 16), $purpose);
|
||||
if ($plain === false) {
|
||||
throw new RuntimeException('AI_ANALYSIS_CIPHER_INVALID');
|
||||
throw new RuntimeException(self::INVALID_PAYLOAD);
|
||||
}
|
||||
try {
|
||||
$decoded = json_decode($plain, true, 512, JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $e) {
|
||||
throw new RuntimeException(self::INVALID_PAYLOAD, 0, $e);
|
||||
}
|
||||
$decoded = json_decode($plain, true, 512, JSON_THROW_ON_ERROR);
|
||||
if (!is_array($decoded)) {
|
||||
throw new RuntimeException('AI_ANALYSIS_CIPHER_INVALID');
|
||||
throw new RuntimeException(self::INVALID_PAYLOAD);
|
||||
}
|
||||
return $decoded;
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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);
|
||||
@@ -243,6 +243,9 @@ CREATE TABLE `la_dev_crontab` (
|
||||
PRIMARY KEY (`id`) USING BTREE
|
||||
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '计划任务表';
|
||||
|
||||
INSERT INTO `la_dev_crontab` (`name`, `type`, `system`, `remark`, `command`, `params`, `status`, `expression`, `last_time`, `create_time`, `update_time`)
|
||||
VALUES ('处方 AI 分析队列', 1, 0, '每分钟巡检资料准备、通义千问和 OpenAI 消费者,只对缺失的队列派发单轮处理', 'prescription-ai:dispatch', '', 1, '* * * * *', UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), UNIX_TIMESTAMP());
|
||||
|
||||
-- ----------------------------
|
||||
-- Table structure for la_dev_pay_config
|
||||
-- ----------------------------
|
||||
|
||||
@@ -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);
|
||||
@@ -0,0 +1,158 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
// Run the registered command against a synthetic think entry point and an in-memory schedule table.
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
require dirname(__DIR__) . '/vendor/topthink/framework/src/helper.php';
|
||||
|
||||
use think\console\Input;
|
||||
use think\console\Output;
|
||||
use app\common\service\prescriptionai\PrescriptionAiLaneGuard as Guard;
|
||||
|
||||
function dispatchExpect(bool $ok, string $message): void
|
||||
{
|
||||
if (!$ok) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
}
|
||||
|
||||
$server = dirname(__DIR__);
|
||||
$directory = sys_get_temp_dir() . '/prescription-ai-dispatch-' . bin2hex(random_bytes(6));
|
||||
mkdir($directory, 0700);
|
||||
$app = new think\App($directory); // No initialize(), .env or database configuration.
|
||||
$config = new think\Config();
|
||||
$app->instance('config', $config);
|
||||
$definition = require $server . '/config/console.php';
|
||||
$name = 'prescription-ai:dispatch';
|
||||
$command = new $definition['commands'][$name]();
|
||||
$command->setApp($app);
|
||||
$run = static fn (): int => $command->run(new Input([]), new Output('buffer'));
|
||||
$lanes = ['prepare', 'qwen', 'openai'];
|
||||
try {
|
||||
$config->set(['enabled' => false], 'prescription_analysis');
|
||||
dispatchExpect($run() === 0, 'Disabled dispatch must exit before accessing the CLI entry point');
|
||||
$config->set(['enabled' => true], 'prescription_analysis');
|
||||
try {
|
||||
$run();
|
||||
throw new LogicException('Missing think entry point was reported as a successful dispatch');
|
||||
} catch (RuntimeException $expected) {
|
||||
dispatchExpect(str_contains($expected->getMessage(), 'think'), 'Launch failure should identify the entry point');
|
||||
}
|
||||
file_put_contents($directory . '/think', <<<'PHP'
|
||||
<?php
|
||||
$lane = substr($argv[2] ?? '', strlen('--lane='));
|
||||
if (!in_array($lane, ['prepare', 'qwen', 'openai'], true)) { exit(2); }
|
||||
file_put_contents(__DIR__ . '/' . $lane, json_encode(array_slice($argv, 1)));
|
||||
// Wait for the parent to finish dispatching all lanes; a synchronous runner hits the deadline.
|
||||
$deadline = microtime(true) + 5;
|
||||
while (!is_file(__DIR__ . '/release') && microtime(true) < $deadline) { usleep(20000); }
|
||||
file_put_contents(__DIR__ . '/' . $lane . '.done', is_file(__DIR__ . '/release') ? 'released' : 'timeout');
|
||||
PHP
|
||||
);
|
||||
$inspect = new Output('buffer');
|
||||
$command->run(new Input(['--check']), $inspect);
|
||||
dispatchExpect(substr_count($inspect->fetch(), 'missing') === 3 && !is_dir($app->getRuntimePath()),
|
||||
'Check-only inspection must report missing lanes without creating locks or dispatching work');
|
||||
$held = [];
|
||||
foreach ($lanes as $lane) {
|
||||
$held[$lane] = Guard::acquire($app->getRuntimePath(), $lane, LOCK_SH);
|
||||
}
|
||||
$healthy = new Output('buffer');
|
||||
dispatchExpect($command->run(new Input([]), $healthy) === 0 && substr_count($healthy->fetch(), 'busy') === 3,
|
||||
'Three supervised workers must satisfy the inspection without spawning children');
|
||||
$worker = new $definition['commands']['prescription-ai:work']();
|
||||
$worker->setApp($app);
|
||||
$skipped = new Output('buffer');
|
||||
dispatchExpect($worker->run(new Input(['--lane=prepare', '--once', '--scheduled']), $skipped) === 0
|
||||
&& $skipped->fetch() === '', 'Scheduled worker must exit before a database claim or idle sweep when locked');
|
||||
foreach ($lanes as $lane) {
|
||||
dispatchExpect(!is_file($directory . '/' . $lane), 'A healthy lane was dispatched');
|
||||
}
|
||||
fclose($held['openai']);
|
||||
dispatchExpect($run() === 0, 'A single missing lane must be dispatched');
|
||||
$deadline = microtime(true) + 5;
|
||||
while (!is_file($directory . '/openai') && microtime(true) < $deadline) { usleep(20000); }
|
||||
dispatchExpect(is_file($directory . '/openai') && !is_file($directory . '/prepare') && !is_file($directory . '/qwen'),
|
||||
'Dispatch should only start the missing lane');
|
||||
touch($directory . '/release');
|
||||
while (!is_file($directory . '/openai.done') && microtime(true) < $deadline) { usleep(20000); }
|
||||
dispatchExpect(is_file($directory . '/openai.done'), 'Single fallback did not finish');
|
||||
if (PHP_OS_FAMILY === 'Linux') {
|
||||
while (Guard::linuxWorkers($directory . '/think') && microtime(true) < $deadline) { usleep(20000); }
|
||||
}
|
||||
unlink($directory . '/openai');
|
||||
unlink($directory . '/openai.done');
|
||||
unlink($directory . '/release');
|
||||
fclose($held['prepare']);
|
||||
fclose($held['qwen']);
|
||||
$single = Guard::acquire($app->getRuntimePath(), 'openai', LOCK_EX | LOCK_NB);
|
||||
dispatchExpect(Guard::acquire($app->getRuntimePath(), 'openai', LOCK_EX | LOCK_NB) === null,
|
||||
'Overlapping scheduled consumers must not process the same lane');
|
||||
fclose($single);
|
||||
dispatchExpect($run() === 0, 'Enabled dispatch must succeed');
|
||||
touch($directory . '/release');
|
||||
$deadline = microtime(true) + 5;
|
||||
foreach ($lanes as $lane) {
|
||||
$result = $directory . '/' . $lane;
|
||||
while (!is_file($result . '.done') && microtime(true) < $deadline) { usleep(20000); }
|
||||
dispatchExpect(is_file($result . '.done') && file_get_contents($result . '.done') === 'released',
|
||||
"Dispatch blocked on the {$lane} worker or did not start it");
|
||||
dispatchExpect(json_decode(file_get_contents($result), true) === ['prescription-ai:work', '--lane=' . $lane, '--once', '--scheduled'],
|
||||
"Unexpected {$lane} worker arguments");
|
||||
}
|
||||
|
||||
// A relative think path must resolve against the observed process, never the inspector's cwd.
|
||||
$proc = $directory . '/proc';
|
||||
foreach (['self', '101/cwd', '102/cwd'] as $path) { mkdir($proc . '/' . $path, 0700, true); }
|
||||
touch($proc . '/self/cmdline');
|
||||
foreach (['101', '102'] as $id) {
|
||||
touch($proc . '/' . $id . '/cwd/think');
|
||||
file_put_contents($proc . '/' . $id . '/comm', 'php8.2');
|
||||
file_put_contents($proc . '/' . $id . '/cmdline', implode("\0", ['php', 'think', 'prescription-ai:work', '--lane=openai']));
|
||||
}
|
||||
$target = $proc . '/101/cwd/think';
|
||||
foreach (['prepare' => [], 'qwen' => ['--lane', 'qwen'], 'openai' => ['--lane=openai']] as $lane => $options) {
|
||||
file_put_contents($proc . '/101/cmdline', implode("\0", array_merge(['php', './think', 'prescription-ai:work'], $options)));
|
||||
dispatchExpect(Guard::linuxWorkers($target, $proc) === [$lane => 'resident'],
|
||||
'Legacy workers must be scoped to this application and exact lane');
|
||||
}
|
||||
file_put_contents($proc . '/101/cmdline', implode("\0", ['php', 'think', 'prescription-ai:work', '--once']));
|
||||
dispatchExpect(Guard::linuxWorkers($target, $proc) === ['prepare' => 'single_run'], 'A running fallback must occupy its lane');
|
||||
if (PHP_OS_FAMILY === 'Linux') {
|
||||
file_put_contents($proc . '/101/cmdline', implode("\0", ['/www/server/php/82/bin/php', $target, 'prescription-ai:work', '--lane=qwen']));
|
||||
dispatchExpect(Guard::linuxWorkers($target, $proc) === ['qwen' => 'resident'], 'Absolute think path from a supervised process');
|
||||
}
|
||||
|
||||
$db = new PDO('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
||||
$db->sqliteCreateFunction('UNIX_TIMESTAMP', 'time');
|
||||
$db->exec('CREATE TABLE zyt_dev_crontab (name TEXT, type INTEGER, system INTEGER, remark TEXT, command TEXT,
|
||||
params TEXT, status INTEGER, expression TEXT, last_time INTEGER, create_time INTEGER, update_time INTEGER, delete_time INTEGER)');
|
||||
$migration = file_get_contents($server . '/database/migrations/2026_12_02_prescription_ai_crontab.sql');
|
||||
$upgrade = file_get_contents($server . '/sql/1.9.20261202/01_prescription_ai_crontab.sql');
|
||||
$db->exec($migration);
|
||||
$db->exec($upgrade);
|
||||
$select = static fn (): array => $db->query('SELECT name,command,params,status,expression FROM zyt_dev_crontab')->fetchAll(PDO::FETCH_ASSOC);
|
||||
$fresh = $select();
|
||||
dispatchExpect(count($fresh) === 1 && $fresh[0]['command'] === $name && $fresh[0]['params'] === ''
|
||||
&& (int) $fresh[0]['status'] === 1 && $fresh[0]['expression'] === '* * * * *', 'Upgrading must enable one per-minute dispatch');
|
||||
$db->exec("UPDATE zyt_dev_crontab SET status = 2, expression = '*/5 * * * *'");
|
||||
$edited = $select();
|
||||
$db->exec($migration);
|
||||
$db->exec($upgrade);
|
||||
dispatchExpect($select() === $edited, 'Repeated upgrades must retain administrator edits');
|
||||
$db->exec('DELETE FROM zyt_dev_crontab');
|
||||
$install = file_get_contents($server . '/public/install/db/like.sql');
|
||||
preg_match('/^INSERT INTO `la_dev_crontab`[^;]+;/m', $install, $match);
|
||||
dispatchExpect(isset($match[0]), 'Installer must seed the schedule with its configurable prefix');
|
||||
$db->exec(str_replace('`la_', '`zyt_', $match[0]));
|
||||
dispatchExpect($select() === $fresh, 'Installer and upgrade must register the same task');
|
||||
echo "Prescription AI dispatch, upgrade and installer checks passed\n";
|
||||
} finally {
|
||||
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory,
|
||||
FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
|
||||
foreach ($files as $file) {
|
||||
$file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname());
|
||||
}
|
||||
rmdir($directory);
|
||||
}
|
||||
@@ -45,7 +45,9 @@ foreach ($terminalExpected as $status => [$stage, $phase]) {
|
||||
}
|
||||
}
|
||||
$retry = Progress::task(array_replace($task, ['status' => 'retry_wait', 'next_run_at' => $now + 30, 'error_code' => 'BUDGET_PAUSED']), $now);
|
||||
$expect($retry['wait_remaining_seconds'] === 30 && str_contains($retry['notice'], '额度'), 'retry waiting explains scheduled budget pause');
|
||||
$expect($retry['wait_remaining_seconds'] === 30 && $retry['next_run_at'] === $now + 30
|
||||
&& str_contains($retry['notice'], '额度') && str_contains($retry['notice'], date('Y-m-d H:i:s', $now + 30)),
|
||||
'retry waiting explains the absolute budget eligibility time to both old and new clients');
|
||||
$expect(str_contains($retry['notice'], '上次进度:整理文字资料') && str_contains($retry['notice'], '本次尝试'),
|
||||
'waiting retries retain a trusted stage description and identify attempt timing');
|
||||
$finishedFailure = array_replace($task, ['status' => 'failed', 'finished_at' => $now - 20, 'updated_at' => $now - 1]);
|
||||
@@ -54,8 +56,9 @@ $expect(Progress::task($finishedFailure, $now + 1000)['elapsed_seconds'] === 100
|
||||
$finishedRetry = array_replace($finishedFailure, ['status' => 'retry_wait', 'next_run_at' => $now + 30]);
|
||||
$expect(Progress::task($finishedRetry, $now + 1000)['elapsed_seconds'] === 100,
|
||||
'scheduled retry backoff does not inflate the previous model attempt duration');
|
||||
$expect(Progress::task(array_replace($task, ['status' => 'retry_wait', 'next_run_at' => $now - 30]), $now)['wait_remaining_seconds'] === 0,
|
||||
'elapsed retry deadlines do not become negative');
|
||||
$due = Progress::task(array_replace($task, ['status' => 'retry_wait', 'next_run_at' => $now - 30]), $now);
|
||||
$expect($due['wait_remaining_seconds'] === 0 && $due['next_run_at'] === $now - 30 && str_contains($due['notice'], '等待后台领取'),
|
||||
'elapsed retry deadlines retain the measured eligibility time and wait for a real claim');
|
||||
foreach ([null, '{}', str_repeat('x', 3000), '{invalid', json_encode(['stage' => 'completed', 'phase' => 'completed'])] as $old) {
|
||||
$result = Progress::task(array_replace($task, ['progress_json' => $old]), $now);
|
||||
$expect($result['stage'] === 'unknown' && $result['phase'] === 'running' && $result['stage_elapsed_seconds'] === null,
|
||||
|
||||
@@ -41,6 +41,7 @@ $manager->setConfig(['default' => 'mysql', 'auto_timestamp' => true, 'datetime_f
|
||||
'prefix' => 'zyt_', 'fields_strict' => true]]]);
|
||||
Container::getInstance()->instance('think\DbManager', $manager);
|
||||
$config = new think\Config();
|
||||
$config->set(['default' => 'file', 'channels' => ['file' => ['type' => 'File', 'close' => true]]], 'log');
|
||||
$config->set(['enabled' => true, 'encryption_key' => str_repeat('isolated-test-', 4), 'debounce_seconds' => 0,
|
||||
'lease_seconds' => 600, 'max_attempts' => 3, 'max_manual_retries' => 2, 'max_parallel_per_model' => 1,
|
||||
'daily_model_tasks' => 200, 'transcript_wait_seconds' => 300], 'prescription_analysis');
|
||||
@@ -299,6 +300,31 @@ try {
|
||||
$statuses = Api::statuses([$rx['id']], 1, $root);
|
||||
$expect($statuses['items'][0]['models']['qwen']['score'] === 80.0, 'list returns persisted numeric score');
|
||||
$expect($statuses['items'][0]['models']['openai']['score'] === null, 'failed score is null rather than zero');
|
||||
Db::startTrans();
|
||||
$testKey = $config->get('prescription_analysis.encryption_key');
|
||||
try {
|
||||
$damagedRx = $fixture();
|
||||
$damagedBatch = $save($damagedRx);
|
||||
// A valid ciphertext authenticated for a different batch must fail verification.
|
||||
Db::name('prescription_ai_batch')->where('id', $damagedBatch)->update([
|
||||
'source_diagnosis_ids_json' => '[1]', 'access_cipher' => $stored['access_cipher'],
|
||||
]);
|
||||
$mixed = Api::statuses([$damagedRx['id'], $rx['id']], 1, $root);
|
||||
$expect(array_column($mixed['items'], 'prescription_id') === [(int) $rx['id']]
|
||||
&& $mixed['items'][0]['models']['qwen']['score'] === 80.0,
|
||||
'unreadable access snapshot is omitted and the healthy score is preserved');
|
||||
|
||||
$config->set(['encryption_key' => 'too-short'], 'prescription_analysis');
|
||||
try {
|
||||
Api::statuses([$rx['id']], 1, $root);
|
||||
$expect(false, 'invalid installation key must surface');
|
||||
} catch (RuntimeException $e) {
|
||||
$expect($e->getMessage() === 'AI_ANALYSIS_KEY_INVALID', 'systemic key failure propagates from statuses');
|
||||
}
|
||||
} finally {
|
||||
$config->set(['encryption_key' => $testKey], 'prescription_analysis');
|
||||
Db::rollback();
|
||||
}
|
||||
$detail = Api::detail($batchId, 1, $root);
|
||||
$expect($detail['models']['qwen']['report']['summary'] === 'synthetic report', 'authorized detail decrypts');
|
||||
$expect($detail['models']['qwen']['progress']['stage'] === 'completed'
|
||||
@@ -344,6 +370,45 @@ try {
|
||||
&& $hiddenDetail['models']['openai']['reason'] !== '', 'hidden metric preserves report, candidate, original, review and failure explanation');
|
||||
$denied(static fn () => Api::statistics([], 1, $root), 'root without selected grant cannot read agreement statistics');
|
||||
Api::review($batchId, 'qwen', 'not_adopted', 'test comment', 1, $root);
|
||||
Db::startTrans();
|
||||
try {
|
||||
$dailyKey = date('Y-m-d') . ':openai';
|
||||
$budget = static fn () => Db::name('prescription_ai_limit')->where('limit_key', $dailyKey);
|
||||
$retryTask = static fn () => Db::name('prescription_ai_task')->where('id', $o['id']);
|
||||
$budget()->update(['used_count' => 200]);
|
||||
$paused = Api::retry($batchId, 'openai', 1, $root);
|
||||
$deadline = strtotime('tomorrow', $paused['progress']['server_time']);
|
||||
$expect($paused['status'] === 'retry_wait' && $paused['error_code'] === 'BUDGET_PAUSED'
|
||||
&& $paused['progress']['next_run_at'] === $deadline && $paused['progress']['wait_remaining_seconds'] > 0
|
||||
&& $paused['manual_retries'] === 1 && $paused['max_manual_retries'] === 2
|
||||
&& $paused['last_error_code'] === 'UPSTREAM_TIMEOUT' && $paused['last_error_message'] !== '',
|
||||
'manual retry acknowledges the real daily budget and preserves the previous attempt cause before any worker poll');
|
||||
$expect((int) $retryTask()->value('next_run_at') === $deadline && (int) $budget()->value('used_count') === 200
|
||||
&& Store::claimTask('openai') === null && Api::retry($batchId, 'openai', 1, $root)['manual_retries'] === 1,
|
||||
'deferred manual round is persisted once without reserving or bypassing a model slot');
|
||||
// This is the shape already stored by older versions before their first post-retry worker scan.
|
||||
$retryTask()->update(['next_run_at' => time() - 5, 'error_code' => '']);
|
||||
$beforePoll = Api::detail($batchId, 1, $root);
|
||||
$waiting = $beforePoll['models']['openai'];
|
||||
$expect($waiting['error_code'] === 'BUDGET_PAUSED' && $waiting['progress']['next_run_at'] === $deadline
|
||||
&& $waiting['last_error_code'] === 'UPSTREAM_TIMEOUT' && $beforePoll['models']['qwen']['status'] === 'success'
|
||||
&& !isset($beforePoll['models']['qwen']['score']) && $retryTask()->value('error_code') === '',
|
||||
'polled legacy retry shows the current budget without writes, has independent model states and preserves metric visibility');
|
||||
$expect(Store::claimTask('openai') === null && $retryTask()->value('error_code') === 'BUDGET_PAUSED'
|
||||
&& (int) $retryTask()->value('total_attempts') === 1, 'worker enforces the same ledger even for legacy due retries');
|
||||
// Simulate the next budget window with an elapsed deadline.
|
||||
$budget()->update(['used_count' => 0]);
|
||||
$retryTask()->update(['next_run_at' => time() - 10]);
|
||||
$eligible = Api::detail($batchId, 1, $root)['models']['openai'];
|
||||
$expect($eligible['error_code'] === '' && $eligible['progress']['wait_remaining_seconds'] === 0
|
||||
&& str_contains($eligible['progress']['notice'], '等待后台领取') && $eligible['last_error_code'] === 'UPSTREAM_TIMEOUT',
|
||||
'past budget pause waits for a real claim without continuing to report yesterday\'s exhaustion');
|
||||
$resumed = Store::claimTask('openai');
|
||||
$expect((int) $resumed['total_attempts'] === 2 && (int) $budget()->value('used_count') === 1,
|
||||
'worker resumes after reset and charges one attempt');
|
||||
} finally {
|
||||
Db::rollback();
|
||||
}
|
||||
$expect(Api::retry($batchId, 'openai', 1, $root)['status'] === 'retry_wait',
|
||||
'agreement restriction does not remove independent report review/retry permission');
|
||||
Visibility::setConfig(['role_ids' => [], 'admin_ids' => [1]], 1);
|
||||
|
||||
Reference in New Issue
Block a user