All files / use-memory-monitor/src/utils leakDetection.ts

94.11% Statements 160/170
84.9% Branches 90/106
100% Functions 22/22
94.33% Lines 150/159

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                                                                            64x   64x 2x       62x 62x 62x 62x 62x   62x 481x 481x 481x 481x 481x       62x   62x       62x 62x     62x 62x 62x   62x 481x 481x 481x     62x   64x                           34x 2x       218x 32x     218x 32x     34x 5x     27x 3x     24x                   15x 1x     136x 14x   14x                             8x   8x                   8x 88x 88x 88x 88x     88x 5x                     8x 8x 5x   8x         8x   8x                                         8x                     8x     8x 4x 4x 2x 2x   2x                     72x 6x 6x   8x                                           8x 6x       4x 2x     4x 2x   8x 8x   2x       2x             10x 10x                                   12x 4x     8x       12x 2x     6x 1x     5x 1x     4x                   2x   2x 2x                                                       8x                 8x 6x 6x       8x 5x 5x         8x 2x     2x   2x   6x   4x       8x 8x 8x       8x 2x 6x 4x         8x             8x   8x                                           11x 11x 11x     11x 1x                         10x     10x 2x                           96x 8x 8x     11x     11x     11x     11x                   11x     11x 2x       8x 1x 7x 6x       8x 3x       8x     8x                   11x   11x                                             4x 1x     3x 3x    
import type {
  BaselineAnalysis,
  GCAnalysis,
  GCEvent,
  LeakAnalysis,
  LeakProbabilityFactors,
  LeakSensitivity,
  MemoryInfo,
  Trend,
} from "../types";
import {
  BASELINE_GROWTH_THRESHOLD,
  GC_DETECTION_THRESHOLD,
  LEAK_PROBABILITY_THRESHOLD,
  LEAK_SENSITIVITY_CONFIG,
  MIN_LEAK_DETECTION_SAMPLES,
} from "../constants";
 
/**
 * Result of linear regression analysis
 */
export interface RegressionResult {
  /** Slope of the regression line (bytes per sample) */
  slope: number;
  /** Y-intercept of the regression line */
  intercept: number;
  /** R-squared value (coefficient of determination, 0-1) */
  rSquared: number;
}
 
/**
 * Perform simple linear regression on a set of points.
 * Uses the least squares method.
 *
 * @param points - Array of [x, y] coordinate pairs
 * @returns Regression result with slope, intercept, and R-squared
 */
export function linearRegression(points: [number, number][]): RegressionResult {
  const n = points.length;
 
  if (n < 2) {
    return { slope: 0, intercept: 0, rSquared: 0 };
  }
 
  // Calculate sums
  let sumX = 0;
  let sumY = 0;
  let sumXY = 0;
  let sumX2 = 0;
  let sumY2 = 0;
 
  for (const [x, y] of points) {
    sumX += x;
    sumY += y;
    sumXY += x * y;
    sumX2 += x * x;
    sumY2 += y * y;
  }
 
  // Calculate slope and intercept
  const denominator = n * sumX2 - sumX * sumX;
 
  Iif (denominator === 0) {
    return { slope: 0, intercept: sumY / n, rSquared: 0 };
  }
 
  const slope = (n * sumXY - sumX * sumY) / denominator;
  const intercept = (sumY - slope * sumX) / n;
 
  // Calculate R-squared (coefficient of determination)
  const meanY = sumY / n;
  let ssTotal = 0; // Total sum of squares
  let ssResidual = 0; // Residual sum of squares
 
  for (const [x, y] of points) {
    const predicted = slope * x + intercept;
    ssTotal += Math.pow(y - meanY, 2);
    ssResidual += Math.pow(y - predicted, 2);
  }
 
  const rSquared = ssTotal === 0 ? 0 : 1 - ssResidual / ssTotal;
 
  return {
    slope,
    intercept,
    rSquared: Math.max(0, Math.min(1, rSquared)), // Clamp to [0, 1]
  };
}
 
