repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/cmprss/__tests__/ab.test.ts

Raw
File outline
import { Buffer } from "node:buffer";
import { describe, expect, test } from "vitest";
import {
	compareWithHistory,
	createBenchmark,
	scoreCandidate,
	summarizeEvents,
} from "../__bench__/ab.ts";
import { __test } from "../index.ts";

const benchmark = createBenchmark();

describe("cmprss A/B benchmark", () => {
	test("deterministically exercises every compressor below Pi's read cap", () => {
		for (const [path, expectedCompressor] of Object.entries(
			benchmark.expectedCompressors,
		)) {
			const content = benchmark.files[path];
			expect(content, path).toBeDefined();
			const size = Buffer.byteLength(content);
			expect(size, `${path} exceeds cmprss threshold`).toBeGreaterThan(20_000);
			expect(size, `${path} exceeds Pi read cap`).toBeLessThan(50_000);
			expect(__test.compressContent(content).compressor, path).toBe(
				expectedCompressor,
			);
		}
	});

	test("embeds every expected value exactly in its fixture", () => {
		expect(benchmark.files["fixtures/data.json"]).toContain(
			`"releaseCode": "${benchmark.expected.jsonCode}"`,
		);
		expect(benchmark.files["fixtures/search.txt"]).toContain(
			`needle=${benchmark.expected.searchNeedle}`,
		);
		expect(benchmark.files["fixtures/change.diff"]).toContain(
			`+export const value20 = "${benchmark.expected.diffNewValue}";`,
		);
		expect(benchmark.files["fixtures/stacktrace.txt"]).toContain(
			`Caused by: Error: ${benchmark.expected.stackRootCause}`,
		);
		expect(benchmark.files["fixtures/build.log"]).toContain(
			`ERROR build failed: ${benchmark.expected.logFailure}`,
		);
		expect(benchmark.files["fixtures/build.log"]).toContain(
			`completion token: ${benchmark.expected.logTail}`,
		);
		expect(benchmark.files["fixtures/narrative.txt"]).toContain(
			`middle token: ${benchmark.expected.textMiddle}`,
		);
	});

	test("preserves structured outliers and retrieves omitted unstructured facts", () => {
		const compressed = Object.fromEntries(
			Object.entries(benchmark.files).map(([path, content]) => [
				path,
				__test.compressContent(content).text,
			]),
		);

		expect(compressed["fixtures/data.json"]).toContain(
			benchmark.expected.jsonCode,
		);
		expect(compressed["fixtures/search.txt"]).toContain(
			benchmark.expected.searchNeedle,
		);
		expect(compressed["fixtures/narrative.txt"]).not.toContain(
			benchmark.expected.textMiddle,
		);
		expect(compressed["fixtures/change.diff"]).toContain(
			benchmark.expected.diffNewValue,
		);
		expect(compressed["fixtures/stacktrace.txt"]).toContain(
			benchmark.expected.stackRootCause,
		);
		expect(compressed["fixtures/build.log"]).toContain(
			benchmark.expected.logFailure,
		);
		expect(compressed["fixtures/build.log"]).toContain(
			benchmark.expected.logTail,
		);
	});

	test("hard-scores exact and fenced JSON answers", () => {
		const exact = JSON.stringify(benchmark.expected);
		const fenced = `\`\`\`json\n${exact}\n\`\`\``;
		expect(scoreCandidate(exact, benchmark.expected).score).toBe(100);
		expect(scoreCandidate(fenced, benchmark.expected).score).toBe(100);

		const wrong = { ...benchmark.expected, textMiddle: "wrong" };
		const score = scoreCandidate(JSON.stringify(wrong), benchmark.expected);
		expect(score.correct).toBe(Object.keys(benchmark.expected).length - 1);
		expect(score.score).toBeLessThan(100);
	});

	test("compares modified runs with the latest persisted controls", () => {
		const result = {
			case: "modified",
			subject: { usage: { totalTokens: 60 }, hardScore: { score: 100 } },
			judge: { result: { score: 90 } },
		};
		const history = [
			{
				case: "current",
				subject: { usage: { totalTokens: 100 }, hardScore: { score: 90 } },
				judge: { result: { score: 80 } },
			},
			{
				case: "baseline",
				subject: { usage: { totalTokens: 120 }, hardScore: { score: 100 } },
				judge: { result: { score: 100 } },
			},
		];

		expect(compareWithHistory(result, history)).toEqual([
			{
				case: "baseline",
				tokenDelta: -60,
				tokenDeltaPercent: -50,
				hardDelta: 0,
				judgeDelta: -10,
			},
			{
				case: "current",
				tokenDelta: -40,
				tokenDeltaPercent: -40,
				hardDelta: 10,
				judgeDelta: 10,
			},
		]);
	});

	test("summarizes provider usage, compression, retrieval, and final answer", () => {
		const events = [
			{
				type: "message_end",
				message: {
					role: "assistant",
					provider: "test",
					model: "luna",
					content: [{ type: "text", text: "working" }],
					usage: {
						input: 100,
						output: 10,
						cacheRead: 20,
						cacheWrite: 5,
						totalTokens: 135,
					},
				},
			},
			{
				type: "tool_execution_end",
				toolName: "read",
				result: {
					content: [{ type: "text", text: "summary" }],
					details: {
						cmprss: { originalBytes: 30_000, compressedBytes: 1_000 },
					},
				},
			},
			{
				type: "tool_execution_end",
				toolName: "cmprss_retrieve",
				result: {
					content: [{ type: "text", text: "retrieved" }],
					details: { returnedBytes: 9 },
				},
			},
			{
				type: "message_end",
				message: {
					role: "assistant",
					provider: "test",
					model: "luna",
					content: [{ type: "text", text: "final" }],
					usage: {
						input: 200,
						output: 20,
						cacheRead: 40,
						cacheWrite: 0,
						totalTokens: 260,
					},
				},
			},
		];

		const summary = summarizeEvents(events);
		expect(summary.usage).toEqual({
			input: 300,
			output: 30,
			cacheRead: 60,
			cacheWrite: 5,
			totalTokens: 395,
		});
		expect(summary.compression).toMatchObject({
			blocks: 1,
			originalBytes: 30_000,
			compressedBytes: 1_000,
			retrievals: 1,
			netSavedBytes: 29_000 - Buffer.byteLength("retrieved"),
		});
		expect(summary.finalText).toBe("final");
		expect(summary.provider).toBe("test");
		expect(summary.model).toBe("luna");
	});
});