This commit is contained in:
Your Name
2026-10-22 16:42:26 +08:00
parent 7982aab721
commit 14abf67d0d
17 changed files with 1179 additions and 54 deletions
@@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
namespace think\facade {
class Cache {
public static array $items = [];
public static int $lastTtl = 0;
public static bool $unavailable = false;
public static function get(string $key) {
if (self::$unavailable) throw new \RuntimeException('offline');
return self::$items[$key] ?? null;
}
public static function set(string $key, $value, int $ttl): void {
if (self::$unavailable) throw new \RuntimeException('offline');
self::$items[$key] = $value;
self::$lastTtl = $ttl;
}
}
}
namespace app\adminapi\service {
function config(string $name): array { return $GLOBALS['compactionConfig']; }
}
namespace app\common\service {
class DifyChatService {
public static array $calls = [];
public static bool $fail = false;
public static function chat($profile, $inputs, $query, $user, $files = [], $options = []): array {
self::$calls[] = compact('profile', 'inputs', 'query', 'options');
if (self::$fail) throw new \RuntimeException('fixture failure');
return ['ok' => true, 'content' => '合成证据片段 ' . $inputs['chunk_index']];
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use app\adminapi\logic\tcm\DiagnosisAiLogic;
use app\adminapi\service\AssistantSseTiming;
use app\common\service\DifyChatService;
use think\facade\Cache;
function compactExpect(bool $ok, string $message): void {
if (!$ok) throw new \RuntimeException($message);
}
$compactionConfig = ['context_compaction_cache_ttl' => 300,
'models' => ['qwen' => ['name' => 'synthetic', 'api_key' => 'fixture-secret']]];
$fit = new \ReflectionMethod(DiagnosisAiLogic::class, 'fitContextForPrompt');
$inputs = new \ReflectionMethod(DiagnosisAiLogic::class, 'buildUpstreamInputs');
$source = 'BEGIN-unique ' . str_repeat('临床合成来源;', 11000) . ' END-unique';
$original = ['case_text' => $source, 'case_lines' => [$source],
'case_json' => json_encode(['case_lines' => [$source]], JSON_UNESCAPED_UNICODE),
'fingerprint' => hash('sha256', $source), 'compaction_cache_scope' => 'authorized-scope-a',
'demographics' => '合成病例', 'source_diagnosis_ids' => [1, 2],
'source_summary' => ['diagnosis_count' => 2, 'snapshot_complete' => true],
'files' => [['type' => 'image', 'url' => 'https://example.test/synthetic.png']]];
$apply = static function (array &$context, string $profile = 'qwen') use ($fit): bool {
return $fit->invokeArgs(null, [&$context, $profile, new AssistantSseTiming()]);
};
$cold = $original;
compactExpect($apply($cold), 'cold compaction succeeds');
compactExpect(count(DifyChatService::$calls) === 2, 'every original chunk is read');
$covered = '';
foreach (DifyChatService::$calls as $call) {
preg_match('/<PATIENT_SOURCE_FRAGMENT>\n(.*)\n<\/PATIENT_SOURCE_FRAGMENT>/su', $call['query'], $match);
$covered .= $match[1];
compactExpect($call['options']['knowledge_mode'] === 'evidence', 'extractor excludes clinical reference synthesis');
}
compactExpect($covered === $source, 'UTF-8 chunks cover the entire exact source in order');
$wire = $inputs->invoke(null, $cold, 'case', 'test');
compactExpect(strlen($wire['herbs_json']) < 2000 && !str_contains($wire['herbs_json'], $source), 'Dify no longer resends the original large source');
compactExpect($cold['fingerprint'] === $original['fingerprint'], 'original provenance stays intact');
compactExpect($cold['files'] === $original['files'] && $cold['source_diagnosis_ids'] === [1, 2], 'attachments and authorization scope are preserved');
compactExpect($cold['source_summary']['analyzed_source_bytes'] === strlen($source), 'complete source byte count is preserved');
$warm = $original;
compactExpect($apply($warm) && $warm['compaction_cache_hit'] === true, 'identical freshly authorized source is reused');
compactExpect(count(DifyChatService::$calls) === 2, 'warm request makes zero new compaction calls');
foreach (['source', 'scope', 'model', 'credential'] as $change) {
$next = $original;
$profile = 'qwen';
if ($change === 'source') $next['case_text'] = 'X' . substr($source, 1);
if ($change === 'scope') $next['compaction_cache_scope'] = 'authorized-scope-b';
if ($change === 'model') $profile = 'openai';
if ($change === 'credential') $compactionConfig['models']['qwen']['api_key'] = 'rotated-fixture';
$count = count(DifyChatService::$calls);
compactExpect($apply($next, $profile) && count(DifyChatService::$calls) === $count + 2, "$change invalidates cache");
}
foreach (array_keys(Cache::$items) as $key) compactExpect(!str_contains($key, 'fixture') && !str_contains($key, '来源'), 'cache keys contain no credentials or source text');
Cache::$items = [];
DifyChatService::$fail = true;
$broken = $original;
compactExpect(!$apply($broken) && Cache::$items === [] && $broken === $original, 'failed extraction cannot poison cache or mutate context');
DifyChatService::$fail = false;
Cache::$unavailable = true;
$uncached = $original;
compactExpect($apply($uncached) && !$uncached['compaction_cache_hit'], 'cache outages fall back to full fresh compaction');
Cache::$unavailable = false;
$compactionConfig['context_compaction_cache_ttl'] = 10000;
$fresh = $original;
compactExpect($apply($fresh) && Cache::$lastTtl === 600, 'cache retention has a hard upper bound');
$compactionConfig['context_compaction_cache_ttl'] = 0;
$fresh = $original;
$count = count(DifyChatService::$calls);
compactExpect($apply($fresh) && count(DifyChatService::$calls) === $count + 2, 'cache can be disabled');
$short = $original;
$short['case_text'] = str_repeat('a', 120000);
$copy = $short;
compactExpect($apply($short) && $short === $copy, 'exact threshold keeps the source untouched');
echo "AI context compaction latency and isolation: OK\n";
}
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace app\common\service {
class DifyChatService {
public static array $blocking = [];
public static bool $emit = false;
public static int $delayUs = 0;
public static function streamChat($profile, $inputs, $query, $user, $onDelta, $abort, $files): array {
if (self::$delayUs) usleep(self::$delayUs);
if (self::$emit) $onDelta('真实合成模型正文');
return ['ok' => false, 'error_code' => 'INCOMPLETE_RESPONSE', 'error' => 'fixture'];
}
public static function chat($profile, $inputs, $query, $user, $files = [], $options = []): array {
self::$blocking[] = $options;
return ['ok' => true, 'content' => '合成模型最终回答'];
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use app\adminapi\logic\tcm\DiagnosisAiLogic;
use app\adminapi\service\AssistantSseTiming;
use app\common\service\DifyChatService;
function retryExpect(bool $ok, string $message): void {
if (!$ok) throw new \RuntimeException($message);
}
$prepared = ['profile' => 'qwen', 'task' => 'summary', 'query' => '合成资料', 'upstream_timeout' => 90];
DifyChatService::$delayUs = 2000;
$run = static function (array $request, ?callable $abort = null) {
return DiagnosisAiLogic::streamPreparedAssistant($request, static fn (string $text): bool => true,
$abort, new AssistantSseTiming());
};
retryExpect($run($prepared) !== null && count(DifyChatService::$blocking) === 1, 'one pre-delta compatibility retry is retained');
$timeout = DifyChatService::$blocking[0]['timeout'];
retryExpect($timeout > 0 && $timeout < 90, 'blocking retry only gets the remaining original budget');
DifyChatService::$blocking = [];
DifyChatService::$emit = true;
retryExpect($run($prepared) === null && DifyChatService::$blocking === [], 'no re-submission after real text delivery');
DifyChatService::$emit = false;
retryExpect($run($prepared, static fn (): bool => true) === null && DifyChatService::$blocking === [], 'no compatibility request after disconnect');
DifyChatService::$delayUs = 1100000;
$prepared['upstream_timeout'] = 1;
retryExpect($run($prepared) === null && DifyChatService::$blocking === [], 'an exhausted stream cannot start another timeout window');
echo "Diagnosis AI assistant retry budget: OK\n";
}
@@ -62,6 +62,28 @@ timingExpect(!isset($one->event('upstream_done', ['error_code' => 'API_KEY_SECRE
$startedAt = hrtime(true);
timingExpect(AssistantSseTiming::elapsedMs($startedAt) >= 0, 'monotonic elapsed time is non-negative');
timingExpect(isset($first['request_elapsed_ms']) && is_int($first['request_elapsed_ms']), 'request timing includes the phase before SSE');
timingExpect($one->event('first_delta')['request_elapsed_ms'] >= $first['request_elapsed_ms'], 'full request time remains monotonic across preparation and first text');
timingExpect($one->event('prepare', ['compaction_cache_hit' => true])['compaction_cache_hit'] === true, 'cache hit is safe boolean telemetry');
// Exercise a buffered web-style channel: timing must reach disk before HTTP end/exit.
$app = new \think\App(dirname(__DIR__) . '/');
$directory = sys_get_temp_dir() . '/zyt-ai-timing-' . bin2hex(random_bytes(8));
$app->config->set(['default' => 'timing', 'channels' => ['timing' => [
'type' => 'File', 'path' => $directory, 'single' => 'timing', 'realtime_write' => false,
]]], 'log');
$logger = $app->make('log');
$channel = $logger->channel('timing');
(new ReflectionProperty(\think\log\Channel::class, 'lazy'))->setValue($channel, true);
$logger->info('buffered control');
$logFile = $directory . '/timing.log';
timingExpect(!is_file($logFile), 'control channel really buffers before the SSE timing write');
$one->log('first_delta', ['duration_ms' => 123, 'api_key' => 'must-not-be-logged']);
timingExpect(is_file($logFile), 'SSE timing persists immediately without HTTP-end save');
$logged = file_get_contents($logFile);
timingExpect(str_contains($logged, $one->id()) && !str_contains($logged, 'must-not-be-logged'), 'persisted timing remains patient and credential free');
unlink($logFile);
rmdir($directory);
$controller = file_get_contents(dirname(__DIR__) . '/app/adminapi/controller/tcm/DiagnosisController.php');
$logic = file_get_contents(dirname(__DIR__) . '/app/adminapi/logic/tcm/DiagnosisAiLogic.php');
@@ -97,6 +97,13 @@ namespace {
}
}
$ancientReuseRequests = [];
$evidence = '合成患者糖尿病。只提取来源事实。';
$extracted = DifyChatService::chat('qwen', ['analysis_stage' => 'evidence_chunk'], $evidence,
'offline-user', [], ['knowledge_mode' => 'evidence']);
ancientReuseExpect($extracted['ok'] && $ancientReuseRequests[0]['query'] === $evidence,
'server-selected evidence extraction adds no clinical knowledge facts');
ancientReuseExpect($extracted['ancient_book_sources'] === [], 'extractor does not claim book citations');
$indexProperty->setValue(null, null);
echo "Dify ancient-books reuse contract passed.\n";
}