/**
 * Calculate the memory trend from samples.
 *
 * @param samples - Array of memory info samples
 * @returns Trend direction
 */
export function calculateTrend(samples: MemoryInfo[]): Trend {
  if (samples.length < 2) {
    return "stable";
  }
 
  // Convert samples to [index, heapUsed] points
  const points: [number, number][] = samples.map((s, i) => [i, s.heapUsed]);
  const { slope } = linearRegression(points);
 
  // Normalize slope by average heap size for relative comparison
  const avgHeap = samples.reduce((sum, s) => sum + s.heapUsed, 0) / samples.length;
  const normalizedSlope = avgHeap > 0 ? slope / avgHeap : 0;
 
  // Use stricter thresholds
  if (normalizedSlope > 0.02) {
    return "increasing";
  }
 
  if (normalizedSlope < -0.02) {
    return "decreasing";
  }
 
  return "stable";
}
 
/**
 * Calculate average growth rate (bytes per sample).
 *
 * @param samples - Array of memory info samples
 * @returns Average growth rate in bytes per sample
 */
export function calculateAverageGrowth(samples: MemoryInfo[]): number {
  if (samples.length < 2) {
    return 0;
  }
 
  const points: [number, number][] = samples.map((s, i) => [i, s.heapUsed]);
  const { slope } = linearRegression(points);
 
  return slope;
}
 
/**
 * Detect GC events in memory samples.
 * A GC event is detected when memory drops significantly between samples.
 *
 * @param samples - Array of memory info samples
 * @param threshold - Minimum drop ratio to consider as GC (default: 0.10 = 10%)
 * @returns GC analysis result
 */
export function detectGCEvents(
  samples: MemoryInfo[],
  threshold: number = GC_DETECTION_THRESHOLD
): GCAnalysis {
  const gcEvents: GCEvent[] = [];
 
  Iif (samples.length < 2) {
    return {
      gcEventCount: 0,
      gcEvents: [],
      avgRecoveryRatio: 0,
      lastGCTimestamp: null,
      isGCEffective: false,
    };
  }
 
  for (let i = 1; i < samples.length; i++) {
    const prev = samples[i - 1];
    const curr = samples[i];
    const drop = prev.heapUsed - curr.heapUsed;
    const dropRatio = drop / prev.heapUsed;
 
    // Significant drop indicates GC
    if (dropRatio >= threshold) {
      gcEvents.push({
        sampleIndex: i,
        memoryBefore: prev.heapUsed,
        memoryAfter: curr.heapUsed,
        recoveryAmount: drop,
        recoveryRatio: dropRatio,
        timestamp: curr.timestamp,
      });
    }
  }
 
  const gcEventCount = gcEvents.length;
  const avgRecoveryRatio = gcEventCount > 0
    ? gcEvents.reduce((sum, e) => sum + e.recoveryRatio, 0) / gcEventCount
    : 0;
  const lastGCTimestamp = gcEventCount > 0
    ? gcEvents[gcEvents.length - 1].timestamp
    : null;
 
  // GC is effective if it recovers at least 15% on average
  const isGCEffective = avgRecoveryRatio >= 0.15;
 
  return {
    gcEventCount,
    gcEvents,
    avgRecoveryRatio,
    lastGCTimestamp,
    isGCEffective,
  };
}
 
/**
 * Calculate baseline from post-GC memory values.
 * Baseline represents the "floor" memory after GC cycles.
 *
 * @param samples - Array of memory info samples
 * @param gcEvents - Detected GC events
 * @returns Baseline analysis
 */
