aisop/tests/VisionDecision.Smoke/ContinuousCheckTests.cs

160 lines
13 KiB
C#

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, MaxChecks = 2, CheckSettleMs = 150,
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()
{
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, .1, 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(() => { engine.ProcessFrame(Frame(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; });
Feed(6, 3.1, 120);
Check(engine.CurrentStep?.Id == 2 && snapshots.Any(s => s.StepId == 1 && s.IsSkipped && !s.IsMet)
&& alarms == 1, "限时多次未通过必须标记跳过、告警并继续下一步");
engine.ProcessFrame(Frame(6, 3.1, 120)); await Until(() => client.Calls.Count == 3);
var next = client.Calls.ElementAt(2);
Check(next.Request.StepId == 2 && next.Request.FrameId == 5 && next.Request.SourceSeconds == .6,
"下一步须使用等待期间的停稳边界原图及时间,提前触发不能消耗轮到本步后的检查预算");
next.Result.SetResult(new(true, .99, "第二步结果可见"));
await Until(() => { engine.ProcessFrame(Frame(6, 3.1, 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, "迟到结果"));
timed.ProcessFrame(Frame(5, 2.1, 120)); await Until(() => 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); hintConfig.Sop.Steps[0].AiConfirmation!.MaxChecks = 3;
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(() => { following.ProcessFrame(Frame(2, .4, 10)); 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(() => { following.ProcessFrame(Frame(4, .8, 10)); 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, CheckSettleMs = 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);
foreach (var seconds in new[] { .4, .8, 1.2, 1.6, 2.0, 2.4, 2.8 }) TemporalFeed(seconds);
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, .1, 120); LeaveFeed(2, .3, 10); LeaveFeed(3, .5, 10);
await Until(() => leaveClient.Calls.Count == 1);
leaveClient.Calls.ElementAt(0).Result.SetResult(new(true, .99, "前序结果"));
await Until(() => { leave.ProcessFrame(Frame(3, .5, 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,
"必须用前序结果之后新发生的离开事件触发检查,已采集的后续证据仍须保留");
leave.Stop();
Console.WriteLine("PASS: 停稳触发、新帧重试、限时跳过、后续动作持续取证、挂起硬截止、迟到结果隔离和非合格整轮统计");
}
}