All files / server/ai validation.ts

58.22% Statements 131/225
49.1% Branches 82/167
60.71% Functions 17/28
59% Lines 118/200

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                        3x   3x 29x     3x 51x     3x 26x 416x 21x   395x                 3x                   1x   1x 3x   3x         1x                       2x 2x                 2x 2x   2x                                                 2x 2x                                                                                             21x 21x                 21x 21x   21x                                               44x 21x 1x 1x                   3x 1x   1x                     1x                                       6x   6x       6x           6x 6x 6x 6x                 6x 6x   6x                                 12x 6x   6x                                                                             4x 4x     4x 1x       3x 3x     4x         4x 4x     4x         4x 1x           3x 6x 6x             6x 6x                               3x 3x   3x         3x 3x     3x         3x 3x     3x 1x       2x 2x     3x 1x                                   3x 3x   3x         3x 3x     3x 1x       2x 2x     3x 1x             3x 2x                             12x 12x 12x     12x 4x   4x               8x 3x 3x               5x 3x 3x                 2x 2x 2x         2x 1x 1x         2x                                           2x         2x               2x               2x                   2x                                     2x              
/**
 * AI Query Validation Engine
 * Validate queries with helpful corrections and suggestions
 */
 
import type { CubeMetadata } from '../types/metadata'
import type { SemanticQuery, Filter } from '../types/query'
import { findBestFieldMatch } from './discovery'
 
/**
 * Validation result with corrections
 */
export interface ValidationResult {
  isValid: boolean
  errors: ValidationError[]
  warnings: ValidationWarning[]
  correctedQuery?: SemanticQuery
}
 
/**
 * Validation error with optional correction
 */
export interface ValidationError {
  type: 'cube_not_found' | 'measure_not_found' | 'dimension_not_found' | 'invalid_filter' | 'invalid_time_dimension' | 'syntax_error'
  message: string
  field?: string
  suggestion?: string
  correctedValue?: string
}
 
/**
 * Validation warning (query will work but may have issues)
 */
export interface ValidationWarning {
  type: 'ambiguous_field' | 'performance' | 'best_practice'
  message: string
  field?: string
  suggestion?: string
}
 
/**
 * Levenshtein distance for fuzzy matching (copied from discovery for standalone use)
 */
function levenshteinDistance(a: string, b: string): number {
  const matrix: number[][] = []
 
  for (let i = 0; i <= b.length; i++) {
    matrix[i] = [i]
  }
 
  for (let j = 0; j <= a.length; j++) {
    matrix[0][j] = j
  }
 
  for (let i = 1; i <= b.length; i++) {
    for (let j = 1; j <= a.length; j++) {
      if (b.charAt(i - 1) === a.charAt(j - 1)) {
        matrix[i][j] = matrix[i - 1][j - 1]
      } else {
        matrix[i][j] = Math.min(
          matrix[i - 1][j - 1] + 1,
          matrix[i][j - 1] + 1,
          matrix[i - 1][j] + 1
        )
      }
    }
  }
 
  return matrix[b.length][a.length]
}
 
/**
 * Find closest match for a field name
 */
function findClosestField(
  fieldName: string,
  availableFields: string[]
): { field: string; distance: number } | null {
  let bestMatch: { field: string; distance: number } | null = null
 
  for (const field of availableFields) {
    const distance = levenshteinDistance(fieldName.toLowerCase(), field.toLowerCase())
    // Allow matches within reasonable edit distance (e.g., typos)
    Iif (distance <= 3 && (!bestMatch || distance < bestMatch.distance)) {
      bestMatch = { field, distance }
    }
  }
 
  return bestMatch
}
 
/**
 * Validate a measure reference
 */
