-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimStewardPlugin.DataCaptureSuite.cs
More file actions
1843 lines (1622 loc) · 85 KB
/
SimStewardPlugin.DataCaptureSuite.cs
File metadata and controls
1843 lines (1622 loc) · 85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#if SIMHUB_SDK
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using IRSDKSharper;
using Sentry;
namespace SimSteward.Plugin
{
public partial class SimStewardPlugin
{
// ── Internal step enum ────────────────────────────────────────────────
private enum SuiteInternalStep
{
T0_Rewind, T0_FrameZero, T0_ScanCooldown, T0_SeekCapture, T0_CaptureSettle,
T1_Rewind, T1_FrameZero, T1_Sweep,
T2, T3, T4,
T5_Switch, T5_Settle,
T5b_Seek, T5b_Cycle, T5b_Settle,
T6,
T7_Rewind, T7_FrameZero, T7_Cooldown,
T8_Trigger, T8_Poll,
TDISC_Seek, TDISC_Settle, TDISC_Capture,
Done
}
// ── Suite fields ──────────────────────────────────────────────────────
private DataCaptureSuitePhase _suitePhase = DataCaptureSuitePhase.Idle;
private SuiteInternalStep _suiteStep = SuiteInternalStep.T0_Rewind;
private string _suiteTestRunId;
private Stopwatch _suiteStopwatch;
private DateTime _suiteEmitCompleteUtc;
private volatile bool _suiteCancelRequested;
private volatile bool _suiteStartRequested;
private string _lokiReadUrl;
private DataCaptureSuiteTestResult[] _suiteResults;
// ── Skip list ────────────────────────────────────────────────────────
private HashSet<string> _suiteSkipList = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// ── Preflight ────────────────────────────────────────────────────────
private enum PreflightStep
{
Idle,
Level1_Check,
Level2_SeekEnd, Level2_SettleEnd, Level2_SeekRestore, Level2_SettleRestore,
Level3_EmitProbe, Level3_WaitProbe, Level3_QueryProbe,
Complete
}
private volatile bool _preflightRequested;
private PreflightSnapshot _preflightSnapshot = new PreflightSnapshot();
private PreflightStep _preflightStep = PreflightStep.Idle;
private int _preflightSavedFrame;
private int _preflightSettleTicks;
private int _preflightLevel; // 0=not run, 1-3
private string _preflightCorrelationId;
private string _preflightReplayScope = "full";
private string _preflightProbeNonce;
private int _preflightProbeWaitTicks;
private long _preflightProbeEmitNs;
private volatile int _preflightLokiProbeResult = -2; // -2=not started, -1=error, 0+=count
private string _suitePreflightCorrelationId;
// T0 scan/select/capture
private List<(int frame, int lap, int carIdx)> _suiteScanCandidates;
private int _suiteFirstScanFrame;
private int[] _suiteSelectedFrames;
private int _suiteCaptureIdx;
private int _suiteCaptureTicks;
// T_60Hz: high-rate capture
private bool _suite60HzEnabled;
private HighRateTelemetryRecorder _suite60HzRecorder;
// T_DISC: data discovery
private int _suiteDiscPositionIdx;
private int[] _suiteDiscTargetFrames;
private int _suiteDiscSettleTicks;
// T0 / T7 shared: ground truth + seek state
private GroundTruthIncident[] _suiteGroundTruth;
private int _suiteGroundTruthIdx;
private GroundTruthIncident[] _suiteReseekCapture;
private int _suiteReseekIdx;
private int _suiteSeekCooldownTicks;
private int _suiteFrameZeroConsecutive;
private int _suiteSeekTimeoutTicks;
// T1: speed sweep
private int _suiteSpeedSweepIdx;
private int _suiteSpeedSweepTicks;
private int _suiteSpeedSweepFrameTarget;
private int _suiteSpeedSweepDetected;
private int _suiteSpeedSweepGtHits;
private int[] _suiteSpeedSweepBaselineFlags;
// T5b: camera cycle
private List<(int groupNum, string groupName)> _suiteCameraGroups;
private int _suiteCameraGroupIdx;
private int _suiteCamSettleTicks;
private int _suiteCamConfirmedMatches;
private readonly List<string> _suiteCamGroupsVisited = new List<string>();
// T8: FF sweep
private bool _suiteFfSweepTriggered;
private int _suiteT8PollTicks;
private bool _suiteT8BuildWasRunning;
// Sentry performance tracing
private ITransactionTracer _sentryTx;
private ISpan _sentryCurrentSpan;
// ── Public entry points (called from DataUpdate / DispatchAction) ──────
private void TryStartDataCaptureSuite(string[] skipIds = null)
{
if (!_preflightSnapshot.AllPassed)
{
_logger?.Warn("DataCaptureSuite: cannot start — preflight not passed.");
return;
}
if (_irsdk == null || !_irsdk.IsConnected)
{
_logger?.Warn("DataCaptureSuite: cannot start — iRacing not connected.");
return;
}
string simMode = _irsdk.Data?.SessionInfo?.WeekendInfo?.SimMode ?? "";
if (!string.Equals(simMode, "replay", StringComparison.OrdinalIgnoreCase))
{
_logger?.Warn("DataCaptureSuite: cannot start — not in replay mode.");
return;
}
_suiteSkipList = new HashSet<string>(skipIds ?? Array.Empty<string>(), StringComparer.OrdinalIgnoreCase);
// T7 depends on T0 ground truth — auto-skip if T0 is skipped
if (_suiteSkipList.Contains("T0")) _suiteSkipList.Add("T7");
_suiteStartRequested = true;
}
/// <summary>Called every telemetry tick from <c>OnIrsdkTelemetryDataForReplayIndex</c>.</summary>
private void ProcessDataCaptureSuiteTick()
{
// ── Preflight (independent of suite phase) ──
if (_preflightRequested)
{
_preflightRequested = false;
// Force-restart even if a previous run got stuck in an intermediate step
_preflightStep = PreflightStep.Idle;
_preflightLevel = 0;
_preflightCorrelationId = null;
_preflightSnapshot = new PreflightSnapshot();
try
{
BeginPreflight();
}
catch (Exception ex)
{
SentrySdk.CaptureException(ex);
_preflightSnapshot.Phase = "error";
_preflightSnapshot.Error = "BeginPreflight: " + ex.GetType().Name + ": " + ex.Message;
_preflightStep = PreflightStep.Complete;
}
}
if (_preflightStep != PreflightStep.Idle && _preflightStep != PreflightStep.Complete)
{
try { TickPreflight(); }
catch (Exception ex)
{
SentrySdk.CaptureException(ex);
_preflightSnapshot.Phase = "error";
_preflightSnapshot.Error = "TickPreflight@" + _preflightStep + ": " + ex.GetType().Name + ": " + ex.Message;
_preflightStep = PreflightStep.Complete;
}
}
if (_suitePhase == DataCaptureSuitePhase.Idle && !_suiteStartRequested && !_suiteCancelRequested)
return;
if (_suiteCancelRequested)
{
_suiteCancelRequested = false;
if (_suitePhase != DataCaptureSuitePhase.Idle)
{
try { _irsdk?.ReplaySetPlaySpeed(1, false); } catch { }
_suiteStopwatch?.Stop();
_suite60HzRecorder?.Dispose();
_suite60HzRecorder = null;
StopReplayIncidentIndexRecordModeLocked("suite_cancel");
EmitSuiteLifecycleEvent("sdk_capture_suite_cancelled", "Suite cancelled.", "T_cancel");
// Sentry: finish spans/transaction as cancelled
_sentryCurrentSpan?.Finish(SpanStatus.Cancelled);
_sentryCurrentSpan = null;
_sentryTx?.Finish(SpanStatus.Cancelled);
_sentryTx = null;
_suitePhase = DataCaptureSuitePhase.Cancelled;
}
return;
}
if (_suitePhase == DataCaptureSuitePhase.Idle && _suiteStartRequested)
{
_suiteStartRequested = false;
BeginDataCaptureSuite();
return;
}
if (_suitePhase == DataCaptureSuitePhase.Running)
{
TickSuiteRunning();
return;
}
if (_suitePhase == DataCaptureSuitePhase.AwaitingLoki)
TickAwaitingLoki();
}
public DataCaptureSuiteSnapshot BuildDataCaptureSuiteSnapshot()
{
var snap = new DataCaptureSuiteSnapshot
{
Phase = _suitePhase.ToString().ToLower(),
TestRunId = _suiteTestRunId ?? "",
ElapsedMs = _suiteStopwatch?.ElapsedMilliseconds ?? 0,
TestResults = _suiteResults,
CurrentStep = (int)_suiteStep,
CurrentStepName = _suitePhase == DataCaptureSuitePhase.Running
? _suiteStep.ToString()
: _suitePhase.ToString().ToLower(),
};
if (!string.IsNullOrEmpty(_suiteTestRunId) && !string.IsNullOrEmpty(_grafanaBaseUrl))
{
snap.GrafanaExploreUrl = LokiQueryClient.BuildGrafanaExploreUrl(_grafanaBaseUrl, _suiteTestRunId);
if (_suiteResults != null)
{
foreach (var r in _suiteResults)
{
if (!string.IsNullOrEmpty(r.EventName))
r.GrafanaEventUrl = LokiQueryClient.BuildGrafanaExploreUrl(_grafanaBaseUrl, _suiteTestRunId, r.EventName);
}
}
}
// Selected incidents summary for dashboard Test Cases panel
if (_suiteGroundTruth != null)
{
var summaries = new List<SelectedIncidentSummary>();
for (int i = 0; i < _suiteGroundTruth.Length; i++)
{
var gt = _suiteGroundTruth[i];
if (gt == null) continue;
string reason = "first_available";
if (_suiteSelectedFrames != null && i < _suiteSelectedFrames.Length)
{
// Determine selection reason based on scan candidates
var usedLaps = new HashSet<int>();
for (int j = 0; j < i; j++)
{
if (_suiteGroundTruth[j] != null) usedLaps.Add(_suiteGroundTruth[j].LapNum);
}
reason = gt.LapNum > DataCaptureSuiteConstants.T0_MinLapForSelection && !usedLaps.Contains(gt.LapNum)
? "different_lap" : "fallback";
}
summaries.Add(new SelectedIncidentSummary
{
Index = i,
Frame = gt.ReplayFrameNum,
Lap = gt.LapNum,
DriverName = gt.DriverName,
CarNumber = gt.CarNumber,
CustId = gt.CustId,
Reason = reason
});
}
if (summaries.Count > 0)
snap.SelectedIncidents = summaries.ToArray();
}
return snap;
}
// ── Skip helper ──────────────────────────────────────────────────────
private bool TrySkipTest(string testId, SuiteInternalStep nextStep)
{
if (!_suiteSkipList.Contains(testId)) return false;
var r = SuiteResult(testId);
if (r != null) r.Status = "skip";
_suiteStep = nextStep;
return true;
}
// ── Preflight state machine ───────────────────────────────────────────
private static PreflightMiniTest[] BuildPreflightMiniTests()
{
return new[]
{
new PreflightMiniTest { Id = "PC_WS", Name = "WebSocket connected", Level = 1 },
new PreflightMiniTest { Id = "PC_PLUGIN", Name = "Plugin responding", Level = 1 },
new PreflightMiniTest { Id = "PC_SIMHUB", Name = "SimHub HTTP server", Level = 1 },
new PreflightMiniTest { Id = "PC_GRAFANA", Name = "Grafana/Loki configured", Level = 1 },
new PreflightMiniTest { Id = "PC_IRACING", Name = "iRacing connected", Level = 1 },
new PreflightMiniTest { Id = "PC_REPLAY", Name = "Replay mode active", Level = 1 },
new PreflightMiniTest { Id = "PC_SESSIONS", Name = "Session map", Level = 1 },
new PreflightMiniTest { Id = "PC_CHECKERED", Name = "Session completed", Level = 2 },
new PreflightMiniTest { Id = "PC_RESULTS", Name = "Results populated", Level = 2 },
new PreflightMiniTest { Id = "PC_LOKI_RT", Name = "Loki roundtrip", Level = 3 },
};
}
private PreflightMiniTest PfTest(string id) =>
Array.Find(_preflightSnapshot.MiniTests ?? Array.Empty<PreflightMiniTest>(), t => t.Id == id);
private void BeginPreflight()
{
// Always run all levels in one pass
int targetLevel = 3;
// Generate correlation ID on first run or reset
if (string.IsNullOrEmpty(_preflightCorrelationId))
_preflightCorrelationId = Guid.NewGuid().ToString("D");
// Build mini-tests (keep existing results for lower levels if re-running)
if (_preflightSnapshot.MiniTests == null || _preflightLevel == 0)
_preflightSnapshot.MiniTests = BuildPreflightMiniTests();
_preflightSnapshot.Phase = "running";
_preflightSnapshot.CorrelationId = _preflightCorrelationId;
_preflightSnapshot.ReplayScope = _preflightReplayScope;
_preflightSavedFrame = SafeGetInt("ReplayFrameNum");
_preflightSettleTicks = 0;
_preflightLevel = targetLevel;
_preflightSnapshot.Level = targetLevel;
// Mark tests at current level as "running", deeper levels as "pending"
foreach (var t in _preflightSnapshot.MiniTests)
{
if (t.Level == targetLevel) t.Status = "running";
else if (t.Level > targetLevel) t.Status = "pending";
// Keep lower-level results as-is
}
_preflightStep = PreflightStep.Level1_Check;
}
private void TickPreflight()
{
switch (_preflightStep)
{
// ── Level 1: passive checks ──────────────────────────────────────
case PreflightStep.Level1_Check:
{
bool irsdkOk = _irsdk != null && _irsdk.IsConnected;
string simMode = "";
try { simMode = _irsdk?.Data?.SessionInfo?.WeekendInfo?.SimMode ?? ""; } catch { }
bool replayOk = string.Equals(simMode, "replay", StringComparison.OrdinalIgnoreCase);
SetPfTest("PC_WS", true, "Plugin-side always true"); // WS is checked dashboard-side; plugin always passes
SetPfTest("PC_PLUGIN", true, "Plugin responding");
SetPfTest("PC_SIMHUB", _simHubHttpListening, _simHubHttpListening ? "HTTP 8888 listening" : "HTTP 8888 not detected");
SetPfTest("PC_GRAFANA", !string.IsNullOrEmpty(_lokiBaseUrl), string.IsNullOrEmpty(_lokiBaseUrl) ? "lokiBaseUrl not set" : _lokiBaseUrl);
SetPfTest("PC_IRACING", irsdkOk, irsdkOk ? "SDK connected" : "SDK not connected");
SetPfTest("PC_REPLAY", replayOk, replayOk ? "SimMode=replay" : "SimMode=" + simMode);
// Session map from YAML
var sessionList = ReadSessionListFromYaml();
_preflightSnapshot.Sessions = sessionList;
_preflightSnapshot.ReplayFrameTotal = _replayFrameTotal;
bool hasSessions = sessionList != null && sessionList.Length > 0;
SetPfTest("PC_SESSIONS", hasSessions,
hasSessions ? sessionList.Length + " session(s): " + string.Join(", ", sessionList.Select(s => s.SessionType))
: "No sessions found in YAML");
// Legacy flat fields
_preflightSnapshot.SimHubOk = _simHubHttpListening;
_preflightSnapshot.GrafanaOk = !string.IsNullOrEmpty(_lokiBaseUrl);
if (_preflightLevel == 1)
{
CompletePreflight();
return;
}
// Check L1 pass — if any L1 test failed, stop here
if (!AllLevelPassed(1))
{
CompletePreflight();
return;
}
// Mark L2 tests as running
foreach (var t in _preflightSnapshot.MiniTests)
if (t.Level == 2) t.Status = "running";
// Handle partial replay scope — skip L2 seek checks
if (_preflightReplayScope == "partial")
{
SetPfTest("PC_CHECKERED", true, "skip");
PfTest("PC_CHECKERED").Status = "skip";
SetPfTest("PC_RESULTS", true, "skip");
PfTest("PC_RESULTS").Status = "skip";
if (_preflightLevel == 2)
{
CompletePreflight();
return;
}
// Jump to L3
foreach (var t in _preflightSnapshot.MiniTests)
if (t.Level == 3) t.Status = "running";
_preflightStep = PreflightStep.Level3_EmitProbe;
return;
}
// Seek to near-end of replay for L2
int seekTarget = Math.Max(0, _replayFrameTotal - 10);
try
{
_irsdk.ReplaySetPlaySpeed(1, false);
_irsdk.ReplaySetPlayPosition(IRacingSdkEnum.RpyPosMode.Begin, seekTarget);
}
catch (Exception ex)
{
SentrySdk.CaptureException(ex);
SetPfTest("PC_CHECKERED", false, "seek_failed: " + ex.Message);
SetPfTest("PC_RESULTS", false, "seek_failed");
_preflightSnapshot.Error = "seek_failed: " + ex.Message;
CompletePreflight();
return;
}
_preflightStep = PreflightStep.Level2_SettleEnd;
break;
}
// ── Level 2: seek to end, read session state ─────────────────────
case PreflightStep.Level2_SettleEnd:
{
_preflightSettleTicks++;
int frame = SafeGetInt("ReplayFrameNum");
int seekTarget = Math.Max(0, _replayFrameTotal - 10);
if (Math.Abs(frame - seekTarget) <= 30 || _preflightSettleTicks > 300)
{
int sessionState = 0;
try { sessionState = _irsdk.Data.GetInt("SessionState"); } catch { }
bool checkeredOk = sessionState >= 6;
bool resultsOk = CheckResultsPositionsPopulated();
_preflightSnapshot.SessionStateAtEnd = sessionState;
_preflightSnapshot.CheckeredOk = checkeredOk;
_preflightSnapshot.ResultsPopulated = resultsOk;
SetPfTest("PC_CHECKERED", checkeredOk, checkeredOk ? "SessionState=" + sessionState : "SessionState=" + sessionState + " (need >=6)");
SetPfTest("PC_RESULTS", resultsOk, resultsOk ? "ResultsPositions found" : "No ResultsPositions");
// Restore saved frame
try { _irsdk.ReplaySetPlayPosition(IRacingSdkEnum.RpyPosMode.Begin, _preflightSavedFrame); }
catch { }
_preflightSettleTicks = 0;
_preflightStep = PreflightStep.Level2_SettleRestore;
}
break;
}
case PreflightStep.Level2_SettleRestore:
{
_preflightSettleTicks++;
if (_preflightSettleTicks > 10)
{
if (_preflightLevel == 2 || !AllLevelPassed(2))
{
CompletePreflight();
return;
}
// Advance to L3
foreach (var t in _preflightSnapshot.MiniTests)
if (t.Level == 3) t.Status = "running";
_preflightStep = PreflightStep.Level3_EmitProbe;
}
break;
}
// ── Level 3: Loki roundtrip probe ────────────────────────────────
case PreflightStep.Level3_EmitProbe:
{
_preflightProbeNonce = Guid.NewGuid().ToString("N").Substring(0, 12);
_preflightProbeEmitNs = LokiQueryClient.NowNs();
// Emit probe event to Loki
var fields = new Dictionary<string, object>
{
["preflight_correlation_id"] = _preflightCorrelationId,
["probe_nonce"] = _preflightProbeNonce,
["domain"] = "test",
["testing"] = "true",
};
MergeSessionAndRoutingFields(fields);
_logger?.Structured("INFO", "simhub-plugin",
DataCaptureSuiteConstants.EventPreflightProbe,
"Preflight probe for Loki roundtrip check.", fields, "test", null);
_preflightProbeWaitTicks = 0;
_preflightStep = PreflightStep.Level3_WaitProbe;
break;
}
case PreflightStep.Level3_WaitProbe:
{
_preflightProbeWaitTicks++;
// Wait ~3 seconds (180 ticks at 60Hz) for Loki ingestion
if (_preflightProbeWaitTicks >= 180)
{
_preflightLokiProbeResult = -2; // reset
string nonce = _preflightProbeNonce;
string lokiUrl = _lokiReadUrl ?? _lokiBaseUrl;
long startNs = _preflightProbeEmitNs;
long endNs = LokiQueryClient.NowNs();
string user = Environment.GetEnvironmentVariable("SIMSTEWARD_LOKI_USER")?.Trim() ?? "";
string pass = Environment.GetEnvironmentVariable("CURSOR_ELEVATED_GRAFANA_TOKEN")?.Trim() ?? "";
System.Threading.Tasks.Task.Run(async () =>
{
try
{
string logql = $"{{app=\"sim-steward\"}}|json|probe_nonce=\"{nonce}\"";
int count = await LokiQueryClient.CountMatchingAsync(lokiUrl, logql, startNs, endNs, user, pass).ConfigureAwait(false);
_preflightLokiProbeResult = count;
}
catch
{
_preflightLokiProbeResult = -1;
}
});
_preflightStep = PreflightStep.Level3_QueryProbe;
}
break;
}
case PreflightStep.Level3_QueryProbe:
{
int result = _preflightLokiProbeResult;
if (result == -2) return; // still waiting for async Task
bool ok = result > 0;
string detail = result == -1 ? "Loki query error"
: result == 0 ? "Probe not found in Loki"
: $"Probe found ({result} match)";
SetPfTest("PC_LOKI_RT", ok, detail);
CompletePreflight();
break;
}
}
}
private void SetPfTest(string id, bool pass, string detail)
{
var t = PfTest(id);
if (t == null) return;
// Don't overwrite a "skip" status
if (t.Status == "skip") return;
t.Status = pass ? "pass" : "fail";
t.Detail = detail;
}
private bool AllLevelPassed(int level)
{
if (_preflightSnapshot.MiniTests == null) return false;
foreach (var t in _preflightSnapshot.MiniTests)
{
if (t.Level > level) continue;
if (t.Status != "pass" && t.Status != "skip") return false;
}
return true;
}
private void CompletePreflight()
{
// Determine allPassed: all tests at completed levels must be pass or skip
bool allPassed = true;
foreach (var t in _preflightSnapshot.MiniTests)
{
if (t.Level > _preflightLevel) continue;
if (t.Status != "pass" && t.Status != "skip") { allPassed = false; break; }
}
_preflightSnapshot.AllPassed = allPassed;
_preflightSnapshot.Phase = "complete";
_preflightStep = PreflightStep.Complete;
// Emit structured log
var fields = new Dictionary<string, object>
{
["preflight_correlation_id"] = _preflightCorrelationId ?? "",
["level"] = _preflightLevel,
["replay_scope"] = _preflightReplayScope,
["all_passed"] = allPassed,
["domain"] = "test",
["testing"] = "true",
};
foreach (var t in _preflightSnapshot.MiniTests)
{
if (t.Level <= _preflightLevel)
fields["pc_" + t.Id.ToLower()] = t.Status;
}
MergeSessionAndRoutingFields(fields);
_logger?.Structured("INFO", "simhub-plugin",
DataCaptureSuiteConstants.EventPreflightCheck,
$"Preflight L{_preflightLevel} complete. all_passed={allPassed}", fields, "test", null);
}
private bool CheckResultsPositionsPopulated()
{
try
{
var sessionInfo = _irsdk?.Data?.SessionInfo;
if (!(sessionInfo?.SessionInfo?.Sessions is IList list)) return false;
foreach (var o in list)
{
if (o == null) continue;
var t = o.GetType();
var typeProp = t.GetProperty("SessionType");
if (!string.Equals(typeProp?.GetValue(o)?.ToString(), "Race", StringComparison.OrdinalIgnoreCase))
continue;
var resultsProp = t.GetProperty("ResultsPositions");
var results = resultsProp?.GetValue(o);
if (results is IList resultsList && resultsList.Count > 0) return true;
}
}
catch { }
return false;
}
// ── Suite init ────────────────────────────────────────────────────────
private void InitSuiteResults()
{
_suiteResults = new[]
{
new DataCaptureSuiteTestResult { TestId = "T0", Name = "Ground Truth Capture", EventName = DataCaptureSuiteConstants.EventGroundTruth },
new DataCaptureSuiteTestResult { TestId = "T1", Name = "Speed Sweep Detection", EventName = DataCaptureSuiteConstants.EventSpeedSample },
new DataCaptureSuiteTestResult { TestId = "T2", Name = "Variable Inventory", EventName = DataCaptureSuiteConstants.EventVariableInventory },
new DataCaptureSuiteTestResult { TestId = "T3", Name = "Player Data Snapshot", EventName = DataCaptureSuiteConstants.EventPlayerSnapshot },
new DataCaptureSuiteTestResult { TestId = "T4", Name = "Driver Roster", EventName = DataCaptureSuiteConstants.EventDriverRoster },
new DataCaptureSuiteTestResult { TestId = "T5", Name = "Camera Switch", EventName = DataCaptureSuiteConstants.EventCameraSwitchDriver },
new DataCaptureSuiteTestResult { TestId = "T5b", Name = "Camera View Cycle", EventName = DataCaptureSuiteConstants.EventCameraViewSample },
new DataCaptureSuiteTestResult { TestId = "T6", Name = "Session Results", EventName = DataCaptureSuiteConstants.EventSessionResults },
new DataCaptureSuiteTestResult { TestId = "T7", Name = "Incident Re-Seek", EventName = DataCaptureSuiteConstants.EventIncidentReseek },
new DataCaptureSuiteTestResult { TestId = "T8", Name = "FF Sweep", EventName = DataCaptureSuiteConstants.EventFfSweepResult },
new DataCaptureSuiteTestResult { TestId = "T_DISC", Name = "Data Point Discovery", EventName = DataCaptureSuiteConstants.EventDataDiscovery },
};
// Append T_60Hz only when feature flag is set
if (_suite60HzEnabled)
{
var list = new List<DataCaptureSuiteTestResult>(_suiteResults);
list.Add(new DataCaptureSuiteTestResult { TestId = "T_60Hz", Name = "60Hz Telemetry Dump", EventName = DataCaptureSuiteConstants.Event60HzSummary });
_suiteResults = list.ToArray();
}
}
private DataCaptureSuiteTestResult SuiteResult(string id)
=> Array.Find(_suiteResults, r => r.TestId == id);
private void BeginDataCaptureSuite()
{
_suiteTestRunId = Guid.NewGuid().ToString("D");
_suitePreflightCorrelationId = _preflightCorrelationId ?? "";
_suiteStopwatch = Stopwatch.StartNew();
_suiteGroundTruth = new GroundTruthIncident[3];
_suiteGroundTruthIdx = 0;
_suiteReseekCapture = new GroundTruthIncident[3];
_suiteReseekIdx = 0;
_suiteSpeedSweepIdx = 0;
_suiteFfSweepTriggered = false;
_suiteT8PollTicks = 0;
_suiteT8BuildWasRunning = false;
_suiteCamGroupsVisited.Clear();
_lokiReadUrl = _lokiBaseUrl;
_suiteDiscPositionIdx = 0;
_suiteDiscTargetFrames = null;
// 60Hz feature flag
_suite60HzEnabled = string.Equals(
Environment.GetEnvironmentVariable("SIMSTEWARD_60HZ_TEST_CAPTURE")?.Trim(), "1");
_suite60HzRecorder?.Dispose();
_suite60HzRecorder = null;
if (_suite60HzEnabled)
_suite60HzRecorder = new HighRateTelemetryRecorder(_suiteTestRunId, _pluginDataPath);
InitSuiteResults();
_suiteStep = SuiteInternalStep.T0_Rewind;
_suitePhase = DataCaptureSuitePhase.Running;
// Sentry performance transaction for the entire suite run
_sentryTx = SentrySdk.StartTransaction("data-capture-suite", "test.run");
_sentryTx.SetExtra("test_run_id", _suiteTestRunId);
SentrySdk.ConfigureScope(scope => scope.Transaction = _sentryTx);
_sentryCurrentSpan = _sentryTx.StartChild("step", SuiteInternalStep.T0_Rewind.ToString());
EmitSuiteLifecycleEvent(DataCaptureSuiteConstants.EventSuiteStarted,
$"Data capture suite started. test_run_id={_suiteTestRunId}", "T_start");
SentrySdk.AddBreadcrumb("Data capture suite started", "lifecycle",
data: new Dictionary<string, string> { ["test_run_id"] = _suiteTestRunId });
_logger?.Info($"DataCaptureSuite started. test_run_id={_suiteTestRunId}");
}
// ── Main tick dispatcher ──────────────────────────────────────────────
private void TickSuiteRunning()
{
var stepBefore = _suiteStep;
switch (_suiteStep)
{
case SuiteInternalStep.T0_Rewind: TickT0_Rewind(); break;
case SuiteInternalStep.T0_FrameZero: TickT0_FrameZero(); break;
case SuiteInternalStep.T0_ScanCooldown: TickT0_ScanCooldown(); break;
case SuiteInternalStep.T0_SeekCapture: TickT0_SeekCapture(); break;
case SuiteInternalStep.T0_CaptureSettle: TickT0_CaptureSettle(); break;
case SuiteInternalStep.T1_Rewind: TickT1_Rewind(); break;
case SuiteInternalStep.T1_FrameZero: TickT1_FrameZero(); break;
case SuiteInternalStep.T1_Sweep: TickT1_Sweep(); break;
case SuiteInternalStep.T2: TickT2(); break;
case SuiteInternalStep.T3: TickT3(); break;
case SuiteInternalStep.T4: TickT4(); break;
case SuiteInternalStep.T5_Switch: TickT5_Switch(); break;
case SuiteInternalStep.T5_Settle: TickT5_Settle(); break;
case SuiteInternalStep.T5b_Seek: TickT5b_Seek(); break;
case SuiteInternalStep.T5b_Cycle: TickT5b_Cycle(); break;
case SuiteInternalStep.T5b_Settle: TickT5b_Settle(); break;
case SuiteInternalStep.T6: TickT6(); break;
case SuiteInternalStep.T7_Rewind: TickT7_Rewind(); break;
case SuiteInternalStep.T7_FrameZero: TickT7_FrameZero(); break;
case SuiteInternalStep.T7_Cooldown: TickT7_Cooldown(); break;
case SuiteInternalStep.T8_Trigger: TickT8_Trigger(); break;
case SuiteInternalStep.T8_Poll: TickT8_Poll(); break;
case SuiteInternalStep.TDISC_Seek: TickTDISC_Seek(); break;
case SuiteInternalStep.TDISC_Settle: TickTDISC_Settle(); break;
case SuiteInternalStep.TDISC_Capture: TickTDISC_Capture(); break;
case SuiteInternalStep.Done: TransitionToLoki(); break;
}
// Sentry: finish previous span and start new one when step changes
if (_suiteStep != stepBefore && _sentryTx != null)
{
_sentryCurrentSpan?.Finish(SpanStatus.Ok);
if (_suiteStep != SuiteInternalStep.Done)
_sentryCurrentSpan = _sentryTx.StartChild("step", _suiteStep.ToString());
else
_sentryCurrentSpan = null;
}
// 60Hz recording: every tick while running
_suite60HzRecorder?.RecordTick(_irsdk);
}
// ── T0: Ground Truth Capture — two-pass scan/select/capture ──────────
private void TickT0_Rewind()
{
if (TrySkipTest("T0", SuiteInternalStep.T1_Rewind)) return;
SuiteResult("T0").Status = "pending";
try
{
_irsdk.ReplaySetPlaySpeed(1, false);
_irsdk.ReplaySearch(IRacingSdkEnum.RpySrchMode.ToStart);
}
catch (Exception ex)
{
_logger?.Warn("DataCaptureSuite T0 rewind: " + ex.Message);
}
StartReplayIncidentIndexRecordModeLocked("suite_t0");
_suiteScanCandidates = new List<(int, int, int)>();
_suiteFirstScanFrame = -1;
_suiteFrameZeroConsecutive = 0;
_suiteSeekTimeoutTicks = 0;
_suiteStep = SuiteInternalStep.T0_FrameZero;
}
private void TickT0_FrameZero()
{
_suiteSeekTimeoutTicks++;
if (_suiteSeekTimeoutTicks > DataCaptureSuiteConstants.SeekTimeoutTicks)
{
SuiteResult("T0").Status = "fail";
SuiteResult("T0").Error = "frame_zero_timeout";
StopReplayIncidentIndexRecordModeLocked("suite_t0_timeout");
StartT1Rewind(0);
return;
}
int frame = SafeGetInt("ReplayFrameNum");
if (frame <= 2) _suiteFrameZeroConsecutive++;
else _suiteFrameZeroConsecutive = 0;
if (_suiteFrameZeroConsecutive < DataCaptureSuiteConstants.FrameZeroStableTicks) return;
// Frame zero stable — begin incident scan
_suiteSeekCooldownTicks = DataCaptureSuiteConstants.NextIncidentCooldownTicks;
try { _irsdk.ReplaySearch(IRacingSdkEnum.RpySrchMode.NextIncident); } catch { }
_suiteStep = SuiteInternalStep.T0_ScanCooldown;
}
private void TickT0_ScanCooldown()
{
if (--_suiteSeekCooldownTicks > 0) return;
int frame = SafeGetInt("ReplayFrameNum");
int camCarIdx = SafeGetInt("CamCarIdx");
int lap = -1;
try { lap = _irsdk.Data.GetInt("CarIdxLap", camCarIdx); } catch { }
// Detect wraparound: if we've looped back near the first scanned frame
if (_suiteFirstScanFrame < 0) _suiteFirstScanFrame = frame;
bool wrapped = _suiteScanCandidates.Count > 0 && frame <= _suiteFirstScanFrame + DataCaptureSuiteConstants.T0_SeekSettleTolerance;
if (!wrapped)
_suiteScanCandidates.Add((frame, lap, camCarIdx));
// Stop scanning if wrapped or hit max
if (wrapped || _suiteScanCandidates.Count >= DataCaptureSuiteConstants.T0_ScanMaxIncidents)
{
// Select best 3 incidents
_suiteSelectedFrames = SelectGroundTruthFrames(_suiteScanCandidates);
if (_suiteSelectedFrames.Length == 0)
{
SuiteResult("T0").Status = "fail";
SuiteResult("T0").Error = "no_incidents_found";
StopReplayIncidentIndexRecordModeLocked("suite_t0_no_incidents");
StartT1Rewind(0);
return;
}
_suiteGroundTruthIdx = 0;
_suiteCaptureIdx = 0;
_suiteStep = SuiteInternalStep.T0_SeekCapture;
return;
}
// Scan next incident
_suiteSeekCooldownTicks = DataCaptureSuiteConstants.NextIncidentCooldownTicks;
try { _irsdk.ReplaySearch(IRacingSdkEnum.RpySrchMode.NextIncident); } catch { }
}
private void TickT0_SeekCapture()
{
if (_suiteCaptureIdx >= _suiteSelectedFrames.Length)
{
FinishT0Capture();
return;
}
try { _irsdk.ReplaySetPlayPosition(IRacingSdkEnum.RpyPosMode.Begin, _suiteSelectedFrames[_suiteCaptureIdx]); }
catch { }
_suiteCaptureTicks = 0;
_suiteStep = SuiteInternalStep.T0_CaptureSettle;
}
private void TickT0_CaptureSettle()
{
_suiteCaptureTicks++;
int frame = SafeGetInt("ReplayFrameNum");
int target = _suiteSelectedFrames[_suiteCaptureIdx];
if (Math.Abs(frame - target) <= DataCaptureSuiteConstants.T0_SeekSettleTolerance || _suiteCaptureTicks > DataCaptureSuiteConstants.SeekTimeoutTicks)
{
CaptureGroundTruthIncident(_suiteCaptureIdx);
_suiteCaptureIdx++;
_suiteStep = SuiteInternalStep.T0_SeekCapture;
}
}
private void FinishT0Capture()
{
int captured = Math.Min(_suiteCaptureIdx, _suiteGroundTruth.Length);
SuiteResult("T0").Status = "emitted";
SuiteResult("T0").KpiLabel = "incidents_captured";
SuiteResult("T0").KpiValue = captured.ToString();
StopReplayIncidentIndexRecordModeLocked("suite_t0_done");
StartT1Rewind(0);
}
private static int[] SelectGroundTruthFrames(List<(int frame, int lap, int carIdx)> candidates)
=> DataCaptureSuiteSelection.SelectGroundTruthFrames(candidates);
private void CaptureGroundTruthIncident(int idx)
{
int camCarIdx = SafeGetInt("CamCarIdx");
int frame = SafeGetInt("ReplayFrameNum");
double rst = 0;
try { rst = _irsdk.Data.GetDouble("ReplaySessionTime"); } catch { }
var flags = new int[ReplayIncidentIndexBuild.CarSlotCount];
for (int i = 0; i < flags.Length; i++)
{
try { flags[i] = _irsdk.Data.GetInt("CarIdxSessionFlags", i); } catch { flags[i] = 0; }
}
int lap = -1;
float lapDistPct = 0f;
try { lap = _irsdk.Data.GetInt("CarIdxLap", camCarIdx); } catch { }
try { lapDistPct = _irsdk.Data.GetFloat("CarIdxLapDistPct", camCarIdx); } catch { }
ResolveDriverFromCarIdx(camCarIdx, out string driverName, out string carNumber, out string custId);
_suiteGroundTruth[idx] = new GroundTruthIncident
{
IncidentIndex = idx,
CarIdx = camCarIdx,
ReplayFrameNum = frame,
ReplaySessionTimeSec = rst,
CarIdxSessionFlagsSnapshot = flags,
DriverName = driverName,
CarNumber = carNumber,
CustId = custId,
LapDistPct = lapDistPct,
LapNum = lap
};
var fields = BuildTestFields("T0");
fields["incident_index"] = idx;
fields["car_idx"] = camCarIdx;
fields["replay_frame"] = frame;
fields["replay_session_time_sec"] = rst;
fields["driver_name"] = driverName;
fields["car_number"] = carNumber;
fields["unique_user_id"] = custId;
fields["lap_dist_pct"] = lapDistPct;
fields["lap_num"] = lap;
MergeSessionAndRoutingFields(fields);
_logger?.Structured("INFO", "simhub-plugin", DataCaptureSuiteConstants.EventGroundTruth,
$"Ground truth {idx}: car_idx={camCarIdx} frame={frame}", fields, "test", null);
}
// ── T1: Speed Sweep (per speed in [1,4,8,16]) ────────────────────────
private void StartT1Rewind(int speedIdx)
{
if (speedIdx == 0 && TrySkipTest("T1", SuiteInternalStep.T2)) return;
_suiteSpeedSweepIdx = speedIdx;
if (speedIdx >= DataCaptureSuiteConstants.SpeedSweepSpeeds.Length)
{
SuiteResult("T1").Status = "emitted";
_suiteStep = SuiteInternalStep.T2;
return;
}
_suiteStep = SuiteInternalStep.T1_Rewind;
}
private void TickT1_Rewind()
{
try
{
_irsdk.ReplaySetPlaySpeed(1, false);
_irsdk.ReplaySearch(IRacingSdkEnum.RpySrchMode.ToStart);
}
catch { }
int speed = DataCaptureSuiteConstants.SpeedSweepSpeeds[_suiteSpeedSweepIdx];
StartReplayIncidentIndexRecordModeLocked("suite_t1_speed_" + speed);
_suiteSpeedSweepBaselineFlags = new int[ReplayIncidentIndexBuild.CarSlotCount];
_suiteSpeedSweepDetected = 0;
_suiteSpeedSweepGtHits = 0;
_suiteSpeedSweepTicks = 0;
_suiteFrameZeroConsecutive = 0;
_suiteSeekTimeoutTicks = 0;
_suiteStep = SuiteInternalStep.T1_FrameZero;
}
private void TickT1_FrameZero()
{
_suiteSeekTimeoutTicks++;
if (_suiteSeekTimeoutTicks > DataCaptureSuiteConstants.SeekTimeoutTicks)
{
StopReplayIncidentIndexRecordModeLocked("suite_t1_timeout");
StartT1Rewind(_suiteSpeedSweepIdx + 1);
return;
}
int frame = SafeGetInt("ReplayFrameNum");
if (frame <= 2) _suiteFrameZeroConsecutive++;
else _suiteFrameZeroConsecutive = 0;
if (_suiteFrameZeroConsecutive < DataCaptureSuiteConstants.FrameZeroStableTicks) return;
// Capture baseline flags
for (int i = 0; i < _suiteSpeedSweepBaselineFlags.Length; i++)
{
try { _suiteSpeedSweepBaselineFlags[i] = _irsdk.Data.GetInt("CarIdxSessionFlags", i); }
catch { _suiteSpeedSweepBaselineFlags[i] = 0; }
}
int lastGtFrame = _suiteGroundTruth.Where(g => g != null)
.Select(g => g.ReplayFrameNum)
.DefaultIfEmpty(0).Max();
_suiteSpeedSweepFrameTarget = lastGtFrame + DataCaptureSuiteConstants.SpeedSweepAdvanceFrames;
int speed = DataCaptureSuiteConstants.SpeedSweepSpeeds[_suiteSpeedSweepIdx];