/** * Copyright 2026 aphrody-code * SPDX-License-Identifier: Apache-2.0 */ /** * @module bxc/queue/frontier/cuckoo-filter * * Scalable Cuckoo filter (Fan et al., 2014) used as the crawler's persisted * seen-set: "was this URL ever enqueued?" answered from memory, so the * frontier database is only touched for genuinely new URLs. * * - 4 slots per bucket, 16-bit fingerprints: ≈ 2·4/2¹⁶ ≈ 0.012 % false * positives per sub-filter, ~2 bytes per item at 95 % load. * - Scales by chaining sub-filters of doubling capacity (a cuckoo filter * cannot be resized without the original keys). * - Supports deletion (unlike a Bloom filter). * - `save()` writes a versioned binary file atomically; `load()` restores it. */ import { renameSync } from "node:fs"; const MAGIC = 0x4b435842; // "BXCK" little-endian const VERSION = 1; const SLOTS = 4; const MAX_KICKS = 500; function hash64(key: string): bigint { return BigInt.asUintN(64, BigInt(Bun.hash(key))); } function mix32(x: number): number { let h = x >>> 0; h = Math.imul(h ^ (h >>> 16), 0x85ebca6b); h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35); return (h ^ (h >>> 16)) >>> 0; } class SubFilter { readonly buckets: number; readonly slots: Uint16Array; count = 0; constructor(buckets: number, slots?: Uint16Array) { this.buckets = buckets; this.slots = slots ?? new Uint16Array(buckets * SLOTS); } get capacity(): number { return this.buckets * SLOTS; } #alt(index: number, fp: number): number { return (index ^ mix32(fp)) & (this.buckets - 1); } #positions(h: bigint): { fp: number; i1: number; i2: number } { const fp = Number((h >> 48n) & 0xffffn) || 1; const i1 = Number(h & BigInt(this.buckets - 1)); return { fp, i1, i2: this.#alt(i1, fp) }; } #find(bucket: number, fp: number): number { const base = bucket * SLOTS; for (let s = 0; s < SLOTS; s++) if (this.slots[base + s] === fp) return base + s; return -1; } #place(bucket: number, fp: number): boolean { const base = bucket * SLOTS; for (let s = 0; s < SLOTS; s++) { if (this.slots[base + s] === 0) { this.slots[base + s] = fp; return true; } } return false; } has(h: bigint): boolean { const { fp, i1, i2 } = this.#positions(h); return this.#find(i1, fp) >= 0 || this.#find(i2, fp) >= 0; } add(h: bigint): boolean { const { fp, i1, i2 } = this.#positions(h); if (this.#place(i1, fp) || this.#place(i2, fp)) { this.count++; return true; } // Evict: random walk between alternate buckets. let bucket = Math.random() < 0.5 ? i1 : i2; let current = fp; const trail: Array<[number, number]> = []; for (let kick = 0; kick < MAX_KICKS; kick++) { const slot = bucket * SLOTS + Math.floor(Math.random() * SLOTS); const evicted = this.slots[slot] as number; this.slots[slot] = current; trail.push([slot, evicted]); current = evicted; bucket = this.#alt(bucket, current); if (this.#place(bucket, current)) { this.count++; return true; } } // Full: undo the walk so no stored fingerprint is lost. for (let i = trail.length - 1; i >= 0; i--) { const [slot, evicted] = trail[i] as [number, number]; this.slots[slot] = evicted; } return false; } remove(h: bigint): boolean { const { fp, i1, i2 } = this.#positions(h); const at = this.#find(i1, fp) >= 0 ? this.#find(i1, fp) : this.#find(i2, fp); if (at < 0) return false; this.slots[at] = 0; this.count--; return true; } } export interface CuckooFilterOptions { /** Expected items for the first sub-filter (rounded up). Default: 1 000 000. */ initialCapacity?: number; } export class CuckooFilter { readonly #filters: SubFilter[]; constructor(options: CuckooFilterOptions = {}) { const wanted = Math.max(64, Math.ceil((options.initialCapacity ?? 1_000_000) / SLOTS / 0.95)); this.#filters = [new SubFilter(2 ** Math.ceil(Math.log2(wanted)))]; } /** Number of stored fingerprints. */ get size(): number { return this.#filters.reduce((sum, f) => sum + f.count, 0); } /** Bytes used by fingerprint storage. */ get byteLength(): number { return this.#filters.reduce((sum, f) => sum + f.slots.byteLength, 0); } /** `true` if `key` may have been added (false positives possible, no false negatives). */ has(key: string): boolean { const h = hash64(key); return this.#filters.some((f) => f.has(h)); } /** * Add `key`. Returns `false` when it was (probably) already present, so * `if (filter.add(url)) enqueue(url)` enqueues each URL once. */ add(key: string): boolean { const h = hash64(key); if (this.#filters.some((f) => f.has(h))) return false; const last = this.#filters[this.#filters.length - 1] as SubFilter; if (last.count < last.capacity * 0.95 && last.add(h)) return true; const grown = new SubFilter(last.buckets * 2); this.#filters.push(grown); grown.add(h); return true; } remove(key: string): boolean { const h = hash64(key); return this.#filters.some((f) => f.has(h) && f.remove(h)); } /** Serialize to a versioned binary buffer. */ serialize(): Uint8Array { const headerBytes = 12 + this.#filters.length * 8; const total = headerBytes + this.byteLength; const out = new Uint8Array(total); const view = new DataView(out.buffer); view.setUint32(0, MAGIC, true); view.setUint32(4, VERSION, true); view.setUint32(8, this.#filters.length, true); let offset = headerBytes; this.#filters.forEach((filter, i) => { view.setUint32(12 + i * 8, filter.buckets, true); view.setUint32(16 + i * 8, filter.count, true); out.set(new Uint8Array(filter.slots.buffer, filter.slots.byteOffset, filter.slots.byteLength), offset); offset += filter.slots.byteLength; }); return out; } static deserialize(bytes: Uint8Array): CuckooFilter { const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); if (bytes.byteLength < 12 || view.getUint32(0, true) !== MAGIC) throw new Error("not a BXC cuckoo filter"); if (view.getUint32(4, true) !== VERSION) throw new Error("unsupported cuckoo filter version"); const count = view.getUint32(8, true); let offset = 12 + count * 8; const filters: SubFilter[] = []; for (let i = 0; i < count; i++) { const buckets = view.getUint32(12 + i * 8, true); const items = view.getUint32(16 + i * 8, true); const byteLength = buckets * SLOTS * 2; if (offset + byteLength > bytes.byteLength) throw new Error("truncated cuckoo filter"); const slots = new Uint16Array(bytes.slice(offset, offset + byteLength).buffer); const filter = new SubFilter(buckets, slots); filter.count = items; filters.push(filter); offset += byteLength; } const instance = new CuckooFilter({ initialCapacity: 64 }); instance.#filters.splice(0, instance.#filters.length, ...filters); return instance; } /** Atomically write to `path` (temp file + rename). */ async save(path: string): Promise { const tmp = `${path}.tmp-${process.pid}`; await Bun.write(tmp, this.serialize()); renameSync(tmp, path); } /** Load from `path`, or create an empty filter when the file does not exist. */ static async load(path: string, options: CuckooFilterOptions = {}): Promise { const file = Bun.file(path); if (!(await file.exists())) return new CuckooFilter(options); return CuckooFilter.deserialize(new Uint8Array(await file.arrayBuffer())); } }