function validateMeasure(
  measure: string,
  metadata: CubeMetadata[],
  errors: ValidationError[],
  corrections: Map<string, string>
): void {
  const parts = measure.split('.')
  Iif (parts.length !== 2) {
    errors.push({
      type: 'syntax_error',
      message: `Invalid measure format: '${measure}'. Expected 'CubeName.measureName'`,
      field: measure
    })
    return
  }
 
  const [cubeName, measureName] = parts
  const cube = metadata.find(c => c.name === cubeName)
 
  Iif (!cube) {
    // Try to find similar cube name
    const cubeNames = metadata.map(c => c.name)
    const closest = findClosestField(cubeName, cubeNames)
 
    if (closest) {
      errors.push({
        type: 'cube_not_found',
        message: `Cube '${cubeName}' not found`,
        field: measure,
        suggestion: `Did you mean '${closest.field}'?`,
        correctedValue: `${closest.field}.${measureName}`
      })
      corrections.set(measure, `${closest.field}.${measureName}`)
    } else {
      errors.push({
        type: 'cube_not_found',
        message: `Cube '${cubeName}' not found`,
        field: measure,
        suggestion: `Available cubes: ${cubeNames.join(', ')}`
      })
    }
    return
  }
 
  const measureExists = cube.measures.some(m => m.name === measure)
  Iif (!measureExists) {
    // Try fuzzy match using discovery
    const match = findBestFieldMatch(metadata, measureName, 'measure')
    if (match && match.cube === cubeName) {
      errors.push({
        type: 'measure_not_found',
        message: `Measure '${measureName}' not found on cube '${cubeName}'`,
        field: measure,
        suggestion: `Did you mean '${match.field}'?`,
        correctedValue: match.field
      })
      corrections.set(measure, match.field)
    } else {
      const availableMeasures = cube.measures.map(m => m.name.split('.').pop()!)
      const closest = findClosestField(measureName, availableMeasures)
 
      if (closest) {
        const correctedField = `${cubeName}.${closest.field}`
        errors.push({
          type: 'measure_not_found',
          message: `Measure '${measureName}' not found on cube '${cubeName}'`,
          field: measure,
          suggestion: `Did you mean '${closest.field}'?`,
          correctedValue: correctedField
        })
        corrections.set(measure, correctedField)
      } else {
        errors.push({
          type: 'measure_not_found',
          message: `Measure '${measureName}' not found on cube '${cubeName}'`,
          field: measure,
          suggestion: `Available measures: ${availableMeasures.slice(0, 5).join(', ')}${availableMeasures.length > 5 ? '...' : ''}`
        })
      }
    }
  }
}
 
/**
 * Validate a dimension reference
 */
function validateDimension(
  dimension: string,
  metadata: CubeMetadata[],
  errors: ValidationError[],
  corrections: Map<string, string>
): void {
  const parts = dimension.split('.')
  Iif (parts.length !== 2) {
    errors.push({
      type: 'syntax_error',
      message: `Invalid dimension format: '${dimension}'. Expected 'CubeName.dimensionName'`,
      field: dimension
    })
    return
  }
 
  const [cubeName, dimensionName] = parts
  const cube = metadata.find(c => c.name === cubeName)
 
  Iif (!cube) {
    const cubeNames = metadata.map(c => c.name)
    const closest = findClosestField(cubeName, cubeNames)
 
    if (closest) {
      errors.push({
        type: 'cube_not_found',
        message: `Cube '${cubeName}' not found`,
        field: dimension,
        suggestion: `Did you mean '${closest.field}'?`,
        correctedValue: `${closest.field}.${dimensionName}`
      })
      corrections.set(dimension, `${closest.field}.${dimensionName}`)
    } else {
      errors.push({
        type: 'cube_not_found',
        message: `Cube '${cubeName}' not found`,
        field: dimension,
        suggestion: `Available cubes: ${cubeNames.join(', ')}`
      })
    }
    return
  }
 
  const dimensionExists = cube.dimensions.some(d => d.name === dimension)
  if (!dimensionExists) {
    const match = findBestFieldMatch(metadata, dimensionName, 'dimension')
    Iif (match && match.cube === cubeName) {
      errors.push({
        type: 'dimension_not_found',
        message: `Dimension '${dimensionName}' not found on cube '${cubeName}'`,
        field: dimension,
        suggestion: `Did you mean '${match.field}'?`,
        correctedValue: match.field
      })
      corrections.set(dimension, match.field)
    } else {
      const availableDimensions = cube.dimensions.map(d => d.name.split('.').pop()!)
      const closest = findClosestField(dimensionName, availableDimensions)
 
      Iif (closest) {
        const correctedField = `${cubeName}.${closest.field}`
        errors.push({
          type: 'dimension_not_found',
          message: `Dimension '${dimensionName}' not found on cube '${cubeName}'`,
          field: dimension,
          suggestion: `Did you mean '${closest.field}'?`,
          correctedValue: correctedField
        })
        corrections.set(dimension, correctedField)
      } else {
        errors.push({
          type: 'dimension_not_found',
          message: `Dimension '${dimensionName}' not found on cube '${cubeName}'`,
          field: dimension,
          suggestion: `Available dimensions: ${availableDimensions.slice(0, 5).join(', ')}${availableDimensions.length > 5 ? '...' : ''}`
        })
      }
    }
  }
}
 
