File size: 12,943 Bytes
7a1ad33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { loadBaselines, updateBaseline } from './memory-baselines.js';
import type { MemoryBaseline, MemoryBaselineFile } from './memory-baselines.js';
import type { TestRig } from './test-rig.js';

/** Configuration for asciichart plot function. */
interface PlotConfig {
  height?: number;
  format?: (x: number) => string;
}

/** Type for the asciichart plot function. */
type PlotFn = (series: number[], config?: PlotConfig) => string;

/**
 * A single memory snapshot at a point in time.
 */
export interface MemorySnapshot {
  timestamp: number;
  label: string;
  heapUsed: number;
  heapTotal: number;
  rss: number;
  external: number;
}

/**
 * Result from running a memory test scenario.
 */
export interface MemoryTestResult {
  scenarioName: string;
  snapshots: MemorySnapshot[];
  peakHeapUsed: number;
  peakRss: number;
  peakExternal: number;
  finalHeapUsed: number;
  finalRss: number;
  finalExternal: number;
  baseline: MemoryBaseline | undefined;
  withinTolerance: boolean;
  deltaPercent: number;
}

/**
 * Options for the MemoryTestHarness.
 */
export interface MemoryTestHarnessOptions {
  /** Path to the baselines JSON file */
  baselinesPath: string;
  /** Default tolerance percentage (0-100). Default: 10 */
  defaultTolerancePercent?: number;
  /** Number of GC cycles to run before each snapshot. Default: 3 */
  gcCycles?: number;
  /** Delay in ms between GC cycles. Default: 100 */
  gcDelayMs?: number;
  /** Number of samples to take for median calculation. Default: 3 */
  sampleCount?: number;
}

/**
 * MemoryTestHarness provides infrastructure for running memory usage tests.
 *
 * It handles:
 * - Extracting memory metrics from CLI process telemetry
 * - Comparing against baselines with configurable tolerance
 * - Generating ASCII chart reports of memory trends
 */
export class MemoryTestHarness {
  private baselines: MemoryBaselineFile;
  private readonly baselinesPath: string;
  private readonly defaultTolerancePercent: number;
  private allResults: MemoryTestResult[] = [];

  constructor(options: MemoryTestHarnessOptions) {
    this.baselinesPath = options.baselinesPath;
    this.defaultTolerancePercent = options.defaultTolerancePercent ?? 10;
    this.baselines = loadBaselines(this.baselinesPath);
  }

  /**
   * Extract memory snapshot from TestRig telemetry.
   */
  async takeSnapshot(
    rig: TestRig,
    label: string = 'snapshot',
    strategy: 'peak' | 'last' = 'last',
  ): Promise<MemorySnapshot> {
    const metrics = rig.readMemoryMetrics(strategy);

    return {
      timestamp: metrics.timestamp,
      label,
      heapUsed: metrics.heapUsed,
      heapTotal: metrics.heapTotal,
      rss: metrics.rss,
      external: metrics.external,
    };
  }

