S8WatchSchedulerService.cs 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  1. using Admin.NET.Plugin.AiDOP.Entity.S8;
  2. using Admin.NET.Plugin.AiDOP.Infrastructure.S8;
  3. using Admin.NET.Plugin.AiDOP.Service.S8.Rules;
  4. using Admin.NET.Plugin.AiDOP.Service.S8.Rules.DataAccess;
  5. using Microsoft.Extensions.Logging;
  6. using SqlSugar;
  7. using System.Globalization;
  8. using System.Text.Json;
  9. namespace Admin.NET.Plugin.AiDOP.Service.S8;
  10. /// <summary>
  11. /// 监视规则轮询调度服务(首轮存根)。
  12. /// 后续接入 Admin.NET 定时任务机制后,由调度器周期调用 <see cref="RunOnceAsync"/>,
  13. /// 按各规则的 PollIntervalSeconds 逐条评估并生成异常记录。
  14. /// </summary>
  15. public class S8WatchSchedulerService : ITransient
  16. {
  17. private readonly SqlSugarRepository<AdoS8WatchRule> _ruleRep;
  18. private readonly SqlSugarRepository<AdoS8Exception> _exceptionRep;
  19. private readonly SqlSugarRepository<AdoS8ExceptionType> _exceptionTypeRep;
  20. private readonly S8NotificationService _notificationService;
  21. private readonly S8NotificationLayerResolver _notificationLayerResolver;
  22. private readonly S8ImpactMetricsService _impactMetricsService;
  23. private readonly S8ManualReportService _manualReportService;
  24. // S8-STEP6E:Watch 主链的业务建单边界(唯一最窄 seam)。仅 :1482 的自动建单走它;
  25. // legacy debug 主链的 CreateFromWatchAsync 保持直连 _manualReportService,行为不变。
  26. private readonly IS8ExceptionReportDispatcher _reportDispatcher;
  27. private readonly S8TimeoutRuleEvaluator _timeoutEvaluator;
  28. private readonly S8ShortageRuleEvaluator _shortageEvaluator;
  29. private readonly S8OutOfRangeRuleEvaluator _outOfRangeEvaluator;
  30. private readonly ILogger<S8WatchSchedulerService> _logger;
  31. private readonly SqlSugarRepository<AdoS8DetectionLog> _detectionLogRep;
  32. private readonly SqlSugarRepository<AdoS8RuleDetectionState> _detectionStateRep;
  33. private const string DetectionTriggerSource = "WATCH_SCHEDULER";
  34. private const string DetectResultCreated = "CREATED";
  35. private const string DetectResultRefreshed = "REFRESHED";
  36. private const string DetectResultRecovered = "RECOVERED";
  37. private const string DetectResultNoHit = "NO_HIT";
  38. private const string DetectResultEvaluateFailed = "EVALUATE_FAILED";
  39. // S8-DETECTION-LOG-WRITE-REDUCE-P1-1:REFRESHED 明细写入限频窗口。
  40. // 同 (tenant, factory, rule_code, dedup_key) 在 10 分钟内最多写一条 REFRESHED detection_log;
  41. // 业务侧 RefreshDetectionAsync / BackfillLegacyExceptionAsync 不受限频影响。
  42. private const int RefreshedRateLimitMinutes = 10;
  43. private const string DefaultTriggerType = "VALUE_DEVIATION";
  44. private const string SqlDataSourceType = "SQL";
  45. // G01-05 未闭环状态集合:复用自 S8ExceptionService 当前 pendingStatuses 事实口径
  46. // (见 S8ExceptionService.GetPagedAsync 中 pendingStatuses 的定义,两处必须保持一致)。
  47. // 这不是“自定义未闭环集合”;若现有口径调整,两处需同步修改。
  48. private static readonly string[] UnclosedExceptionStatuses =
  49. { "NEW", "ASSIGNED", "IN_PROGRESS", "PENDING_VERIFICATION" };
  50. public S8WatchSchedulerService(
  51. SqlSugarRepository<AdoS8WatchRule> ruleRep,
  52. SqlSugarRepository<AdoS8Exception> exceptionRep,
  53. SqlSugarRepository<AdoS8ExceptionType> exceptionTypeRep,
  54. S8NotificationService notificationService,
  55. S8NotificationLayerResolver notificationLayerResolver,
  56. S8ImpactMetricsService impactMetricsService,
  57. S8ManualReportService manualReportService,
  58. IS8ExceptionReportDispatcher reportDispatcher,
  59. S8TimeoutRuleEvaluator timeoutEvaluator,
  60. S8ShortageRuleEvaluator shortageEvaluator,
  61. S8OutOfRangeRuleEvaluator outOfRangeEvaluator,
  62. ILogger<S8WatchSchedulerService> logger,
  63. SqlSugarRepository<AdoS8DetectionLog> detectionLogRep,
  64. SqlSugarRepository<AdoS8RuleDetectionState> detectionStateRep)
  65. {
  66. _ruleRep = ruleRep;
  67. _exceptionRep = exceptionRep;
  68. _exceptionTypeRep = exceptionTypeRep;
  69. _notificationService = notificationService;
  70. _notificationLayerResolver = notificationLayerResolver;
  71. _impactMetricsService = impactMetricsService;
  72. _manualReportService = manualReportService;
  73. _reportDispatcher = reportDispatcher;
  74. _timeoutEvaluator = timeoutEvaluator;
  75. _shortageEvaluator = shortageEvaluator;
  76. _outOfRangeEvaluator = outOfRangeEvaluator;
  77. _logger = logger;
  78. _detectionLogRep = detectionLogRep;
  79. _detectionStateRep = detectionStateRep;
  80. }
  81. public async Task<List<S8TenantFactoryScope>> ListEnabledScopesAsync()
  82. {
  83. return await _ruleRep.Context.Ado.SqlQueryAsync<S8TenantFactoryScope>(
  84. """
  85. SELECT DISTINCT r.tenant_id AS TenantId, r.factory_id AS FactoryId
  86. FROM ado_s8_watch_rule r
  87. INNER JOIN SysTenant t ON t.Id = r.tenant_id AND t.Status = 1
  88. WHERE r.enabled = 1
  89. AND r.tenant_id > 0
  90. AND r.factory_id > 0
  91. ORDER BY r.tenant_id, r.factory_id
  92. """);
  93. }
  94. // 取任意一条匹配的未闭环异常 Id 作为“是否存在重复单”的拦截依据。
  95. // 首版只需要“存在性”,不关心“最早 / 最新”;不在 G01-05 处理排序语义。
  96. /// <summary>
  97. /// 自动建单入口(debug run-once 使用;生产调度走 <see cref="RunDispatchTickAsync"/>)。
  98. ///
  99. /// S8-LEGACY-SQL-RESIDUAL-CLEANUP-3:原先此处还有一段旧 AlertRule 兼容主链
  100. /// (EvaluateDedupAsync → EvaluateHitsAsync → QueryDeviceRowsAsync → 直连 SQL),
  101. /// 该链自行开 SqlSugarScope 执行 rule.expression,
  102. /// 且只装载 rule_type 为空的未分类历史规则 + 需同场景恰好一条可运行 AlertRule。
  103. /// 经证实其唯一入口是 404 门禁的 debug controller,且 LoadExecutionRulesAsync 的过滤条件
  104. /// 在当前数据下恒返回空,已整体删除。本方法现在只保留三类正式 evaluator 路径。
  105. /// </summary>
  106. public async Task<List<S8WatchCreationResult>> CreateExceptionsAsync(long tenantId, long factoryId)
  107. {
  108. var results = new List<S8WatchCreationResult>();
  109. // R6 RunId:本次 CreateExceptionsAsync 调用对应的统一关联 id,落入 detection_log。
  110. var runId = Guid.NewGuid().ToString("N").Substring(0, 16);
  111. results.AddRange(await ProcessRulesByTypeAsync(tenantId, factoryId, _timeoutEvaluator, S8TimeoutRuleEvaluator.RuleTypeCode, runId));
  112. results.AddRange(await ProcessRulesByTypeAsync(tenantId, factoryId, _shortageEvaluator, S8ShortageRuleEvaluator.RuleTypeCode, runId));
  113. results.AddRange(await ProcessRulesByTypeAsync(tenantId, factoryId, _outOfRangeEvaluator, S8OutOfRangeRuleEvaluator.RuleTypeCode, runId));
  114. return results;
  115. }
  116. /// <summary>
  117. /// R2 TIMEOUT 类规则主链:薄包装,复用 <see cref="ProcessRulesByTypeAsync"/>。RunId 由内部生成。
  118. /// </summary>
  119. public Task<List<S8WatchCreationResult>> ProcessTimeoutRulesAsync(long tenantId, long factoryId) =>
  120. ProcessRulesByTypeAsync(tenantId, factoryId, _timeoutEvaluator, S8TimeoutRuleEvaluator.RuleTypeCode, Guid.NewGuid().ToString("N").Substring(0, 16));
  121. /// <summary>
  122. /// R3 SHORTAGE 类规则主链:薄包装,复用 <see cref="ProcessRulesByTypeAsync"/>。RunId 由内部生成。
  123. /// </summary>
  124. public Task<List<S8WatchCreationResult>> ProcessShortageRulesAsync(long tenantId, long factoryId) =>
  125. ProcessRulesByTypeAsync(tenantId, factoryId, _shortageEvaluator, S8ShortageRuleEvaluator.RuleTypeCode, Guid.NewGuid().ToString("N").Substring(0, 16));
  126. /// <summary>
  127. /// R3-OUT_OF_RANGE-REWRITE-1:OUT_OF_RANGE 类规则主链。
  128. /// 复用 <see cref="ProcessRulesByTypeAsync"/>,并对历史 dedup_key=NULL 的旧记录做 compat fallback:
  129. /// (source_rule_id=rule.Id AND related_object_code=hit AND status!=CLOSED AND dedup_key IS NULL AND is_deleted=0)
  130. /// 命中则 backfill 6 列,避免重复建单。RunId 由内部生成。
  131. /// </summary>
  132. public Task<List<S8WatchCreationResult>> ProcessOutOfRangeRulesAsync(long tenantId, long factoryId) =>
  133. ProcessRulesByTypeAsync(tenantId, factoryId, _outOfRangeEvaluator, S8OutOfRangeRuleEvaluator.RuleTypeCode, Guid.NewGuid().ToString("N").Substring(0, 16));
  134. /// <summary>
  135. /// R2/R3 通用规则主链。S8-SCHED-CLEANUP-LEGACY-PATH-1:本方法已收敛为 thin wrapper,
  136. /// 单规则处理(evaluator → reconcile → hit 循环 → CREATED/REFRESHED/NO_HIT/EVALUATE_FAILED 日志)
  137. /// 全部下沉至 <see cref="ProcessSingleRuleAsync"/>,与 Job tick 路径
  138. /// (<see cref="RunDispatchTickAsync"/> → <see cref="RunSingleRuleAsync"/> → ProcessSingleRuleAsync)
  139. /// 共享同一份逻辑,避免双维护。
  140. ///
  141. /// 调用方仅有 <see cref="CreateExceptionsAsync"/>(debug run-once / Process*RulesAsync 公共薄包装)。
  142. /// debug run-once 不持 lease(保留"手动立即跑"语义),但本方法在每条规则结束时通过
  143. /// <see cref="ApplyRunOnceCompletionAsync"/> 同步更新 watch_rule.last_run_at / last_status /
  144. /// last_error / last_duration_ms / last_run_id / consecutive_failure_count,缩小 run-once 与
  145. /// Job tick 之间的 last_* 状态分裂;不动 lock_token / running_started_at / paused_until,避免
  146. /// 与正在持锁运行的 Job 撕扯。
  147. /// </summary>
  148. private async Task<List<S8WatchCreationResult>> ProcessRulesByTypeAsync(
  149. long tenantId, long factoryId, IS8RuleEvaluator evaluator, string ruleType, string runId)
  150. {
  151. var aggregate = new List<S8WatchCreationResult>();
  152. var rules = await _ruleRep.AsQueryable()
  153. .Where(x => x.TenantId == tenantId
  154. && x.FactoryId == factoryId
  155. && x.Enabled
  156. && x.RuleType == ruleType)
  157. .ToListAsync();
  158. if (rules.Count == 0) return aggregate;
  159. foreach (var rule in rules.OrderBy(x => x.Id))
  160. {
  161. // S8-RUN-ONCE-LEASE-AWARENESS-1:debug run-once 不持 lease,但若该 rule 已被 Scheduler Job
  162. // 通过 PickReadyRulesAsync 抢锁(lock_token 非空且 lock_until > now),run-once 跳过该 rule,
  163. // 不写 last_*、不写 detection_log、不动锁,以避免与 Job tick 并发评估同一 rule 而互相覆盖运行态。
  164. // 锁状态用 ToListAsync 的初始快照判定;run-once 与 Job 的微秒级竞速无法在不抢 lease 的前提下
  165. // 完全消除(已登记为 follow-up 风险)。
  166. if (!string.IsNullOrEmpty(rule.LockToken)
  167. && rule.LockUntil.HasValue
  168. && rule.LockUntil.Value > DateTime.Now)
  169. {
  170. _logger.LogInformation(
  171. "run_once_skip_locked ruleId={RuleId} ruleCode={RuleCode} ruleType={RuleType} lockToken={Token} lockedBy={By} lockUntil={Until}",
  172. rule.Id, rule.RuleCode, ruleType, rule.LockToken, rule.LockedBy, rule.LockUntil);
  173. aggregate.Add(BuildSkipResult(rule, "rule_locked_by_scheduler", null));
  174. continue;
  175. }
  176. var sw = System.Diagnostics.Stopwatch.StartNew();
  177. S8RuleRunResult completion;
  178. try
  179. {
  180. var ruleResults = await ProcessSingleRuleAsync(tenantId, factoryId, rule, ruleType, evaluator, runId);
  181. aggregate.AddRange(ruleResults);
  182. completion = new S8RuleRunResult
  183. {
  184. Success = true,
  185. Stats = new S8RuleRunStats
  186. {
  187. Hits = ruleResults.Count,
  188. Created = ruleResults.Count(r => r.Created),
  189. Refreshed = ruleResults.Count(r => r.Reason == "duplicate_pending"),
  190. Pending = ruleResults.Count(r => r.Reason == "antiflap_pending_hit"),
  191. Failed = ruleResults.Count(r => r.Reason == "create_failed" || r.Reason == "refresh_failed" || r.Reason == "antiflap_failed" || r.Reason == "evaluate_failed")
  192. }
  193. };
  194. }
  195. catch (Exception ex)
  196. {
  197. // ProcessSingleRuleAsync 在 evaluator 抛 S8RuleEvaluatorException 时已写 EVALUATE_FAILED
  198. // detection_log 后再 throw(供 RunSingleRuleAsync 标 Success=false)。本路径无 lease,
  199. // 吞异常以保留"逐规则失败不影响其他规则"的旧 ProcessRulesByTypeAsync 语义。
  200. _logger.LogWarning(ex, "process_rule_failed ruleCode={RuleCode} ruleType={RuleType}", rule.RuleCode, ruleType);
  201. aggregate.Add(BuildSkipResult(rule, "evaluate_failed", ex.Message));
  202. completion = new S8RuleRunResult { Success = false, ErrorMessage = ex.Message, Stats = new() };
  203. }
  204. sw.Stop();
  205. try
  206. {
  207. await ApplyRunOnceCompletionAsync(rule, completion, (int)sw.ElapsedMilliseconds, runId);
  208. }
  209. catch (Exception ex)
  210. {
  211. _logger.LogWarning(ex, "run_once_completion_write_failed ruleCode={RuleCode} ruleType={RuleType}", rule.RuleCode, ruleType);
  212. }
  213. }
  214. return aggregate;
  215. }
  216. /// <summary>
  217. /// S8-SCHED-CLEANUP-LEGACY-PATH-1:debug run-once 的 last_* 状态回写(无 lease 版)。
  218. /// 与 <see cref="OnRuleCompletedAsync"/> 的语义平行,差异在于:
  219. /// - 不要求 lock_token 匹配(run-once 不持 lease)
  220. /// - 不写 lock_token / locked_by / lock_until / running_started_at(不与 Job lease 撕扯)
  221. /// - 不做 consecutive_failure_count 阈值的 paused_until 自动暂停(debug 路径不应自动暂停 demo rule)
  222. /// 写入:last_run_at / next_run_at / last_status / last_error / last_duration_ms / last_run_id /
  223. /// consecutive_failure_count / updated_at。
  224. /// </summary>
  225. private async Task ApplyRunOnceCompletionAsync(AdoS8WatchRule rule, S8RuleRunResult result, int durationMs, string runId)
  226. {
  227. var now = DateTime.Now;
  228. var nextRunAt = now.AddSeconds(NormalizePollInterval(rule.PollIntervalSeconds));
  229. if (result.Success)
  230. {
  231. await _ruleRep.Context.Updateable<AdoS8WatchRule>()
  232. .SetColumns(x => new AdoS8WatchRule
  233. {
  234. LastRunAt = now,
  235. NextRunAt = nextRunAt,
  236. LastStatus = "SUCCESS",
  237. LastError = null,
  238. LastDurationMs = durationMs,
  239. LastRunId = runId,
  240. ConsecutiveFailureCount = 0,
  241. UpdatedAt = now
  242. })
  243. .Where(x => x.Id == rule.Id)
  244. .ExecuteCommandAsync();
  245. }
  246. else
  247. {
  248. var errorTrunc = Truncate(result.ErrorMessage, 500);
  249. await _ruleRep.Context.Updateable<AdoS8WatchRule>()
  250. .SetColumns(x => new AdoS8WatchRule
  251. {
  252. LastRunAt = now,
  253. NextRunAt = nextRunAt,
  254. LastStatus = "FAILED",
  255. LastError = errorTrunc,
  256. LastDurationMs = durationMs,
  257. LastRunId = runId,
  258. ConsecutiveFailureCount = x.ConsecutiveFailureCount + 1,
  259. UpdatedAt = now
  260. })
  261. .Where(x => x.Id == rule.Id)
  262. .ExecuteCommandAsync();
  263. }
  264. }
  265. // S8-SCHED-EXEC-1:trigger / recover 抗抖计数兜底,null / <1 / >10 一律按 1,避免非法配置导致永远不建单 / 永远不恢复。
  266. private static int NormalizeAntiflapCount(int raw)
  267. {
  268. if (raw < 1 || raw > 10) return 1;
  269. return raw;
  270. }
  271. /// <summary>
  272. /// 命中时累加 detection_state.consecutive_hit_count;未存在则插入 hitCount=1。
  273. /// 返回当前 state 行(含 Id)以及命中后的 hitCount。
  274. /// 注意:本函数不消费 trigger_count_required;上游决定是否进入 CreateFromHitAsync。
  275. /// </summary>
  276. private async Task<(AdoS8RuleDetectionState? state, int hitCount)> UpsertDetectionStateOnHitAsync(
  277. long tenantId, long factoryId, AdoS8WatchRule rule, S8RuleHit hit)
  278. {
  279. var now = DateTime.Now;
  280. var existing = await _detectionStateRep.AsQueryable()
  281. .Where(x => x.TenantId == tenantId
  282. && x.FactoryId == factoryId
  283. && x.RuleCode == rule.RuleCode
  284. && x.DedupKey == hit.DedupKey)
  285. .FirstAsync();
  286. if (existing == null)
  287. {
  288. var fresh = new AdoS8RuleDetectionState
  289. {
  290. TenantId = tenantId,
  291. FactoryId = factoryId,
  292. RuleCode = rule.RuleCode,
  293. DedupKey = hit.DedupKey,
  294. SourceObjectType = string.IsNullOrEmpty(hit.SourceObjectType) ? null : hit.SourceObjectType,
  295. SourceObjectId = string.IsNullOrEmpty(hit.SourceObjectId) ? null : hit.SourceObjectId,
  296. ConsecutiveHitCount = 1,
  297. ConsecutiveMissCount = 0,
  298. LastSeenAt = now,
  299. LastHitAt = now,
  300. CreatedAt = now,
  301. UpdatedAt = now
  302. };
  303. // BUG-S8-DETECTION-STATE-ACTIVE-EXC-ID-TRIGGER1-001:必须回填 fresh.Id,否则
  304. // trigger=1 首 tick 建单后 UPDATE state SET active_exception_id WHERE id=state.Id
  305. // 命中 0 行(state.Id 为默认 0)。沿用 S8ManualReportService 既定模式。
  306. fresh = await _detectionStateRep.AsInsertable(fresh).ExecuteReturnEntityAsync();
  307. return (fresh, 1);
  308. }
  309. var newHitCount = existing.ConsecutiveHitCount + 1;
  310. await _detectionStateRep.Context.Updateable<AdoS8RuleDetectionState>()
  311. .SetColumns(x => new AdoS8RuleDetectionState
  312. {
  313. ConsecutiveHitCount = x.ConsecutiveHitCount + 1,
  314. ConsecutiveMissCount = 0,
  315. LastSeenAt = now,
  316. LastHitAt = now,
  317. SourceObjectType = string.IsNullOrEmpty(hit.SourceObjectType) ? existing.SourceObjectType : hit.SourceObjectType,
  318. SourceObjectId = string.IsNullOrEmpty(hit.SourceObjectId) ? existing.SourceObjectId : hit.SourceObjectId,
  319. UpdatedAt = now
  320. })
  321. .Where(x => x.Id == existing.Id)
  322. .ExecuteCommandAsync();
  323. existing.ConsecutiveHitCount = newHitCount;
  324. return (existing, newHitCount);
  325. }
  326. private async Task<long> FindOpenExceptionByDedupKeyAsync(long tenantId, long factoryId, string dedupKey)
  327. {
  328. var ids = await _exceptionRep.AsQueryable()
  329. .Where(x => x.TenantId == tenantId
  330. && x.FactoryId == factoryId
  331. && !x.IsDeleted
  332. && x.Status != "CLOSED"
  333. && x.DedupKey == dedupKey)
  334. .Select(x => x.Id)
  335. .Take(1)
  336. .ToListAsync();
  337. return ids.Count > 0 ? ids[0] : 0L;
  338. }
  339. /// <summary>
  340. /// R3 OUT_OF_RANGE compat fallback 查找:用 (source_rule_id, related_object_code, status!=CLOSED,
  341. /// dedup_key IS NULL, is_deleted=0) 严格条件定位旧 AlertRule 主链留下的历史记录。
  342. /// </summary>
  343. private async Task<long> FindLegacyOutOfRangeExceptionAsync(long tenantId, long factoryId, long sourceRuleId, string relatedObjectCode)
  344. {
  345. if (string.IsNullOrWhiteSpace(relatedObjectCode)) return 0L;
  346. var ids = await _exceptionRep.AsQueryable()
  347. .Where(x => x.TenantId == tenantId
  348. && x.FactoryId == factoryId
  349. && !x.IsDeleted
  350. && x.Status != "CLOSED"
  351. && x.DedupKey == null
  352. && x.SourceRuleId == sourceRuleId
  353. && x.RelatedObjectCode == relatedObjectCode)
  354. .Select(x => x.Id)
  355. .Take(1)
  356. .ToListAsync();
  357. return ids.Count > 0 ? ids[0] : 0L;
  358. }
  359. /// <summary>
  360. /// R3 OUT_OF_RANGE compat fallback backfill:把历史记录的 R1 新 6 列(dedup_key/source_rule_code/
  361. /// source_object_type/source_object_id/source_payload/last_detected_at)写入,并刷新 updated_at。
  362. /// </summary>
  363. private async Task BackfillLegacyExceptionAsync(long exceptionId, S8RuleHit hit)
  364. {
  365. await _exceptionRep.Context.Updateable<AdoS8Exception>()
  366. .SetColumns(x => new AdoS8Exception
  367. {
  368. DedupKey = hit.DedupKey,
  369. SourceRuleCode = hit.SourceRuleCode,
  370. SourceObjectType = hit.SourceObjectType,
  371. SourceObjectId = hit.SourceObjectId,
  372. SourcePayload = hit.SourcePayload,
  373. LastDetectedAt = hit.DetectedAt,
  374. UpdatedAt = DateTime.Now
  375. })
  376. .Where(x => x.Id == exceptionId)
  377. .ExecuteCommandAsync();
  378. }
  379. /// <summary>
  380. /// R5 恢复时间最小闭环:对当前 rule 下未关闭、有 dedup_key、recovered_at 仍为 NULL 的异常,
  381. /// 凡不在本轮 hits.dedup_key 集合内的,写入 recovered_at = now、updated_at = now。
  382. /// 仅写这 2 列;不动 status / assignee / verifier / source_payload / last_detected_at;
  383. /// recovered_at 一旦写入,本轮不做复发清空。
  384. /// R6 返回 recoveredIds 供上游决定是否写 NO_HIT 日志,并对每个 recovered exception 写一条 RECOVERED 日志。
  385. /// </summary>
  386. private async Task<List<long>> ReconcileRecoveriesForRuleAsync(
  387. long tenantId, long factoryId, AdoS8WatchRule rule, string ruleType, List<S8RuleHit> hits, string runId)
  388. {
  389. var hitDedupKeys = hits
  390. .Where(h => !string.IsNullOrWhiteSpace(h.DedupKey))
  391. .Select(h => h.DedupKey)
  392. .ToHashSet(StringComparer.Ordinal);
  393. var candidates = await _exceptionRep.AsQueryable()
  394. .Where(x => x.TenantId == tenantId
  395. && x.FactoryId == factoryId
  396. && !x.IsDeleted
  397. && x.Status != "CLOSED"
  398. && x.SourceRuleCode == rule.RuleCode
  399. && x.DedupKey != null
  400. && x.RecoveredAt == null)
  401. .Select(x => new { x.Id, x.DedupKey, x.SourceObjectType, x.SourceObjectId, x.RelatedObjectCode, x.ConsecutiveMissCount })
  402. .ToListAsync();
  403. if (candidates.Count == 0) return new List<long>();
  404. var now = DateTime.Now;
  405. var recoverRequired = NormalizeAntiflapCount(rule.RecoverCountRequired);
  406. var recoveredIds = new List<long>();
  407. foreach (var c in candidates)
  408. {
  409. if (hitDedupKeys.Contains(c.DedupKey!)) continue;
  410. // S8-SCHED-EXEC-1:恢复抗抖累计。
  411. // 1) 每次未命中:异常 ConsecutiveMissCount += 1,ConsecutiveHitCount 清零;
  412. // 2) miss < recover_count_required:仅累计,不写 recovered_at、不写 RECOVERED;
  413. // 3) miss >= recover_count_required:写 recovered_at、写 RECOVERED 日志。
  414. var newMissCount = c.ConsecutiveMissCount + 1;
  415. await _exceptionRep.Context.Updateable<AdoS8Exception>()
  416. .SetColumns(x => new AdoS8Exception
  417. {
  418. ConsecutiveMissCount = x.ConsecutiveMissCount + 1,
  419. ConsecutiveHitCount = 0,
  420. UpdatedAt = now
  421. })
  422. .Where(x => x.Id == c.Id)
  423. .ExecuteCommandAsync();
  424. // detection_state 同步累计 miss(建单后 state.active_exception_id 仍指向 c.Id)。
  425. await _detectionStateRep.Context.Updateable<AdoS8RuleDetectionState>()
  426. .SetColumns(x => new AdoS8RuleDetectionState
  427. {
  428. ConsecutiveMissCount = x.ConsecutiveMissCount + 1,
  429. ConsecutiveHitCount = 0,
  430. LastSeenAt = now,
  431. LastMissAt = now,
  432. UpdatedAt = now
  433. })
  434. .Where(x => x.TenantId == tenantId
  435. && x.FactoryId == factoryId
  436. && x.RuleCode == rule.RuleCode
  437. && x.DedupKey == c.DedupKey)
  438. .ExecuteCommandAsync();
  439. if (newMissCount < recoverRequired)
  440. {
  441. _logger.LogInformation(
  442. "antiflap_pending_recovery ruleCode={RuleCode} dedupKey={DedupKey} missCount={Miss} recoverRequired={Required}",
  443. rule.RuleCode, c.DedupKey, newMissCount, recoverRequired);
  444. continue;
  445. }
  446. await _exceptionRep.Context.Updateable<AdoS8Exception>()
  447. .SetColumns(x => new AdoS8Exception
  448. {
  449. RecoveredAt = now,
  450. UpdatedAt = now
  451. })
  452. .Where(x => x.Id == c.Id)
  453. .ExecuteCommandAsync();
  454. recoveredIds.Add(c.Id);
  455. await WriteDetectionLogAsync(new AdoS8DetectionLog
  456. {
  457. TenantId = tenantId, FactoryId = factoryId,
  458. RuleId = rule.Id, RuleCode = rule.RuleCode, RuleType = ruleType, SceneCode = rule.SceneCode,
  459. SourceObjectType = c.SourceObjectType, SourceObjectId = c.SourceObjectId,
  460. RelatedObjectCode = c.RelatedObjectCode, DedupKey = c.DedupKey,
  461. DetectResult = DetectResultRecovered,
  462. ExceptionId = c.Id,
  463. DetectedAt = now,
  464. PayloadSnapshot = JsonSerializer.Serialize(new { ruleId = rule.Id, ruleCode = rule.RuleCode, reason = "no_longer_hit", missCount = newMissCount, recoverRequired }),
  465. RunId = runId, TriggerSource = DetectionTriggerSource,
  466. Remark = "Rule no longer hit; recovered_at marked"
  467. });
  468. // S8-NOTIFY-WIRE-RECOVERED-1:detection_log 已写入、recovered_at 已落库后挂入恢复通知。
  469. // 通知失败仅 LogWarning,绝不影响恢复状态/检测日志。
  470. await TryDispatchRecoveredLayerNotificationAsync(c.Id);
  471. }
  472. if (recoveredIds.Count > 0)
  473. {
  474. _logger.LogInformation(
  475. "rule_recovered ruleCode={RuleCode} ruleType={RuleType} recoveredCount={Count} recoveredIds={Ids}",
  476. rule.RuleCode, ruleType, recoveredIds.Count, string.Join(",", recoveredIds));
  477. }
  478. return recoveredIds;
  479. }
  480. /// <summary>R6 通用 hit 日志构造(CREATED / REFRESHED 共用)。</summary>
  481. private static AdoS8DetectionLog BuildHitLog(
  482. long tenantId, long factoryId, AdoS8WatchRule rule, string ruleType, S8RuleHit hit,
  483. string detectResult, long exceptionId, string runId) => new()
  484. {
  485. TenantId = tenantId, FactoryId = factoryId,
  486. RuleId = rule.Id, RuleCode = rule.RuleCode, RuleType = ruleType, SceneCode = rule.SceneCode,
  487. SourceObjectType = hit.SourceObjectType, SourceObjectId = hit.SourceObjectId,
  488. RelatedObjectCode = hit.RelatedObjectCode, DedupKey = hit.DedupKey,
  489. DetectResult = detectResult,
  490. ExceptionId = exceptionId,
  491. DetectedAt = hit.DetectedAt,
  492. PayloadSnapshot = hit.SourcePayload,
  493. RunId = runId,
  494. TriggerSource = DetectionTriggerSource
  495. };
  496. /// <summary>R6 日志写入:失败仅 LogWarning,不阻断主链;不抛异常。</summary>
  497. private async Task WriteDetectionLogAsync(AdoS8DetectionLog log)
  498. {
  499. try
  500. {
  501. await _detectionLogRep.InsertAsync(log);
  502. }
  503. catch (Exception ex)
  504. {
  505. _logger.LogWarning(ex,
  506. "detection_log_write_failed runId={RunId} detectResult={Result} ruleCode={RuleCode} exceptionId={ExceptionId}",
  507. log.RunId, log.DetectResult, log.RuleCode, log.ExceptionId);
  508. }
  509. }
  510. /// <summary>
  511. /// S8-DETECTION-LOG-WRITE-REDUCE-P1-1:REFRESHED 明细限频判定。
  512. /// 查询 cutoff = detectedAt - RefreshedRateLimitMinutes 之后,
  513. /// 是否已有同 (tenant_id, factory_id, rule_code, dedup_key, DetectResult=REFRESHED) 的 detection_log;
  514. /// 命中既有索引 idx_s8_detection_log_dedup_time。查询失败仅 LogWarning 后返回 false,
  515. /// 宁可多写一条 REFRESHED 明细,也不阻断调度主链路;ruleCode / dedupKey 空白时同样返回 false(保留写入)。
  516. /// 业务侧 RefreshDetectionAsync / BackfillLegacyExceptionAsync 不在限频范围。
  517. /// </summary>
  518. private async Task<bool> HasRecentRefreshedDetectionLogAsync(
  519. long tenantId, long factoryId, string ruleCode, string dedupKey, DateTime detectedAt)
  520. {
  521. if (string.IsNullOrWhiteSpace(ruleCode) || string.IsNullOrWhiteSpace(dedupKey))
  522. return false;
  523. var cutoff = detectedAt.AddMinutes(-RefreshedRateLimitMinutes);
  524. try
  525. {
  526. return await _detectionLogRep.AsQueryable()
  527. .Where(x => x.TenantId == tenantId
  528. && x.FactoryId == factoryId
  529. && x.DedupKey == dedupKey
  530. && x.RuleCode == ruleCode
  531. && x.DetectResult == DetectResultRefreshed
  532. && x.DetectedAt >= cutoff)
  533. .AnyAsync();
  534. }
  535. catch (Exception ex)
  536. {
  537. _logger.LogWarning(ex,
  538. "detection_log_refreshed_ratelimit_check_failed ruleCode={RuleCode} dedupKey={DedupKey}",
  539. ruleCode, dedupKey);
  540. return false;
  541. }
  542. }
  543. private static string Truncate(string? s, int max) =>
  544. string.IsNullOrEmpty(s) ? string.Empty : (s.Length <= max ? s : s.Substring(0, max));
  545. private async Task RefreshDetectionAsync(long exceptionId, S8RuleHit hit)
  546. {
  547. // S8-SCHED-EXEC-1:刷新阶段抗抖累计 + 复发清空 recovered_at。
  548. // ConsecutiveHitCount += 1(用 SetColumns 内表达式完成原子自增);ConsecutiveMissCount 归零。
  549. // RecoveredAt 不为 NULL 时(复发)一并清空,保持业务对"再次命中即视为活跃"的预期。
  550. await _exceptionRep.Context.Updateable<AdoS8Exception>()
  551. .SetColumns(x => new AdoS8Exception
  552. {
  553. LastDetectedAt = hit.DetectedAt,
  554. SourcePayload = hit.SourcePayload,
  555. ConsecutiveHitCount = x.ConsecutiveHitCount + 1,
  556. ConsecutiveMissCount = 0,
  557. RecoveredAt = null,
  558. UpdatedAt = DateTime.Now
  559. })
  560. .Where(x => x.Id == exceptionId)
  561. .ExecuteCommandAsync();
  562. }
  563. private static S8WatchCreationResult BuildCreatedResult(AdoS8WatchRule rule, S8RuleHit hit, long exceptionId) =>
  564. new()
  565. {
  566. DedupResult = new S8WatchDedupResult
  567. {
  568. Hit = ToWatchHit(rule, hit),
  569. CanCreate = true,
  570. MatchedExceptionId = null,
  571. Reason = "no_pending"
  572. },
  573. Created = true,
  574. Skipped = false,
  575. CreatedExceptionId = exceptionId,
  576. Reason = "auto_created",
  577. ErrorMessage = null
  578. };
  579. private static S8WatchCreationResult BuildSkippedDuplicate(AdoS8WatchRule rule, S8RuleHit hit, long matchedId) =>
  580. new()
  581. {
  582. DedupResult = new S8WatchDedupResult
  583. {
  584. Hit = ToWatchHit(rule, hit),
  585. CanCreate = false,
  586. MatchedExceptionId = matchedId,
  587. Reason = "duplicate_pending"
  588. },
  589. Created = false,
  590. Skipped = true,
  591. CreatedExceptionId = null,
  592. Reason = "duplicate_pending",
  593. ErrorMessage = null
  594. };
  595. private static S8WatchCreationResult BuildSkipResult(AdoS8WatchRule rule, string reason, string? error, S8RuleHit? hit = null) =>
  596. new()
  597. {
  598. DedupResult = new S8WatchDedupResult
  599. {
  600. Hit = hit != null ? ToWatchHit(rule, hit) : new S8WatchHitResult { SourceRuleId = rule.Id, SourceRuleCode = rule.RuleCode },
  601. CanCreate = false,
  602. MatchedExceptionId = null,
  603. Reason = reason
  604. },
  605. Created = false,
  606. Skipped = true,
  607. CreatedExceptionId = null,
  608. Reason = reason,
  609. ErrorMessage = error
  610. };
  611. private static S8WatchHitResult ToWatchHit(AdoS8WatchRule rule, S8RuleHit hit) => new()
  612. {
  613. SourceRuleId = hit.SourceRuleId == 0 ? rule.Id : hit.SourceRuleId,
  614. SourceRuleCode = string.IsNullOrEmpty(hit.SourceRuleCode) ? rule.RuleCode : hit.SourceRuleCode,
  615. DataSourceId = hit.DataSourceId,
  616. RelatedObjectCode = hit.RelatedObjectCode,
  617. Severity = hit.Severity,
  618. OccurrenceDeptId = hit.OccurrenceDeptId,
  619. ResponsibleDeptId = hit.ResponsibleDeptId,
  620. SourcePayload = hit.SourcePayload
  621. };
  622. // G01-04 首版最小比较符集合:>, >=, <, <=。
  623. // 允许首尾空格;非此集合的一律视为“比较符非法”,由调用方跳过。
  624. private static string NormalizeColumnName(string columnName) =>
  625. columnName.Replace("_", string.Empty, StringComparison.Ordinal).Trim().ToUpperInvariant();
  626. // ============================================================
  627. // S8-SCHED-EXEC-1:DB 驱动调度执行层
  628. // ============================================================
  629. private const int LeaseDurationMinutes = 5;
  630. private const int AutoPauseFailureThreshold = 3;
  631. private const int AutoPauseDurationHours = 1;
  632. private const int DefaultPollIntervalSeconds = 300;
  633. private const int MinPollIntervalSeconds = 60;
  634. private const int MaxPollIntervalSeconds = 86400;
  635. /// <summary>
  636. /// S8-SCHED-EXEC-1:释放过期 lease(lock_until &lt; NOW),不修改 last_status / last_error,仅清空 lock 三件套 + running_started_at。
  637. /// 返回释放的行数。
  638. /// </summary>
  639. public async Task<int> ResetExpiredLeasesAsync(long tenantId, long factoryId)
  640. {
  641. var now = DateTime.Now;
  642. var affected = await _ruleRep.Context.Updateable<AdoS8WatchRule>()
  643. .SetColumns(x => new AdoS8WatchRule
  644. {
  645. LockToken = null,
  646. LockedBy = null,
  647. LockUntil = null,
  648. RunningStartedAt = null,
  649. UpdatedAt = now
  650. })
  651. .Where(x => x.TenantId == tenantId
  652. && x.FactoryId == factoryId
  653. && x.LockUntil != null
  654. && x.LockUntil < now)
  655. .ExecuteCommandAsync();
  656. if (affected > 0)
  657. {
  658. _logger.LogWarning(
  659. "lease_reset tenantId={Tenant} factoryId={Factory} releasedCount={Count}",
  660. tenantId, factoryId, affected);
  661. }
  662. return affected;
  663. }
  664. /// <summary>
  665. /// S8-SCHED-EXEC-1:到期规则候选 + 乐观 UPDATE 抢锁,返回成功抢到的 lease 列表。
  666. /// 抢锁条件:enabled=1 AND (paused_until IS NULL OR paused_until &lt;= NOW)
  667. /// AND (next_run_at IS NULL OR next_run_at &lt;= NOW)
  668. /// AND (lock_until IS NULL OR lock_until &lt;= NOW)。
  669. /// 抢锁回写:lock_token / locked_by / lock_until = NOW + 5min / running_started_at = NOW / last_run_id = runId。
  670. /// affectedRows == 1 才算抢到;后续 OnRuleCompletedAsync 必须按 lockToken 回写,避免旧进程覆盖新 lease。
  671. /// </summary>
  672. public async Task<List<S8RuleLease>> PickReadyRulesAsync(long tenantId, long factoryId, int batchSize, string lockedBy, string runId)
  673. {
  674. if (batchSize <= 0) batchSize = 16;
  675. var now = DateTime.Now;
  676. var candidates = await _ruleRep.AsQueryable()
  677. .Where(x => x.TenantId == tenantId
  678. && x.FactoryId == factoryId
  679. && x.Enabled
  680. // S8-STANDARD-DATASET-HARD-CUTOVER-1:取数唯一依赖 dataset_code。
  681. // 保留这条谓词而非依赖 Enable Gate:Gate 只在"切换启用"那一刻生效,
  682. // 而 dataset_code 可能在此之后被清空(历史遗留行、直连改库)。
  683. // 一条没有数据集的规则跑起来只会每 tick 抛一次 dataset_code_missing。
  684. //
  685. // 刻意做成 **SQL 谓词而非内存过滤**:Take(batchSize) 在过滤之前生效,
  686. // 内存过滤会让无效候选占满名额,导致同租户的有效规则被饿死。
  687. && x.DatasetCode != null && x.DatasetCode != ""
  688. && (x.PausedUntil == null || x.PausedUntil <= now)
  689. && (x.NextRunAt == null || x.NextRunAt <= now)
  690. && (x.LockUntil == null || x.LockUntil <= now))
  691. .OrderBy(x => x.NextRunAt, OrderByType.Asc)
  692. .OrderBy(x => x.Id, OrderByType.Asc)
  693. .Take(batchSize)
  694. .Select(x => new { x.Id, x.RuleCode, x.RuleType })
  695. .ToListAsync();
  696. if (candidates.Count == 0) return new();
  697. var leases = new List<S8RuleLease>();
  698. foreach (var c in candidates)
  699. {
  700. var token = Guid.NewGuid().ToString("N");
  701. var lockUntil = DateTime.Now.AddMinutes(LeaseDurationMinutes);
  702. var runningAt = DateTime.Now;
  703. // 乐观 UPDATE:再校验一次条件,affectedRows=1 才算抢到。
  704. var affected = await _ruleRep.Context.Updateable<AdoS8WatchRule>()
  705. .SetColumns(x => new AdoS8WatchRule
  706. {
  707. LockToken = token,
  708. LockedBy = lockedBy,
  709. LockUntil = lockUntil,
  710. RunningStartedAt = runningAt,
  711. LastRunId = runId,
  712. UpdatedAt = runningAt
  713. })
  714. .Where(x => x.Id == c.Id
  715. && x.Enabled
  716. // 抢锁的乐观 UPDATE 复查同一条件:候选查询与本次 UPDATE 之间存在时间窗,
  717. // 期间该行的 dataset_code 可能被清空。
  718. && x.DatasetCode != null && x.DatasetCode != ""
  719. && (x.PausedUntil == null || x.PausedUntil <= runningAt)
  720. && (x.NextRunAt == null || x.NextRunAt <= runningAt)
  721. && (x.LockUntil == null || x.LockUntil <= runningAt))
  722. .ExecuteCommandAsync();
  723. if (affected == 1)
  724. {
  725. leases.Add(new S8RuleLease
  726. {
  727. RuleId = c.Id,
  728. RuleCode = c.RuleCode,
  729. RuleType = c.RuleType,
  730. LockToken = token,
  731. LockedBy = lockedBy,
  732. LockUntil = lockUntil,
  733. RunId = runId,
  734. AcquiredAt = runningAt
  735. });
  736. }
  737. }
  738. return leases;
  739. }
  740. /// <summary>
  741. /// S8-SCHED-EXEC-1:执行单条已抢锁规则的 evaluator → 抗抖去重 → 建单/刷新 → 恢复 reconcile。
  742. /// 不释放 lease(OnRuleCompletedAsync 负责);evaluator 抛异常时 Result.Success=false 并保留 ErrorMessage。
  743. /// </summary>
  744. public async Task<S8RuleRunResult> RunSingleRuleAsync(long tenantId, long factoryId, S8RuleLease lease)
  745. {
  746. // S8-P0-1-SCHEDULER-TRUSTED-SCOPE-1:执行入口必须按本次 tick 的可信作用域绑行。
  747. // 原实现只按 lease.RuleId 装载,不校验 rule 归属;一旦 lease 来源被改写 / 未来新增调用方,
  748. // 就会在 A 租户的 scope 上下文里执行 B 租户的规则,而下游全部以传入的 tenantId/factoryId 落库。
  749. // 这里同时做「谓词绑行」与「归属复核」两层,任一不符即 fail-fast,绝不静默降级。
  750. var rule = await _ruleRep.AsQueryable()
  751. .Where(x => x.Id == lease.RuleId && x.TenantId == tenantId && x.FactoryId == factoryId)
  752. .FirstAsync();
  753. if (rule == null)
  754. {
  755. return new S8RuleRunResult { Success = false, ErrorMessage = "rule_not_found", Stats = new() };
  756. }
  757. if (rule.TenantId != tenantId || rule.FactoryId != factoryId)
  758. {
  759. _logger.LogError(
  760. "rule_scope_mismatch ruleId={RuleId} ruleTenant={RuleTenant} ruleFactory={RuleFactory} scopeTenant={ScopeTenant} scopeFactory={ScopeFactory}",
  761. rule.Id, rule.TenantId, rule.FactoryId, tenantId, factoryId);
  762. return new S8RuleRunResult { Success = false, ErrorMessage = "rule_scope_mismatch", Stats = new() };
  763. }
  764. var ruleType = rule.RuleType;
  765. if (string.IsNullOrWhiteSpace(ruleType))
  766. {
  767. // 未分类的旧规则不在新调度路径承载;标 SKIPPED 但不视为失败。
  768. return new S8RuleRunResult { Success = true, ErrorMessage = "rule_type_empty_skipped", Stats = new() };
  769. }
  770. IS8RuleEvaluator? evaluator = ruleType switch
  771. {
  772. S8TimeoutRuleEvaluator.RuleTypeCode => _timeoutEvaluator,
  773. S8ShortageRuleEvaluator.RuleTypeCode => _shortageEvaluator,
  774. S8OutOfRangeRuleEvaluator.RuleTypeCode => _outOfRangeEvaluator,
  775. _ => null
  776. };
  777. if (evaluator == null)
  778. {
  779. return new S8RuleRunResult { Success = false, ErrorMessage = $"unsupported_rule_type:{ruleType}", Stats = new() };
  780. }
  781. try
  782. {
  783. var results = await ProcessSingleRuleAsync(tenantId, factoryId, rule, ruleType, evaluator, lease.RunId);
  784. var stats = new S8RuleRunStats
  785. {
  786. Hits = results.Count,
  787. Created = results.Count(r => r.Created),
  788. Refreshed = results.Count(r => r.Reason == "duplicate_pending"),
  789. Pending = results.Count(r => r.Reason == "antiflap_pending_hit"),
  790. Failed = results.Count(r => r.Reason == "create_failed" || r.Reason == "refresh_failed" || r.Reason == "antiflap_failed" || r.Reason == "evaluate_failed")
  791. };
  792. return new S8RuleRunResult { Success = true, Stats = stats };
  793. }
  794. catch (Exception ex)
  795. {
  796. return new S8RuleRunResult
  797. {
  798. Success = false,
  799. ErrorMessage = ex.Message,
  800. Stats = new()
  801. };
  802. }
  803. }
  804. /// <summary>
  805. /// S8-SCHED-EXEC-1:单规则处理(evaluator → reconcile → hit 循环)。
  806. /// 与 ProcessRulesByTypeAsync 内单规则循环体语义一致;此处抽出便于新调度路径直接调用单条 rule。
  807. /// </summary>
  808. private async Task<List<S8WatchCreationResult>> ProcessSingleRuleAsync(
  809. long tenantId, long factoryId, AdoS8WatchRule rule, string ruleType,
  810. IS8RuleEvaluator evaluator, string runId)
  811. {
  812. var results = new List<S8WatchCreationResult>();
  813. List<S8RuleHit> hits;
  814. try
  815. {
  816. hits = await evaluator.EvaluateAsync(tenantId, factoryId, rule);
  817. }
  818. catch (Exception ex)
  819. {
  820. var failureReason = ex is S8RuleEvaluatorException sre ? sre.Reason : ex.GetType().Name;
  821. await WriteDetectionLogAsync(new AdoS8DetectionLog
  822. {
  823. TenantId = tenantId, FactoryId = factoryId,
  824. RuleId = rule.Id, RuleCode = rule.RuleCode, RuleType = ruleType, SceneCode = rule.SceneCode,
  825. SourceObjectType = rule.SourceObjectType,
  826. DetectResult = DetectResultEvaluateFailed,
  827. DetectedAt = DateTime.Now,
  828. FailureReason = failureReason,
  829. FailureMessage = Truncate(ex.Message, 1000),
  830. RunId = runId, TriggerSource = DetectionTriggerSource
  831. });
  832. results.Add(BuildSkipResult(rule, "evaluate_failed", ex.Message));
  833. throw;
  834. }
  835. List<long> recoveredIds;
  836. try
  837. {
  838. recoveredIds = await ReconcileRecoveriesForRuleAsync(tenantId, factoryId, rule, ruleType, hits, runId);
  839. }
  840. catch (Exception ex)
  841. {
  842. _logger.LogWarning(ex, "recovery_reconcile_failed ruleCode={RuleCode} ruleType={RuleType}", rule.RuleCode, ruleType);
  843. recoveredIds = new();
  844. }
  845. // S8-DETECTION-LOG-WRITE-REDUCE-P1-1:NO_HIT 不再写 detection_log 明细。
  846. // 规则级"被定期评估"信号由 ado_s8_watch_rule.LastRunAt / LastStatus / LastRunId / LastDurationMs
  847. // 在 OnRuleCompletedAsync / ApplyRunOnceCompletionAsync 中承接,无需 detection_log 冗余记录。
  848. // DetectResultNoHit 常量保留(历史数据反查 / 未来如需恢复明细写入)。
  849. foreach (var hit in hits)
  850. {
  851. if (string.IsNullOrWhiteSpace(hit.DedupKey))
  852. {
  853. results.Add(BuildSkipResult(rule, "missing_dedup_key", null, hit));
  854. continue;
  855. }
  856. long matchedId;
  857. try
  858. {
  859. matchedId = await FindOpenExceptionByDedupKeyAsync(tenantId, factoryId, hit.DedupKey);
  860. }
  861. catch (Exception ex)
  862. {
  863. results.Add(BuildSkipResult(rule, "query_failed", ex.Message, hit));
  864. continue;
  865. }
  866. if (matchedId > 0)
  867. {
  868. try
  869. {
  870. await RefreshDetectionAsync(matchedId, hit);
  871. if (!await HasRecentRefreshedDetectionLogAsync(tenantId, factoryId, rule.RuleCode, hit.DedupKey, hit.DetectedAt))
  872. {
  873. await WriteDetectionLogAsync(BuildHitLog(tenantId, factoryId, rule, ruleType, hit, DetectResultRefreshed, matchedId, runId));
  874. }
  875. results.Add(BuildSkippedDuplicate(rule, hit, matchedId));
  876. }
  877. catch (Exception ex)
  878. {
  879. results.Add(BuildSkipResult(rule, "refresh_failed", ex.Message, hit));
  880. }
  881. continue;
  882. }
  883. if (string.Equals(ruleType, S8OutOfRangeRuleEvaluator.RuleTypeCode, StringComparison.OrdinalIgnoreCase))
  884. {
  885. long compatId;
  886. try
  887. {
  888. compatId = await FindLegacyOutOfRangeExceptionAsync(tenantId, factoryId, rule.Id, hit.RelatedObjectCode);
  889. }
  890. catch (Exception ex)
  891. {
  892. results.Add(BuildSkipResult(rule, "query_failed", ex.Message, hit));
  893. continue;
  894. }
  895. if (compatId > 0)
  896. {
  897. try
  898. {
  899. await BackfillLegacyExceptionAsync(compatId, hit);
  900. if (!await HasRecentRefreshedDetectionLogAsync(tenantId, factoryId, rule.RuleCode, hit.DedupKey, hit.DetectedAt))
  901. {
  902. await WriteDetectionLogAsync(BuildHitLog(tenantId, factoryId, rule, ruleType, hit, DetectResultRefreshed, compatId, runId));
  903. }
  904. results.Add(BuildSkippedDuplicate(rule, hit, compatId));
  905. }
  906. catch (Exception ex)
  907. {
  908. results.Add(BuildSkipResult(rule, "refresh_failed", ex.Message, hit));
  909. }
  910. continue;
  911. }
  912. }
  913. bool typeExists;
  914. try
  915. {
  916. typeExists = await _exceptionTypeRep.AsQueryable()
  917. .Where(t => t.TypeCode == hit.ExceptionTypeCode
  918. && (t.TenantId == 0 || t.TenantId == tenantId)
  919. && (t.FactoryId == 0 || t.FactoryId == factoryId)
  920. && t.Enabled)
  921. .AnyAsync();
  922. }
  923. catch (Exception ex)
  924. {
  925. results.Add(BuildSkipResult(rule, "query_failed", ex.Message, hit));
  926. continue;
  927. }
  928. if (!typeExists)
  929. {
  930. results.Add(BuildSkipResult(rule, "exception_type_missing", null, hit));
  931. continue;
  932. }
  933. int hitCount;
  934. AdoS8RuleDetectionState? state;
  935. try
  936. {
  937. (state, hitCount) = await UpsertDetectionStateOnHitAsync(tenantId, factoryId, rule, hit);
  938. }
  939. catch (Exception ex)
  940. {
  941. results.Add(BuildSkipResult(rule, "antiflap_failed", ex.Message, hit));
  942. continue;
  943. }
  944. var triggerRequired = NormalizeAntiflapCount(rule.TriggerCountRequired);
  945. if (hitCount < triggerRequired)
  946. {
  947. _logger.LogInformation(
  948. "antiflap_pending_hit ruleCode={RuleCode} dedupKey={DedupKey} hitCount={HitCount} trigger={Trigger}",
  949. rule.RuleCode, hit.DedupKey, hitCount, triggerRequired);
  950. results.Add(BuildSkipResult(rule, "antiflap_pending_hit", null, hit));
  951. continue;
  952. }
  953. try
  954. {
  955. var entity = await _reportDispatcher.CreateFromHitAsync(tenantId, factoryId, hit);
  956. await _exceptionRep.Context.Updateable<AdoS8Exception>()
  957. .SetColumns(x => new AdoS8Exception
  958. {
  959. ConsecutiveHitCount = hitCount,
  960. ConsecutiveMissCount = 0,
  961. UpdatedAt = DateTime.Now
  962. })
  963. .Where(x => x.Id == entity.Id)
  964. .ExecuteCommandAsync();
  965. if (state != null)
  966. {
  967. await _detectionStateRep.Context.Updateable<AdoS8RuleDetectionState>()
  968. .SetColumns(x => new AdoS8RuleDetectionState
  969. {
  970. ActiveExceptionId = entity.Id,
  971. UpdatedAt = DateTime.Now
  972. })
  973. .Where(x => x.Id == state.Id)
  974. .ExecuteCommandAsync();
  975. }
  976. await WriteDetectionLogAsync(BuildHitLog(tenantId, factoryId, rule, ruleType, hit, DetectResultCreated, entity.Id, runId));
  977. await TryDispatchLayerNotificationAsync(entity);
  978. results.Add(BuildCreatedResult(rule, hit, entity.Id));
  979. }
  980. catch (Exception ex)
  981. {
  982. results.Add(BuildSkipResult(rule, "create_failed", ex.Message, hit));
  983. }
  984. }
  985. return results;
  986. }
  987. /// <summary>
  988. /// S8-SCHED-EXEC-1:lease 执行完成回写。
  989. /// 必须 WHERE id = lease.RuleId AND lock_token = lease.LockToken;affectedRows = 0 视为 lease 丢失,记录 Warning,不覆盖状态。
  990. /// 失败 ≥ 阈值(默认 3)写 paused_until = NOW + 1h。
  991. /// </summary>
  992. public async Task OnRuleCompletedAsync(long tenantId, long factoryId, S8RuleLease lease, S8RuleRunResult result, int durationMs)
  993. {
  994. var rule = await _ruleRep.AsQueryable().Where(x => x.Id == lease.RuleId).FirstAsync();
  995. if (rule == null)
  996. {
  997. _logger.LogWarning("lease_complete_rule_missing ruleId={RuleId}", lease.RuleId);
  998. return;
  999. }
  1000. var now = DateTime.Now;
  1001. var effectiveInterval = NormalizePollInterval(rule.PollIntervalSeconds);
  1002. var nextRunAt = now.AddSeconds(effectiveInterval);
  1003. int affected;
  1004. if (result.Success)
  1005. {
  1006. affected = await _ruleRep.Context.Updateable<AdoS8WatchRule>()
  1007. .SetColumns(x => new AdoS8WatchRule
  1008. {
  1009. LastRunAt = now,
  1010. NextRunAt = nextRunAt,
  1011. LastStatus = "SUCCESS",
  1012. LastError = null,
  1013. LastDurationMs = durationMs,
  1014. ConsecutiveFailureCount = 0,
  1015. LockToken = null,
  1016. LockedBy = null,
  1017. LockUntil = null,
  1018. RunningStartedAt = null,
  1019. UpdatedAt = now
  1020. })
  1021. .Where(x => x.Id == lease.RuleId && x.LockToken == lease.LockToken)
  1022. .ExecuteCommandAsync();
  1023. }
  1024. else
  1025. {
  1026. var errorTrunc = Truncate(result.ErrorMessage, 500);
  1027. var newFailures = rule.ConsecutiveFailureCount + 1;
  1028. DateTime? pausedUntil = rule.PausedUntil;
  1029. string? pauseReason = rule.PauseReason;
  1030. if (newFailures >= AutoPauseFailureThreshold)
  1031. {
  1032. pausedUntil = now.AddHours(AutoPauseDurationHours);
  1033. pauseReason = Truncate($"AUTO_PAUSED_AFTER_{AutoPauseFailureThreshold}_FAILURES: {errorTrunc}", 64);
  1034. }
  1035. affected = await _ruleRep.Context.Updateable<AdoS8WatchRule>()
  1036. .SetColumns(x => new AdoS8WatchRule
  1037. {
  1038. LastRunAt = now,
  1039. NextRunAt = nextRunAt,
  1040. LastStatus = "FAILED",
  1041. LastError = errorTrunc,
  1042. LastDurationMs = durationMs,
  1043. ConsecutiveFailureCount = x.ConsecutiveFailureCount + 1,
  1044. PausedUntil = pausedUntil,
  1045. PauseReason = pauseReason,
  1046. LockToken = null,
  1047. LockedBy = null,
  1048. LockUntil = null,
  1049. RunningStartedAt = null,
  1050. UpdatedAt = now
  1051. })
  1052. .Where(x => x.Id == lease.RuleId && x.LockToken == lease.LockToken)
  1053. .ExecuteCommandAsync();
  1054. }
  1055. if (affected == 0)
  1056. {
  1057. _logger.LogWarning(
  1058. "lease_lost_on_complete ruleId={RuleId} ruleCode={RuleCode} lockToken={LockToken}",
  1059. lease.RuleId, lease.RuleCode, lease.LockToken);
  1060. }
  1061. }
  1062. /// <summary>
  1063. /// S8-SCHED-EXEC-1:单 tick 完整流程。Job / debug 调度入口。
  1064. /// 1) ResetExpiredLeasesAsync
  1065. /// 2) PickReadyRulesAsync(batchSize)
  1066. /// 3) 每条 rule 独立 try/catch 调用 RunSingleRuleAsync + OnRuleCompletedAsync
  1067. /// 单条规则失败不影响其他规则;整 tick 不抛异常。
  1068. /// </summary>
  1069. public async Task<S8DispatchTickResult> RunDispatchTickAsync(long tenantId, long factoryId, int batchSize, string lockedBy)
  1070. {
  1071. var tickId = Guid.NewGuid().ToString("N").Substring(0, 8);
  1072. var runId = Guid.NewGuid().ToString("N").Substring(0, 16);
  1073. var summary = new S8DispatchTickResult { TickId = tickId, RunId = runId };
  1074. try
  1075. {
  1076. summary.LeaseReleased = await ResetExpiredLeasesAsync(tenantId, factoryId);
  1077. }
  1078. catch (Exception ex)
  1079. {
  1080. _logger.LogError(ex, "tick_reset_lease_failed tickId={TickId}", tickId);
  1081. }
  1082. List<S8RuleLease> leases;
  1083. try
  1084. {
  1085. leases = await PickReadyRulesAsync(tenantId, factoryId, batchSize, lockedBy, runId);
  1086. }
  1087. catch (Exception ex)
  1088. {
  1089. _logger.LogError(ex, "tick_pick_failed tickId={TickId}", tickId);
  1090. return summary;
  1091. }
  1092. summary.Picked = leases.Count;
  1093. foreach (var lease in leases)
  1094. {
  1095. var sw = System.Diagnostics.Stopwatch.StartNew();
  1096. S8RuleRunResult runResult;
  1097. try
  1098. {
  1099. runResult = await RunSingleRuleAsync(tenantId, factoryId, lease);
  1100. }
  1101. catch (Exception ex)
  1102. {
  1103. runResult = new S8RuleRunResult { Success = false, ErrorMessage = ex.Message, Stats = new() };
  1104. }
  1105. sw.Stop();
  1106. try
  1107. {
  1108. await OnRuleCompletedAsync(tenantId, factoryId, lease, runResult, (int)sw.ElapsedMilliseconds);
  1109. }
  1110. catch (Exception ex)
  1111. {
  1112. _logger.LogError(ex, "tick_complete_failed tickId={TickId} ruleId={RuleId} ruleCode={RuleCode}", tickId, lease.RuleId, lease.RuleCode);
  1113. }
  1114. _logger.LogInformation(
  1115. "tick_rule_done tickId={TickId} runId={RunId} ruleId={RuleId} ruleCode={RuleCode} status={Status} durationMs={Dur} hits={Hits} created={Created} refreshed={Refreshed} pending={Pending} failed={Failed} error={Error}",
  1116. tickId, runId, lease.RuleId, lease.RuleCode,
  1117. runResult.Success ? "SUCCESS" : "FAILED",
  1118. sw.ElapsedMilliseconds,
  1119. runResult.Stats.Hits, runResult.Stats.Created, runResult.Stats.Refreshed, runResult.Stats.Pending, runResult.Stats.Failed,
  1120. runResult.ErrorMessage);
  1121. if (runResult.Success)
  1122. {
  1123. summary.Success++;
  1124. summary.Created += runResult.Stats.Created;
  1125. summary.Refreshed += runResult.Stats.Refreshed;
  1126. summary.Pending += runResult.Stats.Pending;
  1127. summary.PerRuleFailed += runResult.Stats.Failed;
  1128. }
  1129. else
  1130. {
  1131. summary.Failed++;
  1132. }
  1133. }
  1134. return summary;
  1135. }
  1136. private static int NormalizePollInterval(int raw)
  1137. {
  1138. if (raw < MinPollIntervalSeconds || raw > MaxPollIntervalSeconds) return DefaultPollIntervalSeconds;
  1139. return raw;
  1140. }
  1141. /// <summary>
  1142. /// S8-NOTIFY-WIRE-WATCH-1:异常自动建单成功后,非破坏性挂入通知分层路由。
  1143. /// 全程异常隔离:任何异常仅 LogWarning,不抛回主流程,不影响 detection_log / 事务 /
  1144. /// 异常状态机;该方法独立于 CreateFromWatchAsync / CreateFromHitAsync 的事务边界
  1145. /// (两者已 commit 后才返回 entity,故在此调用安全)。
  1146. /// sceneCode:先从 entity.SceneCode;空则 fallback 到 "S8_DEMO_DEFAULT"(demo 路径)。
  1147. /// severity:直接取 entity.Severity(CreateFromWatchAsync/CreateFromHitAsync 已保证非空)。
  1148. /// </summary>
  1149. private async Task TryDispatchLayerNotificationAsync(AdoS8Exception entity)
  1150. {
  1151. if (entity == null || entity.Id <= 0) return;
  1152. try
  1153. {
  1154. var sceneCode = string.IsNullOrWhiteSpace(entity.SceneCode) ? "S8_DEMO_DEFAULT" : entity.SceneCode;
  1155. // S8-SEVERITY-FOLLOW-SERIOUS-STANDARDIZE-EXEC-1:写入前 Normalize,落 FOLLOW/SERIOUS。
  1156. var severity = S8SeverityCode.Normalize(entity.Severity);
  1157. // S8-DEMO-IMPACT-SORT-NOTICE-1:附带 30 天影响统计(重复次数 / 累计损失 / 建议关注级别)。
  1158. // 计算失败不阻断通知主链路;snap==null 时 BuildNotification 仅写基础 Context。
  1159. ExceptionImpactSnapshot? snap = null;
  1160. try
  1161. {
  1162. snap = await _impactMetricsService.ComputeOneAsync(entity);
  1163. }
  1164. catch (Exception ex)
  1165. {
  1166. _logger.LogWarning(ex, "notify_impact_compute_throw exceptionId={ExceptionId}", entity.Id);
  1167. }
  1168. var baseContent =
  1169. $"异常 {entity.ExceptionCode}:{entity.Title}(场景 {sceneCode},严重度 {severity}" +
  1170. (string.IsNullOrWhiteSpace(entity.SourceRuleCode) ? "" : $",规则 {entity.SourceRuleCode}") + ")";
  1171. var content = snap == null
  1172. ? baseContent
  1173. : baseContent
  1174. + Environment.NewLine
  1175. + $"过去30天同类异常发生 {snap.RepeatCount30d} 次,已关闭累计损失 {snap.CumulativeLossHours30d.ToString("0.#")} 小时,建议关注级别:{snap.SuggestedAttentionLabel}";
  1176. await _notificationLayerResolver.DispatchByLayerAsync(new S8NotificationLayerResolver.DispatchByLayerInput
  1177. {
  1178. TenantId = entity.TenantId,
  1179. FactoryId = entity.FactoryId,
  1180. ExceptionId = entity.Id,
  1181. ExceptionNo = entity.ExceptionCode,
  1182. SceneCode = sceneCode,
  1183. Severity = severity,
  1184. Title = entity.Title ?? string.Empty,
  1185. Content = content,
  1186. Status = entity.Status,
  1187. SourceRuleCode = entity.SourceRuleCode,
  1188. JumpUrl = $"/aidop/s8/exceptions/{entity.Id}",
  1189. RepeatCount30d = snap?.RepeatCount30d,
  1190. CumulativeLossHours30d = snap?.CumulativeLossHours30d,
  1191. SuggestedAttentionLevel = snap?.SuggestedAttentionLevel,
  1192. SuggestedAttentionLabel = snap?.SuggestedAttentionLabel,
  1193. ImpactReason = snap?.ImpactReason,
  1194. });
  1195. }
  1196. catch (Exception ex)
  1197. {
  1198. _logger.LogWarning(ex, "notify_dispatch_throw exceptionId={ExceptionId}", entity.Id);
  1199. }
  1200. }
  1201. /// <summary>
  1202. /// S8-NOTIFY-WIRE-RECOVERED-1:异常恢复(recovered_at 已写入、RECOVERED detection_log 已落库)后,
  1203. /// 非破坏性挂入分层通知。全程异常隔离:任何异常仅 LogWarning,不抛回主流程,不影响 detection_log /
  1204. /// 状态机;call site 已在事务边界外(recovered 路径无事务)。
  1205. /// 重新读取 entity 拿场景/严重度/编号/状态/规则代码(恢复事件相对低频,1 次额外读可接受)。
  1206. /// S8-DEMO-IMPACT-SORT-NOTICE-1:恢复事件**不**追加影响统计字段,保持原有恢复语义不变。
  1207. /// </summary>
  1208. private async Task TryDispatchRecoveredLayerNotificationAsync(long exceptionId)
  1209. {
  1210. if (exceptionId <= 0) return;
  1211. try
  1212. {
  1213. var entity = await _exceptionRep.GetByIdAsync(exceptionId);
  1214. if (entity == null)
  1215. {
  1216. _logger.LogWarning("notify_recovered_dispatch_entity_missing exceptionId={ExceptionId}", exceptionId);
  1217. return;
  1218. }
  1219. var sceneCode = string.IsNullOrWhiteSpace(entity.SceneCode) ? "S8_DEMO_DEFAULT" : entity.SceneCode;
  1220. // S8-SEVERITY-FOLLOW-SERIOUS-STANDARDIZE-EXEC-1:写入前 Normalize,落 FOLLOW/SERIOUS。
  1221. var severity = S8SeverityCode.Normalize(entity.Severity);
  1222. var title = $"【已恢复】{entity.ExceptionCode}";
  1223. var content =
  1224. $"异常 {entity.ExceptionCode} 已恢复,场景 {sceneCode},严重度 {severity}" +
  1225. (string.IsNullOrWhiteSpace(entity.SourceRuleCode) ? "" : $",规则 {entity.SourceRuleCode}");
  1226. await _notificationLayerResolver.DispatchByLayerAsync(new S8NotificationLayerResolver.DispatchByLayerInput
  1227. {
  1228. TenantId = entity.TenantId,
  1229. FactoryId = entity.FactoryId,
  1230. ExceptionId = entity.Id,
  1231. ExceptionNo = entity.ExceptionCode,
  1232. SceneCode = sceneCode,
  1233. Severity = severity,
  1234. Title = title,
  1235. Content = content,
  1236. Status = entity.Status,
  1237. SourceRuleCode = entity.SourceRuleCode,
  1238. JumpUrl = $"/aidop/s8/exceptions/{entity.Id}",
  1239. Recovered = true,
  1240. });
  1241. }
  1242. catch (Exception ex)
  1243. {
  1244. _logger.LogWarning(ex, "notify_recovered_dispatch_throw exceptionId={ExceptionId}", exceptionId);
  1245. }
  1246. }
  1247. }
  1248. /// <summary>
  1249. /// G01-05 去重结果对象。仅服务 G01-06 建单前拦截,由 CanCreate 单决策位决定是否建单。
  1250. /// 只服务首版唯一场景 S2(迁移后由 S2S6_PRODUCTION 切到单模块 S2)+ 唯一 trigger_type VALUE_DEVIATION + 设备对象。
  1251. /// 不预留多 trigger_type / 平台化去重扩展结构。
  1252. /// Reason 值域:no_pending / duplicate_pending / missing_dedup_key / query_failed。
  1253. /// </summary>
  1254. public sealed class S8WatchDedupResult
  1255. {
  1256. public S8WatchHitResult Hit { get; set; } = new();
  1257. public bool CanCreate { get; set; }
  1258. public long? MatchedExceptionId { get; set; }
  1259. public string Reason { get; set; } = string.Empty;
  1260. }
  1261. /// <summary>
  1262. /// G01-06 建单结果对象。仅服务 G-01 首版主线验收,由 Created / Skipped 两位决定结局。
  1263. /// 只服务首版唯一场景 S2(迁移后由 S2S6_PRODUCTION 切到单模块 S2)+ 唯一 trigger_type VALUE_DEVIATION + 设备对象。
  1264. /// 不预留多 trigger_type / 平台化工单扩展结构。
  1265. /// Reason 值域:auto_created / create_failed / 透传自 DedupResult.Reason。
  1266. /// </summary>
  1267. public sealed class S8WatchCreationResult
  1268. {
  1269. public S8WatchDedupResult DedupResult { get; set; } = new();
  1270. public bool Created { get; set; }
  1271. public bool Skipped { get; set; }
  1272. public long? CreatedExceptionId { get; set; }
  1273. public string Reason { get; set; } = string.Empty;
  1274. public string? ErrorMessage { get; set; }
  1275. }
  1276. /// <summary>
  1277. /// G01-04 命中结果对象。承载 G01-05 去重与 G01-06 建单所需最小追溯字段,
  1278. /// 仅服务首版唯一场景 S2(迁移后由 S2S6_PRODUCTION 切到单模块 S2)+ 唯一 trigger_type VALUE_DEVIATION + 设备对象。
  1279. /// 不预留多 trigger_type / 多场景 / 平台化扩展结构。
  1280. /// </summary>
  1281. public sealed class S8WatchHitResult
  1282. {
  1283. public long SourceRuleId { get; set; }
  1284. public string SourceRuleCode { get; set; } = string.Empty;
  1285. public long DataSourceId { get; set; }
  1286. public string RelatedObjectCode { get; set; } = string.Empty;
  1287. public decimal CurrentValue { get; set; }
  1288. public decimal ThresholdValue { get; set; }
  1289. public string TriggerCondition { get; set; } = string.Empty;
  1290. public string Severity { get; set; } = string.Empty;
  1291. public long? OccurrenceDeptId { get; set; }
  1292. public long? ResponsibleDeptId { get; set; }
  1293. public string SourcePayload { get; set; } = string.Empty;
  1294. }
  1295. /// <summary>S8-SCHED-EXEC-1:lease 抢占成功后传递的最小标识对象。</summary>
  1296. public sealed class S8RuleLease
  1297. {
  1298. public long RuleId { get; set; }
  1299. public string RuleCode { get; set; } = string.Empty;
  1300. public string? RuleType { get; set; }
  1301. public string LockToken { get; set; } = string.Empty;
  1302. public string LockedBy { get; set; } = string.Empty;
  1303. public DateTime LockUntil { get; set; }
  1304. public string RunId { get; set; } = string.Empty;
  1305. public DateTime AcquiredAt { get; set; }
  1306. }
  1307. /// <summary>S8-SCHED-EXEC-1:单条规则执行结果,OnRuleCompletedAsync 据此更新状态。</summary>
  1308. public sealed class S8RuleRunResult
  1309. {
  1310. public bool Success { get; set; }
  1311. public string? ErrorMessage { get; set; }
  1312. public S8RuleRunStats Stats { get; set; } = new();
  1313. }
  1314. public sealed class S8RuleRunStats
  1315. {
  1316. public int Hits { get; set; }
  1317. public int Created { get; set; }
  1318. public int Refreshed { get; set; }
  1319. public int Pending { get; set; }
  1320. public int Failed { get; set; }
  1321. }
  1322. /// <summary>S8-SCHED-EXEC-1:单 tick 调度结果聚合。</summary>
  1323. public sealed class S8DispatchTickResult
  1324. {
  1325. public string TickId { get; set; } = string.Empty;
  1326. public string RunId { get; set; } = string.Empty;
  1327. public int LeaseReleased { get; set; }
  1328. public int Picked { get; set; }
  1329. public int Success { get; set; }
  1330. public int Failed { get; set; }
  1331. public int Created { get; set; }
  1332. public int Refreshed { get; set; }
  1333. public int Pending { get; set; }
  1334. public int PerRuleFailed { get; set; }
  1335. }