diff --git a/open-sse/services/compression/engines/index.ts b/open-sse/services/compression/engines/index.ts index 4be7b5f93e97..239aad8bb266 100644 --- a/open-sse/services/compression/engines/index.ts +++ b/open-sse/services/compression/engines/index.ts @@ -5,6 +5,7 @@ import { sessionDedupEngine } from "./session-dedup/index.ts"; import { headroomEngine } from "./headroom/index.ts"; import { ccrEngine } from "./ccr/index.ts"; import { llmlinguaEngine } from "./llmlingua/index.ts"; +import { ionizerEngine } from "./ionizer/index.ts"; let registered = false; @@ -26,6 +27,7 @@ export function registerBuiltinCompressionEngines(): void { { id: "headroom", engine: headroomEngine }, { id: "ccr", engine: ccrEngine }, { id: "llmlingua", engine: llmlinguaEngine }, + { id: "ionizer", engine: ionizerEngine }, ]; for (const { id, engine } of engines) { diff --git a/open-sse/services/compression/engines/ionizer/index.ts b/open-sse/services/compression/engines/ionizer/index.ts new file mode 100644 index 000000000000..36945dff2ae2 --- /dev/null +++ b/open-sse/services/compression/engines/ionizer/index.ts @@ -0,0 +1,124 @@ +// open-sse/services/compression/engines/ionizer/index.ts +import { createCompressionStats } from "../../stats.ts"; +import { runIonizerPass } from "./sample.ts"; +import type { + CompressionEngine, + CompressionEngineApplyOptions, + EngineConfigField, + EngineValidationResult, +} from "../types.ts"; +import type { CompressionResult } from "../../types.ts"; + +const ENGINE_ID = "ionizer"; + +type MessageLike = { role?: string; content?: unknown; [key: string]: unknown }; + +const IONIZER_SCHEMA: EngineConfigField[] = [ + { key: "enabled", type: "boolean", label: "Enabled", defaultValue: true }, + { + key: "threshold", + type: "number", + label: "Row threshold", + description: "Only arrays with more than this many object rows are sampled. Default: 200.", + defaultValue: 200, + min: 2, + max: 1000000, + }, + { + key: "targetRows", + type: "number", + label: "Target kept rows", + description: "Approximate number of rows kept inline after sampling. Default: 50.", + defaultValue: 50, + min: 1, + max: 100000, + }, +]; + +function validateIonizerConfig(config: Record): EngineValidationResult { + const errors: string[] = []; + if (config["enabled"] !== undefined && typeof config["enabled"] !== "boolean") { + errors.push("enabled must be a boolean"); + } + for (const k of ["threshold", "targetRows"]) { + if (config[k] !== undefined) { + const v = config[k]; + if (typeof v !== "number" || !Number.isFinite(v) || v < 1) { + errors.push(`${k} must be a positive number`); + } + } + } + return { valid: errors.length === 0, errors }; +} + +export const ionizerEngine: CompressionEngine = { + id: ENGINE_ID, + name: "Ionizer", + description: + "Lossy statistical sampling of oversized homogeneous JSON arrays. Keeps schema + error rows " + + "+ first/last rows + a seeded uniform middle sample inline; stores the whole array in CCR " + + "for recovery. Complements headroom (lossless) as the fallback when columnar still overflows.", + icon: "filter_alt", + targets: ["messages"], + stackable: true, + // stackPriority 13 = between rtk (10) and headroom (15): sample raw rows BEFORE headroom + // losslessly compacts the survivors. + stackPriority: 13, + sampling: true, + metadata: { + id: ENGINE_ID, + name: "Ionizer", + description: + "Lossy statistical sampling of oversized homogeneous JSON arrays, reversible via CCR.", + inputScope: "messages", + targetLatencyMs: 2, + supportsPreview: true, + stable: true, + }, + + apply(body: Record, options?: CompressionEngineApplyOptions): CompressionResult { + const stepConfig = options?.stepConfig ?? {}; + if (stepConfig["enabled"] === false) { + return { body, compressed: false, stats: null }; + } + const messages = body["messages"]; + if (!Array.isArray(messages) || messages.length === 0) { + return { body, compressed: false, stats: null }; + } + + const start = performance.now(); + const { messages: finalMessages, ionizedCount } = runIonizerPass( + messages as MessageLike[], + stepConfig, + options?.principalId + ); + + if (ionizedCount === 0) { + return { body, compressed: false, stats: null }; + } + + const newBody: Record = { ...body, messages: finalMessages }; + const durationMs = Math.round(performance.now() - start); + const stats = createCompressionStats( + body, + newBody, + "stacked", + ["ionizer"], + [`ionizer-${ionizedCount}-arrays-sampled`], + durationMs + ); + return { body: newBody, compressed: true, stats }; + }, + + compress(body: Record, config?: Record): CompressionResult { + return this.apply(body, { stepConfig: config ?? {} }); + }, + + getConfigSchema(): EngineConfigField[] { + return IONIZER_SCHEMA; + }, + + validateConfig(config: Record): EngineValidationResult { + return validateIonizerConfig(config); + }, +}; diff --git a/open-sse/services/compression/engines/ionizer/sample.ts b/open-sse/services/compression/engines/ionizer/sample.ts new file mode 100644 index 000000000000..172429d2a867 --- /dev/null +++ b/open-sse/services/compression/engines/ionizer/sample.ts @@ -0,0 +1,200 @@ +// open-sse/services/compression/engines/ionizer/sample.ts +import { storeBlock } from "../ccr/index.ts"; + +type MessageLike = { role?: string; content?: unknown; [key: string]: unknown }; + +/** Hard cap on rows parsed by the O(n) pass (fail-safe bound). */ +export const MAX_IONIZER_ROWS = 100000; + +/** FNV-1a 32-bit hash (deterministic, cheap, no Math.random) — seeds the middle sample. */ +export function fnv1a(s: string): number { + let h = 0x811c9dc5; + for (let i = 0; i < s.length; i++) { + h ^= s.charCodeAt(i); + h = Math.imul(h, 0x01000193); + } + return h >>> 0; +} + +/** mulberry32 PRNG — deterministic, seeded (no Math.random). */ +function mulberry32(seed: number): () => number { + let a = seed >>> 0; + return function () { + a |= 0; + a = (a + 0x6d2b79f5) | 0; + let t = Math.imul(a ^ (a >>> 15), 1 | a); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/** Union of all keys across rows, in first-seen order. */ +export function schemaUnion(rows: Array>): string[] { + const seen = new Set(); + const out: string[] = []; + for (const row of rows) { + for (const key of Object.keys(row)) { + if (!seen.has(key)) { + seen.add(key); + out.push(key); + } + } + } + return out; +} + +/** Structural heuristic: does this row represent an error/failure? (always kept) */ +export function isErrorRow(row: Record): boolean { + for (const key of Object.keys(row)) { + if (/error|fail|exception|stderr|denied/i.test(key) && row[key]) return true; + } + for (const k of ["status", "statusCode", "code"]) { + const v = row[k]; + if (typeof v === "number" && v >= 400 && v <= 599) return true; + } + return false; +} + +/** k deterministic, seeded elements of `pool`, preserving pool order. k>=n → all. */ +export function seededSample(pool: T[], k: number, seed: number): T[] { + if (k >= pool.length) return pool.slice(); + const idx = pool.map((_, i) => i); + const rand = mulberry32(seed); + for (let i = 0; i < k; i++) { + const j = i + Math.floor(rand() * (idx.length - i)); + const tmp = idx[i]; + idx[i] = idx[j]; + idx[j] = tmp; + } + return idx + .slice(0, k) + .sort((a, b) => a - b) + .map((i) => pool[i]); +} + +export interface IonizeOptions { + targetRows: number; + firstK: number; + lastK: number; + seed: number; +} +export interface IonizeResult { + kept: Array>; + keptCount: number; + totalCount: number; +} + +/** + * Pick a representative subset of rows: schema-cover (first row introducing each new key) + * ∪ ALL error rows ∪ first-K ∪ last-K ∪ a seeded uniform sample of the remaining middle, + * up to targetRows. Deterministic. Returns the kept rows in ORIGINAL order. + */ +export function ionize(rows: Array>, opts: IonizeOptions): IonizeResult { + const n = rows.length; + if (n <= opts.targetRows) return { kept: rows, keptCount: n, totalCount: n }; + + const keep = new Set(); + const seenKeys = new Set(); + for (let i = 0; i < n; i++) { + let novel = false; + for (const key of Object.keys(rows[i])) { + if (!seenKeys.has(key)) { + seenKeys.add(key); + novel = true; + } + } + if (novel) keep.add(i); + } + for (let i = 0; i < n; i++) if (isErrorRow(rows[i])) keep.add(i); + for (let i = 0; i < Math.min(opts.firstK, n); i++) keep.add(i); + for (let i = Math.max(0, n - opts.lastK); i < n; i++) keep.add(i); + if (keep.size < opts.targetRows) { + const middle: number[] = []; + for (let i = 0; i < n; i++) if (!keep.has(i)) middle.push(i); + const need = opts.targetRows - keep.size; + for (const idx of seededSample(middle, need, opts.seed)) keep.add(idx); + } + + const keptIdx = [...keep].sort((a, b) => a - b); + return { kept: keptIdx.map((i) => rows[i]), keptCount: keptIdx.length, totalCount: n }; +} + +export interface IonizerPassOptions { + threshold: number; + targetRows: number; + principalId?: string; +} +export interface IonizerPassResult { + messages: MessageLike[]; + ionizedCount: number; +} + +function isPlainObjectArray(v: unknown): v is Array> { + return ( + Array.isArray(v) && + v.every((el) => el !== null && typeof el === "object" && !Array.isArray(el)) + ); +} + +/** + * For each non-system string-content message that parses as a homogeneous array of plain + * objects longer than `threshold`, replace it with a deterministic inline sample + a recoverable + * CCR marker (the whole original array stored via storeBlock). Only when the marker shrinks it. + * FAIL-OPEN: any error → no-op. + */ +export function applyIonizerPass( + messages: MessageLike[], + opts: IonizerPassOptions +): IonizerPassResult { + try { + let ionizedCount = 0; + const out = messages.map((m) => { + if (m.role === "system" || typeof m.content !== "string") return m; + const serialized = m.content; + let parsed: unknown; + try { + parsed = JSON.parse(serialized); + } catch { + return m; + } + if (!Array.isArray(parsed) || parsed.length <= opts.threshold) return m; + if (parsed.length > MAX_IONIZER_ROWS) return m; + if (!isPlainObjectArray(parsed)) return m; + + const res = ionize(parsed, { + targetRows: opts.targetRows, + firstK: 3, + lastK: 3, + seed: fnv1a(serialized), + }); + if (res.keptCount >= res.totalCount) return m; + + const hash = storeBlock(serialized, opts.principalId); + const marker = `[ionizer: kept ${res.keptCount}/${res.totalCount} rows; full → CCR retrieve hash=${hash} chars=${serialized.length}]`; + const newContent = `${JSON.stringify(res.kept)}\n${marker}`; + if (newContent.length >= serialized.length) return m; + + ionizedCount++; + return { ...m, content: newContent }; + }); + return ionizedCount > 0 ? { messages: out, ionizedCount } : { messages, ionizedCount: 0 }; + } catch { + return { messages, ionizedCount: 0 }; + } +} + +/** + * Resolve the ionizer step-config off `stepConfig` (enabled / threshold / targetRows) and run the + * pass. Returns the messages unchanged + `ionizedCount: 0` when disabled. Keeps the engine's + * `apply()` thin (config normalization + dispatch live here). + */ +export function runIonizerPass( + messages: MessageLike[], + stepConfig: Record, + principalId?: string +): IonizerPassResult { + if (stepConfig["enabled"] === false) return { messages, ionizedCount: 0 }; + const threshold = typeof stepConfig["threshold"] === "number" ? (stepConfig["threshold"] as number) : 200; + const targetRows = typeof stepConfig["targetRows"] === "number" ? (stepConfig["targetRows"] as number) : 50; + return applyIonizerPass(messages, { threshold, targetRows, principalId }); +} diff --git a/open-sse/services/compression/engines/types.ts b/open-sse/services/compression/engines/types.ts index 02cb601023dc..dcbca19b961b 100644 --- a/open-sse/services/compression/engines/types.ts +++ b/open-sse/services/compression/engines/types.ts @@ -47,6 +47,11 @@ export interface CompressionEngine { targets: CompressionEngineTarget[]; stackable: boolean; stackPriority: number; + /** + * Marks an intentionally-lossy sampling engine (e.g. ionizer). The fidelity gate SKIPS such + * engines: their drop is deliberate and recoverable via CCR, not accidental corruption. + */ + sampling?: boolean; metadata: CompressionEngineMetadata; apply(body: Record, options?: CompressionEngineApplyOptions): CompressionResult; /** diff --git a/open-sse/services/compression/fidelityGateStep.ts b/open-sse/services/compression/fidelityGateStep.ts index ce0a1e6cbc70..cdec453b8a70 100644 --- a/open-sse/services/compression/fidelityGateStep.ts +++ b/open-sse/services/compression/fidelityGateStep.ts @@ -2,6 +2,7 @@ import { extractTextContent } from "./messageContent.ts"; import { checkFidelity, type FidelityGateConfig } from "./fidelityGate.ts"; import type { CompressionResult } from "./types.ts"; import type { StackAccumulator } from "./strategySelector.ts"; +import { getCompressionEngine } from "./engines/registry.ts"; function bodyToText(body: Record): string { const messages = body.messages; @@ -18,9 +19,11 @@ export function gateAdvance( result: CompressionResult, inputBody: Record, fidelityGate: FidelityGateConfig | undefined, - acc: StackAccumulator + acc: StackAccumulator, + engineId?: string ): boolean { if (!fidelityGate?.enabled) return true; + if (engineId && getCompressionEngine(engineId)?.sampling) return true; // lossy-by-design, CCR-recoverable const verdict = checkFidelity(bodyToText(inputBody), bodyToText(result.body), fidelityGate); if (verdict.passed) return true; // mergeStackStep only pushed a breakdown entry when result.stats exists; only then is diff --git a/open-sse/services/compression/strategySelector.ts b/open-sse/services/compression/strategySelector.ts index 6f8ea2779b89..03dbcb222735 100644 --- a/open-sse/services/compression/strategySelector.ts +++ b/open-sse/services/compression/strategySelector.ts @@ -751,14 +751,14 @@ export function applyStackedCompression( continue; } mergeStackStep(acc, step.engine, result); - if (decideStep(result, bailout).advance && gateAdvance(result, currentBody, fidelityGate, acc)) { + if (decideStep(result, bailout).advance && gateAdvance(result, currentBody, fidelityGate, acc, step.engine)) { currentBody = result.body; compressed = true; } } else { const result = engine.apply(currentBody, buildStepOptions(step, options)); mergeStackStep(acc, step.engine, result); - if (result.compressed && gateAdvance(result, currentBody, fidelityGate, acc)) { + if (result.compressed && gateAdvance(result, currentBody, fidelityGate, acc, step.engine)) { currentBody = result.body; compressed = true; } @@ -825,7 +825,7 @@ export async function applyStackedCompressionAsync( continue; } mergeStackStep(acc, step.engine, result); - if (decideStep(result, bailout).advance && gateAdvance(result, currentBody, fidelityGate, acc)) { + if (decideStep(result, bailout).advance && gateAdvance(result, currentBody, fidelityGate, acc, step.engine)) { currentBody = result.body; compressed = true; } @@ -834,7 +834,7 @@ export async function applyStackedCompressionAsync( ? await engine.applyAsync(currentBody, stepOptions) : engine.apply(currentBody, stepOptions); mergeStackStep(acc, step.engine, result); - if (result.compressed && gateAdvance(result, currentBody, fidelityGate, acc)) { + if (result.compressed && gateAdvance(result, currentBody, fidelityGate, acc, step.engine)) { currentBody = result.body; compressed = true; } diff --git a/src/app/(dashboard)/dashboard/compression/studio/PlaygroundInput.tsx b/src/app/(dashboard)/dashboard/compression/studio/PlaygroundInput.tsx index fefa12c7e442..e1e894824fc2 100644 --- a/src/app/(dashboard)/dashboard/compression/studio/PlaygroundInput.tsx +++ b/src/app/(dashboard)/dashboard/compression/studio/PlaygroundInput.tsx @@ -1,5 +1,5 @@ "use client"; -export const LANE_ENGINES = ["session-dedup", "ccr", "lite", "rtk", "headroom", "caveman", "aggressive", "ultra"] as const; +export const LANE_ENGINES = ["session-dedup", "ccr", "lite", "rtk", "ionizer", "headroom", "caveman", "aggressive", "ultra"] as const; export interface PlaygroundInputProps { text: string; onText: (t: string) => void; active: string[]; onToggleActive: (engine: string) => void; onRun: () => void; loading: boolean; fidelityGate: boolean; onToggleFidelity: () => void; fuzzyDedup: boolean; onToggleFuzzy: () => void; } export function PlaygroundInput({ text, onText, active, onToggleActive, onRun, loading, fidelityGate, onToggleFidelity, fuzzyDedup, onToggleFuzzy }: PlaygroundInputProps) { return ( diff --git a/tests/unit/compression/ionizerEngine.test.ts b/tests/unit/compression/ionizerEngine.test.ts new file mode 100644 index 000000000000..fa2fa67335dd --- /dev/null +++ b/tests/unit/compression/ionizerEngine.test.ts @@ -0,0 +1,40 @@ +// tests/unit/compression/ionizerEngine.test.ts +import test from "node:test"; +import assert from "node:assert/strict"; +import { ionizerEngine } from "../../../open-sse/services/compression/engines/ionizer/index.ts"; +import { retrieveBlock, resetCcrStore } from "../../../open-sse/services/compression/engines/ccr/index.ts"; + +const bigArray = JSON.stringify(Array.from({ length: 400 }, (_, i) => ({ i, v: `row-${i}` }))); + +test("ionizer enabled: oversized homogeneous array → inline sample + recoverable CCR marker", () => { + resetCcrStore(); + const body = { messages: [{ role: "user", content: bigArray }] }; + const res = ionizerEngine.apply(body, { stepConfig: {}, principalId: "p1" }); + assert.equal(res.compressed, true); + const content = (res.body.messages as Array<{ content: string }>)[0].content; + assert.match(content, /\[ionizer: kept \d+\/400 rows; full → CCR retrieve hash=[0-9a-f]{24} chars=\d+\]$/); + const hash = content.match(/hash=([0-9a-f]{24})/)![1]; + assert.equal(retrieveBlock(hash, "p1"), bigArray); +}); + +test("ionizer disabled via enabled:false → no-op", () => { + resetCcrStore(); + const body = { messages: [{ role: "user", content: bigArray }] }; + const res = ionizerEngine.apply(body, { stepConfig: { enabled: false }, principalId: "p1" }); + assert.equal(res.compressed, false); +}); + +test("small array / non-array / non-homogeneous → no-op", () => { + resetCcrStore(); + const small = { messages: [{ role: "user", content: JSON.stringify([{ a: 1 }, { a: 2 }]) }] }; + assert.equal(ionizerEngine.apply(small, { stepConfig: {} }).compressed, false); + const notArr = { messages: [{ role: "user", content: '{"a":1}' }] }; + assert.equal(ionizerEngine.apply(notArr, { stepConfig: {} }).compressed, false); + const mixed = { messages: [{ role: "user", content: JSON.stringify([{ a: 1 }, 2, "x"]) }] }; + assert.equal(ionizerEngine.apply(mixed, { stepConfig: {} }).compressed, false); +}); + +test("engine declares sampling:true and is registered", () => { + assert.equal(ionizerEngine.sampling, true); + assert.equal(ionizerEngine.id, "ionizer"); +}); diff --git a/tests/unit/compression/ionizerGateSkip.test.ts b/tests/unit/compression/ionizerGateSkip.test.ts new file mode 100644 index 000000000000..eb6394db7f5b --- /dev/null +++ b/tests/unit/compression/ionizerGateSkip.test.ts @@ -0,0 +1,22 @@ +// tests/unit/compression/ionizerGateSkip.test.ts +import test from "node:test"; +import assert from "node:assert/strict"; +import { applyStackedCompression } from "../../../open-sse/services/compression/strategySelector.ts"; +import { registerBuiltinCompressionEngines } from "../../../open-sse/services/compression/engines/index.ts"; +import { resetCcrStore } from "../../../open-sse/services/compression/engines/ccr/index.ts"; + +registerBuiltinCompressionEngines(); + +// 400-row array; ionizer drops most rows → a numeric/json-key gate would normally REJECT a lossy +// step. Because ionizer is sampling:true, the fidelity gate must SKIP it and keep the sampled output. +const bigArray = JSON.stringify(Array.from({ length: 400 }, (_, i) => ({ id: i, port: 8080 + i }))); + +test("fidelity gate ON skips the ionizer step (sampling) and keeps the sampled output", () => { + resetCcrStore(); + const body = { messages: [{ role: "user", content: bigArray }] }; + const res = applyStackedCompression(body, [{ engine: "ionizer" }], { + fidelityGate: { enabled: true }, + }); + const content = (res.body.messages as Array<{ content: string }>)[0].content; + assert.match(content, /\[ionizer: kept \d+\/400 rows/); +}); diff --git a/tests/unit/compression/ionizerSample.test.ts b/tests/unit/compression/ionizerSample.test.ts new file mode 100644 index 000000000000..29c328411a40 --- /dev/null +++ b/tests/unit/compression/ionizerSample.test.ts @@ -0,0 +1,60 @@ +// tests/unit/compression/ionizerSample.test.ts +import test from "node:test"; +import assert from "node:assert/strict"; +import { + schemaUnion, isErrorRow, seededSample, ionize, applyIonizerPass, +} from "../../../open-sse/services/compression/engines/ionizer/sample.ts"; +import { retrieveBlock, resetCcrStore } from "../../../open-sse/services/compression/engines/ccr/index.ts"; + +test("schemaUnion: union of all keys across rows, stable order", () => { + const u = schemaUnion([{ a: 1 }, { b: 2 }, { a: 3, c: 4 }]); + assert.deepEqual(u, ["a", "b", "c"]); +}); + +test("isErrorRow: error/exception key truthy or status 4xx/5xx → true; normal → false", () => { + assert.equal(isErrorRow({ error: "boom" }), true); + assert.equal(isErrorRow({ status: 500 }), true); + assert.equal(isErrorRow({ statusCode: 404 }), true); + assert.equal(isErrorRow({ ok: true, status: 200 }), false); + assert.equal(isErrorRow({ name: "fine" }), false); +}); + +test("seededSample: deterministic, k>=n returns all, in-range", () => { + const pool = [10, 11, 12, 13, 14, 15, 16, 17]; + const a = seededSample(pool, 3, 42); + assert.deepEqual(a, seededSample(pool, 3, 42)); // deterministic + assert.equal(a.length, 3); + assert.ok(a.every((x) => pool.includes(x))); + assert.deepEqual(seededSample(pool, 99, 42).slice().sort((x, y) => x - y), pool); // k>=n → all +}); + +test("ionize: keeps schema-cover + error rows + first/last K + seeded middle ≤ targetRows, original order", () => { + const rows: Array> = []; + for (let i = 0; i < 100; i++) rows.push({ i, v: `row-${i}` }); + rows[50] = { i: 50, v: "x", error: "boom" }; // an error row in the middle + const res = ionize(rows, { targetRows: 20, firstK: 3, lastK: 3, seed: 7 }); + assert.ok(res.keptCount <= 20 + 2); // target + mandatory overflow tolerance + assert.equal(res.totalCount, 100); + assert.equal(res.kept[0].i, 0); + assert.equal(res.kept[res.kept.length - 1].i, 99); + assert.ok(res.kept.some((r) => r.error === "boom")); + const idxs = res.kept.map((r) => r.i as number); + assert.deepEqual(idxs, idxs.slice().sort((a, b) => a - b)); + const small = [{ a: 1 }, { a: 2 }]; + assert.equal(ionize(small, { targetRows: 20, firstK: 3, lastK: 3, seed: 1 }).keptCount, 2); +}); + +test("applyIonizerPass: big homogeneous array → inline sample + recoverable CCR marker; below threshold untouched", () => { + resetCcrStore(); + const arr = Array.from({ length: 300 }, (_, i) => ({ i, v: `r${i}` })); + const content = JSON.stringify(arr); + const messages = [{ role: "user", content }]; + const out = applyIonizerPass(messages, { threshold: 200, targetRows: 50, principalId: "p1" }); + assert.equal(out.ionizedCount, 1); + const newContent = out.messages[0].content as string; + assert.match(newContent, /\[ionizer: kept \d+\/300 rows; full → CCR retrieve hash=[0-9a-f]{24} chars=\d+\]$/); + const hash = newContent.match(/hash=([0-9a-f]{24})/)![1]; + assert.equal(retrieveBlock(hash, "p1"), content); // whole original array recoverable verbatim + const small = [{ role: "user", content: JSON.stringify(Array.from({ length: 10 }, (_, i) => ({ i }))) }]; + assert.equal(applyIonizerPass(small, { threshold: 200, targetRows: 50, principalId: "p1" }).ionizedCount, 0); +}); diff --git a/tests/unit/compression/previewRouteIonizer.test.ts b/tests/unit/compression/previewRouteIonizer.test.ts new file mode 100644 index 000000000000..eebcb0989d6a --- /dev/null +++ b/tests/unit/compression/previewRouteIonizer.test.ts @@ -0,0 +1,27 @@ +// tests/unit/compression/previewRouteIonizer.test.ts +import test from "node:test"; +import assert from "node:assert/strict"; +import { join } from "node:path"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +const TEST_DATA_DIR = mkdtempSync(join(tmpdir(), "preview-ionizer-")); +process.env.DATA_DIR = TEST_DATA_DIR; +process.env.API_KEY_SECRET = process.env.API_KEY_SECRET ?? "test-secret-32-chars-min-aaaaaaaa"; +delete process.env.INITIAL_PASSWORD; +const core = await import("../../../src/lib/db/core.ts"); +const route = await import("../../../src/app/api/compression/preview/route.ts"); +function makeReq(body: unknown) { + return new Request("http://localhost/api/compression/preview", { + method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), + }); +} +test.beforeEach(() => core.resetDbInstance()); +test.after(() => { core.resetDbInstance(); rmSync(TEST_DATA_DIR, { recursive: true, force: true }); }); + +test("the ionizer lane samples an oversized JSON array into a CCR marker", async () => { + const big = JSON.stringify(Array.from({ length: 400 }, (_, i) => ({ i, v: `r${i}` }))); + const res = await route.POST(makeReq({ messages: [{ role: "user", content: big }], engineId: "ionizer" })); + assert.equal(res.status, 200); + const body = await res.json(); + assert.match(body.compressed, /\[ionizer: kept \d+\/400 rows; full → CCR retrieve hash=[0-9a-f]{24}/); +}); diff --git a/tests/unit/ui/ionizerLane.test.tsx b/tests/unit/ui/ionizerLane.test.tsx new file mode 100644 index 000000000000..f32a5c06eddb --- /dev/null +++ b/tests/unit/ui/ionizerLane.test.tsx @@ -0,0 +1,9 @@ +// @vitest-environment jsdom +// tests/unit/ui/ionizerLane.test.tsx +import { describe, it, expect } from "vitest"; +import { LANE_ENGINES } from "@/app/(dashboard)/dashboard/compression/studio/PlaygroundInput"; +describe("studio lane engines", () => { + it("includes the ionizer engine so it has its own playground lane", () => { + expect(LANE_ENGINES).toContain("ionizer"); + }); +});