export function calculateBaseline(
  samples: MemoryInfo[],
  gcEvents: GCEvent[]
): BaselineAnalysis {
  Iif (samples.length === 0) {
    return {
      baselineHeap: 0,
      currentHeap: 0,
      growthFromBaseline: 0,
      growthRatio: 0,
      isBaselineEstablished: false,
      isSignificantGrowth: false,
    };
  }
 
  const currentHeap = samples[samples.length - 1].heapUsed;
 
  // If we have GC events, use post-GC values as baseline
  if (gcEvents.length >= 2) {
    const postGCValues = gcEvents.map(e => e.memoryAfter);
    const baselineHeap = postGCValues.reduce((sum, v) => sum + v, 0) / postGCValues.length;
    const growthFromBaseline = currentHeap - baselineHeap;
    const growthRatio = baselineHeap > 0 ? growthFromBaseline / baselineHeap : 0;
 
    return {
      baselineHeap,
      currentHeap,
      growthFromBaseline,
      growthRatio,
      isBaselineEstablished: true,
      isSignificantGrowth: growthRatio > BASELINE_GROWTH_THRESHOLD,
    };
  }
 
  // Without enough GC events, use minimum value as approximate baseline
  const minHeap = Math.min(...samples.map(s => s.heapUsed));
  const growthFromBaseline = currentHeap - minHeap;
  const growthRatio = minHeap > 0 ? growthFromBaseline / minHeap : 0;
 
  return {
    baselineHeap: minHeap,
    currentHeap,
    growthFromBaseline,
    growthRatio,
    isBaselineEstablished: false,
    isSignificantGrowth: growthRatio > BASELINE_GROWTH_THRESHOLD,
  };
}
 
/**
 * Analyze trend of post-GC baselines.
 * If baselines are increasing over time, it indicates a true leak.
 *
 * @param gcEvents - Detected GC events
 * @returns Trend of baseline growth
 */
export function analyzeBaselineTrend(gcEvents: GCEvent[]): {
  trend: Trend;
  slope: number;
  rSquared: number;
} {
  if (gcEvents.length < 2) {
    return { trend: "stable", slope: 0, rSquared: 0 };
  }
 
  // Use post-GC values indexed by event order
  const points: [number, number][] = gcEvents.map((e, i) => [i, e.memoryAfter]);
  const { slope, rSquared } = linearRegression(points);
 
  // Normalize by average post-GC memory
  const avgPostGC = gcEvents.reduce((sum, e) => sum + e.memoryAfter, 0) / gcEvents.length;
  const normalizedSlope = avgPostGC > 0 ? slope / avgPostGC : 0;
 
  let trend: Trend = "stable";
  Iif (normalizedSlope > 0.02) {
    trend = "increasing";
  I} else if (normalizedSlope < -0.02) {
    trend = "decreasing";
  }
 
  return { trend, slope, rSquared };
}
 
/**
 * Calculate observation time from samples
 */
function calculateObservationTime(samples: MemoryInfo[]): number {
  Iif (samples.length < 2) return 0;
  return samples[samples.length - 1].timestamp - samples[0].timestamp;
}
 
/**
 * Generate a human-readable recommendation based on leak analysis.
 *
 * @param probability - Leak probability (0-100)
 * @param trend - Memory trend
 * @param averageGrowth - Average growth rate in bytes
 * @param gcAnalysis - GC analysis results
 * @returns Recommendation string
 */
export function generateRecommendation(
  probability: number,
  trend: Trend,
  averageGrowth: number,
  gcAnalysis?: GCAnalysis
): string | undefined {
  if (probability < 30) {
    return undefined;
  }
 
  const gcInfo = gcAnalysis && gcAnalysis.gcEventCount > 0
    ? ` GC has occurred ${gcAnalysis.gcEventCount} time(s) with ${(gcAnalysis.avgRecoveryRatio * 100).toFixed(0)}% average recovery.`
    : "";
 
  if (probability >= 80) {
    return `Critical: High probability of memory leak detected. Memory is growing at ${formatGrowthRate(averageGrowth)} per sample even after GC.${gcInfo} Consider profiling with browser DevTools.`;
  }
 
  if (probability >= 60) {
    return `Warning: Possible memory leak detected. Memory trend is ${trend}.${gcInfo} Monitor closely and check for retained references.`;
  }
 
  if (probability >= 30 && trend === "increasing") {
    return `Note: Memory usage is trending upward.${gcInfo} This may be normal for your application, but consider monitoring.`;
  }
 
  return undefined;
}
 