/**
 * Validate filters recursively
 */
function validateFilters(
  filters: Filter[],
  metadata: CubeMetadata[],
  errors: ValidationError[],
  corrections: Map<string, string>
): void {
  for (const filter of filters) {
    // Handle logical filters (AND/OR)
    Iif ('and' in filter && Array.isArray(filter.and)) {
      validateFilters(filter.and, metadata, errors, corrections)
      continue
    }
    Iif ('or' in filter && Array.isArray(filter.or)) {
      validateFilters(filter.or, metadata, errors, corrections)
      continue
    }
 
    // Handle simple filter
    Eif ('member' in filter) {
      const member = filter.member
      const parts = member.split('.')
      Iif (parts.length !== 2) {
        errors.push({
          type: 'invalid_filter',
          message: `Invalid filter member format: '${member}'`,
          field: member
        })
        continue
      }
 
      const [cubeName, fieldName] = parts
      const cube = metadata.find(c => c.name === cubeName)
 
      Iif (!cube) {
        const cubeNames = metadata.map(c => c.name)
        const closest = findClosestField(cubeName, cubeNames)
        if (closest) {
          corrections.set(member, `${closest.field}.${fieldName}`)
        }
        errors.push({
          type: 'cube_not_found',
          message: `Cube '${cubeName}' not found in filter`,
          field: member,
          suggestion: closest ? `Did you mean '${closest.field}'?` : undefined,
          correctedValue: closest ? `${closest.field}.${fieldName}` : undefined
        })
        continue
      }
 
      // Check if member is a valid dimension or measure
      const isDimension = cube.dimensions.some(d => d.name === member)
      const isMeasure = cube.measures.some(m => m.name === member)
 
      Iif (!isDimension && !isMeasure) {
        const allFields = [
          ...cube.dimensions.map(d => d.name.split('.').pop()!),
          ...cube.measures.map(m => m.name.split('.').pop()!)
        ]
        const closest = findClosestField(fieldName, allFields)
 
        if (closest) {
          const correctedField = `${cubeName}.${closest.field}`
          corrections.set(member, correctedField)
          errors.push({
            type: 'invalid_filter',
            message: `Filter field '${fieldName}' not found on cube '${cubeName}'`,
            field: member,
            suggestion: `Did you mean '${closest.field}'?`,
            correctedValue: correctedField
          })
        } else {
          errors.push({
            type: 'invalid_filter',
            message: `Filter field '${fieldName}' not found on cube '${cubeName}'`,
            field: member
          })
        }
      }
    }
  }
}
 
/**
 * Validate funnel query structure
 */
