validation-observability.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. import { createHash } from 'node:crypto';
  2. import type { LocalRuntimeLogger } from '../common/logger.js';
  3. import { logger as defaultLogger } from '../common/logger.js';
  4. import type { MetricsClient } from '../common/metrics.js';
  5. import type { PreparedReview } from './preparation.js';
  6. export type ReviewValidationStage = 'candidate' | 'document' | 'finding' | 'correction';
  7. export type ReviewValidationOutcome = 'first_pass' | 'recovered' | 'partial' | 'failed';
  8. type ReviewValidationCategory = 'format' | 'projection';
  9. export interface ReviewValidationObservabilityOptions {
  10. metricsClient?: MetricsClient;
  11. logger?: Pick<LocalRuntimeLogger, 'warn' | 'error'>;
  12. model?: string;
  13. }
  14. interface ReviewValidationIdentity {
  15. sessionId: string;
  16. turnId: string;
  17. prepared: PreparedReview;
  18. }
  19. interface ReviewValidationFailureInput extends ReviewValidationIdentity {
  20. stage: ReviewValidationStage;
  21. error: unknown;
  22. candidateText: string;
  23. reasonCode?: string;
  24. details?: unknown;
  25. assistant?: ReviewAssistantEventContext;
  26. }
  27. export interface ReviewAssistantEventContext {
  28. stopReason: string;
  29. errorMessage?: string;
  30. responseId?: string;
  31. responseModel?: string;
  32. contentTypes: string[];
  33. diagnostics?: unknown;
  34. signalAborted: boolean;
  35. }
  36. interface RecordedFailure {
  37. fields: Record<string, unknown>;
  38. }
  39. export class ReviewValidationObserver {
  40. private readonly metricsClient: MetricsClient | undefined;
  41. private readonly validationLogger: Pick<LocalRuntimeLogger, 'warn' | 'error'>;
  42. private readonly model: string | undefined;
  43. private sawFailure = false;
  44. private sawFormatFailure = false;
  45. private resultRecorded = false;
  46. private lastFailure: RecordedFailure | undefined;
  47. constructor(options: ReviewValidationObservabilityOptions = {}) {
  48. this.metricsClient = options.metricsClient;
  49. this.validationLogger = options.logger ?? defaultLogger;
  50. this.model = options.model;
  51. }
  52. recordFailure(input: ReviewValidationFailureInput): void {
  53. const attempt = this.sawFailure ? 'retry' : 'initial';
  54. const message = errorMessage(input.error);
  55. const invalidEntityLocation =
  56. input.stage === 'document' ? findUnescapedXmlEntity(input.candidateText) : undefined;
  57. const reasonCode =
  58. input.reasonCode ??
  59. (invalidEntityLocation
  60. ? 'xml_invalid_entity'
  61. : classifyReviewValidationError(input.stage, message));
  62. const category = validationCategory(input.stage, reasonCode);
  63. const location = invalidEntityLocation ?? parseXmlErrorLocation(message);
  64. this.sawFailure = true;
  65. if (category === 'format') this.sawFormatFailure = true;
  66. const fields = {
  67. event: 'code_review_candidate_validation_failed',
  68. session_id: input.sessionId,
  69. turn_id: input.turnId,
  70. review_run_id: input.prepared.context.reviewRunId,
  71. trigger: input.prepared.trigger,
  72. mode: input.prepared.mode,
  73. attempt,
  74. stage: input.stage,
  75. category,
  76. reason_code: reasonCode,
  77. error: message,
  78. ...(location ?? {}),
  79. candidate_length: input.candidateText.length,
  80. candidate_sha256: createHash('sha256').update(input.candidateText).digest('hex'),
  81. // Review candidates are capped at 1 MB by the XML parser. Keep the full
  82. // rejected document in the local engineering log so field reports retain
  83. // enough evidence to reproduce model-format failures.
  84. candidate_xml: input.candidateText,
  85. ...(input.assistant ? assistantEventFields(input.assistant, attempt) : {}),
  86. ...(this.model ? { model: this.model } : {}),
  87. ...(input.details !== undefined ? { details: input.details } : {}),
  88. };
  89. this.lastFailure = { fields };
  90. this.validationLogger.warn(fields, 'Code review candidate validation failed');
  91. this.metricsClient?.counter('code_review_candidate_validation_failure_total', 1, {
  92. attempt,
  93. category,
  94. mode: input.prepared.mode,
  95. reasonCode,
  96. stage: input.stage,
  97. trigger: input.prepared.trigger,
  98. });
  99. }
  100. recordIgnoredTerminalEmpty(
  101. input: ReviewValidationIdentity & {
  102. candidateText: string;
  103. assistant: ReviewAssistantEventContext;
  104. },
  105. ): void {
  106. const attempt = this.sawFailure ? 'retry' : 'initial';
  107. const fields = {
  108. event: 'code_review_assistant_empty_ignored',
  109. session_id: input.sessionId,
  110. turn_id: input.turnId,
  111. review_run_id: input.prepared.context.reviewRunId,
  112. trigger: input.prepared.trigger,
  113. mode: input.prepared.mode,
  114. attempt,
  115. reason_code: `assistant_empty_${input.assistant.stopReason}`,
  116. candidate_length: input.candidateText.length,
  117. candidate_sha256: createHash('sha256').update(input.candidateText).digest('hex'),
  118. candidate_xml: input.candidateText,
  119. ...assistantEventFields(input.assistant, attempt),
  120. ...(this.model ? { model: this.model } : {}),
  121. };
  122. this.validationLogger.warn(fields, 'Code review ignored an empty terminal assistant event');
  123. }
  124. recordResult(identity: ReviewValidationIdentity, outcome?: ReviewValidationOutcome): void {
  125. if (this.resultRecorded) return;
  126. this.resultRecorded = true;
  127. this.metricsClient?.counter('code_review_candidate_result_total', 1, {
  128. mode: identity.prepared.mode,
  129. formatStatus: this.sawFormatFailure ? 'invalid' : 'valid',
  130. outcome: outcome ?? (this.sawFailure ? 'recovered' : 'first_pass'),
  131. trigger: identity.prepared.trigger,
  132. });
  133. }
  134. recordExhausted(identity: ReviewValidationIdentity): void {
  135. this.recordResult(identity, 'failed');
  136. const fields = {
  137. ...(this.lastFailure?.fields ?? {
  138. session_id: identity.sessionId,
  139. turn_id: identity.turnId,
  140. review_run_id: identity.prepared.context.reviewRunId,
  141. trigger: identity.prepared.trigger,
  142. mode: identity.prepared.mode,
  143. }),
  144. event: 'code_review_candidate_validation_exhausted',
  145. };
  146. this.validationLogger.error(fields, 'Code review candidate validation exhausted');
  147. }
  148. }
  149. function assistantEventFields(
  150. assistant: ReviewAssistantEventContext,
  151. attempt: 'initial' | 'retry',
  152. ): Record<string, unknown> {
  153. return {
  154. assistant_stop_reason: assistant.stopReason,
  155. assistant_error_message: assistant.errorMessage,
  156. assistant_response_id: assistant.responseId,
  157. assistant_response_model: assistant.responseModel,
  158. assistant_content_types: assistant.contentTypes,
  159. assistant_diagnostics: assistant.diagnostics,
  160. candidate_retry_pending: attempt === 'retry',
  161. signal_aborted: assistant.signalAborted,
  162. };
  163. }
  164. function findUnescapedXmlEntity(text: string): { line: number; column: number } | undefined {
  165. const match = /&(?!amp;|lt;|gt;|quot;|apos;|#\d+;|#x[\da-f]+;)/iu.exec(text);
  166. if (!match || match.index < 0) return undefined;
  167. const before = text.slice(0, match.index);
  168. const lines = before.split('\n');
  169. return {
  170. line: lines.length,
  171. column: (lines.at(-1)?.length ?? 0) + 1,
  172. };
  173. }
  174. function parseXmlErrorLocation(message: string): { line: number; column: number } | undefined {
  175. const match = /(?:^|\s)(\d+):(\d+):\s/u.exec(message);
  176. if (!match) return undefined;
  177. const line = Number(match[1]);
  178. const column = Number(match[2]);
  179. if (!Number.isSafeInteger(line) || !Number.isSafeInteger(column)) return undefined;
  180. return { line, column };
  181. }
  182. function validationCategory(
  183. stage: ReviewValidationStage,
  184. reasonCode: string,
  185. ): ReviewValidationCategory {
  186. if (stage === 'finding') {
  187. return reasonCode === 'finding_schema_invalid' ? 'format' : 'projection';
  188. }
  189. return reasonCode === 'correction_application_failed' ? 'projection' : 'format';
  190. }
  191. function errorMessage(error: unknown): string {
  192. return error instanceof Error ? error.message : String(error);
  193. }
  194. export function classifyReviewValidationError(
  195. stage: ReviewValidationStage,
  196. message: string,
  197. ): string {
  198. if (stage === 'candidate') return 'candidate_missing';
  199. if (/entity/iu.test(message)) return 'xml_invalid_entity';
  200. if (/too large/iu.test(message)) return 'document_too_large';
  201. if (/too many nodes/iu.test(message)) return 'document_node_limit';
  202. if (/deeply nested/iu.test(message)) return 'document_depth_limit';
  203. if (/doctype/iu.test(message)) return 'xml_doctype_not_allowed';
  204. if (/processing instruction/iu.test(message)) return 'xml_processing_instruction_not_allowed';
  205. if (/comment/iu.test(message) && /not allowed/iu.test(message)) return 'xml_comment_not_allowed';
  206. if (/exactly one root/iu.test(message)) return 'xml_multiple_roots';
  207. if (/outside review candidate xml root/iu.test(message)) return 'xml_outside_text';
  208. if (/not closed|unexpected close|unclosed|text data outside of root/iu.test(message)) {
  209. return 'xml_not_well_formed';
  210. }
  211. if (stage === 'finding') {
  212. if (/outside the local changes/iu.test(message)) return 'target_outside_changes';
  213. if (/does not overlap a deleted line/iu.test(message)) return 'old_target_not_deleted';
  214. if (/invalid finding schema/iu.test(message)) return 'finding_schema_invalid';
  215. return 'finding_validation_failed';
  216. }
  217. if (stage === 'correction') return 'correction_invalid';
  218. return 'document_schema_invalid';
  219. }