/**
 * Format growth rate for display.
 *
 * @param bytesPerSample - Growth rate in bytes per sample
 * @returns Formatted string
 */
function formatGrowthRate(bytesPerSample: number): string {
  const absBytes = Math.abs(bytesPerSample);
 
  Eif (absBytes >= 1024 * 1024) {
    return `${(bytesPerSample / (1024 * 1024)).toFixed(2)} MB`;
  }
 
  if (absBytes >= 1024) {
    return `${(bytesPerSample / 1024).toFixed(2)} KB`;
  }
 
  return `${bytesPerSample.toFixed(0)} bytes`;
}
 
/**
 * Calculate leak probability using multiple weighted factors.
 *
 * Factors:
 * - Slope contribution (0-30): How fast memory is growing
 * - R² contribution (0-20): How consistent the growth pattern is
 * - GC contribution (0-25): Whether GC fails to reclaim memory
 * - Time contribution (0-15): Longer observation = more confidence
 * - Baseline contribution (0-10): Whether post-GC baseline is rising
 */
function calculateWeightedProbability(
  slope: number,
  rSquared: number,
  gcAnalysis: GCAnalysis,
  baselineAnalysis: BaselineAnalysis,
  observationTime: number,
  config: typeof LEAK_SENSITIVITY_CONFIG["medium"]
): { probability: number; factors: LeakProbabilityFactors } {
  const factors: LeakProbabilityFactors = {
    slopeContribution: 0,
    rSquaredContribution: 0,
    gcContribution: 0,
    timeContribution: 0,
    baselineContribution: 0,
  };
 
  // 1. Slope contribution (max 30 points)
  if (slope > 0) {
    const slopeRatio = slope / config.minSlope;
    factors.slopeContribution = Math.min(30, slopeRatio * 15);
  }
 
  // 2. R² contribution (max 20 points)
  if (rSquared >= config.minR2) {
    const rSquaredBonus = (rSquared - config.minR2) / (1 - config.minR2);
    factors.rSquaredContribution = 10 + rSquaredBonus * 10;
  }
 
  // 3. GC contribution (max 25 points)
  // If GC is happening but not reclaiming memory, it's likely a leak
  if (gcAnalysis.gcEventCount >= config.minGCCycles) {
    Iif (!gcAnalysis.isGCEffective) {
      // GC is happening but not effective
      factors.gcContribution = 25;
    E} else if (gcAnalysis.avgRecoveryRatio < 0.3) {
      // GC recovery is poor
      factors.gcContribution = 15;
    }
  } else if (gcAnalysis.gcEventCount === 0 && slope > 0) {
    // No GC detected but memory growing - could be early stage leak
    factors.gcContribution = 5;
  }
 
  // 4. Time contribution (max 15 points)
  Eif (observationTime >= config.minObservationTime) {
    const timeRatio = Math.min(2, observationTime / config.minObservationTime);
    factors.timeContribution = timeRatio * 7.5;
  }
 
  // 5. Baseline contribution (max 10 points)
  if (baselineAnalysis.isBaselineEstablished && baselineAnalysis.isSignificantGrowth) {
    factors.baselineContribution = 10;
  } else if (baselineAnalysis.isSignificantGrowth) {
    factors.baselineContribution = 5;
  }
 
  // Sum all contributions
  const rawProbability =
    factors.slopeContribution +
    factors.rSquaredContribution +
    factors.gcContribution +
    factors.timeContribution +
    factors.baselineContribution;
 
  // Apply sensitivity multiplier and clamp
  const probability = Math.min(100, Math.max(0, rawProbability * config.probabilityMultiplier));
 
  return { probability, factors };
}
 
/**
 * Analyze memory samples for potential leaks with enhanced algorithm.
 *
 * The enhanced algorithm considers:
 * 1. GC cycles - true leaks persist even after GC
 * 2. Baseline trend - post-GC memory should not grow over time
 * 3. Observation time - requires sufficient data before making judgment
 * 4. Multiple factors - weighted scoring system for accuracy
 *
 * @param samples - Array of memory info samples (minimum 10 recommended)
 * @param sensitivity - Detection sensitivity level
 * @param customThreshold - Optional custom growth threshold (bytes/sample)
 * @returns Leak analysis result
 */
