Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions open-sse/services/compression/engines/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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) {
Expand Down
124 changes: 124 additions & 0 deletions open-sse/services/compression/engines/ionizer/index.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>): 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`);
}
}
}
Comment on lines +43 to +50

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Robustness / Type Safety: The configuration fields threshold and targetRows represent row counts and must be integers. Using Number.isFinite(v) allows floating-point numbers (e.g., 2.5), which can lead to unexpected behavior in loop iterations and array slicing (e.g., in seededSample where k is used as a loop limit and slice index).

Suggestion: Use Number.isInteger(v) to strictly enforce integer values.

Suggested change
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`);
}
}
}
for (const k of ["threshold", "targetRows"]) {
if (config[k] !== undefined) {
const v = config[k];
if (typeof v !== "number" || !Number.isInteger(v) || v < 1) {
errors.push(`${k} must be a positive integer`);
}
}
}

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<string, unknown>, 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<string, unknown> = { ...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<string, unknown>, config?: Record<string, unknown>): CompressionResult {
return this.apply(body, { stepConfig: config ?? {} });
},

getConfigSchema(): EngineConfigField[] {
return IONIZER_SCHEMA;
},

validateConfig(config: Record<string, unknown>): EngineValidationResult {
return validateIonizerConfig(config);
},
};
200 changes: 200 additions & 0 deletions open-sse/services/compression/engines/ionizer/sample.ts
Original file line number Diff line number Diff line change
@@ -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<Record<string, unknown>>): string[] {
const seen = new Set<string>();
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<string, unknown>): 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<T>(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<Record<string, unknown>>;
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<Record<string, unknown>>, opts: IonizeOptions): IonizeResult {
const n = rows.length;
if (n <= opts.targetRows) return { kept: rows, keptCount: n, totalCount: n };

const keep = new Set<number>();
const seenKeys = new Set<string>();
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<Record<string, unknown>> {
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;
Comment on lines +170 to +175

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Efficiency / Resource Leak: storeBlock is called to write the full serialized array to the CCR store before checking if the compressed content actually shrinks the payload (newContent.length >= serialized.length). Since this engine targets oversized arrays, calling storeBlock prematurely can result in storing megabytes of orphaned data in the CCR store and performing unnecessary I/O operations when the compression is ultimately discarded.

Suggestion: Perform a pre-check using the serialized length of the kept rows and an estimated marker length (using a dummy 24-character hash) before calling storeBlock.

      if (res.keptCount >= res.totalCount) return m;

      const keptSerialized = JSON.stringify(res.kept);
      const dummyHash = "000000000000000000000000";
      const dummyMarker = `[ionizer: kept ${res.keptCount}/${res.totalCount} rows; full → CCR retrieve hash=${dummyHash} chars=${serialized.length}]`;
      if (keptSerialized.length + 1 + dummyMarker.length >= serialized.length) 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 = `${keptSerialized}\n${marker}`;


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<string, unknown>,
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 });
}
5 changes: 5 additions & 0 deletions open-sse/services/compression/engines/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>, options?: CompressionEngineApplyOptions): CompressionResult;
/**
Expand Down
5 changes: 4 additions & 1 deletion open-sse/services/compression/fidelityGateStep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, unknown>): string {
const messages = body.messages;
Expand All @@ -18,9 +19,11 @@ export function gateAdvance(
result: CompressionResult,
inputBody: Record<string, unknown>,
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
Expand Down
Loading
Loading