  /**
   * Run a memory test scenario.
   *
   * @param rig - The TestRig instance running the CLI
   * @param name - Scenario name (must match baseline key)
   * @param fn - Async function that executes the scenario. Receives a
   *   `recordSnapshot` callback for recording intermediate snapshots.
   * @param tolerancePercent - Override default tolerance for this scenario
   */
  async runScenario(
    rig: TestRig,
    name: string,
    fn: (
      recordSnapshot: (label: string) => Promise<MemorySnapshot>,
    ) => Promise<void>,
    tolerancePercent?: number,
  ): Promise<MemoryTestResult> {
    const tolerance = tolerancePercent ?? this.defaultTolerancePercent;
    const snapshots: MemorySnapshot[] = [];

    // Record initial snapshot
    const beforeSnap = await this.takeSnapshot(rig, 'before');
    snapshots.push(beforeSnap);

    // Record a callback for intermediate snapshots
    const recordSnapshot = async (label: string): Promise<MemorySnapshot> => {
      // Small delay to allow telemetry to flush if needed
      await rig.waitForTelemetryReady();
      const snap = await this.takeSnapshot(rig, label);
      snapshots.push(snap);
      return snap;
    };

    // Run the scenario
    await fn(recordSnapshot);

    // Final wait for telemetry to ensure everything is flushed
    await rig.waitForTelemetryReady();

    // After snapshot
    const afterSnap = await this.takeSnapshot(rig, 'after');
    snapshots.push(afterSnap);

    // Calculate peak values from ALL snapshots seen during the scenario
    const allSnapshots = rig.readAllMemorySnapshots();
    const scenarioSnapshots = allSnapshots.filter(
      (s) =>
        s.timestamp >= beforeSnap.timestamp &&
        s.timestamp <= afterSnap.timestamp,
    );

    const peakHeapUsed = Math.max(
      ...scenarioSnapshots.map((s) => s.heapUsed),
      ...snapshots.map((s) => s.heapUsed),
    );
    const peakRss = Math.max(
      ...scenarioSnapshots.map((s) => s.rss),
      ...snapshots.map((s) => s.rss),
    );
    const peakExternal = Math.max(
      ...scenarioSnapshots.map((s) => s.external),
      ...snapshots.map((s) => s.external),
    );

    // Get baseline
    const baseline = this.baselines.scenarios[name];

    // Determine if within tolerance
    let deltaPercent = 0;
    let withinTolerance = true;

    if (baseline) {
      const measuredMB = afterSnap.heapUsed / (1024 * 1024);
      deltaPercent =
        ((measuredMB - baseline.heapUsedMB) / baseline.heapUsedMB) * 100;
      withinTolerance = deltaPercent <= tolerance;
    }

    const result: MemoryTestResult = {
      scenarioName: name,
      snapshots,
      peakHeapUsed,
      peakRss,
      peakExternal,
      finalHeapUsed: afterSnap.heapUsed,
      finalRss: afterSnap.rss,
      finalExternal: afterSnap.external,
      baseline,
      withinTolerance,
      deltaPercent,
    };

    this.allResults.push(result);
    return result;
  }

  /**
   * Assert that a scenario result is within the baseline tolerance.
   * Throws an assertion error with details if it exceeds the threshold.
   */
  assertWithinBaseline(
    result: MemoryTestResult,
    tolerancePercent?: number,
  ): void {
    const tolerance = tolerancePercent ?? this.defaultTolerancePercent;

    if (!result.baseline) {
      console.warn(
        `⚠ No baseline found for "${result.scenarioName}". ` +
          `Run with UPDATE_MEMORY_BASELINES=true to create one. ` +
          `Measured: ${formatMB(result.finalHeapUsed)} heap used.`,
      );
      return; // Don't fail if no baseline exists yet
    }

    const measuredMB = result.finalHeapUsed / (1024 * 1024);
    const deltaPercent =
      ((measuredMB - result.baseline.heapUsedMB) / result.baseline.heapUsedMB) *
      100;

    if (deltaPercent > tolerance) {
      throw new Error(
        `Memory regression detected for "${result.scenarioName}"!\n` +
          `  Measured:  ${formatMB(result.finalHeapUsed)} heap used\n` +
          `  Baseline:  ${result.baseline.heapUsedMB.toFixed(1)} MB heap used\n` +
          `  Delta:     ${deltaPercent.toFixed(1)}% (tolerance: ${tolerance}%)\n` +
          `  Peak heap: ${formatMB(result.peakHeapUsed)}\n` +
          `  Peak RSS:  ${formatMB(result.peakRss)}\n` +
          `  Peak External:  ${formatMB(result.peakExternal)}`,
      );
    }
  }

  /**
   * Update the baseline for a scenario with the current measured values.
   */
  updateScenarioBaseline(result: MemoryTestResult): void {
    const lastSnapshot = result.snapshots[result.snapshots.length - 1];
    updateBaseline(this.baselinesPath, result.scenarioName, {
      heapUsedMB: Number((result.finalHeapUsed / (1024 * 1024)).toFixed(1)),
      heapTotalMB: Number(
        ((lastSnapshot?.heapTotal ?? 0) / (1024 * 1024)).toFixed(1),
      ),
      rssMB: Number((result.finalRss / (1024 * 1024)).toFixed(1)),
      externalMB: Number((result.finalExternal / (1024 * 1024)).toFixed(1)),
    });
    // Reload baselines after update
    this.baselines = loadBaselines(this.baselinesPath);
  }

