更新
This commit is contained in:
@@ -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