function validateFunnelQuery(
  query: SemanticQuery,
  metadata: CubeMetadata[],
  errors: ValidationError[],
  warnings: ValidationWarning[],
  corrections: Map<string, string>
): void {
  const funnel = query.funnel
  Iif (!funnel) return
 
  // Required fields
  if (!funnel.bindingKey) {
    errors.push({
      type: 'syntax_error',
      message: 'funnel.bindingKey is required'
    })
  E} else if (typeof funnel.bindingKey === 'string') {
    validateDimension(funnel.bindingKey, metadata, errors, corrections)
  }
 
  Iif (!funnel.timeDimension) {
    errors.push({
      type: 'syntax_error',
      message: 'funnel.timeDimension is required'
    })
  E} else if (typeof funnel.timeDimension === 'string') {
    validateDimension(funnel.timeDimension, metadata, errors, corrections)
  }
 
  Iif (!funnel.steps || !Array.isArray(funnel.steps)) {
    errors.push({
      type: 'syntax_error',
      message: 'funnel.steps array is required'
    })
  } else if (funnel.steps.length < 2) {
    errors.push({
      type: 'syntax_error',
      message: 'funnel requires at least 2 steps'
    })
  } else {
    // Validate each step's filter
    for (let i = 0; i < funnel.steps.length; i++) {
      const step = funnel.steps[i]
      Iif (!step.name) {
        warnings.push({
          type: 'best_practice',
          message: `Step ${i + 1} is missing a name`,
          suggestion: 'Add descriptive names to funnel steps'
        })
      }
      Eif (step.filter && 'member' in step.filter) {
        validateFilters([step.filter], metadata, errors, corrections)
      }
    }
  }
}
 
/**
 * Validate flow query structure
 */
function validateFlowQuery(
  query: SemanticQuery,
  metadata: CubeMetadata[],
  errors: ValidationError[],
  warnings: ValidationWarning[],
  corrections: Map<string, string>
): void {
  const flow = query.flow
  Iif (!flow) return
 
  Iif (!flow.bindingKey) {
    errors.push({
      type: 'syntax_error',
      message: 'flow.bindingKey is required'
    })
  E} else if (typeof flow.bindingKey === 'string') {
    validateDimension(flow.bindingKey, metadata, errors, corrections)
  }
 
  Iif (!flow.timeDimension) {
    errors.push({
      type: 'syntax_error',
      message: 'flow.timeDimension is required'
    })
  E} else if (typeof flow.timeDimension === 'string') {
    validateDimension(flow.timeDimension, metadata, errors, corrections)
  }
 
  if (!flow.eventDimension) {
    errors.push({
      type: 'syntax_error',
      message: 'flow.eventDimension is required'
    })
  E} else if (typeof flow.eventDimension === 'string') {
    validateDimension(flow.eventDimension, metadata, errors, corrections)
  }
 
  if (flow.stepsBefore === undefined && flow.stepsAfter === undefined) {
    warnings.push({
      type: 'best_practice',
      message: 'Neither stepsBefore nor stepsAfter specified',
      suggestion: 'Set stepsBefore and/or stepsAfter to see event sequences'
    })
  }
}
 
/**
 * Validate retention query structure
 */
function validateRetentionQuery(
  query: SemanticQuery,
  metadata: CubeMetadata[],
  errors: ValidationError[],
  warnings: ValidationWarning[],
  corrections: Map<string, string>
): void {
  const retention = query.retention
  Iif (!retention) return
 
  Iif (!retention.bindingKey) {
    errors.push({
      type: 'syntax_error',
      message: 'retention.bindingKey is required'
    })
  E} else if (typeof retention.bindingKey === 'string') {
    validateDimension(retention.bindingKey, metadata, errors, corrections)
  }
 
  if (!retention.timeDimension) {
    errors.push({
      type: 'syntax_error',
      message: 'retention.timeDimension is required'
    })
  E} else if (typeof retention.timeDimension === 'string') {
    validateDimension(retention.timeDimension, metadata, errors, corrections)
  }
 
  if (!retention.granularity) {
    warnings.push({
      type: 'best_practice',
      message: 'retention.granularity not specified',
      suggestion: 'Specify granularity: "day", "week", or "month"'
    })
  }
 
  if (!retention.periods) {
    warnings.push({
      type: 'best_practice',
      message: 'retention.periods not specified',
      suggestion: 'Specify number of periods to analyze'
    })
  }
}
 
/**
 * Validate a query with helpful corrections
 */
