Merge branch 'master' of http://git.zhenyangtang.com.cn/ZYT/zyt
This commit is contained in:
@@ -111,5 +111,22 @@ namespace {
|
||||
$short['case_text'] = str_repeat('a', 120000);
|
||||
$copy = $short;
|
||||
compactExpect($apply($short) && $short === $copy, 'exact threshold keeps the source untouched');
|
||||
Cache::$items = [];
|
||||
$compactionConfig['context_compaction_cache_ttl'] = 300;
|
||||
DifyChatService::$calls = [];
|
||||
$cancelledContext = $original;
|
||||
$progress = [];
|
||||
$cancelOptions = ['should_abort' => static fn (): bool => count(DifyChatService::$calls) >= 1,
|
||||
'on_cancel_task' => static fn (string $taskId, callable $stop): array => ['accepted' => false, 'pending' => true],
|
||||
'on_terminal' => static function (string $taskId, string $status): void {},
|
||||
'on_progress' => static function (array $event) use (&$progress): void { $progress[] = $event; }];
|
||||
compactExpect(!$fit->invokeArgs(null, [&$cancelledContext, 'qwen', new AssistantSseTiming(), $cancelOptions]), 'cancel during preprocessing terminates preparation');
|
||||
compactExpect(count(DifyChatService::$calls) === 1 && Cache::$items === [] && $cancelledContext === $original, 'cancelled partial evidence never enters cache or final prompt');
|
||||
compactExpect(DifyChatService::$calls[0]['options']['knowledge_mode'] === 'evidence'
|
||||
&& is_callable(DifyChatService::$calls[0]['options']['should_abort'])
|
||||
&& DifyChatService::$calls[0]['options']['on_cancel_task'] === $cancelOptions['on_cancel_task']
|
||||
&& DifyChatService::$calls[0]['options']['on_terminal'] === $cancelOptions['on_terminal'],
|
||||
'intermediate evidence request preserves abort, shared stop and terminal observers');
|
||||
compactExpect(count($progress) === 1 && $progress[0]['completed'] === 0 && $progress[0]['total'] === 2, 'chunk progress counts only completed evidence results');
|
||||
echo "AI context compaction latency and isolation: OK\n";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service {
|
||||
function config(string $name): array { return $GLOBALS['drainConfig']; }
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use app\adminapi\service\AssistantRequestControl;
|
||||
use app\common\service\DifyChatService;
|
||||
|
||||
function drainExpect(bool $ok, string $message): void {
|
||||
if (!$ok) throw new RuntimeException($message);
|
||||
}
|
||||
|
||||
// A real loopback HTTP peer. It accepts the stop on another socket while the
|
||||
// generation stays open, then either sends terminal metadata or stays silent.
|
||||
if (($argv[1] ?? '') === 'server') {
|
||||
$scenario = $argv[2];
|
||||
$listener = stream_socket_server('tcp://127.0.0.1:0', $error, $message);
|
||||
if ($listener === false) exit(2);
|
||||
stream_set_blocking($listener, false);
|
||||
echo json_encode(['address' => stream_socket_get_name($listener, false)]) . "\n";
|
||||
flush();
|
||||
$clients = []; $generation = null; $generationAt = null; $terminalAt = null; $tailAt = null;
|
||||
$earlySent = false; $taskSent = false; $done = false;
|
||||
$metrics = ['stop_count' => 0, 'generation_open_on_stop' => false, 'title_disabled' => false,
|
||||
'inputs_object' => false, 'generation_eof' => false, 'terminal_tail_sent' => false,
|
||||
'closed_before_terminal_tail' => false];
|
||||
$deadline = microtime(true) + 8;
|
||||
while (!$done && microtime(true) < $deadline) {
|
||||
while (($socket = @stream_socket_accept($listener, 0)) !== false) {
|
||||
stream_set_blocking($socket, false);
|
||||
$clients[(int) $socket] = ['socket' => $socket, 'buffer' => '', 'handled' => false];
|
||||
}
|
||||
foreach (array_keys($clients) as $key) {
|
||||
$socket = $clients[$key]['socket'];
|
||||
$chunk = @fread($socket, 65536);
|
||||
if ($chunk === '' && feof($socket)) {
|
||||
if ($generation === $key) {
|
||||
$metrics['generation_eof'] = true;
|
||||
$metrics['closed_before_terminal_tail'] = $tailAt !== null;
|
||||
$done = true;
|
||||
}
|
||||
fclose($socket); unset($clients[$key]); continue;
|
||||
}
|
||||
if ($clients[$key]['handled']) continue;
|
||||
$clients[$key]['buffer'] .= is_string($chunk) ? $chunk : '';
|
||||
$parts = explode("\r\n\r\n", $clients[$key]['buffer'], 2);
|
||||
if (count($parts) !== 2) continue;
|
||||
preg_match('/Content-Length:\s*(\d+)/i', $parts[0], $length);
|
||||
if (strlen($parts[1]) < (int) ($length[1] ?? 0)) continue;
|
||||
$clients[$key]['handled'] = true;
|
||||
$payload = json_decode($parts[1]);
|
||||
if (preg_match('#^POST /v1/chat-messages/synthetic-drain-task/stop #', $parts[0])) {
|
||||
++$metrics['stop_count'];
|
||||
$metrics['generation_open_on_stop'] = $generation !== null && isset($clients[$generation]);
|
||||
$metrics['user_matches'] = ($payload->user ?? '') === 'synthetic-drain-user';
|
||||
$body = '{"result":"success"}';
|
||||
fwrite($socket, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: "
|
||||
. strlen($body) . "\r\nConnection: close\r\n\r\n" . $body);
|
||||
fclose($socket); unset($clients[$key]);
|
||||
if (in_array($scenario, ['late_metadata', 'terminal_tail', 'terminal_silent'], true)) $terminalAt = microtime(true) + 0.08;
|
||||
} else {
|
||||
$generation = $key; $generationAt = microtime(true);
|
||||
$metrics['title_disabled'] = ($payload->auto_generate_name ?? null) === false;
|
||||
$metrics['inputs_object'] = is_object($payload->inputs ?? null);
|
||||
if ($scenario !== 'silent_headers') {
|
||||
fwrite($socket, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n");
|
||||
}
|
||||
if (in_array($scenario, ['no_terminal', 'terminal_tail', 'terminal_silent'], true)) {
|
||||
fwrite($socket, "data: {\"event\":\"workflow_started\",\"task_id\":\"synthetic-drain-task\"}\n\n");
|
||||
$taskSent = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($generation !== null && isset($clients[$generation])) {
|
||||
$socket = $clients[$generation]['socket'];
|
||||
if ($scenario === 'late_metadata' && !$earlySent && microtime(true) - $generationAt >= 0.12) {
|
||||
// Cancellation has already been requested, but task metadata is
|
||||
// still absent. This body must not short-circuit the grace.
|
||||
fwrite($socket, "data: {\"event\":\"message\",\"answer\":\"discard-before-task\"}\n\n");
|
||||
$earlySent = true;
|
||||
}
|
||||
if ($scenario === 'late_metadata' && !$taskSent && microtime(true) - $generationAt >= 0.20) {
|
||||
fwrite($socket, "data: {\"event\":\"workflow_started\",\"task_id\":\"synthetic-drain-task\"}\n\n");
|
||||
$taskSent = true;
|
||||
}
|
||||
if ($terminalAt !== null && microtime(true) >= $terminalAt) {
|
||||
if (in_array($scenario, ['terminal_tail', 'terminal_silent'], true)) {
|
||||
fwrite($socket, "data: {\"event\":\"workflow_finished\",\"task_id\":\"synthetic-drain-task\",\"data\":{\"status\":\"stopped\"}}\n\n");
|
||||
$terminalAt = null;
|
||||
if ($scenario === 'terminal_tail') $tailAt = microtime(true) + 0.20;
|
||||
continue;
|
||||
}
|
||||
fwrite($socket, "data: {\"event\":\"message\",\"task_id\":\"synthetic-drain-task\",\"answer\":\"discard-tail\"}\n\n"
|
||||
. "data: {\"event\":\"message_end\"}\n\n"
|
||||
. "data: {\"event\":\"workflow_finished\",\"task_id\":\"synthetic-drain-task\",\"data\":{\"status\":\"stopped\"}}\n\n");
|
||||
fclose($socket); unset($clients[$generation]); $done = true;
|
||||
}
|
||||
if ($tailAt !== null && microtime(true) >= $tailAt) {
|
||||
$metrics['terminal_tail_sent'] = true;
|
||||
fwrite($socket, "data: {\"event\":\"message_end\"}\n\n");
|
||||
$tailAt = null;
|
||||
fclose($socket); unset($clients[$generation]); $done = true;
|
||||
}
|
||||
}
|
||||
usleep(1000);
|
||||
}
|
||||
foreach ($clients as $client) fclose($client['socket']);
|
||||
fclose($listener);
|
||||
echo json_encode($metrics) . "\n";
|
||||
exit($done ? 0 : 3);
|
||||
}
|
||||
|
||||
$directory = sys_get_temp_dir() . '/zyt-drain-' . bin2hex(random_bytes(8));
|
||||
$rows = [];
|
||||
try {
|
||||
foreach (['late_metadata', 'terminal_tail', 'terminal_silent', 'no_terminal', 'silent_headers', 'silent_body'] as $index => $scenario) {
|
||||
$process = proc_open([PHP_BINARY, __FILE__, 'server', $scenario],
|
||||
[0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
|
||||
drainExpect(is_resource($process), 'loopback server starts');
|
||||
fclose($pipes[0]); stream_set_timeout($pipes[1], 10);
|
||||
$ready = json_decode((string) fgets($pipes[1]), true);
|
||||
drainExpect(isset($ready['address']), 'loopback server reports its ephemeral port');
|
||||
$drainConfig = ['enable' => true, 'base_url' => 'http://' . $ready['address'] . '/v1/chat-messages',
|
||||
'timeout' => 6, 'models' => ['qwen' => ['name' => 'synthetic', 'api_key' => 'loopback-only']]];
|
||||
$requestId = sprintf('12345678-1234-4234-8234-%012d', $index);
|
||||
$control = new AssistantRequestControl(7, 11, $requestId, $directory);
|
||||
drainExpect($control->begin(), 'fresh synthetic control begins');
|
||||
$transferAt = null; $cancelAt = null; $deltas = []; $terminals = [];
|
||||
$abort = static function () use ($control, &$transferAt, &$cancelAt): bool {
|
||||
if ($transferAt !== null && $cancelAt === null && hrtime(true) / 1e9 - $transferAt >= 0.08) {
|
||||
$cancelAt = hrtime(true) / 1e9;
|
||||
$control->signalCancel();
|
||||
}
|
||||
return $control->shouldAbort();
|
||||
};
|
||||
$result = DifyChatService::streamChat('qwen', [], '合成取消测试,无真实患者', 'synthetic-drain-user',
|
||||
static function (string $text) use (&$deltas): bool { $deltas[] = $text; return true; }, $abort, [], [
|
||||
'knowledge_mode' => 'evidence',
|
||||
'on_progress' => static function (array $event) use (&$transferAt): void {
|
||||
if ($transferAt === null) $transferAt = hrtime(true) / 1e9;
|
||||
},
|
||||
'on_task' => static fn (string $taskId) => $control->bindTask('qwen', 'synthetic-drain-user', $taskId),
|
||||
'on_cancel_task' => static function (string $taskId, callable $stop) use ($control): array {
|
||||
$control->signalCancel(); return $control->stopBoundTask($stop, $taskId);
|
||||
},
|
||||
'on_terminal' => static function (string $taskId, string $status) use ($control, &$terminals): void {
|
||||
$terminals[] = $status; $control->markTerminal($taskId, $status);
|
||||
},
|
||||
'on_stop' => static fn (bool $accepted, string $taskId) => $control->markStop($accepted, $taskId),
|
||||
'on_transfer_end' => static fn (string $taskId) => $control->clearTask($taskId !== '' ? $taskId : null),
|
||||
]);
|
||||
$cancelMs = (hrtime(true) / 1e9 - $cancelAt) * 1000;
|
||||
$control->finish('cancelled');
|
||||
$state = $control->publicState();
|
||||
$peer = json_decode((string) fgets($pipes[1]), true);
|
||||
$stderr = stream_get_contents($pipes[2]);
|
||||
fclose($pipes[1]); fclose($pipes[2]);
|
||||
drainExpect(proc_close($process) === 0 && $stderr === '', $scenario . ': loopback peer exits cleanly');
|
||||
drainExpect(($result['error_code'] ?? '') === 'AI_ASSISTANT_CANCELLED' && $deltas === [],
|
||||
$scenario . ': cancellation delivers no body and returns cancelled');
|
||||
drainExpect($peer['title_disabled'] && $peer['inputs_object'], 'real wire disables titles and preserves input object');
|
||||
drainExpect($cancelMs < 2900, $scenario . ': absolute cancellation budget bounds a silent upstream');
|
||||
if (in_array($scenario, ['late_metadata', 'terminal_tail'], true)) {
|
||||
drainExpect($peer['stop_count'] === 1 && $peer['generation_open_on_stop'] && $peer['user_matches'],
|
||||
'known task stops once before the generation closes using its exact user');
|
||||
drainExpect($terminals === ['stopped'] && $state['upstream_terminal_confirmed']
|
||||
&& $state['upstream_terminal_status'] === 'stopped', 'discarded tails still expose workflow terminal metadata');
|
||||
if ($scenario === 'terminal_tail') {
|
||||
drainExpect($peer['terminal_tail_sent'] && !$peer['closed_before_terminal_tail'],
|
||||
'workflow_finished preserves the connection through delayed message_end and natural EOF');
|
||||
}
|
||||
} elseif ($scenario === 'terminal_silent') {
|
||||
drainExpect($peer['stop_count'] === 1 && $state['upstream_terminal_confirmed']
|
||||
&& $peer['generation_eof'] && $cancelMs >= 2400,
|
||||
'terminal followed by silence exits on the original budget without repeated stop');
|
||||
} elseif ($scenario === 'no_terminal') {
|
||||
drainExpect($peer['stop_count'] === 1 && $state['upstream_stop_confirmed']
|
||||
&& !$state['upstream_terminal_confirmed'] && $peer['generation_eof'],
|
||||
'stop acceptance without terminal metadata remains distinct after bounded draining');
|
||||
drainExpect($cancelMs >= 2400, 'known task gets its bounded terminal observation window');
|
||||
} else {
|
||||
drainExpect($peer['stop_count'] === 0 && !$state['upstream_stop_confirmed']
|
||||
&& !$state['upstream_terminal_confirmed'] && $peer['generation_eof'],
|
||||
'unknown task closes transport without inventing upstream stop or terminal confirmation');
|
||||
drainExpect($cancelMs >= 1900 && $cancelMs < 2300, 'unknown metadata grace is bounded to two seconds');
|
||||
}
|
||||
$rows[] = ['scenario' => $scenario, 'cancel_ms' => round($cancelMs, 2), 'stop_count' => $peer['stop_count']];
|
||||
}
|
||||
echo 'Diagnosis AI real loopback cancel drain / terminal / silent bounds: OK ' . json_encode($rows) . "\n";
|
||||
} finally {
|
||||
foreach (glob($directory . '/*') ?: [] as $path) unlink($path);
|
||||
if (is_file($directory . '/.gc.lock')) unlink($directory . '/.gc.lock');
|
||||
if (is_dir($directory)) rmdir($directory);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use app\adminapi\service\AssistantRequestControl;
|
||||
use app\adminapi\http\middleware\AuthMiddleware;
|
||||
|
||||
function cancelExpect(bool $ok, string $message): void {
|
||||
if (!$ok) throw new RuntimeException($message);
|
||||
}
|
||||
|
||||
if (($argv[1] ?? '') === 'worker') {
|
||||
$control = new AssistantRequestControl(7, 11, $argv[4], $argv[3]);
|
||||
if ($argv[2] === 'cancel') echo json_encode($control->requestCancel());
|
||||
else echo json_encode(['began' => $control->begin()]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$directory = sys_get_temp_dir() . '/zyt-assistant-control-' . bin2hex(random_bytes(8));
|
||||
$id = '12345678-1234-4234-8234-123456789abc';
|
||||
$make = static fn (int $admin = 7, int $diagnosis = 11): AssistantRequestControl => new AssistantRequestControl($admin, $diagnosis, $id, $directory);
|
||||
try {
|
||||
$control = $make();
|
||||
$tombstone = $control->requestCancel();
|
||||
cancelExpect($tombstone['status'] === 'cancel_requested' && !$tombstone['transport_closed'] && !$tombstone['upstream_stop_confirmed'], 'early cancel is only requested');
|
||||
cancelExpect($control->begin() && $control->shouldAbort(), 'prepare preserves cancellation that arrived before begin');
|
||||
cancelExpect(!$control->begin(), 'same request id cannot reenter or resubmit');
|
||||
cancelExpect(!$make(8)->shouldAbort() && !$make(7, 12)->shouldAbort(), 'admin and canonical diagnosis isolate cancellation');
|
||||
$control->bindTask('qwen', 'synthetic-user', 'synthetic-task');
|
||||
$calls = 0;
|
||||
$stop = static function (array $task) use (&$calls): bool { ++$calls; return $task['task_id'] === 'synthetic-task'; };
|
||||
cancelExpect($control->requestCancel($stop)['upstream_stop_confirmed'], 'bound task can be stopped by a different control instance');
|
||||
$make()->requestCancel($stop);
|
||||
cancelExpect($calls === 1, 'confirmed stop is idempotent');
|
||||
$control->finish('cancelled');
|
||||
cancelExpect($control->publicState()['transport_closed'], 'owning worker alone confirms transfer has ended');
|
||||
cancelExpect(!str_contains(json_encode($control->publicState()), 'synthetic-task'), 'public status excludes task identity');
|
||||
|
||||
$id2 = '22345678-1234-4234-8234-123456789abc';
|
||||
$control2 = new AssistantRequestControl(7, 11, $id2, $directory);
|
||||
cancelExpect($control2->begin(), 'fresh request begins');
|
||||
$run = static function (string $mode, string $requestId) use ($directory): array {
|
||||
$pipes = [];
|
||||
$process = proc_open([PHP_BINARY, __FILE__, 'worker', $mode, $directory, $requestId],
|
||||
[0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
|
||||
if (!is_resource($process)) throw new RuntimeException('Cannot start independent PHP worker');
|
||||
fclose($pipes[0]);
|
||||
return [$process, $pipes];
|
||||
};
|
||||
[$process, $pipes] = $run('cancel', $id2);
|
||||
$status = json_decode(stream_get_contents($pipes[1]), true);
|
||||
$stderr = stream_get_contents($pipes[2]);
|
||||
fclose($pipes[1]); fclose($pipes[2]);
|
||||
cancelExpect(proc_close($process) === 0 && $stderr === '' && $status['cancel_requested'], 'independent PHP process accepts cancellation');
|
||||
cancelExpect($control2->shouldAbort(), 'original process observes cancellation through flock state');
|
||||
|
||||
$id3 = '32345678-1234-4234-8234-123456789abc';
|
||||
$workers = [];
|
||||
for ($i = 0; $i < 4; ++$i) $workers[] = $run('begin', $id3);
|
||||
$began = 0;
|
||||
foreach ($workers as [$process, $pipes]) {
|
||||
$result = json_decode(stream_get_contents($pipes[1]), true);
|
||||
$stderr = stream_get_contents($pipes[2]);
|
||||
fclose($pipes[1]); fclose($pipes[2]);
|
||||
cancelExpect(proc_close($process) === 0 && $stderr === '', 'racing worker terminates cleanly');
|
||||
$began += (int) $result['began'];
|
||||
}
|
||||
cancelExpect($began === 1, 'flock allows exactly one of four independent workers to begin');
|
||||
|
||||
$path = $directory . '/' . hash('sha256', '7:11:' . $id3) . '.json';
|
||||
file_put_contents($path, json_encode(['begun' => true, 'expires_at' => time() - 1]));
|
||||
touch($path, time() - 700);
|
||||
new AssistantRequestControl(7, 11, $id3, $directory);
|
||||
cancelExpect(!is_file($path), 'expired request files are reclaimed under a directory guard');
|
||||
|
||||
$alias = new ReflectionMethod(AuthMiddleware::class, 'matchPermissionAlias');
|
||||
cancelExpect($alias->invoke(new AuthMiddleware(), 'tcm.diagnosis/cancelaiassistant', ['tcm.diagnosis/aiassistant']), 'cancel action uses existing assistant menu permission');
|
||||
cancelExpect(!$alias->invoke(new AuthMiddleware(), 'tcm.diagnosis/cancelaiassistant', []), 'cancel alias denies ungranted administrator');
|
||||
cancelExpect(!AssistantRequestControl::validRequestId('../secret') && !AssistantRequestControl::validRequestId('arbitrary'), 'only UUID identities are accepted');
|
||||
echo "Diagnosis AI assistant cancellation / independent Windows PHP workers: OK\n";
|
||||
} finally {
|
||||
foreach (glob($directory . '/*') ?: [] as $path) unlink($path);
|
||||
if (is_file($directory . '/.gc.lock')) unlink($directory . '/.gc.lock');
|
||||
if (is_dir($directory)) rmdir($directory);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\adminapi\logic\firstvisit {
|
||||
class MyPatientLogic {
|
||||
public static bool $allowed = true;
|
||||
public static function canAccessDiagnosis($id, $adminId, $adminInfo): bool {
|
||||
$GLOBALS['lifecycle'][] = 'scope_checked';
|
||||
return self::$allowed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace app\adminapi\logic\tcm {
|
||||
function config(string $key): array {
|
||||
return ['timeout' => 5, 'models' => ['qwen' => ['name' => 'synthetic', 'label' => '合成模型']]];
|
||||
}
|
||||
class DiagnosisLogic {
|
||||
public static function detail($params, $adminInfo): array {
|
||||
$GLOBALS['lifecycle'][] = 'diagnosis_loaded';
|
||||
return ['id' => $params['id'], 'patient_id' => 99, 'gender' => '女', 'age' => 42];
|
||||
}
|
||||
}
|
||||
class PatientAiReportLogic {
|
||||
public static function contextForAuthorizedDiagnosis($diagnosis, $adminId, $adminInfo): array {
|
||||
$GLOBALS['lifecycle'][] = 'aggregate';
|
||||
if (!empty($GLOBALS['cancelInAggregate'])) $GLOBALS['lifecycleCancelled'] = true;
|
||||
return ['snapshot' => ['clinical_source' => '合成资料,无真实患者'],
|
||||
'source_summary' => ['diagnosis_count' => 2, 'doctor_note_count' => 3, 'snapshot_complete' => true, 'may_be_truncated' => false],
|
||||
'source_diagnosis_ids' => [11, 12], 'files' => []];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
use app\adminapi\logic\tcm\DiagnosisAiLogic;
|
||||
use app\adminapi\logic\firstvisit\MyPatientLogic;
|
||||
function lifecycleExpect(bool $ok, string $message): void { if (!$ok) throw new RuntimeException($message); }
|
||||
$lifecycle = []; $lifecycleCancelled = false; $cancelInAggregate = false;
|
||||
$options = ['should_abort' => static fn (): bool => $GLOBALS['lifecycleCancelled'],
|
||||
'on_authorized' => static function (array $metadata): bool {
|
||||
$GLOBALS['lifecycle'][] = 'start';
|
||||
lifecycleExpect($metadata === ['diagnosis_id' => 11, 'task' => 'summary', 'model_key' => 'qwen'], 'early start exposes only authorized identity and model key');
|
||||
return true;
|
||||
},
|
||||
'on_progress' => static function (array $event): void { $GLOBALS['lifecycle'][] = $event; }];
|
||||
$prepared = DiagnosisAiLogic::prepareAssistant(11, 'summary', '', 7, ['root' => 1], null, $options);
|
||||
lifecycleExpect(is_array($prepared), 'authorized synthetic preparation succeeds');
|
||||
lifecycleExpect(array_slice($lifecycle, 0, 5) === ['scope_checked', 'diagnosis_loaded', 'start',
|
||||
['phase' => 'preparing', 'status' => 'aggregating', 'message' => '正在聚合本次授权范围内的患者资料'], 'aggregate'], 'start and truthful preparation progress occur after scope but before aggregation');
|
||||
lifecycleExpect($prepared['source_form'] === 'full_context' && $prepared['source_summary']['doctor_note_count'] === 3, 'real aggregate counts and full source form are preserved');
|
||||
lifecycleExpect(end($lifecycle)['status'] === 'ready', 'ready occurs after successful aggregation');
|
||||
$lifecycle = [];
|
||||
MyPatientLogic::$allowed = false;
|
||||
lifecycleExpect(DiagnosisAiLogic::prepareAssistant(11, 'summary', '', 7, ['root' => 1], null, $options) === null
|
||||
&& $lifecycle === ['scope_checked'], 'denied DataScope produces no start/progress or aggregation');
|
||||
lifecycleExpect(DiagnosisAiLogic::cancelAssistant(11, '12345678-1234-4234-8234-123456789abc', 7, ['root' => 1]) === null
|
||||
&& DiagnosisAiLogic::getError() === '诊单不存在或无权访问', 'cancel has the same canonical DataScope restriction');
|
||||
MyPatientLogic::$allowed = true;
|
||||
$lifecycle = []; $cancelInAggregate = true;
|
||||
lifecycleExpect(DiagnosisAiLogic::prepareAssistant(11, 'summary', '', 7, ['root' => 1], null, $options) === null
|
||||
&& DiagnosisAiLogic::getAssistantErrorCode() === 'AI_ASSISTANT_CANCELLED', 'cancellation during aggregation blocks final prompt preparation');
|
||||
lifecycleExpect(end($lifecycle) === 'aggregate', 'cancelled aggregation never claims prepared or submitted');
|
||||
echo "Diagnosis AI assistant early start / DataScope / preparation lifecycle: OK\n";
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use app\adminapi\service\AssistantRequestControl;
|
||||
|
||||
function stopExpect(bool $ok, string $message): void {
|
||||
if (!$ok) throw new RuntimeException($message);
|
||||
}
|
||||
|
||||
if (($argv[1] ?? '') === 'worker') {
|
||||
[$unused, $workerFlag, $mode, $directory, $id] = $argv;
|
||||
$control = new AssistantRequestControl(7, 11, $id, $directory);
|
||||
$deadline = microtime(true) + 5;
|
||||
while (!is_file($directory . '/gate') && microtime(true) < $deadline) usleep(1000);
|
||||
echo json_encode($control->requestCancel(static function (array $task) use ($directory, $mode): bool {
|
||||
file_put_contents($directory . '/calls', $task['task_id'] . "\n", FILE_APPEND | LOCK_EX);
|
||||
if ($mode === 'abandon') exit(0); // Simulate a worker dying with its lease still held.
|
||||
usleep(180000);
|
||||
return true;
|
||||
}));
|
||||
exit;
|
||||
}
|
||||
|
||||
$directory = sys_get_temp_dir() . '/zyt-stop-coordination-' . bin2hex(random_bytes(8));
|
||||
$make = static function (int $number) use ($directory): AssistantRequestControl {
|
||||
$control = new AssistantRequestControl(7, 11, sprintf('12345678-1234-4234-8234-%012d', $number), $directory);
|
||||
stopExpect($control->begin(), 'fresh control begins');
|
||||
$control->bindTask('qwen', 'synthetic-stop-user', 'synthetic-stop-' . $number);
|
||||
return $control;
|
||||
};
|
||||
$launch = static function (string $mode, int $number) use ($directory): array {
|
||||
$pipes = [];
|
||||
$process = proc_open([PHP_BINARY, __FILE__, 'worker', $mode, $directory,
|
||||
sprintf('12345678-1234-4234-8234-%012d', $number)],
|
||||
[0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
|
||||
stopExpect(is_resource($process), 'independent stop worker launches');
|
||||
fclose($pipes[0]);
|
||||
return [$process, $pipes];
|
||||
};
|
||||
$join = static function (array $worker): string {
|
||||
[$process, $pipes] = $worker;
|
||||
$stdout = stream_get_contents($pipes[1]); $stderr = stream_get_contents($pipes[2]);
|
||||
fclose($pipes[1]); fclose($pipes[2]);
|
||||
stopExpect(proc_close($process) === 0 && $stderr === '', 'independent stop worker exits cleanly');
|
||||
return $stdout;
|
||||
};
|
||||
try {
|
||||
$control = $make(1);
|
||||
$workers = [];
|
||||
for ($index = 0; $index < 4; ++$index) $workers[] = $launch('race', 1);
|
||||
file_put_contents($directory . '/gate', '1');
|
||||
foreach ($workers as $worker) $join($worker);
|
||||
$calls = file($directory . '/calls', FILE_IGNORE_NEW_LINES);
|
||||
stopExpect(count($calls) === 1 && $control->publicState()['upstream_stop_confirmed'],
|
||||
'four independent workers send exactly one accepted stop for the same task');
|
||||
stopExpect(!$control->publicState()['upstream_terminal_confirmed'], 'stop API acceptance does not imply workflow termination');
|
||||
$ownerCalls = 0;
|
||||
$ownerOutcome = $control->stopBoundTask(static function () use (&$ownerCalls): bool { ++$ownerCalls; return true; }, 'synthetic-stop-1');
|
||||
stopExpect($ownerOutcome['accepted'] && $ownerCalls === 0, 'owner observes peer acceptance without a second HTTP stop');
|
||||
|
||||
$abandoned = $make(2);
|
||||
$join($launch('abandon', 2));
|
||||
$takeovers = 0;
|
||||
$compensate = static function () use (&$takeovers): bool { ++$takeovers; return true; };
|
||||
stopExpect($abandoned->stopBoundTask($compensate)['pending'] && $takeovers === 0,
|
||||
'an active claim lease blocks a duplicate stop');
|
||||
usleep(1300000);
|
||||
stopExpect($abandoned->stopBoundTask($compensate)['accepted'] && $takeovers === 1,
|
||||
'an abandoned lease expires and allows one bounded takeover');
|
||||
|
||||
$failed = $make(3); $failed->signalCancel();
|
||||
$attempts = 0;
|
||||
$reject = static function () use (&$attempts): bool { ++$attempts; return false; };
|
||||
stopExpect(!$failed->stopBoundTask($reject)['accepted'], 'a rejected stop remains unconfirmed');
|
||||
$failed->clearTask('synthetic-stop-3'); $failed->finish('cancelled');
|
||||
usleep(260000);
|
||||
$retryState = $failed->requestCancel(static function () use (&$attempts): bool { ++$attempts; return true; });
|
||||
stopExpect($attempts === 2 && $retryState['upstream_stop_confirmed'] && $retryState['transport_closed'],
|
||||
'failed known task remains available for compensation after local transport termination');
|
||||
$failed->requestCancel($reject);
|
||||
stopExpect($attempts === 2, 'accepted compensation stays idempotent');
|
||||
|
||||
$bounded = $make(4); $bounded->signalCancel(); $attempts = 0;
|
||||
$bounded->stopBoundTask($reject); usleep(260000); $bounded->stopBoundTask($reject);
|
||||
usleep(260000); $bounded->requestCancel($reject);
|
||||
stopExpect($attempts === 2 && !$bounded->publicState()['upstream_stop_confirmed'], 'failure never creates an unbounded stop retry loop');
|
||||
|
||||
$expired = $make(5); $expired->signalCancel();
|
||||
$path = $directory . '/' . hash('sha256', '7:11:12345678-1234-4234-8234-000000000005') . '.json';
|
||||
$state = json_decode((string) file_get_contents($path), true);
|
||||
$state['stop_retry_until'] = microtime(true) - 1;
|
||||
file_put_contents($path, json_encode($state));
|
||||
$attempts = 0; $expired->requestCancel($reject);
|
||||
stopExpect($attempts === 0, 'expired compensation window is not extended by repeated cancel requests');
|
||||
|
||||
$generation = $make(6); $generation->signalCancel();
|
||||
$oldResult = $generation->stopBoundTask(static function () use ($generation): bool {
|
||||
$generation->bindTask('qwen', 'synthetic-stop-user', 'synthetic-next-generation');
|
||||
return true;
|
||||
}, 'synthetic-stop-6');
|
||||
$generation->markStop(true, 'synthetic-stop-6');
|
||||
$generation->markTerminal('synthetic-stop-6', 'stopped');
|
||||
$generation->clearTask('synthetic-stop-6');
|
||||
stopExpect(!$oldResult['accepted'] && !$generation->publicState()['upstream_stop_confirmed']
|
||||
&& !$generation->publicState()['upstream_terminal_confirmed'], 'late stop and terminal callbacks cannot poison the next task generation');
|
||||
$attempts = 0;
|
||||
$generation->stopBoundTask($reject, 'synthetic-stop-6');
|
||||
stopExpect($attempts === 0, 'a stale owner cannot stop a different task generation');
|
||||
stopExpect($generation->stopBoundTask(static fn (): bool => true, 'synthetic-next-generation')['accepted'],
|
||||
'current task generation remains independently stoppable');
|
||||
$generation->markTerminal('synthetic-next-generation', 'running');
|
||||
stopExpect(!$generation->publicState()['upstream_terminal_confirmed'], 'running metadata is never accepted as terminal');
|
||||
$generation->markTerminal('synthetic-next-generation', 'stopped');
|
||||
$generation->markTerminal('synthetic-next-generation', 'failed');
|
||||
stopExpect($generation->publicState()['upstream_terminal_confirmed']
|
||||
&& $generation->publicState()['upstream_terminal_status'] === 'stopped', 'only matching terminal metadata confirms the workflow state');
|
||||
$sibling = $make(7);
|
||||
stopExpect(!$sibling->shouldAbort() && !$sibling->publicState()['upstream_stop_confirmed'], 'new request UUID is isolated from all old task callbacks');
|
||||
stopExpect(!str_contains(json_encode($generation->publicState()), 'synthetic-next-generation'), 'public state never discloses task identifiers');
|
||||
$legacy = $make(8); $legacy->signalCancel();
|
||||
$legacyPath = $directory . '/' . hash('sha256', '7:11:12345678-1234-4234-8234-000000000008') . '.json';
|
||||
$legacyState = json_decode((string) file_get_contents($legacyPath), true);
|
||||
unset($legacyState['upstream']['generation']);
|
||||
file_put_contents($legacyPath, json_encode($legacyState));
|
||||
stopExpect($legacy->stopBoundTask(static fn (): bool => true)['accepted'], 'in-flight task state from the previous release is upgraded before claiming');
|
||||
echo "Diagnosis AI stop claims / multi-process dedup / lease recovery / compensation / task generations: OK\n";
|
||||
} finally {
|
||||
foreach (glob($directory . '/*') ?: [] as $path) unlink($path);
|
||||
if (is_file($directory . '/.gc.lock')) unlink($directory . '/.gc.lock');
|
||||
if (is_dir($directory)) rmdir($directory);
|
||||
}
|
||||
@@ -69,13 +69,19 @@ assistantStreamExpect(
|
||||
);
|
||||
|
||||
$actionStart = strpos($controller, 'public function aiAssistantStream()');
|
||||
$checkAt = strpos($controller, "goCheck('aiAssistant')", $actionStart);
|
||||
$checkAt = strpos($controller, "goCheck('aiAssistantStream')", $actionStart);
|
||||
$prepareAt = strpos($controller, 'DiagnosisAiLogic::prepareAssistant(', $actionStart);
|
||||
$runAt = strpos($controller, '$this->runAssistantSse($prepared, $timing)', $actionStart);
|
||||
$runAt = strpos($controller, '$this->runAssistantSse($prepared, $timing,', $actionStart);
|
||||
$headerAt = strpos($controller, "header('Content-Type: text/event-stream; charset=utf-8')", $actionStart);
|
||||
$logicPrepareAt = strpos($logic, 'public static function prepareAssistant(');
|
||||
$authorizeAt = strpos($logic, '$diagnosis = self::loadAuthorizedDiagnosis(', $logicPrepareAt);
|
||||
$startCallbackAt = strpos($logic, "is_callable(\$options['on_authorized']", $authorizeAt);
|
||||
$aggregateAt = strpos($logic, '$context = self::buildCaseContext(', $startCallbackAt);
|
||||
assistantStreamExpect(
|
||||
$actionStart !== false && $checkAt > $actionStart && $prepareAt > $checkAt && $runAt > $prepareAt && $headerAt > $runAt,
|
||||
'request validation and authorized preparation occur before every SSE header'
|
||||
$actionStart !== false && $checkAt > $actionStart && $prepareAt > $checkAt && $runAt > $prepareAt && $headerAt > $runAt
|
||||
&& $authorizeAt < $startCallbackAt && $startCallbackAt < $aggregateAt
|
||||
&& str_contains($controller, '$emit = $this->openAssistantSse();'),
|
||||
'request validation and diagnosis authorization precede early start; aggregation follows it'
|
||||
);
|
||||
assistantStreamExpect(
|
||||
str_contains($validate, "return \$this->only(['id', 'task', 'prompt']);"),
|
||||
@@ -88,10 +94,20 @@ assistantStreamExpect(
|
||||
'stream preparation reuses assistant permission and canonical diagnosis row authorization'
|
||||
);
|
||||
assistantStreamExpect(
|
||||
str_contains($auth, "\$accessUri === 'tcm.diagnosis/aiassistantstream'")
|
||||
str_contains($auth, "['tcm.diagnosis/aiassistantstream', 'tcm.diagnosis/cancelaiassistant']")
|
||||
&& str_contains($auth, "'tcm.diagnosis/aiassistant', \$adminUris"),
|
||||
'middleware maps stream access to the old registered assistant permission'
|
||||
);
|
||||
|
||||
$progressProtocol = new AssistantSseProtocol();
|
||||
assistantStreamExpect($progressProtocol->encode('progress', ['phase' => 'preparing']) === null, 'progress cannot precede authenticated start');
|
||||
$progressProtocol->encode('start', []);
|
||||
$progressFrame = parseAssistantSse((string) $progressProtocol->encode('progress', ['phase' => 'attachments', 'status' => 'submitted']));
|
||||
assistantStreamExpect($progressFrame['data']['seq'] === 2, 'real preparation and submission progress shares monotonic event sequence');
|
||||
$progressProtocol->encode('progress', ['phase' => 'cancelled', 'status' => 'cancelled']);
|
||||
$cancelFrame = parseAssistantSse((string) $progressProtocol->encode('error', ['code' => 'AI_ASSISTANT_CANCELLED']));
|
||||
assistantStreamExpect($cancelFrame['data']['seq'] === 4 && $progressProtocol->encode('done', []) === null
|
||||
&& $progressProtocol->encode('progress', []) === null, 'cancellation has exactly one terminal event and no late success or progress');
|
||||
$matchPermissionAlias = (new ReflectionClass(AuthMiddleware::class))->getMethod('matchPermissionAlias');
|
||||
$authMiddleware = new AuthMiddleware();
|
||||
assistantStreamExpect(
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace think\facade {
|
||||
class Log {
|
||||
public static function warning(string $message): void {}
|
||||
}
|
||||
}
|
||||
|
||||
namespace app\common\service {
|
||||
require __DIR__ . '/fixtures/CancellableCurlMultiStub.php';
|
||||
function config(string $name): array { return $GLOBALS['integrationConfig']; }
|
||||
function curl_init(): \stdClass { return new \stdClass(); }
|
||||
function curl_setopt_array(\stdClass $handle, array $options): bool {
|
||||
$handle->options = $options;
|
||||
$handle->url = $options[CURLOPT_URL];
|
||||
$handle->payload = json_decode($options[CURLOPT_POSTFIELDS], true);
|
||||
return true;
|
||||
}
|
||||
function curl_exec(\stdClass $handle) {
|
||||
$payload = $handle->payload;
|
||||
$streaming = ($payload['response_mode'] ?? '') === 'streaming' || !empty($payload['stream']);
|
||||
$GLOBALS['integrationRequests'][] = ['url' => $handle->url, 'payload' => $payload, 'streaming' => $streaming];
|
||||
$scenario = $GLOBALS['integrationScenario'];
|
||||
if (($scenario === 'blocking_only' || $scenario === 'cancel_blocking') && $streaming) $handle->code = 400;
|
||||
elseif ($scenario === 'file_rejected' && !empty($payload['files'])) $handle->code = 400;
|
||||
elseif ($scenario === 'protocol_fallback' && str_ends_with($handle->url, '/chat-messages')) $handle->code = 404;
|
||||
else $handle->code = 200;
|
||||
if (isset($handle->options[CURLOPT_HEADERFUNCTION])) {
|
||||
($handle->options[CURLOPT_HEADERFUNCTION])($handle, 'HTTP/1.1 ' . $handle->code . " Synthetic\r\n");
|
||||
}
|
||||
if ($handle->code !== 200) return $streaming ? true : '{}';
|
||||
$progressOption = defined('CURLOPT_XFERINFOFUNCTION') ? CURLOPT_XFERINFOFUNCTION : CURLOPT_PROGRESSFUNCTION;
|
||||
$progress = $handle->options[$progressOption] ?? null;
|
||||
if (!$streaming) {
|
||||
if ($scenario === 'cancel_blocking') $GLOBALS['integrationCancelled'] = true;
|
||||
if (is_callable($progress) && $progress($handle, 0, 0, 100, 100)) return false;
|
||||
return json_encode(['answer' => '合成完整回答']);
|
||||
}
|
||||
if (is_callable($progress) && $progress($handle, 0, 0, 100, 100)) return false;
|
||||
$write = $handle->options[CURLOPT_WRITEFUNCTION];
|
||||
if (str_ends_with($handle->url, '/chat-messages')) {
|
||||
$write($handle, 'data: ' . json_encode(['event' => 'message', 'answer' => '合成完整回答']) . "\n\n");
|
||||
$write($handle, "data: {\"event\":\"message_end\"}\n\n");
|
||||
} else {
|
||||
$write($handle, 'data: ' . json_encode(['choices' => [['delta' => ['content' => '合成完整回答']]]]) . "\n\n");
|
||||
$write($handle, "data: [DONE]\n\n");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function curl_errno(\stdClass $handle): int { return 0; }
|
||||
function curl_getinfo(\stdClass $handle, int $option): int { return $handle->code ?? 200; }
|
||||
function curl_close(\stdClass $handle): void { ++$GLOBALS['integrationClosed']; }
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
use app\common\service\DifyChatService;
|
||||
use app\adminapi\logic\tcm\DiagnosisAiLogic;
|
||||
use app\adminapi\service\AssistantSseTiming;
|
||||
function integrationExpect(bool $ok, string $message): void { if (!$ok) throw new RuntimeException($message); }
|
||||
$integrationConfig = ['enable' => true, 'base_url' => 'https://synthetic.invalid/v1/chat-messages', 'timeout' => 5,
|
||||
'max_files' => 2, 'models' => ['qwen' => ['name' => 'synthetic', 'api_key' => 'fixture-only']]];
|
||||
$reset = static function (string $scenario = 'success'): void {
|
||||
$GLOBALS['integrationScenario'] = $scenario;
|
||||
$GLOBALS['integrationRequests'] = [];
|
||||
$GLOBALS['integrationCancelled'] = false;
|
||||
$GLOBALS['integrationClosed'] = 0;
|
||||
};
|
||||
$abort = static fn (): bool => $GLOBALS['integrationCancelled'];
|
||||
$strict = ['strict_files' => true, 'knowledge_mode' => 'evidence', 'should_abort' => $abort];
|
||||
$images = array_map(static fn (int $id): array => ['type' => 'image', 'url' => 'https://synthetic.invalid/' . $id . '.png'], [1, 2, 3]);
|
||||
$document = [['type' => 'document', 'url' => 'https://synthetic.invalid/report.pdf']];
|
||||
$call = static fn (array $files): array => DifyChatService::chat('qwen', [], '合成资料', 'synthetic-user', $files, $strict);
|
||||
|
||||
$reset();
|
||||
integrationExpect($call($images)['error_code'] === 'STRICT_FILES_INVALID_OR_LIMIT' && $integrationRequests === [], 'strict + abort rejects over-limit files before transport');
|
||||
integrationExpect($call([['type' => 'image', 'url' => 'invalid']])['error_code'] === 'STRICT_FILES_INVALID_OR_LIMIT'
|
||||
&& $integrationRequests === [], 'strict + abort rejects invalid files before transport');
|
||||
$result = $call([$images[0], $images[0]]);
|
||||
integrationExpect(!empty($result['ok']) && $result['transmitted_file_count'] === 2 && $result['attachment_transport'] === 'dify'
|
||||
&& count($integrationRequests[0]['payload']['files']) === 2, 'strict stream retains logical duplicates and exact success metadata');
|
||||
|
||||
$reset('file_rejected');
|
||||
$result = $call([$images[0]]);
|
||||
integrationExpect(empty($result['ok']) && count($integrationRequests) === 1 && count($integrationRequests[0]['payload']['files']) === 1,
|
||||
'strict rejected files never trigger a text-only success fallback');
|
||||
$integrationConfig['base_url'] = 'https://synthetic.invalid/v1/chat/completions';
|
||||
$reset();
|
||||
integrationExpect($call($document)['error_code'] === 'FILE_TYPE_UNSUPPORTED' && $integrationRequests === [], 'strict documents cannot be omitted by OpenAI transport');
|
||||
$result = $call([$images[0]]);
|
||||
integrationExpect(!empty($result['ok']) && $result['transmitted_file_count'] === 1 && $result['attachment_transport'] === 'openai', 'strict supported OpenAI images retain success metadata');
|
||||
$integrationConfig['base_url'] = 'https://synthetic.invalid/v1';
|
||||
$reset('protocol_fallback');
|
||||
integrationExpect($call($document)['error_code'] === 'FILE_TYPE_UNSUPPORTED' && count($integrationRequests) === 1,
|
||||
'strict protocol fallback fails explicitly before an unsupported document request');
|
||||
|
||||
$integrationConfig['base_url'] = 'https://synthetic.invalid/v1/chat-messages';
|
||||
$prepared = ['profile' => 'qwen', 'task' => 'summary', 'query' => '合成资料', 'inputs' => [], 'user' => 'synthetic-user', 'upstream_timeout' => 5];
|
||||
$runAssistant = static function () use ($prepared, $abort): array {
|
||||
$stops = []; $ends = 0; $deltas = []; $progress = [];
|
||||
$result = DiagnosisAiLogic::streamPreparedAssistant($prepared,
|
||||
static function (string $text) use (&$deltas): bool { $deltas[] = $text; return true; }, $abort, new AssistantSseTiming(), [
|
||||
'knowledge_mode' => 'evidence',
|
||||
'on_stop' => static function (bool $accepted) use (&$stops): void { $stops[] = $accepted; },
|
||||
'on_transfer_end' => static function () use (&$ends): void { ++$ends; },
|
||||
'on_progress' => static function (array $event) use (&$progress): void { $progress[] = $event; },
|
||||
]);
|
||||
return compact('result', 'stops', 'ends', 'deltas', 'progress');
|
||||
};
|
||||
$reset('blocking_only');
|
||||
$test = $runAssistant();
|
||||
integrationExpect(is_array($test['result']) && $test['result']['answer'] === '合成完整回答', 'actual blocking-only gateway compatibility succeeds');
|
||||
integrationExpect(array_column($integrationRequests, 'streaming') === [true, false]
|
||||
&& array_column(array_column($integrationRequests, 'payload'), 'response_mode') === ['streaming', 'blocking'], 'compatibility sends streaming once then genuine blocking once');
|
||||
integrationExpect($test['ends'] === 2 && $test['stops'] === [], 'completed compatibility transfer does not invent stop acceptance');
|
||||
|
||||
$reset('cancel_blocking');
|
||||
$test = $runAssistant();
|
||||
integrationExpect($test['result'] === null && DiagnosisAiLogic::getAssistantErrorCode() === 'AI_ASSISTANT_CANCELLED', 'cancellation during real blocking compatibility terminates safely');
|
||||
integrationExpect(array_column($integrationRequests, 'streaming') === [true, false] && $integrationClosed === 2
|
||||
&& $test['ends'] === 2 && $test['stops'] === [false] && $test['deltas'] === [], 'cancel closes blocking curl, leaves remote stop unconfirmed and sends no retry or late text');
|
||||
echo "Diagnosis AI strict files + cancellation / actual blocking compatibility integration: OK\n";
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace think\facade {
|
||||
class Log {
|
||||
public static function warning(string $message): void { $GLOBALS['safeLogs'][] = $message; }
|
||||
}
|
||||
}
|
||||
|
||||
namespace app\common\service {
|
||||
require __DIR__ . '/fixtures/CancellableCurlMultiStub.php';
|
||||
function config(string $name): array { return $GLOBALS['transportConfig']; }
|
||||
function curl_init(): \stdClass { return new \stdClass(); }
|
||||
function curl_setopt_array(\stdClass $handle, array $options): bool {
|
||||
$handle->options = $options;
|
||||
$handle->url = $options[CURLOPT_URL];
|
||||
$handle->body = json_decode($options[CURLOPT_POSTFIELDS], true);
|
||||
return true;
|
||||
}
|
||||
function curl_exec(\stdClass $handle) {
|
||||
$GLOBALS['requests'][] = ['url' => $handle->url, 'body' => $handle->body];
|
||||
if (str_ends_with($handle->url, '/stop')) {
|
||||
if ($GLOBALS['closed'] !== 0) throw new \RuntimeException('Stop must precede generation close');
|
||||
return json_encode(['result' => $GLOBALS['stopAccepted'] ? 'success' : 'failed']);
|
||||
}
|
||||
if (($GLOBALS['mode'] === 'file_rejection' && !empty($handle->body['files']))
|
||||
|| ($GLOBALS['mode'] === 'protocol_fallback' && str_ends_with($handle->url, 'chat-messages'))) {
|
||||
$handle->code = $GLOBALS['mode'] === 'file_rejection' ? 400 : 404;
|
||||
($handle->options[CURLOPT_HEADERFUNCTION])($handle, 'HTTP/1.1 ' . $handle->code . " Rejected\r\n");
|
||||
return true;
|
||||
}
|
||||
($handle->options[CURLOPT_HEADERFUNCTION])($handle, "HTTP/1.1 200 OK\r\n");
|
||||
$progressOption = defined('CURLOPT_XFERINFOFUNCTION') ? CURLOPT_XFERINFOFUNCTION : CURLOPT_PROGRESSFUNCTION;
|
||||
$progress = $handle->options[$progressOption];
|
||||
$write = $handle->options[CURLOPT_WRITEFUNCTION];
|
||||
$progress($handle, 0, 0, 100, 100);
|
||||
$mode = $GLOBALS['mode'];
|
||||
if ($mode === 'before_metadata') $GLOBALS['cancelled'] = true;
|
||||
if (!str_contains($handle->url, 'chat/completions')) {
|
||||
$write($handle, "data: {\"event\":\"workflow_started\",\"task_id\":\"synthetic-task\"}\n\n");
|
||||
}
|
||||
if ($mode === 'before_text') $GLOBALS['cancelled'] = true;
|
||||
if ($progress($handle, 0, 0, 100, 100)) return false;
|
||||
$write($handle, str_contains($handle->url, 'chat/completions')
|
||||
? "data: {\"choices\":[{\"delta\":{\"content\":\"合成回答\"}}]}\n\n"
|
||||
: "data: {\"event\":\"message\",\"task_id\":\"synthetic-task\",\"answer\":\"合成回答\"}\n\n");
|
||||
if ($mode === 'after_text') $GLOBALS['cancelled'] = true;
|
||||
if ($progress($handle, 0, 0, 100, 100)) return false;
|
||||
$write($handle, str_contains($handle->url, 'chat/completions') ? "data: [DONE]\n\n" : "data: {\"event\":\"message_end\"}\n\n");
|
||||
return true;
|
||||
}
|
||||
function curl_errno(\stdClass $handle): int { return 0; }
|
||||
function curl_getinfo(\stdClass $handle, int $option): int { return $handle->code ?? 200; }
|
||||
function curl_close(\stdClass $handle): void { if (!str_ends_with($handle->url, '/stop')) ++$GLOBALS['closed']; }
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
use app\common\service\DifyChatService;
|
||||
function transportExpect(bool $ok, string $message): void { if (!$ok) throw new RuntimeException($message); }
|
||||
$transportConfig = ['enable' => true, 'base_url' => 'https://synthetic.invalid/v1/chat-messages', 'timeout' => 5,
|
||||
'max_files' => 2, 'models' => ['qwen' => ['name' => 'synthetic', 'api_key' => 'fixture-only']]];
|
||||
$run = static function (string $scenario, bool $accept = true, bool $blocking = false) {
|
||||
$GLOBALS['mode'] = $scenario; $GLOBALS['cancelled'] = false; $GLOBALS['requests'] = [];
|
||||
$GLOBALS['closed'] = 0; $GLOBALS['stopAccepted'] = $accept;
|
||||
$progress = []; $deltas = []; $tasks = []; $stops = []; $ends = 0;
|
||||
$abort = static fn (): bool => $GLOBALS['cancelled'];
|
||||
$options = ['knowledge_mode' => 'evidence', 'source_summary' => ['diagnosis_count' => 4],
|
||||
'source_form' => 'evidence_summary', 'evidence_cache_hit' => true,
|
||||
'on_progress' => static function (array $event) use (&$progress): void { $progress[] = $event; },
|
||||
'on_task' => static function (string $task) use (&$tasks): void { $tasks[] = $task; },
|
||||
'on_stop' => static function (bool $ok) use (&$stops): void { $stops[] = $ok; },
|
||||
'on_transfer_end' => static function () use (&$ends): void { ++$ends; }];
|
||||
$files = array_map(static fn (int $i): array => ['type' => 'image', 'url' => 'https://synthetic.invalid/' . $i . '.png'], [1, 2, 3]);
|
||||
$delta = static function (string $text) use (&$deltas): bool { $deltas[] = $text; return true; };
|
||||
$result = $blocking
|
||||
? DifyChatService::chat('qwen', [], '合成资料', 'synthetic-user', [], $options + ['should_abort' => $abort])
|
||||
: DifyChatService::streamChat('qwen', [], '合成资料', 'synthetic-user', $delta, $abort, $files, $options);
|
||||
return compact('result', 'progress', 'deltas', 'tasks', 'stops', 'ends');
|
||||
};
|
||||
foreach (['before_metadata', 'before_text', 'after_text'] as $scenario) {
|
||||
$test = $run($scenario);
|
||||
transportExpect(($test['result']['error_code'] ?? '') === 'AI_ASSISTANT_CANCELLED', $scenario . ': cancellation returned');
|
||||
transportExpect($test['stops'] === [true] && $test['ends'] === 1, $scenario . ': stop accepted and transfer ended');
|
||||
transportExpect(count($requests) === 2 && str_ends_with($requests[1]['url'], '/synthetic-task/stop'), $scenario . ': exactly one generation and one stop; no retry');
|
||||
transportExpect($requests[1]['body'] === ['user' => 'synthetic-user'], 'stop uses exact original user');
|
||||
transportExpect(count($test['deltas']) === ($scenario === 'after_text' ? 1 : 0), 'no post-cancel text is delivered');
|
||||
transportExpect(!str_contains(json_encode([$test['result'], $test['progress']]), 'synthetic-task'), 'no task identity leaks to progress or response');
|
||||
}
|
||||
$test = $run('before_text', false);
|
||||
transportExpect($test['stops'] === [false], 'unaccepted stop is never reported as confirmed');
|
||||
$test = $run('before_text', true, true);
|
||||
transportExpect($test['stops'] === [true] && $requests[0]['body']['response_mode'] === 'streaming', 'cancellable blocking preprocessing uses stoppable Dify streaming');
|
||||
transportExpect($test['progress'][0]['source_form'] === 'evidence_summary', 'progress identifies cached evidence rather than full raw source');
|
||||
$test = $run('success');
|
||||
transportExpect(!empty($test['result']['ok']), 'noncancelled stream preserves success');
|
||||
$submitted = array_values(array_filter($test['progress'], static fn (array $p): bool => ($p['phase'] ?? '') === 'attachments' && $p['status'] === 'submitted'))[0];
|
||||
transportExpect($submitted['attachment_count'] === 2 && count($submitted['items']) === 3 && $submitted['items'][2]['status'] === 'omitted', 'actual file limit is reflected without claiming omitted file submission');
|
||||
transportExpect($submitted['source_summary']['diagnosis_count'] === 4 && $submitted['attachment_transfer'] === 'remote_url_references', 'real source counts and URL transfer form are shown');
|
||||
transportExpect(!str_contains(json_encode($submitted), 'https://'), 'safe labels never disclose remote patient URLs');
|
||||
$test = $run('file_rejection');
|
||||
$attempts = array_values(array_filter($test['progress'], static fn (array $p): bool => ($p['phase'] ?? '') === 'attachments'));
|
||||
$last = end($attempts);
|
||||
transportExpect(!empty($test['result']['ok']) && count($requests) === 2 && $last['attachment_count'] === 0
|
||||
&& array_unique(array_column($last['items'], 'status')) === ['omitted'], 'file rejection updates final attempt to zero inline files and all omitted');
|
||||
transportExpect(in_array('failed', array_column($attempts, 'status'), true), 'rejected submission has an explicit failed state before fallback');
|
||||
$transportConfig['base_url'] = 'https://synthetic.invalid/v1';
|
||||
$test = $run('protocol_fallback');
|
||||
transportExpect(!empty($test['result']['ok']) && count($requests) === 2
|
||||
&& str_ends_with($requests[1]['url'], '/chat/completions'), 'progress follows the actual protocol fallback attempt');
|
||||
$transportConfig['base_url'] = 'https://synthetic.invalid/v1/chat/completions';
|
||||
$test = $run('after_text');
|
||||
transportExpect(count($requests) === 1 && $test['stops'] === [false] && $test['ends'] === 1, 'OpenAI cancellation closes transport without inventing a Dify stop');
|
||||
$requests = [];
|
||||
$neverStarted = DifyChatService::streamChat('qwen', [], '合成资料', 'synthetic-user', static fn (): bool => true,
|
||||
static fn (): bool => true, [], ['knowledge_mode' => 'evidence']);
|
||||
transportExpect($neverStarted['error_code'] === 'AI_ASSISTANT_CANCELLED' && $requests === [], 'cancellation before any upstream work sends no generation request');
|
||||
echo "Diagnosis AI assistant cancellable transport / task stop / real progress: OK\n";
|
||||
}
|
||||
@@ -42,6 +42,13 @@ prescriptionPermissionExpect(
|
||||
);
|
||||
|
||||
PrescriptionGenerateAuthCacheDouble::$uris = ['tcm.diagnosis/aiAssistant'];
|
||||
$earlyStarts = 0;
|
||||
$deniedOptions = ['on_authorized' => static function () use (&$earlyStarts): void { ++$earlyStarts; }];
|
||||
prescriptionPermissionExpect(
|
||||
DiagnosisAiLogic::prepareAssistant(1, 'prescription_generate', '', 7, ['root' => 0], null, $deniedOptions) === null
|
||||
&& $earlyStarts === 0,
|
||||
'a denied task cannot invoke early SSE start or progress callbacks'
|
||||
);
|
||||
prescriptionPermissionExpect(
|
||||
DiagnosisAiLogic::prepareAssistant(1, 'prescription_generate', '', 7, ['root' => 0]) === null,
|
||||
'general assistant permission alone cannot generate a prescription'
|
||||
@@ -66,6 +73,11 @@ prescriptionPermissionExpect(
|
||||
);
|
||||
|
||||
PrescriptionGenerateAuthCacheDouble::$uris = ['tcm.diagnosis/aiGeneratePrescription'];
|
||||
prescriptionPermissionExpect(
|
||||
DiagnosisAiLogic::cancelAssistant(1, '12345678-1234-4234-8234-123456789abc', 7, ['root' => 0]) === null
|
||||
&& DiagnosisAiLogic::getError() === '权限不足,无法取消诊单 AI 助手',
|
||||
'cancel endpoint enforces the assistant permission before touching shared control state'
|
||||
);
|
||||
prescriptionPermissionExpect(
|
||||
DiagnosisAiLogic::prepareAssistant(1, 'prescription_generate', '', 7, ['root' => 0]) === null,
|
||||
'prescription permission alone does not bypass the general assistant permission'
|
||||
|
||||
@@ -63,6 +63,12 @@ $generic = callPrivate('buildRequestSpecs', [
|
||||
expectSame(2, count($generic), 'ambiguous /v1 base should support both protocols');
|
||||
expectSame('https://ai.example.test/v1/chat-messages', $generic[0]['url'], 'Dify endpoint');
|
||||
expectSame('blocking', $generic[0]['payload']['response_mode'], 'Dify blocking request');
|
||||
expectSame(false, $generic[0]['payload']['auto_generate_name'], 'Dify blocking generation disables background titles');
|
||||
expectSame(false, array_key_exists('auto_generate_name', $generic[1]['payload']), 'OpenAI protocol has no Dify title field');
|
||||
$streamingSpecs = callPrivate('buildRequestSpecs', ['https://ai.example.test/v1', 'model-name', [],
|
||||
'clinical prompt', 'server-user', true]);
|
||||
expectSame(false, $streamingSpecs[0]['payload']['auto_generate_name'], 'Dify streaming generation disables background titles');
|
||||
expectSame(true, $streamingSpecs[0]['payload']['inputs'] instanceof stdClass, 'empty inputs retain JSON object semantics');
|
||||
expectSame('https://ai.example.test/v1/chat/completions', $generic[1]['url'], 'OpenAI endpoint');
|
||||
expectSame('model-name', $generic[1]['payload']['model'], 'profile model selection');
|
||||
expectSame('clinical prompt', $generic[1]['payload']['messages'][0]['content'], 'OpenAI prompt');
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\common\service;
|
||||
|
||||
// Adapt the existing synchronous HTTP fixtures to the cancellable multi pump.
|
||||
function curl_multi_init(): \stdClass { return new \stdClass(); }
|
||||
function curl_multi_add_handle(\stdClass $multi, \stdClass $handle): int { $multi->handle = $handle; return CURLM_OK; }
|
||||
function curl_multi_exec(\stdClass $multi, ?int &$running): int {
|
||||
curl_exec($multi->handle);
|
||||
$multi->completion = ['handle' => $multi->handle, 'result' => curl_errno($multi->handle)];
|
||||
$running = 0;
|
||||
return CURLM_OK;
|
||||
}
|
||||
function curl_multi_info_read(\stdClass $multi): array|false {
|
||||
$info = $multi->completion ?? false;
|
||||
unset($multi->completion);
|
||||
return $info;
|
||||
}
|
||||
function curl_multi_select(\stdClass $multi, float $timeout): int { return 0; }
|
||||
function curl_multi_remove_handle(\stdClass $multi, \stdClass $handle): int { return CURLM_OK; }
|
||||
function curl_multi_close(\stdClass $multi): void {}
|
||||
Reference in New Issue
Block a user