Merge branch 'ai-12-4'

This commit is contained in:
Your Name
2026-12-05 11:00:01 +08:00
5 changed files with 77 additions and 3 deletions
@@ -1627,6 +1627,10 @@ class DifyChatService
$patterns = [
'authentication' => '/\b(?:api[ _-]?key|credentials?|authentication|authorization)\b.{0,80}\b(?:invalid|missing|failed|unauthorized)\b|\b(?:invalid|missing)\b.{0,40}\b(?:api[ _-]?key|credentials?)\b/i',
'quota' => '/\b(?:quota|rate[ _-]?limit)\b.{0,60}\b(?:exceeded|exhausted|reached|insufficient)\b|\binsufficient\s+(?:quota|credits?|balance)\b/i',
// Dify 把工作流内模型节点的失败包成 400 invalid_param「Run failed: ...」返回,
// 与真正的参数错误同码。只有带模型插件调用痕迹、且是网关无可用账号、5xx/408/429、
// 过载或超时这类暂时性故障时才归为 unavailable(可重试);404 等配置错误不在此列。
'unavailable' => '/\b(?:Run failed|PluginInvokeError|PluginDaemon\w*Error|InvokeError)\b.{0,4000}?(?:\bstatus code (?:408|429|5\d\d)\b|no_available_provider|no eligible account|service_unavailable|upstream_unavailable|\bserver_error\b|\boverloaded\b|killed by timeout|\btimed out\b)/is',
'response_mode_unsupported' => '/\bresponse_mode\b.{0,100}\b(?:invalid|unsupported|not supported|blocking|streaming)\b|\bstreaming\b.{0,50}\b(?:not supported|unsupported|disabled)\b/i',
'file_count' => '/\b(?:number|count)\s+of\s+(?:uploaded\s+)?(?:files|images|attachments)\b.{0,100}\b(?:limit|exceed|maximum)\b|\btoo many\s+(?:files|images|attachments)\b|\b(?:file|image|attachment)[ _-]?(?:count|number|limit)\b.{0,80}\b(?:exceed|maximum|limit)\b/i',
'file_size' => '/\b(?:file|image|attachment)(?:\s+size)?\b.{0,80}\b(?:too large|size limit|maximum size|exceeds? (?:the )?(?:size|maximum))\b/i',
@@ -110,9 +110,17 @@ final class PrescriptionAiPolicy
? 'cancelled' : 'failed';
}
public static function retryAt(int $attempts, int $now, bool $retryable, int $maxAttempts): ?int
public static function retryAt(int $attempts, int $now, bool $retryable, int $maxAttempts, string $code = ''): ?int
{
return $retryable && $attempts < $maxAttempts ? $now + ($attempts <= 1 ? 30 : 120) : null;
if (!$retryable || $attempts >= $maxAttempts) {
return null;
}
// 模型网关暂时无可用账号/繁忙时往往持续数分钟,30 秒内重试只会再撞一次;
// 拉长等待让重试越过这段时间。已完成的阶段有缓存,重试从失败处继续。
if (in_array($code, ['UPSTREAM_BUSY', 'UPSTREAM_UNAVAILABLE'], true)) {
return $now + ($attempts <= 1 ? 120 : 600);
}
return $now + ($attempts <= 1 ? 30 : 120);
}
public static function errorMessage(string $code): string
@@ -404,7 +404,7 @@ final class PrescriptionAiStore
$now = time();
$code = preg_match('/^[A-Z0-9_]{1,64}$/D', $code) ? $code : 'INTERNAL_ERROR';
$next = PrescriptionAiPolicy::retryAt((int) $task['attempts'], $now, $retryable,
max(1, (int) config('prescription_analysis.max_attempts', 3)));
max(1, (int) config('prescription_analysis.max_attempts', 3)), $code);
Db::name('prescription_ai_task')->where('id', $task['id'])->where('lock_token', $task['lock_token'])
->where('status', 'running')->update([
'status' => $next === null ? 'failed' : 'retry_wait', 'next_run_at' => $next ?? $now,
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
/**
* Dify 把工作流内模型节点的失败包成 400 invalid_param「Run failed: ...」返回。
* 模型网关暂时无可用账号、5xx、超时等必须归为可重试的 UPSTREAM_BUSY,
* 配置性 404 与真正的参数错误仍是 UPSTREAM_REJECTED。纯离线,不发请求。
*/
require dirname(__DIR__) . '/vendor/autoload.php';
use app\common\service\DifyChatService;
$checks = 0;
$expect = static function (bool $ok, string $message) use (&$checks): void {
if (!$ok) { throw new RuntimeException($message); }
$checks++;
};
$call = static function (string $method, array $args) {
$reflection = new ReflectionMethod(DifyChatService::class, $method);
$reflection->setAccessible(true);
return $reflection->invokeArgs(null, $args);
};
$secret = 'fixture-only-secret';
$body = static fn (string $message): string => json_encode(['code' => 'invalid_param', 'message' => $message, 'status' => 400]);
$transient = [
// 2026-12-05 生产实际出现的网关故障形态
'Run failed: req_id: 0123456789 PluginInvokeError: {"args":{"description":"[models] Error: API request failed with status code 503: {\"error\":{\"message\":\"The gateway found no eligible account for this request.\",\"type\":\"server_error\",\"code\":\"no_available_provider\"}}"},"error_type":"InvokeError"} ' . $secret,
'Run failed: [openai_api_compatible] Error: req_id: ab12 PluginDaemonInternalServerError: killed by timeout',
"Run failed: req_id: ab12 PluginInvokeError: {\"args\":{},\"error_type\":\"ValueError\",\"message\":\"{'type': 'server_error', 'code': 'upstream_unavailable'}\"}",
"Run failed: req_id: ab12 PluginInvokeError: {\"args\":{},\"error_type\":\"ValueError\",\"message\":\"{'message': 'Our servers are currently overloaded. Please try again later.'}\"}",
'Run failed: [models] Error: API request failed with status code 408: request timeout',
'Run failed: [models] Error: API request failed with status code 502: bad gateway',
];
foreach ($transient as $message) {
$meta = $call('upstreamErrorMetadata', [json_decode($body($message), true)]);
$expect($meta['upstream_code'] === 'invalid_param' && $meta['upstream_reason'] === 'unavailable', 'transient: ' . substr($message, 0, 80));
$result = $call('formatUpstreamRejection', [['http_code' => 400, 'body' => $body($message)], 10]);
$expect($result['error_code'] === 'UPSTREAM_BUSY' && !str_contains(json_encode($result), $secret), 'retryable busy: ' . substr($message, 0, 80));
// 同一载荷以 SSE error 帧到达(HTTP 200)时走同一分类
$stream = $call('formatUpstreamRejection', [['http_code' => 200, 'upstream_error' => true,
'upstream_reason' => $meta['upstream_reason'], 'upstream_code' => $meta['upstream_code']], 10]);
$expect($stream['error_code'] === 'UPSTREAM_BUSY', 'stream frame busy: ' . substr($message, 0, 80));
}
$rejected = [
'Run failed: [models] Error: API request failed with status code 404: 404 page not found',
'query is required',
'Run failed: [models] Error: API request failed with status code 401: invalid api key',
'inputs too long',
];
foreach ($rejected as $message) {
$result = $call('formatUpstreamRejection', [['http_code' => 400, 'body' => $body($message)], 10]);
$expect($result['error_code'] !== 'UPSTREAM_BUSY', 'not an outage: ' . $message);
}
echo "Dify gateway outage classification (no network): {$checks} checks OK\n";
@@ -36,6 +36,9 @@ $expect(Policy::aggregate(['success', 'failed']) === 'partial', 'one result rema
$expect(Policy::aggregate(['failed', 'failed']) === 'failed', 'both failures');
$expect(Policy::aggregate(['success', 'success']) === 'success', 'both results');
$expect(Policy::retryAt(3, 100, true, 3) === null && Policy::retryAt(1, 100, false, 3) === null, 'bounded and terminal failures');
$expect(Policy::retryAt(1, 100, true, 3) === 130 && Policy::retryAt(2, 100, true, 3) === 220, 'ordinary retry backoff unchanged');
$expect(Policy::retryAt(1, 100, true, 3, 'UPSTREAM_BUSY') === 220 && Policy::retryAt(2, 100, true, 3, 'UPSTREAM_UNAVAILABLE') === 700
&& Policy::retryAt(3, 100, true, 3, 'UPSTREAM_BUSY') === null, 'gateway outages wait longer but stay bounded');
$cipher = new Cipher(str_repeat('test-only-key-', 4));
$secret = ['report' => 'private synthetic fixture'];
$encrypted = $cipher->encrypt($secret, 'report:1');