export function analyzeLeakProbability(
  samples: MemoryInfo[],
  sensitivity: LeakSensitivity = "medium",
  customThreshold?: number
): LeakAnalysis {
  const config = LEAK_SENSITIVITY_CONFIG[sensitivity];
  const trend = calculateTrend(samples);
  const averageGrowth = calculateAverageGrowth(samples);
 
  // Not enough samples for reliable analysis
  if (samples.length < MIN_LEAK_DETECTION_SAMPLES) {
    return {
      isLeaking: false,
      probability: 0,
      trend,
      averageGrowth,
      rSquared: 0,
      samples,
      recommendation: undefined,
      confidence: 0,
    };
  }
 
  // Calculate observation time
  const observationTime = calculateObservationTime(samples);
 
  // Not enough observation time
  if (observationTime < config.minObservationTime) {
    return {
      isLeaking: false,
      probability: 0,
      trend,
      averageGrowth,
      rSquared: 0,
      samples,
      recommendation: undefined,
      observationTime,
      confidence: Math.round((observationTime / config.minObservationTime) * 50),
    };
  }
 
  // Perform linear regression
  const points: [number, number][] = samples.map((s, i) => [i, s.heapUsed]);
  const { slope, rSquared } = linearRegression(points);
  const threshold = customThreshold ?? config.minSlope;
 
  // Detect GC events
  const gcAnalysis = detectGCEvents(samples);
 
  // Calculate baseline
  const baselineAnalysis = calculateBaseline(samples, gcAnalysis.gcEvents);
 
  // Check baseline trend if we have enough GC cycles
  const baselineTrend = analyzeBaselineTrend(gcAnalysis.gcEvents);
 
  // Calculate weighted probability
  const { probability: rawProbability, factors } = calculateWeightedProbability(
    slope,
    rSquared,
    gcAnalysis,
    baselineAnalysis,
    observationTime,
    config
  );
 
  // Apply additional checks for false positive reduction
  let probability = rawProbability;
 
  // If GC is effective and baseline is stable, reduce probability
  if (gcAnalysis.isGCEffective && baselineTrend.trend !== "increasing") {
    probability = Math.max(0, probability - 20);
  }
 
  // If trend is decreasing or stable, cap probability
  if (trend === "decreasing") {
    probability = Math.min(probability, 10);
  } else if (trend === "stable") {
    probability = Math.min(probability, 30);
  }
 
  // If slope is negative or very small, cap probability
  if (slope <= 0 || slope < threshold * 0.3) {
    probability = Math.min(probability, 20);
  }
 
  // Round probability
  probability = Math.round(probability);
 
  // Calculate confidence based on data quality
  const confidence = Math.round(
    Math.min(100,
      (samples.length / 20) * 25 + // Sample count contribution
      (gcAnalysis.gcEventCount >= config.minGCCycles ? 25 : gcAnalysis.gcEventCount * 10) + // GC observation
      (observationTime / config.minObservationTime) * 25 + // Time contribution
      rSquared * 25 // Fit quality
    )
  );
 
  // Determine if leaking (using stricter threshold)
  const isLeaking = probability >= LEAK_PROBABILITY_THRESHOLD;
 
  return {
    isLeaking,
    probability,
    trend,
    averageGrowth: slope,
    rSquared,
    samples,
    recommendation: generateRecommendation(probability, trend, slope, gcAnalysis),
    gcAnalysis,
    baselineAnalysis,
    observationTime,
    confidence,
    factors,
  };
}
 
/**
 * Quick check if memory is trending upward (without full analysis).
 *
 * @param samples - Array of memory info samples
 * @returns True if memory appears to be growing
 */
export function isMemoryGrowing(samples: MemoryInfo[]): boolean {
  if (samples.length < 3) {
    return false;
  }
 
  const trend = calculateTrend(samples);
  return trend === "increasing";
}