File size: 11,017 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
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
/**
 * TV1 β€” Transversal compression bail-out discipline (OPT-IN).
 *
 * Proves:
 *  1. An engine that THROWS in apply() β†’ step skipped (no throw, original body kept).
 *  2. An engine whose gain is < minGainPercent (10%) β†’ step skipped.
 *  3. An engine with gain β‰₯ 10% β†’ applied normally.
 *  4. With bail-out DISABLED (default) β†’ a <10%-gain engine IS applied
 *     (proving that opt-in default never changes existing behaviour).
 */
import { describe, it, before, after } from "node:test";
import assert from "node:assert/strict";

import {
  applyStackedCompression,
  applyStackedCompressionAsync,
} from "../../../open-sse/services/compression/index.ts";
import {
  registerCompressionEngine,
  unregisterCompressionEngine,
} from "../../../open-sse/services/compression/engines/registry.ts";
import type {
  CompressionEngine,
  CompressionEngineTarget,
} from "../../../open-sse/services/compression/engines/types.ts";
import type {
  CompressionPipelineStep,
  CompressionResult,
} from "../../../open-sse/services/compression/types.ts";

// ── helpers ──────────────────────────────────────────────────────────────────

/** Base skeleton shared by all fake engines. */
function makeBaseEngine(id: string): Omit<CompressionEngine, "apply"> {
  return {
    id,
    name: id,
    description: id,
    icon: "x",
    targets: ["messages"] as CompressionEngineTarget[],
    stackable: true,
    stackPriority: 0,
    metadata: {
      id,
      name: id,
      description: id,
      inputScope: "messages",
      targetLatencyMs: 1,
      supportsPreview: false,
      stable: true,
    },
    compress: (body) => ({ body, compressed: false, stats: null }),
    getConfigSchema: () => [],
    validateConfig: () => ({ valid: true, errors: [] }),
  };
}

/** Engine that always throws during apply(). */
const THROW_ENGINE_ID = "bailout-throw-engine";
const throwEngine: CompressionEngine = {
  ...makeBaseEngine(THROW_ENGINE_ID),
  apply: (_body) => {
    throw new Error("simulated engine failure");
  },
};

/** Engine that returns a low gain (5% < 10% threshold). */
const LOW_GAIN_ENGINE_ID = "bailout-low-gain-engine";
function makeLowGainEngine(id = LOW_GAIN_ENGINE_ID): CompressionEngine {
  return {
    ...makeBaseEngine(id),
    apply: (body) => {
      const messages = (body.messages as Array<{ role: string; content: string }>) ?? [];
      const next = messages.map((m) =>
        m.role === "user" ? { ...m, content: m.content + "|low" } : m
      );
      return {
        body: { ...body, messages: next },
        compressed: true,
        stats: {
          originalTokens: 100,
          compressedTokens: 95,
          savingsPercent: 5, // 5% < 10% threshold
          techniquesUsed: [id],
          mode: "stacked",
          timestamp: 0,
          durationMs: 0.1,
        },
      };
    },
  };
}

/** Engine that returns a high gain (20% β‰₯ 10% threshold). */
const HIGH_GAIN_ENGINE_ID = "bailout-high-gain-engine";
const highGainEngine: CompressionEngine = {
  ...makeBaseEngine(HIGH_GAIN_ENGINE_ID),
  apply: (body) => {
    const messages = (body.messages as Array<{ role: string; content: string }>) ?? [];
    const next = messages.map((m) =>
      m.role === "user" ? { ...m, content: m.content + "|high" } : m
    );
    return {
      body: { ...body, messages: next },
      compressed: true,
      stats: {
        originalTokens: 100,
        compressedTokens: 80,
        savingsPercent: 20, // 20% β‰₯ 10% threshold
        techniquesUsed: [HIGH_GAIN_ENGINE_ID],
        mode: "stacked",
        timestamp: 0,
        durationMs: 0.1,
      },
    };
  },
};

/** Async variant of the low-gain engine. */
const LOW_GAIN_ASYNC_ID = "bailout-low-gain-async";
const lowGainAsyncEngine: CompressionEngine = {
  ...makeLowGainEngine(LOW_GAIN_ASYNC_ID),
  apply: (body) => ({ body, compressed: false, stats: null }), // sync pass-through (async-only pattern)
  applyAsync: async (body) => makeLowGainEngine(LOW_GAIN_ASYNC_ID).apply(body),
};

/** Async variant of the throw engine. */
const THROW_ASYNC_ID = "bailout-throw-async";
const throwAsyncEngine: CompressionEngine = {
  ...makeBaseEngine(THROW_ASYNC_ID),
  apply: (body) => ({ body, compressed: false, stats: null }), // sync pass-through
  applyAsync: async (_body) => {
    throw new Error("simulated async engine failure");
  },
};

function pipeline(...ids: string[]): CompressionPipelineStep[] {
  return ids.map((engine) => ({ engine })) as unknown as CompressionPipelineStep[];
}

function userContent(result: CompressionResult): string {
  const messages = result.body.messages as Array<{ role: string; content: string }>;
  return messages.find((m) => m.role === "user")!.content;
}

const BAILOUT_ON = { bailout: { enabled: true, minGainPercent: 10 } };
const BAILOUT_OFF = {}; // default β€” no bailout field

// ── suite ────────────────────────────────────────────────────────────────────

