File size: 12,780 Bytes
f96921d | 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 | import { describe, it, before, beforeEach, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const tmpDir = mkdtempSync(join(tmpdir(), "omniroute-test-"));
process.env.DATA_DIR = tmpDir;
const core = await import("../../../src/lib/db/core.ts");
core.resetDbInstance();
const { insertCompressionAnalyticsRow, getCompressionAnalyticsSummary } =
await import("../../../src/lib/db/compressionAnalytics.ts");
const { attachCompressionUsageReceipt } =
await import("../../../src/lib/db/compressionAnalytics.ts");
const { getDbInstance } = core;
describe("compressionAnalytics", () => {
before(() => {
const db = getDbInstance();
db.exec(`
CREATE TABLE IF NOT EXISTS compression_analytics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
combo_id TEXT,
provider TEXT,
mode TEXT NOT NULL,
original_tokens INTEGER NOT NULL,
compressed_tokens INTEGER NOT NULL,
tokens_saved INTEGER NOT NULL,
duration_ms INTEGER,
request_id TEXT
)
`);
});
beforeEach(() => {
// Clear table before each test for full isolation
const db = getDbInstance();
db.exec("DELETE FROM compression_analytics");
});
after(() => {
core.closeDbInstance();
rmSync(tmpDir, { recursive: true, force: true });
});
it("empty table returns zeroed summary", () => {
const summary = getCompressionAnalyticsSummary();
assert.deepEqual(summary, {
totalRequests: 0,
totalTokensSaved: 0,
avgSavingsPct: 0,
avgDurationMs: 0,
byMode: {},
byEngine: {},
byCompressionCombo: {},
byProvider: {},
last24h: summary.last24h,
validationFallbacks: 0,
realUsage: {
requestsWithReceipts: 0,
promptTokens: 0,
completionTokens: 0,
totalTokens: 0,
cacheReadTokens: 0,
cacheWriteTokens: 0,
estimatedUsdSaved: 0,
bySource: {},
},
mcpDescriptionCompression: {
snapshots: 0,
estimatedTokensSaved: 0,
},
});
assert.equal(summary.last24h.length, 24);
});
it("insert single row does not throw", () => {
const row = {
timestamp: new Date().toISOString(),
mode: "lite",
original_tokens: 1000,
compressed_tokens: 800,
tokens_saved: 200,
};
assert.doesNotThrow(() => insertCompressionAnalyticsRow(row));
const summary = getCompressionAnalyticsSummary();
assert.equal(summary.totalRequests, 1);
});
it("stores all RTK raw output pointers when provided", () => {
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "rtk",
original_tokens: 1000,
compressed_tokens: 500,
tokens_saved: 500,
rtk_raw_output_pointer: "raw_1",
rtk_raw_output_bytes: 100,
rtk_raw_output_pointers: JSON.stringify(["raw_1", "raw_2"]),
rtk_raw_output_total_bytes: 250,
});
const db = getDbInstance();
const row = db
.prepare(
"SELECT rtk_raw_output_pointer, rtk_raw_output_bytes, rtk_raw_output_pointers, rtk_raw_output_total_bytes FROM compression_analytics LIMIT 1"
)
.get() as {
rtk_raw_output_pointer: string;
rtk_raw_output_bytes: number;
rtk_raw_output_pointers: string;
rtk_raw_output_total_bytes: number;
};
assert.equal(row.rtk_raw_output_pointer, "raw_1");
assert.equal(row.rtk_raw_output_bytes, 100);
assert.equal(row.rtk_raw_output_pointers, JSON.stringify(["raw_1", "raw_2"]));
assert.equal(row.rtk_raw_output_total_bytes, 250);
});
it("summary counts correctly after multiple inserts", () => {
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "lite",
original_tokens: 1000,
compressed_tokens: 800,
tokens_saved: 200,
});
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "standard",
original_tokens: 300,
compressed_tokens: 280,
tokens_saved: 20,
});
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "aggressive",
original_tokens: 500,
compressed_tokens: 400,
tokens_saved: 100,
});
const summary = getCompressionAnalyticsSummary();
assert.equal(summary.totalRequests, 3);
});
it("totalTokensSaved sums correctly", () => {
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "lite",
original_tokens: 1000,
compressed_tokens: 800,
tokens_saved: 200,
});
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "standard",
original_tokens: 300,
compressed_tokens: 280,
tokens_saved: 20,
});
const summary = getCompressionAnalyticsSummary();
assert.equal(summary.totalTokensSaved, 220);
});
it("byMode groups correctly", () => {
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "lite",
original_tokens: 1000,
compressed_tokens: 800,
tokens_saved: 200,
});
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "lite",
original_tokens: 500,
compressed_tokens: 400,
tokens_saved: 100,
});
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "standard",
original_tokens: 300,
compressed_tokens: 270,
tokens_saved: 30,
});
const summary = getCompressionAnalyticsSummary();
assert.equal(summary.byMode["lite"].count, 2);
assert.equal(summary.byMode["lite"].tokensSaved, 300);
assert.equal(summary.byMode["standard"].count, 1);
});
it("byProvider groups correctly", () => {
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "lite",
original_tokens: 1000,
compressed_tokens: 800,
tokens_saved: 200,
provider: "ProviderA",
});
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "lite",
original_tokens: 500,
compressed_tokens: 400,
tokens_saved: 100,
provider: "ProviderB",
});
const summary = getCompressionAnalyticsSummary();
assert.deepEqual(summary.byProvider["ProviderA"], { count: 1, tokensSaved: 200 });
assert.deepEqual(summary.byProvider["ProviderB"], { count: 1, tokensSaved: 100 });
});
it("since=24h filters rows older than 24h", () => {
const oldTimestamp = new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString();
const recentTimestamp = new Date().toISOString();
insertCompressionAnalyticsRow({
timestamp: oldTimestamp,
mode: "lite",
original_tokens: 2000,
compressed_tokens: 1800,
tokens_saved: 200,
});
insertCompressionAnalyticsRow({
timestamp: recentTimestamp,
mode: "lite",
original_tokens: 1000,
compressed_tokens: 900,
tokens_saved: 100,
});
const summary24h = getCompressionAnalyticsSummary("24h");
assert.equal(summary24h.totalRequests, 1);
assert.equal(summary24h.totalTokensSaved, 100);
});
it("since=undefined returns all rows including old ones", () => {
const oldTimestamp = new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString();
const recentTimestamp = new Date().toISOString();
insertCompressionAnalyticsRow({
timestamp: oldTimestamp,
mode: "lite",
original_tokens: 2000,
compressed_tokens: 1800,
tokens_saved: 200,
});
insertCompressionAnalyticsRow({
timestamp: recentTimestamp,
mode: "lite",
original_tokens: 1000,
compressed_tokens: 900,
tokens_saved: 100,
});
const summaryAll = getCompressionAnalyticsSummary();
assert.equal(summaryAll.totalRequests, 2);
assert.equal(summaryAll.totalTokensSaved, 300);
});
it("avgSavingsPct calculates correctly", () => {
// 200/1000 = 20%, 100/500 = 20% → avg = 20%
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "lite",
original_tokens: 1000,
compressed_tokens: 800,
tokens_saved: 200,
});
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "standard",
original_tokens: 500,
compressed_tokens: 400,
tokens_saved: 100,
});
const summary = getCompressionAnalyticsSummary();
assert.equal(summary.avgSavingsPct, 20);
});
it("last24h hourly buckets have correct shape", () => {
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "lite",
original_tokens: 1000,
compressed_tokens: 800,
tokens_saved: 200,
});
const hourly = getCompressionAnalyticsSummary("24h").last24h;
assert(Array.isArray(hourly));
assert(hourly.length <= 24);
hourly.forEach((bucket) => {
assert(typeof bucket.hour === "string");
assert(typeof bucket.count === "number");
assert(typeof bucket.tokensSaved === "number");
});
});
it("attaches real usage receipts to the latest compression row", () => {
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "standard",
original_tokens: 1000,
compressed_tokens: 700,
tokens_saved: 300,
request_id: "req-receipt",
});
attachCompressionUsageReceipt(
"req-receipt",
{
prompt_tokens: 710,
completion_tokens: 42,
total_tokens: 752,
prompt_tokens_details: { cached_tokens: 100, cache_creation_tokens: 12 },
},
"provider"
);
const summary = getCompressionAnalyticsSummary();
assert.equal(summary.realUsage.requestsWithReceipts, 1);
assert.equal(summary.realUsage.promptTokens, 710);
assert.equal(summary.realUsage.completionTokens, 42);
assert.equal(summary.realUsage.totalTokens, 752);
assert.equal(summary.realUsage.cacheReadTokens, 100);
assert.equal(summary.realUsage.cacheWriteTokens, 12);
assert.equal(summary.realUsage.bySource.provider, 1);
});
it("aggregates estimated USD savings separately from token estimates", () => {
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "standard",
original_tokens: 1000,
compressed_tokens: 700,
tokens_saved: 300,
request_id: "req-usd",
estimated_usd_saved: 0.0015,
});
attachCompressionUsageReceipt("req-usd", { prompt_tokens: 700, total_tokens: 700 }, "provider");
const summary = getCompressionAnalyticsSummary();
assert.equal(summary.realUsage.requestsWithReceipts, 1);
assert.equal(summary.realUsage.estimatedUsdSaved, 0.0015);
});
it("summarizes validation fallback and output mode rows", () => {
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "output-caveman",
original_tokens: 900,
compressed_tokens: 900,
tokens_saved: 0,
request_id: "req-output",
validation_fallback: true,
output_mode: "full",
});
attachCompressionUsageReceipt(
"req-output",
{ prompt_tokens: 900, completion_tokens: 120, total_tokens: 1020 },
"provider"
);
const summary = getCompressionAnalyticsSummary();
assert.equal(summary.validationFallbacks, 1);
assert.equal(summary.byMode["output-caveman"].count, 1);
assert.equal(summary.realUsage.requestsWithReceipts, 1);
assert.equal(summary.realUsage.totalTokens, 1020);
});
it("summarizes MCP description estimates without counting them as provider receipts", () => {
insertCompressionAnalyticsRow({
timestamp: new Date().toISOString(),
mode: "mcp-description",
engine: "mcp-description",
original_tokens: 20,
compressed_tokens: 12,
tokens_saved: 8,
mcp_description_tokens_saved: 8,
});
const summary = getCompressionAnalyticsSummary();
assert.equal(summary.mcpDescriptionCompression.snapshots, 1);
assert.equal(summary.mcpDescriptionCompression.estimatedTokensSaved, 8);
assert.equal(summary.realUsage.requestsWithReceipts, 0);
assert.equal(summary.realUsage.bySource.mcp_metadata_estimate, undefined);
});
});
|