import { createHash } from "node:crypto"; import type { AttemptToolCatalog, ModelContextSnapshot } from "@opengeni/contracts"; import { and, eq, sql } from "drizzle-orm"; import type { Database } from "./database"; import { anyOf } from "./sql-arrays"; import * as schema from "./schema"; /** * Session-scoped content-addressed storage for large, highly repetitive JSON. * * Long sessions record a tool catalog and a model-request snapshot for every * attempt. Consecutive attempts repeat nearly all of that content, so storing * each copy inline makes those two tables the largest in the database. Writers * now externalize the repetitive parts into `session_content_blobs`, keyed by * the SHA-256 of their canonical JSON, and keep only digests in the owning row. * Readers hydrate both the encoded and the legacy inline form, so the stored * representation is an implementation detail: hydrated values are exactly the * values that were written. * * Blobs are owned by one session (never shared across sessions or workspaces), * so their lifecycle is the session's: they cascade with it and move with it * into a session archive. A blob that no stored row names any more (a * snapshot's chunks after the next request replaced it) is deleted by the * collector in `session-content-garbage.ts`; writers and snapshot readers hold * the session's content lock shared so that never races them. */ export const SESSION_CONTENT_REFS_VERSION = 1 as const; export type AttemptToolCatalogContentRefs = { v: typeof SESSION_CONTENT_REFS_VERSION; entries: string[]; }; export type ModelContextSnapshotContentRefs = { v: typeof SESSION_CONTENT_REFS_VERSION; instructions: string; layers: string; tools: string; skills: string; /** Content-defined chunks of `providerRequest.body`; null when inline or absent. */ body: string[] | null; }; export type SessionContentScope = { accountId: string; workspaceId: string; sessionId: string; }; export class SessionContentBlobMissingError extends Error { readonly code = "session_content_blob_missing"; constructor(readonly digest: string) { super("A session content blob referenced by a stored row is missing"); this.name = "SessionContentBlobMissingError"; } } /** Sort object keys recursively; arrays keep their order. Matches jsonb equality. */ export function canonicalJsonForContentDigest(value: unknown): string { if (value === null || typeof value !== "object") { const encoded = JSON.stringify(value); if (encoded === undefined) throw new TypeError("Content value is not JSON"); return encoded; } if (Array.isArray(value)) { return `[${value.map((item) => canonicalJsonForContentDigest(item ?? null)).join(",")}]`; } const entries = Object.entries(value as Record) .filter(([, item]) => item !== undefined) .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)); return `{${entries .map(([key, item]) => `${JSON.stringify(key)}:${canonicalJsonForContentDigest(item)}`) .join(",")}}`; } export function digestContentValue(value: unknown): string { return createHash("sha256").update(canonicalJsonForContentDigest(value), "utf8").digest("hex"); } // Content-defined chunking over UTF-16 code units (gear rolling hash). Chunk // boundaries depend only on nearby content, so a string that grows or changes // near its end keeps the same leading chunks. The table and parameters affect // only deduplication efficiency, never correctness: hydration concatenates. const CHUNK_MIN_UNITS = 2_048; const CHUNK_MAX_UNITS = 65_536; const CHUNK_BOUNDARY_MASK = 0x1fff; // ~8 Ki code units on average past the minimum. const GEAR = (() => { const table = new Uint32Array(256); let state = 0x9e3779b9; for (let index = 0; index < table.length; index += 1) { state ^= state << 13; state ^= state >>> 17; state ^= state << 5; table[index] = state >>> 0; } return table; })(); function isHighSurrogate(code: number): boolean { return code >= 0xd800 && code <= 0xdbff; } /** Split text into content-defined chunks; never splits a surrogate pair. */ export function chunkTextByContent(text: string): string[] { if (text.length <= CHUNK_MIN_UNITS) return [text]; return chunkTextFrom(text, 0, []); } /** * Continue chunking at `start`, which must be 0 or a chunk boundary. The * rolling hash restarts at every boundary, so chunks after a boundary depend * only on the text from it: this is exactly what a whole-text pass appends. */ function chunkTextFrom(text: string, from: number, chunks: string[]): string[] { let start = from; let hash = 0; for (let index = from; index < text.length; index += 1) { const code = text.charCodeAt(index); hash = ((hash << 1) + GEAR[(code ^ (code >>> 8)) & 0xff]!) >>> 0; const length = index + 1 - start; if ( ((length >= CHUNK_MIN_UNITS && (hash & CHUNK_BOUNDARY_MASK) === 0) || length >= CHUNK_MAX_UNITS) && !isHighSurrogate(code) ) { chunks.push(text.slice(start, index + 1)); start = index + 1; hash = 0; } } if (start < text.length) chunks.push(text.slice(start)); return chunks; } type EncodedValue = { stored: Stored; refs: Refs; blobs: Map; }; function addBlob(blobs: Map, value: unknown): string { const digest = digestContentValue(value); if (!blobs.has(digest)) blobs.set(digest, value); return digest; } /** Externalize every catalog entry; the stored catalog keeps all identity fields. */ export function encodeAttemptToolCatalogContent( catalog: AttemptToolCatalog, ): EncodedValue { const blobs = new Map(); const entries = catalog.entries.map((entry) => addBlob(blobs, entry)); return { stored: { ...catalog, entries: [] }, refs: { v: SESSION_CONTENT_REFS_VERSION, entries }, blobs, }; } /** Externalize the repeated instruction/tool/skill prefix and the raw request body. */ export function encodeModelContextSnapshotContent( snapshot: ModelContextSnapshot, cache?: ModelContextSnapshotContentCache, ): EncodedValue { const blobs = new Map(); const body = snapshot.providerRequest?.body; const field = (name: SnapshotContentField) => { const value = snapshot[name]; if (!cache) return addBlob(blobs, value); const digest = cache.fieldDigest(name, value); if (!blobs.has(digest)) blobs.set(digest, value); return digest; }; const bodyChunks = (text: string) => { if (!cache) return chunkTextByContent(text).map((chunk) => addBlob(blobs, chunk)); const { chunks, digests } = cache.bodyChunks(text); return digests.map((digest, index) => { if (!blobs.has(digest)) blobs.set(digest, chunks[index]); return digest; }); }; const refs: ModelContextSnapshotContentRefs = { v: SESSION_CONTENT_REFS_VERSION, instructions: field("instructions"), layers: field("layers"), tools: field("tools"), skills: field("skills"), body: typeof body === "string" ? bodyChunks(body) : null, }; const stored: ModelContextSnapshot = { ...snapshot, instructions: "", layers: [], tools: [], skills: [], ...(snapshot.providerRequest && refs.body !== null ? { providerRequest: { ...snapshot.providerRequest, body: null } } : {}), }; return { stored, refs, blobs }; } type BlobReader = Pick; type SnapshotContentField = "instructions" | "layers" | "tools" | "skills"; type BodyChunks = { readonly text: string; readonly chunks: readonly string[]; readonly digests: readonly string[]; /** `Buffer.byteLength(JSON.stringify(chunk))` per chunk. */ readonly jsonBytes: readonly number[]; }; type FieldMemo = { /** Private copy: never handed out, so nothing can change it after the fact. */ copy: unknown; digest: string; /** Measured from the copy on first reuse; equal plain data prints alike. */ jsonBytes?: number; }; /** Recent values per field; a run alternates SDK-prefix and wire-body captures. */ const FIELD_MEMO_DEPTH = 2; /** * Per-attempt memo for consecutive model-context snapshots of one run. Each * request repeats the previous request's instructions, layers, tools and * skills, and its body starts with the previous body. The memo recognizes a * repeated value by comparing it with a private copy (structure and every * primitive) and the shared prefix of a body chunk by chunk, so only new * content is serialized and hashed. Every digest, chunk and byte count is * exactly what the uncached functions compute. */ export class ModelContextSnapshotContentCache { private readonly fields = new Map(); private body: BodyChunks | null = null; /** `Buffer.byteLength(JSON.stringify(value))` of a repeated field, when known. */ fieldJsonBytes(name: SnapshotContentField, value: unknown): number | undefined { const memo = this.match(name, value); if (!memo) return undefined; memo.jsonBytes ??= Buffer.byteLength(JSON.stringify(memo.copy), "utf8"); return memo.jsonBytes; } fieldDigest(name: SnapshotContentField, value: unknown): string { const known = this.match(name, value); if (known) return known.digest; const digest = digestContentValue(value); let copy: unknown; try { copy = structuredClone(value); } catch { return digest; } const memos = this.fields.get(name) ?? []; memos.unshift({ copy, digest }); memos.length = Math.min(memos.length, FIELD_MEMO_DEPTH); this.fields.set(name, memos); return digest; } /** `chunkTextByContent(text)` and each chunk's digest, reusing the shared prefix. */ bodyChunks(text: string): BodyChunks { if (this.body?.text === text) return this.body; const chunks: string[] = []; const digests: string[] = []; const jsonBytes: number[] = []; const previous = this.body; let offset = 0; if (previous && text.length > CHUNK_MIN_UNITS) { // A previous chunk ended at a boundary only if another chunk followed it. for (let index = 0; index < previous.chunks.length - 1; index += 1) { const chunk = previous.chunks[index]!; if (!text.startsWith(chunk, offset)) break; chunks.push(chunk); digests.push(previous.digests[index]!); jsonBytes.push(previous.jsonBytes[index]!); offset += chunk.length; } } const reused = chunks.length; if (text.length <= CHUNK_MIN_UNITS) chunks.push(text); else chunkTextFrom(text, offset, chunks); for (let index = reused; index < chunks.length; index += 1) { const encoded = canonicalJsonForContentDigest(chunks[index]!); digests.push(createHash("sha256").update(encoded, "utf8").digest("hex")); jsonBytes.push(Buffer.byteLength(encoded, "utf8")); } this.body = { text, chunks, digests, jsonBytes }; return this.body; } /** `Buffer.byteLength(JSON.stringify(text))`; chunks never split a surrogate pair. */ bodyJsonBytes(text: string): number { const { jsonBytes } = this.bodyChunks(text); return jsonBytes.reduce((total, bytes) => total + bytes - 2, 2); } private match(name: SnapshotContentField, value: unknown): FieldMemo | undefined { const memos = this.fields.get(name); if (!memos) return undefined; for (const memo of memos) if (samePlainValue(value, memo.copy)) return memo; return undefined; } } /** * Same plain data: ordinary objects with the same own enumerable keys in the * same order, dense arrays, and identical primitives. Anything else (a class * instance, a function, NaN) is reported different, which only costs a * recomputation. Equal values serialize identically under any JSON encoding. */ function samePlainValue(value: unknown, copy: unknown): boolean { if (typeof value !== "object" || value === null) { return value === copy && typeof value !== "function" && typeof value !== "symbol"; } if (typeof copy !== "object" || copy === null) return false; if (Array.isArray(value)) { if (Object.getPrototypeOf(value) !== Array.prototype) return false; if (!Array.isArray(copy) || value.length !== copy.length) return false; for (let index = 0; index < value.length; index += 1) { if (!(index in value) || !(index in copy)) return false; if (!samePlainValue(value[index], copy[index])) return false; } return Object.keys(value).length === value.length; } if (Object.getPrototypeOf(value) !== Object.prototype || Array.isArray(copy)) return false; const keys = Object.keys(value); const copyKeys = Object.keys(copy); if (keys.length !== copyKeys.length) return false; for (let index = 0; index < keys.length; index += 1) { const key = keys[index]!; if (key !== copyKeys[index]) return false; const descriptor = Object.getOwnPropertyDescriptor(value, key); if (!descriptor || !("value" in descriptor)) return false; if (!samePlainValue(descriptor.value, (copy as Record)[key])) return false; } return true; } /** * `Buffer.byteLength(JSON.stringify(snapshot), "utf8")` for a parsed (plain) * snapshot, reusing the memo for repeated fields and the request body. */ export function modelContextSnapshotJsonUtf8Bytes( snapshot: ModelContextSnapshot, cache?: ModelContextSnapshotContentCache, ): number { if (!cache || Object.getPrototypeOf(snapshot) !== Object.prototype || "toJSON" in snapshot) return Buffer.byteLength(JSON.stringify(snapshot), "utf8"); let total = 2; let members = 0; for (const key of Object.keys(snapshot)) { const value = (snapshot as Record)[key]; let bytes: number | undefined; if (key === "instructions" || key === "layers" || key === "tools" || key === "skills") { bytes = cache.fieldJsonBytes(key, value); } else if (key === "providerRequest" && isBodyCarrier(value)) { bytes = Buffer.byteLength(JSON.stringify({ ...value, body: null }), "utf8") - 4 + cache.bodyJsonBytes(value.body); } if (bytes === undefined) { const encoded = JSON.stringify(value); if (encoded === undefined) continue; bytes = Buffer.byteLength(encoded, "utf8"); } total += Buffer.byteLength(JSON.stringify(key), "utf8") + 1 + bytes; members += 1; } return total + Math.max(0, members - 1); } function isBodyCarrier(value: unknown): value is Record & { body: string } { return ( !!value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype && typeof (value as { body?: unknown }).body === "string" && !("toJSON" in value) ); } type BlobWriter = Pick; const BLOB_STATEMENT_BATCH = 500; /** * Hold the session's content lock shared until the transaction ends. The * unreferenced-blob collector takes it exclusively (and only when free), so a * transaction holding it can rely on a blob it found staying until it commits * the row that refers to it, and on reading the blobs of a snapshot row it * read. Call it inside a transaction, before the first read it protects. */ export async function lockSessionContentShared( tx: Pick, sessionId: string, ): Promise { await tx.execute( sql`select pg_advisory_xact_lock_shared(hashtextextended(${`session-content-blobs:${sessionId}`}, 0))`, ); } /** * Insert the values this session does not already hold. Idempotent and * race-safe; must run in the transaction that writes the row referring to them. */ export async function writeSessionContentBlobs( tx: BlobWriter, scope: SessionContentScope, blobs: ReadonlyMap, ): Promise { const digests = [...blobs.keys()]; if (digests.length === 0) return 0; await lockSessionContentShared(tx, scope.sessionId); let inserted = 0; for (let offset = 0; offset < digests.length; offset += BLOB_STATEMENT_BATCH) { const batch = digests.slice(offset, offset + BLOB_STATEMENT_BATCH); const present = await tx .select({ digest: schema.sessionContentBlobs.digest }) .from(schema.sessionContentBlobs) .where( and( eq(schema.sessionContentBlobs.workspaceId, scope.workspaceId), eq(schema.sessionContentBlobs.sessionId, scope.sessionId), anyOf(schema.sessionContentBlobs.digest, batch), ), ); const known = new Set(present.map((row) => row.digest)); const missing = batch.filter((digest) => !known.has(digest)); if (missing.length === 0) continue; await tx .insert(schema.sessionContentBlobs) .values( missing.map((digest) => ({ accountId: scope.accountId, workspaceId: scope.workspaceId, sessionId: scope.sessionId, digest, value: blobs.get(digest), })), ) .onConflictDoNothing(); inserted += missing.length; } return inserted; } /** Load exact referenced values; a missing blob is corruption, never an empty value. */ export async function readSessionContentBlobs( tx: BlobReader, scope: Pick, digests: readonly string[], ): Promise> { const unique = [...new Set(digests)]; const values = new Map(); for (let offset = 0; offset < unique.length; offset += BLOB_STATEMENT_BATCH) { const batch = unique.slice(offset, offset + BLOB_STATEMENT_BATCH); const rows = await tx .select({ digest: schema.sessionContentBlobs.digest, // As text, decoded once here. postgres.js already parses jsonb and // drizzle's jsonb column parses a string result again, so a stored // string that is itself JSON (a small request body, one chunk) would // come back as the object it spells. value: sql`${schema.sessionContentBlobs.value}::text`, }) .from(schema.sessionContentBlobs) .where( and( eq(schema.sessionContentBlobs.workspaceId, scope.workspaceId), eq(schema.sessionContentBlobs.sessionId, scope.sessionId), anyOf(schema.sessionContentBlobs.digest, batch), ), ); for (const row of rows) values.set(row.digest, JSON.parse(row.value) as unknown); } for (const digest of unique) { if (!values.has(digest)) throw new SessionContentBlobMissingError(digest); } return values; } function isCatalogRefs(value: unknown): value is AttemptToolCatalogContentRefs { return ( !!value && typeof value === "object" && (value as { v?: unknown }).v === SESSION_CONTENT_REFS_VERSION && Array.isArray((value as { entries?: unknown }).entries) ); } function isSnapshotRefs(value: unknown): value is ModelContextSnapshotContentRefs { const refs = value as Partial | null; return ( !!refs && typeof refs === "object" && refs.v === SESSION_CONTENT_REFS_VERSION && typeof refs.instructions === "string" && typeof refs.layers === "string" && typeof refs.tools === "string" && typeof refs.skills === "string" && (refs.body === null || Array.isArray(refs.body)) ); } /** Return the exact catalog that was written, from either stored form. Unverified. */ export async function hydrateStoredAttemptToolCatalog( tx: BlobReader, row: { catalog: unknown; contentRefs: unknown }, ): Promise { if (row.contentRefs === null || row.contentRefs === undefined) return row.catalog; if (!isCatalogRefs(row.contentRefs)) throw new TypeError("Invalid tool catalog content refs"); const catalog = row.catalog as { workspaceId?: unknown; sessionId?: unknown }; if (typeof catalog.workspaceId !== "string" || typeof catalog.sessionId !== "string") { throw new TypeError("Stored tool catalog is missing its session identity"); } const values = await readSessionContentBlobs( tx, { workspaceId: catalog.workspaceId, sessionId: catalog.sessionId }, row.contentRefs.entries, ); return { ...(row.catalog as Record), entries: row.contentRefs.entries.map((digest) => values.get(digest)), }; } /** Return the exact snapshot that was written, from either stored form. Unverified. */ export async function hydrateStoredModelContextSnapshot( tx: BlobReader, scope: Pick, row: { snapshot: unknown; contentRefs: unknown }, ): Promise { if (row.contentRefs === null || row.contentRefs === undefined) return row.snapshot; if (!isSnapshotRefs(row.contentRefs)) throw new TypeError("Invalid snapshot content refs"); const refs = row.contentRefs; const values = await readSessionContentBlobs(tx, scope, [ refs.instructions, refs.layers, refs.tools, refs.skills, ...(refs.body ?? []), ]); return hydrateModelContextSnapshotFromValues(row.snapshot, refs, values); } /** The digests a stored snapshot's content refs name, or null when it has none. */ export function modelContextSnapshotRefDigests(contentRefs: unknown): string[] | null { if (contentRefs === null || contentRefs === undefined) return null; if (!isSnapshotRefs(contentRefs)) throw new TypeError("Invalid snapshot content refs"); return [ contentRefs.instructions, contentRefs.layers, contentRefs.tools, contentRefs.skills, ...(contentRefs.body ?? []), ]; } /** * Rebuild a stored snapshot from blob values already read (the archive bundle * keeps blobs as their own rows). Unverified, like the database form. */ export function hydrateModelContextSnapshotFromValues( snapshot: unknown, contentRefs: unknown, values: ReadonlyMap, ): unknown { if (contentRefs === null || contentRefs === undefined) return snapshot; if (!isSnapshotRefs(contentRefs)) throw new TypeError("Invalid snapshot content refs"); const refs = contentRefs; const stored = snapshot as ModelContextSnapshot; return { ...stored, instructions: values.get(refs.instructions), layers: values.get(refs.layers), tools: values.get(refs.tools), skills: values.get(refs.skills), ...(stored.providerRequest && refs.body !== null ? { providerRequest: { ...stored.providerRequest, body: refs.body.map((digest) => values.get(digest) as string).join(""), }, } : {}), }; }