export function validateQuery(
  query: SemanticQuery,
  metadata: CubeMetadata[]
): ValidationResult {
  const errors: ValidationError[] = []
  const warnings: ValidationWarning[] = []
  const corrections: Map<string, string> = new Map()
 
  // Detect query type and validate accordingly
  if (query.funnel) {
    validateFunnelQuery(query, metadata, errors, warnings, corrections)
    // Skip standard validation for funnel queries
    return {
      isValid: errors.length === 0,
      errors,
      warnings,
      correctedQuery: undefined // Funnel corrections not implemented yet
    }
  }
 
  if (query.flow) {
    validateFlowQuery(query, metadata, errors, warnings, corrections)
    return {
      isValid: errors.length === 0,
      errors,
      warnings,
      correctedQuery: undefined
    }
  }
 
  if (query.retention) {
    validateRetentionQuery(query, metadata, errors, warnings, corrections)
    return {
      isValid: errors.length === 0,
      errors,
      warnings,
      correctedQuery: undefined
    }
  }
 
  // Validate measures
  Eif (query.measures) {
    for (const measure of query.measures) {
      validateMeasure(measure, metadata, errors, corrections)
    }
  }
 
  // Validate dimensions
  if (query.dimensions) {
    for (const dimension of query.dimensions) {
      validateDimension(dimension, metadata, errors, corrections)
    }
  }
 
  // Validate timeDimensions
  Iif (query.timeDimensions) {
    for (const timeDim of query.timeDimensions) {
      validateDimension(timeDim.dimension, metadata, errors, corrections)
 
      // Check that the dimension is a time type
      const [cubeName] = timeDim.dimension.split('.')
      const cube = metadata.find(c => c.name === cubeName)
      if (cube) {
        const dimension = cube.dimensions.find(d => d.name === timeDim.dimension)
        if (dimension && dimension.type !== 'time') {
          warnings.push({
            type: 'best_practice',
            message: `Dimension '${timeDim.dimension}' is not a time type (it's '${dimension.type}')`,
            field: timeDim.dimension,
            suggestion: 'Use a dimension with type "time" for timeDimensions'
          })
        }
      }
    }
  }
 
  // Validate filters
  Iif (query.filters) {
    validateFilters(query.filters, metadata, errors, corrections)
  }
 
  // Check for empty query
  Iif (!query.measures?.length && !query.dimensions?.length) {
    errors.push({
      type: 'syntax_error',
      message: 'Query must have at least one measure or dimension'
    })
  }
 
  // Performance warnings
  Iif (query.measures && query.measures.length > 10) {
    warnings.push({
      type: 'performance',
      message: `Query has ${query.measures.length} measures, which may impact performance`,
      suggestion: 'Consider splitting into multiple queries'
    })
  }
 
  Iif (query.dimensions && query.dimensions.length > 5) {
    warnings.push({
      type: 'performance',
      message: `Query has ${query.dimensions.length} dimensions, which may produce many rows`,
      suggestion: 'Consider adding filters or reducing dimensions'
    })
  }
 
  // Build corrected query if we have corrections
  let correctedQuery: SemanticQuery | undefined
  Iif (corrections.size > 0) {
    const clonedQuery: SemanticQuery = JSON.parse(JSON.stringify(query)) // Deep clone
 
    if (clonedQuery.measures) {
      clonedQuery.measures = clonedQuery.measures.map(m => corrections.get(m) || m)
    }
    if (clonedQuery.dimensions) {
      clonedQuery.dimensions = clonedQuery.dimensions.map(d => corrections.get(d) || d)
    }
    if (clonedQuery.timeDimensions) {
      clonedQuery.timeDimensions = clonedQuery.timeDimensions.map(td => ({
        ...td,
        dimension: corrections.get(td.dimension) || td.dimension
      }))
    }
    // Note: Filter corrections would require recursive update
    correctedQuery = clonedQuery
  }
 
  return {
    isValid: errors.length === 0,
    errors,
    warnings,
    correctedQuery: corrections.size > 0 ? correctedQuery : undefined
  }
}