aisop/tests/VisionDecision.Smoke/ContinuousCheckTests.cs

187 lines
15 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.Concurrent;
using SopHelper.Engine.Common;
using SopHelper.Engine.Sop;
internal static class ContinuousCheckTests
{
private static void Check(bool condition, string reason) { if (!condition) throw new Exception(reason); }
private static async Task Until(Func<bool> condition)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
while (!condition() && watch.Elapsed.TotalSeconds < 3) await Task.Delay(5);
Check(condition(), "异步限时检查没有推进");
}
private sealed class Client : IVisionDecisionClient
{
public bool SupportsSequences => true;
public ConcurrentQueue<(VisionDecisionRequest Request, TaskCompletionSource<VisionDecisionResult> Result)> Calls = new();
public Task<VisionDecisionResult> DecideAsync(VisionDecisionRequest request, CancellationToken token)
{
var result = new TaskCompletionSource<VisionDecisionResult>(); Calls.Enqueue((request, result)); return result.Task;
}
}
private static SopConfig Config(int steps = 2)
{
var config = new SopConfig(); config.Sop.Settings.AutoResetOnComplete = false;
for (var i = 0; i < steps; i++)
{
config.Sop.Regions["r" + i] = new() { X1 = i * 100, Y1 = 0, X2 = i * 100 + 90, Y2 = 100 };
config.Sop.Steps.Add(new() { Id = i + 1, Name = "工序" + i, Description = "结果到位",
Detection = new() { Method = ConditionMethod.HandInRegion, Region = "r" + i, Hand = "right", StableFrames = 1 },
AiConfirmation = new() { CheckWindowMs = 2000,
RetryDelayMs = 500, ObservationSampleMs = 100 } });
}
return config;
}
private static FrameResult Frame(int id, double seconds, int x) => new() { FrameId = id, SourceSeconds = seconds,
Timestamp = DateTime.UnixEpoch.AddSeconds(seconds), Size = (200, 100),
Hands = [new() { HandType = HandType.Right, Rect = new(x, 20, 10, 10) }] };
public static async Task RunAsync()
{
// 旧配方中的次数上限不再生效,超过原上限20次仍可在窗口内通过。
var unlimitedConfig = Config(1);
unlimitedConfig.Sop.Steps[0].AiConfirmation!.CheckWindowMs = 10000;
unlimitedConfig.Sop.Steps[0].AiConfirmation!.RetryDelayMs = 50;
var legacyYaml = SopConfigLoader.ToYaml(unlimitedConfig).Replace("check_window_ms: 10000", "check_window_ms: 10000\n max_checks: 1\n check_settle_ms: 3000");
var legacyConfig = SopConfigLoader.Parse(legacyYaml);
Check(!SopConfigLoader.ToYaml(legacyConfig).Contains("max_checks")
&& !SopConfigLoader.ToYaml(legacyConfig).Contains("check_settle_ms"), "旧次数和停稳参数须忽略且不再保存");
var unlimitedClient = new Client();
var unlimited = new SopEngine { VisionDecisionClient = unlimitedClient };
unlimited.Load(legacyConfig); unlimited.Start();
var unlimitedResults = 0;
unlimited.DecisionEvaluated += (_, _, _) => unlimitedResults++;
void UnlimitedFeed(int id) => unlimited.ProcessFrame(Frame(id, id * .01, 10), () => [(byte)id]);
UnlimitedFeed(0);
for (var attempt = 1; attempt <= 21; attempt++)
{
await Until(() => { UnlimitedFeed(attempt); return unlimitedClient.Calls.Count == attempt; });
unlimitedClient.Calls.ElementAt(attempt - 1).Result.SetResult(new(attempt == 21, .99, "检查结果"));
await Until(() => { unlimited.ProcessFrame(Frame(attempt, attempt * .01, 10)); return unlimitedResults == attempt; });
if (attempt < 21) Check(unlimited.CurrentStep?.Id == 1 && unlimited.SkippedSteps.Count == 0,
"窗口内不能因为检查次数提前跳过");
}
Check(unlimited.State == EngineState.Completed && unlimited.RoundPassed, "第21次检查通过应正常完成");
unlimited.Stop();
var source = Enumerable.Range(0, 7).Select(i => new VisionEvidenceFrame(i, DateTime.UnixEpoch.AddSeconds(i), [(byte)i], i)).ToArray();
Check(InspectionFrameSelector.Select(source, new Dictionary<long, double>(), [source[^1]], 2.4)?.FrameId == 3,
"已缓存较长操作片段的首次检查应覆盖中段,避免只检查动作结束后的尾图");
var coverage = new Dictionary<long, double> { [6] = 6 };
var recovered = InspectionFrameSelector.Select(source, coverage, []);
Check(recovered?.FrameId == 3, "已经检查过较晚帧后,重试须能补查缓存中间帧,不能永远只检查更晚画面");
Check(InspectionFrameSelector.Select(source, new Dictionary<long, double> { [3] = 3 }, [])?.FrameId == 6,
"有新画面时应交替检查新结果,不能把全部次数都用于历史补查");
Check(InspectionFrameSelector.Select(source, new Dictionary<long, double> { [1] = 1, [3] = 3 }, [], preferLatest: true)?.FrameId == 6,
"窗口硬截止前必须优先检查最新未检结果,不能把最后机会用于较早帧");
coverage[3] = 3;
Check(InspectionFrameSelector.Select(source, coverage, [])?.FrameId != 3, "已检查的历史帧不能重复消耗次数");
var client = new Client(); var engine = new SopEngine { VisionDecisionClient = client }; engine.Load(Config()); engine.Start();
var snapshots = new List<StepSnapshot>(); int evaluated = 0, alarms = 0; bool? passed = null;
engine.StepSnapshotChanged += snapshots.Add; engine.DecisionEvaluated += (_, _, _) => evaluated++;
engine.ViolationRaised += _ => alarms++; engine.RoundFinished += result => passed = result;
void Feed(int id, double seconds, int x) => engine.ProcessFrame(Frame(id, seconds, x), () => [(byte)id]);
Feed(1, 0, 10); Feed(2, .05, 30);
Check(client.Calls.Count == 0, "进入后仍在移动不能立即检查");
Feed(3, .3, 30); await Until(() => client.Calls.Count == 1);
var first = client.Calls.ElementAt(0);
Check(first.Request.FrameId == 3, "停稳后须使用当时的新画面,不能送刚进入的旧画面");
Feed(4, .4, 120); Feed(5, .6, 120); // 人继续做第二步,第一步 AI 仍在途。
first.Result.SetResult(new(false, .9, "未完成"));
await Until(() => { engine.ProcessFrame(Frame(5, .6, 120)); return evaluated == 1; });
await Until(() => { Feed(5, .6, 120); return client.Calls.Count == 2; });
var retry = client.Calls.ElementAt(1);
Check(retry.Request.StepId == 1 && retry.Request.FrameId > first.Request.FrameId, "窗口内重试应使用新证据");
retry.Result.SetResult(new(false, .9, "仍未完成"));
await Until(() => { engine.ProcessFrame(Frame(5, .6, 120)); return evaluated == 2; });
Check(engine.CurrentStep?.Id == 1 && !snapshots.Any(s => s.IsSkipped) && alarms == 0,
"多次未通过但窗口未到期时必须继续等待,不能提前跳过");
Feed(6, 2.1, 120);
Check(engine.CurrentStep?.Id == 2 && snapshots.Any(s => s.StepId == 1 && s.IsSkipped && !s.IsMet)
&& alarms == 1, "检查窗口到期未通过必须标记跳过、告警并继续下一步");
Feed(7, 2.3, 120); await Until(() => { Feed(7, 2.3, 120); return client.Calls.Count == 3; });
var next = client.Calls.ElementAt(2);
Check(next.Request.StepId == 2 && next.Request.FrameId == 7 && next.Request.SourceSeconds == 2.3,
"下一步须使用当前新图,不能回填已经过期的等待期间旧图");
next.Result.SetResult(new(true, .99, "第二步结果可见"));
await Until(() => { engine.ProcessFrame(Frame(7, 2.3, 120)); return engine.State == EngineState.Completed; });
Check(passed == false && !engine.RoundPassed && engine.Statistics.CompletedCount == 0 && engine.SkippedSteps.Contains(1),
"跳过不能算合格完成或增加合格产量");
engine.Reset(); Check(engine.SkippedSteps.Count == 0 && !engine.HasPendingDecision, "复位必须清空跳过状态和所有窗口");
// 服务永不返回:窗口硬截止取消本步;迟到的 true 不得影响下一步。
var slow = new Client(); var timed = new SopEngine { VisionDecisionClient = slow }; timed.Load(Config()); timed.Start();
var timedOut = 0;
timed.DecisionEvaluated += (_, result, accepted) =>
{ if (!accepted && result.EffectiveStatus == VisionDecisionStatus.Insufficient && result.Reason.Contains("未获得模型结果")) timedOut++; };
void SlowFeed(int id, double seconds, int x) => timed.ProcessFrame(Frame(id, seconds, x), () => [(byte)id]);
SlowFeed(1, 0, 10); SlowFeed(2, .2, 10); await Until(() => slow.Calls.Count == 1);
SlowFeed(3, .4, 120); SlowFeed(4, .6, 120); SlowFeed(5, 2.1, 120);
Check(timed.CurrentStep?.Id == 2 && timed.SkippedSteps.Contains(1) && timedOut == 1,
"服务挂起不能阻塞到检查窗口之外,且须明确反馈未收到结果而不是误记为模型否决");
slow.Calls.ElementAt(0).Result.SetResult(new(true, 1, "迟到结果"));
SlowFeed(6, 2.3, 120); await Until(() => { SlowFeed(6, 2.3, 120); return slow.Calls.Count == 2; });
Check(timed.CurrentStep?.Id == 2 && timed.SkippedSteps.Contains(1), "已跳过步骤的迟到结果不能放行后续步骤");
timed.Stop(); Check(!timed.HasPendingDecision, "停止必须取消限时检查和未来步骤缓存");
var sameRegion = Config(); sameRegion.Sop.Steps[1].Detection!.Region = "r0";
var same = new SopEngine { VisionDecisionClient = new Client() }; same.Load(sameRegion); same.Start();
var secondTriggered = false;
same.TriggerEvaluated += (id, _, result, _) => { if (id == 2 && result.IsMet) secondTriggered = true; };
void SameFeed(int id, double seconds, int x) => same.ProcessFrame(Frame(id, seconds, x), () => [(byte)id]);
SameFeed(1, 0, 10); SameFeed(2, .1, 10); SameFeed(3, .3, 10);
Check(!secondTriggered, "同区域持续停留不得直接触发下一步");
SameFeed(4, .5, 35);
Check(secondTriggered, "同区域停稳后开始新运动,应能触发下一步,不能强求手离开操作区");
same.Stop();
var hintConfig = Config(1);
var hinted = new Client(); var following = new SopEngine { VisionDecisionClient = hinted };
following.Load(hintConfig); following.Start(); var hintResults = 0;
following.DecisionEvaluated += (_, _, _) => hintResults++;
void HintFeed(int id, double seconds) => following.ProcessFrame(Frame(id, seconds, 10), () => [(byte)id]);
HintFeed(0, 0); HintFeed(1, .2); await Until(() => hinted.Calls.Count == 1);
HintFeed(2, .4); hinted.Calls.ElementAt(0).Result.SetResult(new(true, .7, "结果尚不够清晰"));
await Until(() => { following.ProcessFrame(Frame(2, .4, 10)); return hintResults == 1; });
await Until(() => { HintFeed(2, .4); return hinted.Calls.Count == 2; });
HintFeed(3, .6); HintFeed(4, .8); hinted.Calls.ElementAt(1).Result.SetResult(new(true, .7, "仍未达到完成门槛"));
await Until(() => { following.ProcessFrame(Frame(4, .8, 10)); return hintResults == 2; });
await Until(() => { HintFeed(4, .8); return hinted.Calls.Count == 3; });
Check(following.State == EngineState.Running && hinted.Calls.ElementAt(2).Request.FrameId == 4,
"低于阈值的正向线索不能放行,但下一次检查应跟进新结果,不能回退到较早历史帧");
following.Stop();
var temporalConfig = Config();
temporalConfig.Sop.Steps[0].AiConfirmation = new() { CheckWindowMs = 10000, RetryDelayMs = 2500, ObservationMinMs = 5000 };
temporalConfig.Sop.Steps[1].AiConfirmation = new() { CheckWindowMs = 10000, EvidenceMode = VisionEvidenceMode.Sequence };
var temporalClient = new Client(); var temporal = new SopEngine { VisionDecisionClient = temporalClient };
temporal.Load(temporalConfig); temporal.Start(); var frameIndex = 0;
void TemporalFeed(double seconds, int x = 120) => temporal.ProcessFrame(Frame(frameIndex++, seconds, x), () => [(byte)frameIndex]);
TemporalFeed(0, 10);
TemporalFeed(2.8);
await Until(() => temporalClient.Calls.Count == 1);
Check(temporalClient.Calls.ElementAt(0).Request.SourceSeconds == 2.8, "测试前序结果必须来自实际较晚帧");
temporalClient.Calls.ElementAt(0).Result.SetResult(new(true, .99, "前序完成"));
await Until(() => { temporal.ProcessFrame(Frame(frameIndex, 2.8, 120)); return temporal.CurrentStep?.Id == 2; });
foreach (var seconds in new[] { 3.2, 3.6, 4.0 }) TemporalFeed(seconds);
Check(temporalClient.Calls.Count == 1, "预热窗口就绪不代表前序完成后的有效过程片段已经足够,不能只看三张图就送检");
foreach (var seconds in new[] { 4.4, 4.8, 5.3, 5.8 }) TemporalFeed(seconds);
await Until(() => temporalClient.Calls.Count == 2);
var effective = temporalClient.Calls.ElementAt(1).Request.Frames!;
Check(effective[^1].SourceSeconds - effective[0].SourceSeconds >= 2.4, "首次过程检查必须覆盖配置要求的实际有效片段时长");
temporal.Stop();
var leaveConfig = Config(); leaveConfig.Sop.Steps[1].Detection!.Method = ConditionMethod.HandLeaveRegion;
var leaveClient = new Client(); var leave = new SopEngine { VisionDecisionClient = leaveClient };
leave.Load(leaveConfig); leave.Start();
void LeaveFeed(int id, double seconds, int x) => leave.ProcessFrame(Frame(id, seconds, x), () => [(byte)id]);
LeaveFeed(0, 0, 10); LeaveFeed(1, .02, 120); LeaveFeed(2, .04, 10); LeaveFeed(3, .2, 10);
await Until(() => leaveClient.Calls.Count == 1);
leaveClient.Calls.ElementAt(0).Result.SetResult(new(true, .99, "前序结果"));
await Until(() => { leave.ProcessFrame(Frame(3, .2, 10)); return leave.CurrentStep?.Id == 2; });
LeaveFeed(4, .7, 10);
Check(leaveClient.Calls.Count == 1, "离散动作不能复用早于前序完成的旧离开事件");
LeaveFeed(5, .9, 120); LeaveFeed(6, 1.1, 10); LeaveFeed(7, 1.3, 10);
await Until(() => leaveClient.Calls.Count == 2);
Check(leaveClient.Calls.ElementAt(1).Request.SourceSeconds >= 1.1 && leaveClient.Calls.ElementAt(1).Request.TriggerObservation?.SourceSeconds == 1.1,
$"必须用前序结果之后新发生的离开事件触发检查:图={leaveClient.Calls.ElementAt(1).Request.SourceSeconds},触发={leaveClient.Calls.ElementAt(1).Request.TriggerObservation?.SourceSeconds}");
leave.Stop();
Console.WriteLine("PASS: 停稳触发、新帧重试、限时跳过、后续动作持续取证、挂起硬截止、迟到结果隔离和非合格整轮统计");
}
}