File size: 6,750 Bytes
cd8bd0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { describe, it, before } from "node:test";
import assert from "node:assert/strict";

import {
  BENCHMARK_CORPUS,
  engineToCompressFn,
  benchmarkEngines,
  compareReports,
  runBenchmarkGate,
} from "../../../open-sse/services/compression/harness/benchmark.ts";

// ── RED/GREEN proof: all assertions here must hold once benchmark.ts exists ──

describe("benchmark β€” engineToCompressFn adapter", () => {
  it("returns a function for a known engine id", () => {
    const fn = engineToCompressFn("rtk");
    assert.equal(typeof fn, "function");
  });

  it("compressFn returns a string for any text input", async () => {
    const fn = engineToCompressFn("rtk");
    const noisy =
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n".repeat(10) +
      "Unnecessary filler words that add no value whatsoever indeed actually.";
    const out = await fn(noisy);
    assert.equal(typeof out, "string");
  });

  it("compressFn output is shorter or equal for clearly compressible prose", async () => {
    // A highly redundant input that caveman rules should shorten
    const fn = engineToCompressFn("caveman");
    const repetitive =
      "This is a very redundant message. This is a very redundant message.\n".repeat(8);
    const out = await fn(repetitive);
    // The adapter must return a string and it must not be longer than the input
    assert.ok(
      out.length <= repetitive.length,
      `expected shorter output, got ${out.length} vs ${repetitive.length}`
    );
  });
});

describe("benchmark β€” benchmarkEngines", () => {
  let reports: Awaited<ReturnType<typeof benchmarkEngines>>;

  before(async () => {
    reports = await benchmarkEngines(BENCHMARK_CORPUS, ["rtk", "caveman", "headroom"]);
  });

  it("returns one report per requested engine", () => {
    assert.deepEqual(Object.keys(reports).sort(), ["caveman", "headroom", "rtk"]);
  });

  it("each report has a valid meanSavingsPercent (a number)", () => {
    for (const [engineId, report] of Object.entries(reports)) {
      assert.equal(
        typeof report.meanSavingsPercent,
        "number",
        `${engineId}: meanSavingsPercent must be a number`
      );
    }
  });

  it("each report has meanRetention in [0, 1]", () => {
    for (const [engineId, report] of Object.entries(reports)) {
      assert.ok(
        report.meanRetention >= 0 && report.meanRetention <= 1,
        `${engineId}: meanRetention ${report.meanRetention} must be in [0,1]`
      );
    }
  });

  it("each report has results for every corpus item", () => {
    for (const [engineId, report] of Object.entries(reports)) {
      assert.equal(
        report.results.length,
        BENCHMARK_CORPUS.length,
        `${engineId}: expected ${BENCHMARK_CORPUS.length} result(s), got ${report.results.length}`
      );
    }
  });
});

describe("benchmark β€” compareReports", () => {
  it("returns one summary row per engine", async () => {
    const reports = await benchmarkEngines(BENCHMARK_CORPUS, ["rtk", "caveman"]);
    const summary = compareReports(reports);
    assert.equal(summary.length, 2);
    for (const row of summary) {
      assert.ok("engine" in row);
      assert.ok("meanSavingsPercent" in row);
      assert.ok("meanRetention" in row);
      assert.ok("totalCompressedTokens" in row);
    }
  });

  it("is sorted by meanSavingsPercent descending (best saver first)", async () => {
    const reports = await benchmarkEngines(BENCHMARK_CORPUS, ["rtk", "caveman"]);
    const summary = compareReports(reports);
    for (let i = 1; i < summary.length; i++) {
      assert.ok(
        summary[i - 1].meanSavingsPercent >= summary[i].meanSavingsPercent,
        `row ${i - 1} savings ${summary[i - 1].meanSavingsPercent} should be >= row ${i} savings ${summary[i].meanSavingsPercent}`
      );
    }
  });
});

describe("benchmark β€” runBenchmarkGate (N4)", () => {
  it("passes when baselines match current costs", async () => {
    const reports = await benchmarkEngines(BENCHMARK_CORPUS, ["rtk"]);
    // Baseline = exact current tokensPerTask β†’ must pass
    const rtkReport = reports["rtk"];
    const baselines: Record<string, { tasks: Record<string, number> }> = {};
    const taskTotals: Record<string, { sum: number; count: number }> = {};
    for (const r of rtkReport.results) {
      const t = taskTotals[r.task] ?? { sum: 0, count: 0 };
      t.sum += r.compressedTokens;
      t.count += 1;
      taskTotals[r.task] = t;
    }
    baselines["rtk"] = {
      tasks: Object.fromEntries(
        Object.entries(taskTotals).map(([k, v]) => [k, Math.round(v.sum / v.count)])
      ),
    };

    const gateResults = runBenchmarkGate(reports, baselines);
    const rtkGate = gateResults.find((g) => g.engine === "rtk");
    assert.ok(rtkGate, "rtk gate result missing");
    assert.equal(rtkGate.gate.passed, true, "gate should pass when baseline matches current");
  });

  it("fails (regression) when baseline is tighter than actual cost", async () => {
    const reports = await benchmarkEngines(BENCHMARK_CORPUS, ["rtk"]);
    // Set an impossibly tight baseline (1 token per task) β†’ regression guaranteed
    const impossibleBaselines: Record<string, { tasks: Record<string, number> }> = {
      rtk: { tasks: { prose: 1, "tool-output": 1, json: 1 } },
    };
    const gateResults = runBenchmarkGate(reports, impossibleBaselines);
    const rtkGate = gateResults.find((g) => g.engine === "rtk");
    assert.ok(rtkGate, "rtk gate result missing");
    assert.equal(rtkGate.gate.passed, false, "gate should fail when baseline is impossibly tight");
    assert.ok(rtkGate.gate.regressions.length > 0, "regressions array must be non-empty");
  });
});

describe("benchmark β€” reproducibility", () => {
  it("two runs on the same corpus yield identical meanSavingsPercent", async () => {
    const engines = ["rtk", "caveman"];
    // Run the two passes SEQUENTIALLY: this asserts determinism (same input β†’ same
    // output), not concurrency-safety. Running them in parallel (Promise.all) shares the
    // engine singletons across both passes and races their internal state under load.
    const r1 = await benchmarkEngines(BENCHMARK_CORPUS, engines);
    const r2 = await benchmarkEngines(BENCHMARK_CORPUS, engines);
    for (const id of engines) {
      assert.equal(
        r1[id].meanSavingsPercent,
        r2[id].meanSavingsPercent,
        `${id}: non-deterministic meanSavingsPercent`
      );
      assert.equal(
        r1[id].meanRetention,
        r2[id].meanRetention,
        `${id}: non-deterministic meanRetention`
      );
      assert.equal(
        r1[id].totalCompressedTokens,
        r2[id].totalCompressedTokens,
        `${id}: non-deterministic totalCompressedTokens`
      );
    }
  });
});