  /**
   * Analyze snapshots to detect sustained leaks.
   * A leak is flagged if growth is observed in both phases.
   */
  analyzeSnapshots(
    snapshots: MemorySnapshot[],
    thresholdBytes: number = 1024 * 1024, // 1 MB
  ): { leaked: boolean; message: string } {
    if (snapshots.length < 3) {
      return { leaked: false, message: 'Not enough snapshots to analyze' };
    }

    const snap1 = snapshots[snapshots.length - 3];
    const snap2 = snapshots[snapshots.length - 2];
    const snap3 = snapshots[snapshots.length - 1];

    const growth1 = snap2.heapUsed - snap1.heapUsed;
    const growth2 = snap3.heapUsed - snap2.heapUsed;

    const leaked = growth1 > thresholdBytes && growth2 > thresholdBytes;
    let message = leaked
      ? `Memory bloat detected: sustained growth (${formatMB(growth1)} -> ${formatMB(growth2)})`
      : `No sustained growth detected above threshold.`;

    return { leaked, message };
  }

  /**
   * Assert that memory returns to a baseline level after a peak.
   * Useful for verifying that large tool outputs or history are not retained.
   */
  assertMemoryReturnsToBaseline(
    snapshots: MemorySnapshot[],
    tolerancePercent: number = 10,
  ): void {
    if (snapshots.length < 3) {
      throw new Error('Need at least 3 snapshots to check return to baseline');
    }

    // Find the first non-zero snapshot as baseline
    const baseline = snapshots.find((s) => s.heapUsed > 0);
    if (!baseline) {
      return; // No memory reported yet
    }

    const final = snapshots[snapshots.length - 1]!;

    const tolerance = baseline.heapUsed * (tolerancePercent / 100);
    const delta = final.heapUsed - baseline.heapUsed;

    if (delta > tolerance) {
      throw new Error(
        `Memory did not return to baseline!\n` +
          `  Baseline: ${formatMB(baseline.heapUsed)} (${baseline.label})\n` +
          `  Final:    ${formatMB(final.heapUsed)} (${final.label})\n` +
          `  Delta:    ${formatMB(delta)} (tolerance: ${formatMB(tolerance)})`,
      );
    }
  }

  /**
   * Generate a report with ASCII charts and summary table.
   * Uses the `asciichart` library for terminal visualization.
   */
  async generateReport(results?: MemoryTestResult[]): Promise<string> {
    const resultsToReport = results ?? this.allResults;
    const lines: string[] = [];

    lines.push('');
    lines.push('═══════════════════════════════════════════════════');
    lines.push('         MEMORY USAGE TEST REPORT');
    lines.push('═══════════════════════════════════════════════════');
    lines.push('');

    for (const result of resultsToReport) {
      const measured = formatMB(result.finalHeapUsed);
      const baseline = result.baseline
        ? `${result.baseline.heapUsedMB.toFixed(1)} MB`
        : 'N/A';
      const delta = result.baseline
        ? `${result.deltaPercent >= 0 ? '+' : ''}${result.deltaPercent.toFixed(1)}%`
        : 'N/A';
      const status = !result.baseline
        ? 'NEW'
        : result.withinTolerance
          ? 'βœ…'
          : '❌';

      lines.push(
        `${result.scenarioName}: ${measured} (Baseline: ${baseline}, Delta: ${delta}) ${status}`,
      );
    }
    lines.push('');

    // Generate ASCII chart for each scenario with multiple snapshots
    try {
      // @ts-expect-error - asciichart may not have types
      const asciichart = (await import('asciichart')) as {
        default?: { plot?: PlotFn };
        plot?: PlotFn;
      };
      const plot: PlotFn | undefined =
        asciichart.default?.plot ?? asciichart.plot;

      for (const result of resultsToReport) {
        if (result.snapshots.length > 2) {
          lines.push(`πŸ“ˆ Memory trend: ${result.scenarioName}`);
          lines.push('─'.repeat(60));

          const heapDataMB = result.snapshots.map(
            (s) => s.heapUsed / (1024 * 1024),
          );

          if (plot) {
            const chart = plot(heapDataMB, {
              height: 10,
              format: (x: number) => `${x.toFixed(1)} MB`.padStart(10),
            });
            lines.push(chart);
          }

          // Label the x-axis with snapshot labels
          const labels = result.snapshots.map((s) => s.label);
          lines.push('  ' + labels.join(' β†’ '));
          lines.push('');
        }
      }
    } catch {
      lines.push(
        '(asciichart not available β€” install with: npm install --save-dev asciichart)',
      );
      lines.push('');
    }

    lines.push('═══════════════════════════════════════════════════');
    lines.push('');

    const report = lines.join('\n');
    console.log(report);
    return report;
  }
}

/**
 * Format bytes as a human-readable MB string.
 */
function formatMB(bytes: number): string {
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}