describe("TV1 β€” stacked pipeline bail-out discipline (OPT-IN)", () => {
  before(() => {
    registerCompressionEngine(throwEngine);
    registerCompressionEngine(makeLowGainEngine());
    registerCompressionEngine(highGainEngine);
    registerCompressionEngine(lowGainAsyncEngine);
    registerCompressionEngine(throwAsyncEngine);
  });

  after(() => {
    unregisterCompressionEngine(THROW_ENGINE_ID);
    unregisterCompressionEngine(LOW_GAIN_ENGINE_ID);
    unregisterCompressionEngine(HIGH_GAIN_ENGINE_ID);
    unregisterCompressionEngine(LOW_GAIN_ASYNC_ID);
    unregisterCompressionEngine(THROW_ASYNC_ID);
  });

  // ── SYNC tests ────────────────────────────────────────────────────────────

  describe("sync β€” applyStackedCompression", () => {
    it("bail-out ON: throwing engine β†’ step skipped, pipeline does NOT throw", () => {
      const body = { messages: [{ role: "user", content: "hello" }] };

      // Must not throw and original body is kept (throw engine was the only step)
      const result = applyStackedCompression(body, pipeline(THROW_ENGINE_ID), BAILOUT_ON);

      assert.equal(result.compressed, false);
      assert.equal(userContent(result), "hello"); // body unchanged

      // TV1 fix: a crashing engine must be RECORDED in telemetry, not silently gone.
      assert.equal(result.stats?.fallbackApplied, true, "throw must set fallbackApplied");
      assert.ok(
        result.stats?.validationErrors?.some((e) => e.includes(THROW_ENGINE_ID)),
        "throwing engine must be recorded in validationErrors"
      );
    });

    it("bail-out ON: throwing engine before a good engine β†’ good engine still runs", () => {
      const body = { messages: [{ role: "user", content: "hello" }] };

      // throw engine first, then high-gain engine β€” the high-gain must still run
      const result = applyStackedCompression(
        body,
        pipeline(THROW_ENGINE_ID, HIGH_GAIN_ENGINE_ID),
        BAILOUT_ON
      );

      // high-gain engine appends "|high"
      assert.equal(userContent(result), "hello|high");
      assert.equal(result.compressed, true);
    });

    it("bail-out ON: low-gain engine (5%) β†’ body NOT advanced (step skipped)", () => {
      const body = { messages: [{ role: "user", content: "hello" }] };

      const result = applyStackedCompression(body, pipeline(LOW_GAIN_ENGINE_ID), BAILOUT_ON);

      // low-gain would append "|low" but it should be skipped
      assert.equal(userContent(result), "hello");
      // compressed is false because the only step was skipped
      assert.equal(result.compressed, false);
    });

    it("bail-out ON: high-gain engine (20%) β†’ body IS advanced normally", () => {
      const body = { messages: [{ role: "user", content: "hello" }] };

      const result = applyStackedCompression(body, pipeline(HIGH_GAIN_ENGINE_ID), BAILOUT_ON);

      assert.equal(userContent(result), "hello|high");
      assert.equal(result.compressed, true);
    });

    it("bail-out ON: low-gain then high-gain β†’ only high-gain advances body", () => {
      const body = { messages: [{ role: "user", content: "hello" }] };

      const result = applyStackedCompression(
        body,
        pipeline(LOW_GAIN_ENGINE_ID, HIGH_GAIN_ENGINE_ID),
        BAILOUT_ON
      );

      // "|low" should be absent; "|high" should be present
      assert.equal(userContent(result), "hello|high");
    });

    it("bail-out OFF (default): low-gain engine IS applied (opt-in guard)", () => {
      const body = { messages: [{ role: "user", content: "hello" }] };

      // No bailout config at all β€” original behavior
      const result = applyStackedCompression(body, pipeline(LOW_GAIN_ENGINE_ID), BAILOUT_OFF);

      // Without bail-out, the step is always applied
      assert.equal(userContent(result), "hello|low");
      assert.equal(result.compressed, true);
    });

    it("bail-out OFF (default): throwing engine propagates β€” unchanged existing behavior", () => {
      const body = { messages: [{ role: "user", content: "hello" }] };

      // Without bail-out, a throw is NOT caught β†’ pipeline throws
      assert.throws(() => {
        applyStackedCompression(body, pipeline(THROW_ENGINE_ID), BAILOUT_OFF);
      }, /simulated engine failure/);
    });
  });

  // ── ASYNC tests ───────────────────────────────────────────────────────────

  describe("async β€” applyStackedCompressionAsync", () => {
    it("bail-out ON: async throwing engine β†’ step skipped, no throw", async () => {
      const body = { messages: [{ role: "user", content: "hello" }] };

      const result = await applyStackedCompressionAsync(body, pipeline(THROW_ASYNC_ID), BAILOUT_ON);

      assert.equal(userContent(result), "hello");
      assert.equal(result.compressed, false);
    });

    it("bail-out ON: async low-gain engine (5%) β†’ step skipped", async () => {
      const body = { messages: [{ role: "user", content: "hello" }] };

      const result = await applyStackedCompressionAsync(
        body,
        pipeline(LOW_GAIN_ASYNC_ID),
        BAILOUT_ON
      );

      assert.equal(userContent(result), "hello");
      assert.equal(result.compressed, false);
    });

    it("bail-out OFF (default): async low-gain engine IS applied", async () => {
      const body = { messages: [{ role: "user", content: "hello" }] };

      const result = await applyStackedCompressionAsync(
        body,
        pipeline(LOW_GAIN_ASYNC_ID),
        BAILOUT_OFF
      );

      assert.equal(userContent(result), "hello|low");
      assert.equal(result.compressed, true);
    });
  });
});