/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @module bxc/queue/sharded/seen-set * * Cluster-wide "URL already seen" set: a partitioned Bloom filter. * * Sizing, for `n` expected items and a target false-positive rate `p`: * * k = ceil(log2(1 / p)) hash functions = partitions * m = ceil(-n · ln(p) / (ln 2)²) total bits * m_part = ceil(m / k) bits per partition * * Each key sets exactly one bit in each of the `k` partitions. After `n` * insertions a partition is filled to `1 − e^(−n / m_part) ≈ 1/2`, so the * false-positive rate is `(1 − e^(−n / m_part))^k ≈ 2^(−k) ≈ p`. * Defaults (50 M items, 1 %): k = 7, m ≈ 479 M bits ≈ 57 MiB, 8.6 MiB per * partition — each partition is its own Redis string (limit 512 MiB), so a * filter scales to ~3 billion items at 1 % before a partition hits the limit. * * Bit positions use double hashing (Kirsch–Mitzenmacher): * `offset_i = (h1 + i · h2) mod m_part` with `h1`, `h2` two seeded xxHash32 * values, computed client-side so the Lua script stays trivial. * * Implementations: * - {@link RedisSeenSet}: bitmaps in Redis without modules (`SETBIT` / * `GETBIT` inside one atomic Lua script per batch), shared by all workers; * - {@link MemorySeenSet}: same filter on `Uint8Array`s for single-node mode. * * A Bloom filter has no false negatives: a key that was added is always * reported as seen. False positives make a never-seen URL look seen, so the * sharded frontier only consults the filter for cross-shard submissions. */ import type { RedisClient } from "bun"; import { openRedis, RedisScript, toInt } from "./redis.ts"; const SEED_H1 = 0x5bd1e995; const SEED_H2 = 0x9e3779b9; /** Keys per Lua call (7 offsets each at the default rate). */ const REDIS_BATCH = 1_000; export const DEFAULT_SEEN_EXPECTED_ITEMS = 50_000_000; export const DEFAULT_SEEN_FALSE_POSITIVE_RATE = 0.01; /** Bits addressable in one Redis string (512 MiB). */ const MAX_PARTITION_BITS = 2 ** 32; export interface BloomParams { /** Capacity the filter was sized for. */ expectedItems: number; /** Target false-positive rate at capacity. */ falsePositiveRate: number; /** Number of hash functions (= partitions). */ hashes: number; /** Bits per partition. */ partitionBits: number; /** Total bits (`hashes · partitionBits`). */ totalBits: number; } /** Size a partitioned Bloom filter (see the module documentation for the formula). */ export function bloomParams( expectedItems: number = DEFAULT_SEEN_EXPECTED_ITEMS, falsePositiveRate: number = DEFAULT_SEEN_FALSE_POSITIVE_RATE, ): BloomParams { if (!(expectedItems >= 1) || !Number.isFinite(expectedItems)) { throw new RangeError(`expectedItems must be >= 1, got ${expectedItems}`); } if (!(falsePositiveRate > 0 && falsePositiveRate < 1)) { throw new RangeError(`falsePositiveRate must be in (0, 1), got ${falsePositiveRate}`); } const n = Math.ceil(expectedItems); const hashes = Math.max(1, Math.ceil(Math.log2(1 / falsePositiveRate))); const totalBits = Math.ceil((-n * Math.log(falsePositiveRate)) / (Math.LN2 * Math.LN2)); const partitionBits = Math.max(8, Math.ceil(totalBits / hashes)); if (partitionBits > MAX_PARTITION_BITS) { throw new RangeError( `seen-set partition of ${partitionBits} bits exceeds the Redis string limit; lower expectedItems or raise falsePositiveRate`, ); } return { expectedItems: n, falsePositiveRate, hashes, partitionBits, totalBits: partitionBits * hashes, }; } /** Expected false-positive rate after `count` distinct insertions. */ export function estimatedFalsePositiveRate(params: BloomParams, count: number): number { if (count <= 0) return 0; return (1 - Math.exp(-count / params.partitionBits)) ** params.hashes; } /** Bit offset of `key` in each partition. */ export function bloomOffsets(key: string, params: BloomParams): number[] { const h1 = Bun.hash.xxHash32(key, SEED_H1) >>> 0; const h2 = (Bun.hash.xxHash32(key, SEED_H2) | 1) >>> 0; const offsets: number[] = Array.from({ length: params.hashes }); for (let i = 0; i < params.hashes; i++) { // h1 + i·h2 < 2^53 for any realistic k: exact in a double. offsets[i] = (h1 + i * h2) % params.partitionBits; } return offsets; } /** Shared seen-set contract (Redis-backed or in-process). */ export interface SeenSet { readonly params: BloomParams; /** Add keys; `true` at index `i` when `keys[i]` was not seen before (first occurrence in the batch). */ addMany(keys: readonly string[]): Promise; /** Membership test without insertion (`true` = probably seen). */ hasMany(keys: readonly string[]): Promise; /** Number of keys reported as newly added so far (≈ distinct keys). */ count(): Promise; /** Forget every key. */ clear(): Promise; /** Release resources (does not clear shared state). */ close(): Promise; } export interface SeenSetOptions { expectedItems?: number; falsePositiveRate?: number; } // --------------------------------------------------------------------------- // In-process implementation // --------------------------------------------------------------------------- /** Partitioned Bloom filter in memory (single-node mode, tests). */ export class MemorySeenSet implements SeenSet { readonly params: BloomParams; readonly #partitions: Array; #count = 0; constructor(options: SeenSetOptions = {}) { this.params = bloomParams(options.expectedItems, options.falsePositiveRate); this.#partitions = Array.from({ length: this.params.hashes }, () => null); } #partition(i: number): Uint8Array { let bits = this.#partitions[i]; if (!bits) { bits = new Uint8Array(Math.ceil(this.params.partitionBits / 8)); this.#partitions[i] = bits; } return bits; } /** Synchronous {@link addMany}. */ addManySync(keys: readonly string[]): boolean[] { const out: boolean[] = Array.from({ length: keys.length }); for (let j = 0; j < keys.length; j++) { const offsets = bloomOffsets(keys[j] as string, this.params); let fresh = false; for (let i = 0; i < offsets.length; i++) { const bits = this.#partition(i); const offset = offsets[i] as number; const byte = offset >>> 3; const mask = 1 << (offset & 7); if ((bits[byte] & mask) === 0) { bits[byte] |= mask; fresh = true; } } out[j] = fresh; if (fresh) this.#count++; } return out; } /** Synchronous {@link hasMany}. */ hasManySync(keys: readonly string[]): boolean[] { return keys.map((key) => { const offsets = bloomOffsets(key, this.params); for (let i = 0; i < offsets.length; i++) { const bits = this.#partitions[i]; const offset = offsets[i] as number; if (!bits || (bits[offset >>> 3] & (1 << (offset & 7))) === 0) return false; } return true; }); } async addMany(keys: readonly string[]): Promise { return this.addManySync(keys); } async hasMany(keys: readonly string[]): Promise { return this.hasManySync(keys); } async count(): Promise { return this.#count; } async clear(): Promise { this.#partitions.fill(null); this.#count = 0; } async close(): Promise {} } // --------------------------------------------------------------------------- // Redis implementation // --------------------------------------------------------------------------- /** * KEYS: partition bitmaps (k), counter. ARGV: k, then k offsets per key. * Returns 1 per key when at least one bit was 0 (newly added). */ export const SEEN_ADD_LUA = ` local k = tonumber(ARGV[1]) local n = (#ARGV - 1) / k local out = {} local added = 0 for j = 0, n - 1 do local base = 1 + j * k local fresh = 0 for i = 1, k do if redis.call('SETBIT', KEYS[i], ARGV[base + i], 1) == 0 then fresh = 1 end end out[j + 1] = fresh added = added + fresh end if added > 0 then redis.call('INCRBY', KEYS[k + 1], added) end return out `; const SEEN_HAS_LUA = ` local k = tonumber(ARGV[1]) local n = (#ARGV - 1) / k local out = {} for j = 0, n - 1 do local base = 1 + j * k local hit = 1 for i = 1, k do if redis.call('GETBIT', KEYS[i], ARGV[base + i]) == 0 then hit = 0 break end end out[j + 1] = hit end return out `; const ADD_SCRIPT = new RedisScript(SEEN_ADD_LUA); const HAS_SCRIPT = new RedisScript(SEEN_HAS_LUA); /** Redis key names of a seen-set under `prefix`. */ export function seenSetKeys(prefix: string, params: BloomParams) { return { meta: `${prefix}:seen:meta`, count: `${prefix}:seen:count`, partitions: Array.from({ length: params.hashes }, (_, i) => `${prefix}:seen:bits:${i}`), }; } interface StoredSeenMeta { version: 1; expectedItems: number; falsePositiveRate: number; hashes: number; partitionBits: number; } export interface RedisSeenSetOptions extends SeenSetOptions { /** Existing client (not closed by the seen-set). */ client?: RedisClient; /** Redis URL when no client is given. */ redisUrl?: string; /** Key prefix, e.g. `bxc:{frontier}`. */ prefix: string; } /** * Seen-set shared by every worker. Sizing is fixed by the first opener and * stored in `:seen:meta`; later openers adopt it regardless of their * own options, so all workers compute identical bit offsets. */ export class RedisSeenSet implements SeenSet { readonly params: BloomParams; readonly keys: ReturnType; readonly #client: RedisClient; readonly #ownsClient: boolean; private constructor(client: RedisClient, ownsClient: boolean, prefix: string, params: BloomParams) { this.#client = client; this.#ownsClient = ownsClient; this.params = params; this.keys = seenSetKeys(prefix, params); } static async open(options: RedisSeenSetOptions): Promise { const client = options.client ?? openRedis(options.redisUrl); const ownsClient = !options.client; try { const wanted = bloomParams(options.expectedItems, options.falsePositiveRate); const metaKey = `${options.prefix}:seen:meta`; const meta: StoredSeenMeta = { version: 1, expectedItems: wanted.expectedItems, falsePositiveRate: wanted.falsePositiveRate, hashes: wanted.hashes, partitionBits: wanted.partitionBits, }; await client.send("SET", [metaKey, JSON.stringify(meta), "NX"]); const stored = JSON.parse(String(await client.send("GET", [metaKey]))) as StoredSeenMeta; const params: BloomParams = { expectedItems: stored.expectedItems, falsePositiveRate: stored.falsePositiveRate, hashes: stored.hashes, partitionBits: stored.partitionBits, totalBits: stored.hashes * stored.partitionBits, }; return new RedisSeenSet(client, ownsClient, options.prefix, params); } catch (err) { if (ownsClient) client.close(); throw err; } } /** Flattened `[k, offsets…]` arguments for a batch. */ #args(keys: readonly string[]): number[] { const args: number[] = [this.params.hashes]; for (const key of keys) { for (const offset of bloomOffsets(key, this.params)) args.push(offset); } return args; } async addMany(keys: readonly string[]): Promise { const out: boolean[] = []; for (let start = 0; start < keys.length; start += REDIS_BATCH) { const batch = keys.slice(start, start + REDIS_BATCH); const reply = (await ADD_SCRIPT.run( this.#client, [...this.keys.partitions, this.keys.count], this.#args(batch), )) as unknown[]; for (const flag of reply) out.push(toInt(flag) === 1); } return out; } async hasMany(keys: readonly string[]): Promise { const out: boolean[] = []; for (let start = 0; start < keys.length; start += REDIS_BATCH) { const batch = keys.slice(start, start + REDIS_BATCH); const reply = (await HAS_SCRIPT.run(this.#client, this.keys.partitions, this.#args(batch))) as unknown[]; for (const flag of reply) out.push(toInt(flag) === 1); } return out; } async count(): Promise { return toInt(await this.#client.send("GET", [this.keys.count])); } async clear(): Promise { await this.#client.send("DEL", [...this.keys.partitions, this.keys.count, this.keys.meta]); } async close(): Promise { if (this.#ownsClient) this.#client.close(); } } /** * Open a seen-set: Redis-backed when `redisUrl` or `client` is given, * otherwise in-process. */ export async function createSeenSet( options: SeenSetOptions & { redisUrl?: string; client?: RedisClient; prefix?: string } = {}, ): Promise { if (options.redisUrl || options.client) { return RedisSeenSet.open({ ...options, prefix: options.prefix ?? "bxc:{default}" }); } return new MemorySeenSet(options); }