/** * THE CLASSIFIER IN THE OBJECT (owner, 29 Oct 2026; lifted out of the * calendar engine the same day so any table can use it): a choice column * whose definition carries exemplar phrases for its choices (`examples`) and * names the columns a record is said with (`says`) is filled by the object * itself — a typed value, never a sentence. An event's kind is the first * (event.json: `kind`, `says: ["title", "notes", "location"]`). * * A record laid with the column empty (made, or its words changed, or the * value cleared) is said as its first `says` column, and as all of them * together, and each is embedded with `@cf/baai/bge-base-en-v1.5`; it is * compared (cosine) with every choice's exemplar phrases, and a choice scores * its nearest phrase over both sayings. The nearest choice is written when it * scores CHOICE_AT; a member that falls short whose family (`families`) still * scores FAMILY_AT — the member's own score or any of its family's — is * written as the family; else nothing is written. The two thresholds were * read off bge-base-en-v1.5 itself (the same weights run locally) over 76 * invented event titles and the owner's 157 events: at 0.70/0.66 no * unclassifiable title is filled and what is filled is right but for a near * kind (a dentist's appointment as an appointment); lower fills more and * wrongly. * * - A value a person wrote is never written over: only an empty one is * filled, and a cleared one is filled again. * - Each record is judged once for what it holds (`classify_seen`: the row's * version when it was judged, and what it wrote), so one that matches * nothing is not asked again until it changes. * - The exemplars are embedded once for each vocabulary the object holds * (`classify_exemplars`, keyed by a hash of the model, the table, the * column and its choices, families and phrases — a new kit's words are a * new vocabulary), never per record. * - A pass judges at most PER_PASS records of a column, the oldest changed * first, among at most SCAN rows written since the column's mark (AUDIT D: * never the whole table); one that stopped at its bound says so and its * caller carries on soon (the backfill). A record in the table's bin (its `archived` column * set) is not judged. A failed embedding leaves every value as it was, is * said once for the pass, and is tried again at the next pass. */ import { parseSeal } from "./seal.ts"; import type { Engine, Outcome } from "./engine.ts"; import type { Store, StoredRow } from "./store.ts"; /** The model the choices are embedded with, in Workers AI's catalogue. */ export const MODEL = "@cf/baai/bge-base-en-v1.5"; /** The nearest choice is written at this score. */ export const CHOICE_AT = 0.7; /** A member short of CHOICE_AT is written as its family when the family scores this. */ export const FAMILY_AT = 0.66; /** Records judged in one pass: two sayings each, a hundred texts, Workers AI's one batch. */ export const PER_PASS = 50; /** Texts in one embedding call. */ const BATCH = 100; /** What turns words into vectors: Workers AI in the object, a fake in a test. */ export interface Embedder { embed(texts: string[]): Promise; } /** Workers AI's bge-base-en-v1.5, a hundred texts a call. */ export function workersAi(ai: Ai): Embedder { return { async embed(texts) { const out: number[][] = []; for (let i = 0; i < texts.length; i += BATCH) { const answer = (await ai.run(MODEL, { text: texts.slice(i, i + BATCH) })) as { data?: number[][] }; if (!Array.isArray(answer.data) || answer.data.length !== Math.min(BATCH, texts.length - i)) throw new Error(`${MODEL} answered no vector for every text`); out.push(...answer.data); } return out; }, }; } /** * A development object's embedder: the same model served on the developer's * own machine (`KIND_EMBEDDINGS_URL`, `wrangler dev` only — a production * object refuses it), answering `{ data }` for `{ text }` as Workers AI does. */ export function servedAt(url: string): Embedder { return { async embed(texts) { const res = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ text: texts }) }); const answer = (await res.json().catch(() => ({}))) as { data?: number[][] }; if (!res.ok || !Array.isArray(answer.data) || answer.data.length !== texts.length) throw new Error(`the embeddings at ${url} answered ${res.status}`); return answer.data; }, }; } /** What the classifier needs of the object: its store and SQL, and one write in its own transaction and version. */ export interface ClassifyHost { store: Store; sql: SqlStorage; write(fn: (engine: Engine, version: number, outcome: Outcome) => T): T; } /** One choice column the object fills, as its table's definition holds it. */ export interface Vocabulary { table: string; column: string; choices: string[]; families: Record; examples: Record; /** The columns a record is said with: the first alone, then all together. */ says: string[]; /** The table's bin column: a record with it set is not judged. */ archived: string | null; } export const SCHEMA = ` CREATE TABLE IF NOT EXISTS classify_exemplars (basis TEXT NOT NULL, n INTEGER NOT NULL, choice TEXT NOT NULL, phrase TEXT NOT NULL, vector BLOB NOT NULL, PRIMARY KEY (basis, n)); CREATE TABLE IF NOT EXISTS classify_seen (table_id TEXT NOT NULL, column_key TEXT NOT NULL, id TEXT NOT NULL, version INTEGER NOT NULL, wrote TEXT, PRIMARY KEY (table_id, column_key, id)); CREATE TABLE IF NOT EXISTS classify_meta (table_id TEXT NOT NULL, column_key TEXT NOT NULL, basis TEXT NOT NULL, PRIMARY KEY (table_id, column_key)); CREATE TABLE IF NOT EXISTS classify_mark (job TEXT PRIMARY KEY, version INTEGER NOT NULL, table_id TEXT NOT NULL, id TEXT NOT NULL); `; /** How many changed rows (every table's) one pass reads past its mark (AUDIT D, the row-read rule). */ // 1,000: the calendar's jobs each walk their own mark, and one alarm's regular pass stays under READ COST's bound. export const SCAN = 1000; /** Where a job's walk of changed rows stands: the last row along rows_cursor (version, table_id, id) it is done with. */ export interface Mark { version: number; table_id: string; id: string; } export function markOf(host: Pick, job: string): Mark { return host.sql.exec<{ version: number; table_id: string; id: string }>("SELECT version, table_id, id FROM classify_mark WHERE job = ?", job).toArray()[0] ?? { version: -1, table_id: "", id: "" }; } export function setMark(host: Pick, job: string, m: Mark): void { host.sql.exec("INSERT INTO classify_mark (job, version, table_id, id) VALUES (?, ?, ?, ?) ON CONFLICT (job) DO UPDATE SET version = excluded.version, table_id = excluded.table_id, id = excluded.id", job, m.version, m.table_id, m.id); } /** * AUDIT D: the rows written after `m`, every table's, at most SCAN, along rows_cursor. A row only becomes something a * job must look at by being written (its version moves past every mark), so a job that walks forward from its mark * reads only what changed since, never the whole table (a pass of the classifier read 200k to 400k events). */ export function changedAfter(host: Pick, m: Mark): Mark[] { return host.store.query<{ version: number; table_id: string; id: string }>("SELECT version, table_id, id FROM rows INDEXED BY rows_cursor WHERE (version, table_id, id) > (?, ?, ?) ORDER BY version, table_id, id LIMIT ?", m.version, m.table_id, m.id, SCAN); } const KEY = /^[a-z][a-z0-9_]*$/; /** The vocabularies a table's definition carries: each choice column with exemplars and the columns it is said with. */ export function vocabularies(definition: Record | undefined): Vocabulary[] { const table = typeof definition?.id === "string" ? definition.id : ""; const columns = Array.isArray(definition?.columns) ? (definition.columns as Record[]) : []; const keys = new Set(columns.map((c) => c.key).filter((k): k is string => typeof k === "string" && KEY.test(k))); const archived = typeof definition?.archived === "string" && keys.has(definition.archived) ? definition.archived : null; const seal = definition ? parseSeal(definition) : null; const out: Vocabulary[] = []; for (const column of columns) { if (column.type !== "choice" || typeof column.key !== "string" || !KEY.test(column.key) || !Array.isArray(column.choices)) continue; if (!column.examples || typeof column.examples !== "object" || !Array.isArray(column.says)) continue; const says = (column.says as unknown[]).filter((k): k is string => typeof k === "string" && keys.has(k)); if (!says.length) continue; // Words the table seals are not the object's to read (e2e rulings R1): it judges nothing by them, and the column is the person's to fill. if (seal && says.some((k) => !seal.clear.includes(k))) continue; const choices = (column.choices as unknown[]).filter((c): c is string => typeof c === "string"); const examples: Record = {}; for (const [id, phrases] of Object.entries(column.examples as Record)) { if (choices.includes(id) && Array.isArray(phrases)) examples[id] = phrases.filter((p): p is string => typeof p === "string" && p.trim() !== ""); } const families: Record = {}; for (const [member, family] of Object.entries((column.families ?? {}) as Record)) { if (choices.includes(member) && typeof family === "string" && choices.includes(family)) families[member] = family; } if (table && Object.values(examples).some((p) => p.length)) out.push({ table, column: column.key, choices, families, examples, says, archived }); } return out; } /** The vocabulary of `definition`'s choice column `column`, or null when it carries none to judge by. */ export function vocabulary(definition: Record | undefined, column: string): Vocabulary | null { return vocabularies(definition).find((v) => v.column === column) ?? null; } export function cosine(a: ArrayLike, b: ArrayLike): number { let dot = 0; let x = 0; let y = 0; for (let i = 0; i < a.length; i++) { dot += a[i]! * b[i]!; x += a[i]! * a[i]!; y += b[i]! * b[i]!; } return x && y ? dot / Math.sqrt(x * y) : 0; } /** * The choice `scores` (each choice's best) settle on: the nearest at * CHOICE_AT; a member short of it whose family scores FAMILY_AT — the best * of the family's own phrases and its members' — as the family; else none. */ export function decide(scores: Map, families: Record): string | null { let best: string | null = null; let top = -Infinity; for (const [choice, score] of scores) { if (score > top) { best = choice; top = score; } } if (best === null) return null; if (top >= CHOICE_AT) return best; const family = families[best]; if (!family) return null; let kin = scores.get(family) ?? -Infinity; for (const [choice, score] of scores) if (families[choice] === family) kin = Math.max(kin, score); return kin >= FAMILY_AT ? family : null; } /** A record as it is said: its first `says` column, and all of them together (the same words once when the rest say nothing). */ export function sayings(data: Record, says: string[]): string[] { const words = (key: string) => (typeof data[key] === "string" ? (data[key] as string).trim() : ""); const first = words(says[0] ?? ""); const whole = says.map(words).filter(Boolean).join("\n"); return whole === first ? [first] : [first, whole]; } interface Exemplar { choice: string; vector: Float32Array; } async function basisOf(vocab: Vocabulary): Promise { const text = JSON.stringify([MODEL, vocab.table, vocab.column, vocab.choices, vocab.families, vocab.choices.map((c) => vocab.examples[c] ?? [])]); const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)); return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join(""); } /** The vocabulary's exemplars, embedded once and kept; the column's earlier vocabularies' kept ones go. */ async function exemplars(host: ClassifyHost, vocab: Vocabulary, embedder: Embedder): Promise { const basis = await basisOf(vocab); const phrases = vocab.choices.flatMap((choice) => (vocab.examples[choice] ?? []).map((phrase) => ({ choice, phrase }))); const held = host.sql.exec<{ choice: string; vector: ArrayBuffer }>("SELECT choice, vector FROM classify_exemplars WHERE basis = ? ORDER BY n", basis).toArray(); if (held.length === phrases.length) return held.map((row) => ({ choice: row.choice, vector: new Float32Array(row.vector) })); const vectors = await embedder.embed(phrases.map((p) => p.phrase)); const mine = host.sql.exec<{ basis: string }>("SELECT basis FROM classify_meta WHERE table_id = ? AND column_key = ?", vocab.table, vocab.column).toArray()[0]?.basis; if (mine) host.sql.exec("DELETE FROM classify_exemplars WHERE basis = ?", mine); host.sql.exec("DELETE FROM classify_exemplars WHERE basis = ?", basis); phrases.forEach((p, n) => host.sql.exec("INSERT INTO classify_exemplars (basis, n, choice, phrase, vector) VALUES (?, ?, ?, ?, ?)", basis, n, p.choice, p.phrase, new Float32Array(vectors[n]!).buffer)); host.sql.exec("INSERT INTO classify_meta (table_id, column_key, basis) VALUES (?, ?, ?) ON CONFLICT (table_id, column_key) DO UPDATE SET basis = excluded.basis", vocab.table, vocab.column, basis); return phrases.map((p, n) => ({ choice: p.choice, vector: new Float32Array(vectors[n]!) })); } /** The classifier's own tables, made where they are not. */ export function ready(host: Pick): void { host.sql.exec(SCHEMA); } /** What a pass over one column did. */ export interface ClassifyAnswer { /** Records whose value was written. */ written: number; /** Records judged and left empty: nothing scored enough. */ unsure: number; /** The pass stopped at its bound with records still to judge. */ more: boolean; /** Why no record was judged, when one was due and none could be. */ failed?: string; } /** Which records a caller leaves to itself: a column whose value set takes a record out (an event's moved occurrence, `series_id`). */ export interface Leave { leave?: string[]; } /** * Records with the column empty, not in the bin, not left by the caller, not judged as they stand, among the rows * written since the column's mark, the oldest changed first (AUDIT D: the whole table was read every pass). The mark * moves past every row looked at up to the first one due, so a row due and not yet judged (the pass's bound, no * embedder) is looked at again; `behind` says rows past this page are still to look at. */ function due(host: ClassifyHost, vocab: Vocabulary, limit: number, options: Leave): { rows: StoredRow[]; behind: boolean } { const path = (key: string) => `'$.${key}'`; const out = [...(options.leave ?? []), ...(vocab.archived ? [vocab.archived] : [])].filter((k) => KEY.test(k)); const job = `${vocab.table}.${vocab.column}`; const page = changedAfter(host, markOf(host, job)); const mine = page.filter((r) => r.table_id === vocab.table).map((r) => r.id); const dueIds = new Set( mine.length ? host.store .query<{ id: string }>( `SELECT r.id AS id FROM rows r LEFT JOIN classify_seen s ON s.table_id = r.table_id AND s.column_key = ? AND s.id = r.id WHERE r.table_id = ? AND r.id IN (SELECT value FROM json_each(?)) AND r.deleted = 0 AND COALESCE(json_extract(r.data, ${path(vocab.column)}), '') = '' ${out.map((k) => `AND json_extract(r.data, ${path(k)}) IS NULL`).join(" ")} AND (s.version IS NULL OR s.version < r.version)`, vocab.column, vocab.table, JSON.stringify(mine), ) .map((r) => r.id) : [], ); const first = page.findIndex((r) => r.table_id === vocab.table && dueIds.has(r.id)); if (first > 0) setMark(host, job, page[first - 1]!); else if (first < 0 && page.length) setMark(host, job, page[page.length - 1]!); const ordered = page.filter((r) => r.table_id === vocab.table && dueIds.has(r.id)); const rows = ordered .slice(0, limit) .map((r) => host.store.get(vocab.table, r.id)) .filter((r): r is StoredRow => r !== null); return { rows, behind: page.length === SCAN || ordered.length > limit }; } /** Whether a pass has records of the column to judge, or rows still to look at. */ export function pending(host: ClassifyHost, vocab: Vocabulary, options: Leave = {}): boolean { ready(host); const { rows, behind } = due(host, vocab, 1, options); return rows.length > 0 || behind; } /** Marks record `id` judged at `version`, and what was written (null: nothing); the caller made the tables (`ready`). */ export function seen(host: Pick, vocab: Pick, id: string, version: number, wrote: string | null): void { host.sql.exec( "INSERT INTO classify_seen (table_id, column_key, id, version, wrote) VALUES (?, ?, ?, ?, ?) ON CONFLICT (table_id, column_key, id) DO UPDATE SET version = excluded.version, wrote = excluded.wrote", vocab.table, vocab.column, id, version, wrote, ); } /** One pass over one column (see above). Never throws: a failure is said once and every value stays as it was. */ export async function classify(host: ClassifyHost, vocab: Vocabulary, embedder: Embedder | null, options: Leave = {}): Promise { ready(host); const answer: ClassifyAnswer = { written: 0, unsure: 0, more: false }; const { rows: records, behind } = due(host, vocab, PER_PASS, options); answer.more = behind; if (!records.length) return answer; const named = `${vocab.table}.${vocab.column}`; if (!embedder) { answer.failed = "no embedder"; console.error(`cottondb: classify ${named}: ${records.length} record(s) wait for a value and the object has no embedder`); return answer; } let scored: Map[]; try { const known = await exemplars(host, vocab, embedder); const said = records.map((r) => sayings(r.data, vocab.says)); const vectors = await embedder.embed(said.flat()); let at = 0; scored = said.map((s) => { const mine = vectors.slice(at, (at += s.length)); const best = new Map(); for (const e of known) { const score = Math.max(...mine.map((v) => cosine(v, e.vector))); if (score > (best.get(e.choice) ?? -Infinity)) best.set(e.choice, score); } return best; }); } catch (error) { answer.failed = error instanceof Error ? error.message : String(error); console.error(`cottondb: classify ${named}: the embedding failed, ${records.length} record(s) left as they are: ${answer.failed}`); return answer; } answer.more = behind || records.length === PER_PASS; const decided = records.map((r, i) => ({ record: r, choice: decide(scored[i]!, vocab.families) })); // Every record judged is marked, so one that matched nothing is not asked again until it changes. host.write((engine, version, outcome) => { for (const { record, choice } of decided) { const now = engine.store.get(vocab.table, record.id); const held = now?.data[vocab.column]; // Changed while it was judged, or given a value meanwhile: the next pass sees it as it is. if (!now || now.version !== record.version || (typeof held === "string" && held !== "")) continue; if (choice === null) { seen(host, vocab, record.id, now.version, null); answer.unsure++; continue; } const after = engine.update(now, { [vocab.column]: choice }, version, outcome); seen(host, vocab, record.id, after.version, choice); answer.written++; } }); return answer; }