Skip to content

knotkit/static-filter

Builds immutable Binary Fuse membership filters over a known set of byte keys, with no false negatives and fewer bytes than a Bloom filter at the same false-positive rate

import {
function binaryFuse8StaticFilter(keys: Iterable<Uint8Array>, options?: StaticFilterOptions): StaticFilter

Build an immutable binary-fuse-8 filter from a known set of keys: one byte per slot, about 9 to 10 bits per key, and a false-positive rate near 2^-8 (0.39%).

Every key is hashed with XXH64 under seed, repeated hashes are dropped, and the rest are placed by peeling a 3-wise Binary Fuse hypergraph (Graf and Lemire, 2022). A probe reads three slots in three adjacent segments. Builds in expected O(n) time after hashing n inputs, with O(d) temporary storage for d distinct hashes.

@throws ― {StaticFilterInvalidInputError} With INVALID_KEYS when keys is not iterable, INVALID_KEY when a key is not a Uint8Array, INVALID_SEED when seed is not an unsigned 64-bit bigint, MAX_CAPACITY_EXCEEDED past 2^30 distinct keys or when the runtime refuses the allocation, and CONSTRUCTION_FAILED when 100 attempts all fail to peel, which a set of distinct hashes does not reach in practice.

binaryFuse8StaticFilter
} from 'knotkit/static-filter'
const
const encoder: TextEncoder
encoder
= new
var TextEncoder: new () => TextEncoder

The TextEncoder interface takes a stream of code points as input and emits a stream of UTF-8 bytes.

MDN Reference

An implementation of the WHATWG Encoding Standard TextEncoder API. All instances of TextEncoder only support UTF-8 encoding.

const encoder = new TextEncoder();
const uint8array = encoder.encode('this is some data');

TextEncoder
()
const
const keys: Uint8Array<ArrayBuffer>[]
keys
= ['user:1', 'user:2', 'user:3', 'user:2'].
Array<string>.map<Uint8Array<ArrayBuffer>>(callbackfn: (value: string, index: number, array: string[]) => Uint8Array<ArrayBuffer>, thisArg?: any): Uint8Array<ArrayBuffer>[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
((
key: string
key
) =>
const encoder: TextEncoder
encoder
.
TextEncoder.encode(input?: string): Uint8Array<ArrayBuffer>

The TextEncoder.encode() method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object.

MDN Reference

encode
(
key: string
key
))
const
const filter: StaticFilter
filter
=
function binaryFuse8StaticFilter(keys: Iterable<Uint8Array>, options?: StaticFilterOptions): StaticFilter

Build an immutable binary-fuse-8 filter from a known set of keys: one byte per slot, about 9 to 10 bits per key, and a false-positive rate near 2^-8 (0.39%).

Every key is hashed with XXH64 under seed, repeated hashes are dropped, and the rest are placed by peeling a 3-wise Binary Fuse hypergraph (Graf and Lemire, 2022). A probe reads three slots in three adjacent segments. Builds in expected O(n) time after hashing n inputs, with O(d) temporary storage for d distinct hashes.

@throws ― {StaticFilterInvalidInputError} With INVALID_KEYS when keys is not iterable, INVALID_KEY when a key is not a Uint8Array, INVALID_SEED when seed is not an unsigned 64-bit bigint, MAX_CAPACITY_EXCEEDED past 2^30 distinct keys or when the runtime refuses the allocation, and CONSTRUCTION_FAILED when 100 attempts all fail to peel, which a set of distinct hashes does not reach in practice.

binaryFuse8StaticFilter
(
const keys: Uint8Array<ArrayBuffer>[]
keys
, {
StaticFilterOptions.seed?: bigint | undefined

Seed for the XXH64 hash of every key and for the first construction attempt, an unsigned 64-bit bigint; 0n when omitted. The same keys and seed build byte-identical filters in every runtime.

seed
: 42n })
const filter: StaticFilter
filter
.
StaticFilter.size: number

Number of distinct keys the filter was built from. Repeated keys count once.

size
// 3: the repeated key counts once
const filter: StaticFilter
filter
.
StaticFilter.mightContain: (key: Uint8Array) => boolean

Whether key may be one of the keys the filter was built from: always true for those keys, and true with probability about falsePositiveRateEstimate for any other key. Three array reads after one XXH64 hash.

@throws ― {StaticFilterInvalidInputError} With INVALID_KEY when key is not a Uint8Array.

mightContain
(
const encoder: TextEncoder
encoder
.
TextEncoder.encode(input?: string): Uint8Array<ArrayBuffer>

The TextEncoder.encode() method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object.

MDN Reference

encode
('user:2')) // true, for every key the filter was built from
const filter: StaticFilter
filter
.
StaticFilter.mightContain: (key: Uint8Array) => boolean

Whether key may be one of the keys the filter was built from: always true for those keys, and true with probability about falsePositiveRateEstimate for any other key. Three array reads after one XXH64 hash.

@throws ― {StaticFilterInvalidInputError} With INVALID_KEY when key is not a Uint8Array.

mightContain
(
const encoder: TextEncoder
encoder
.
TextEncoder.encode(input?: string): Uint8Array<ArrayBuffer>

The TextEncoder.encode() method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object.

MDN Reference

encode
('user:404')) // false, except for about 1 key in 256
const filter: StaticFilter
filter
.
StaticFilter.byteLength: number

Bytes of the fingerprint array: one per slot for binary-fuse-8, two for binary-fuse-16, 0 when empty.

byteLength
// 12: one byte per slot
static-filter.ts
  • skip a disk or network read for a key that an immutable table or file certainly does not hold
  • check membership in a set of byte keys that is known in full before the first query and never changes
  • keep a membership test for millions of keys in the smallest memory a Worker or browser tab can spare
  • ship a compact membership summary beside an SSTable, a static index, or a release artifact and reload it later
  • pick between a 0.39% and a 0.0015% false-positive rate at 9 to 10 or 18 to 20 bits per key
FactoryChoose whenCost
binaryFuse8StaticFilter
kind binary-fuse-8
the key set is complete before the first query, never changes, and about one false positive per 256 absent-key probes fits the read budget1 byte per slot, 12,800 bytes for 10,000 keys and 61,440 for 50,000 (9.8 bits per key); 0.39% false positives
binaryFuse16StaticFilter
kind binary-fuse-16
the key set is complete before the first query, never changes, and one false positive per 256 absent-key probes exceeds the read budget, one per 65,536 fits, and memory allows two bytes per slot2 bytes per slot, 25,600 bytes for 10,000 keys and 122,880 for 50,000 (19.7 bits per key); 0.0015% false positives

Performance and benchmarks for this module

ExportReturnsDoes
binaryFuse8StaticFilterStaticFilterImmutable 3-wise Binary Fuse filter with 8-bit fingerprints, built once from a known set of Uint8Array keys hashed with XXH64; repeated keys count once.
binaryFuse16StaticFilterStaticFilterThe same filter with 16-bit fingerprints: twice the bytes for a false-positive rate near 2^-16.

Cost per member. Open a row for every operation.

binaryFuse8StaticFilter 3 members
MemberCost
buildO(n) expected, plus O(total key bytes) hashing
mightContainO(key length) hash plus 3 slot reads
sizeO(1)
binaryFuse16StaticFilter 3 members
MemberCost
buildO(n) expected, plus O(total key bytes) hashing
mightContainO(key length) hash plus 3 slot reads
sizeO(1)
InputTypeGet one from
seed, defaulting to `0n`, that selects the XXH64 identity every key and probe is hashed under and the first construction attempt; the same keys and seed build byte-identical filtersbigintknotkit/hash

Every error this module throws is StaticFilterInvalidInputError or StaticFilterParseError, with a code from a closed, exported list. Branch on the code; the message is for people.

StaticFilterInvalidInputError
INVALID_KEYS INVALID_KEY INVALID_SEED CONSTRUCTION_FAILED MAX_CAPACITY_EXCEEDED
StaticFilterParseError
FOREIGN_STATIC_FILTER INVALID_PACKAGE_HEADER UNKNOWN_KIND CORRUPT_FILTER_PAYLOAD INVALID_MAGIC UNSUPPORTED_ENVELOPE_VERSION UNSUPPORTED_PAYLOAD_VERSION INVALID_SECTION_GEOMETRY NONZERO_PADDING MISALIGNED_SECTION TRUNCATED_PAYLOAD INVALID_CODEC_RESULT DECODE_BUDGET_EXCEEDED UNSTABLE_BUFFER WRONG_FORMAT INTEGRITY_MISMATCH

Serialization lives in a separate entrypoint, knotkit/static-filter/wire, so code that never saves a structure never loads a parser.

Functions
serializeStaticFilter, deserializeStaticFilter
Formats
binary
Compatibility
schema-versioned, envelope v1
If you need to…Use instead
add keys one at a time after the filter is built, or merge filters from several partitionsknotkit/scalar-sketch
an exact set, where a false positive is unacceptableSet
read back, list, or count the keys that were storedknotkit/sorted-block
count distinct keys or estimate how often a key occursknotkit/scalar-sketch
membership against an adversary who can choose keys to collide, or a signed proof of membershipa cryptographic accumulator or a Merkle tree

Measured by the suite in packages/static-filter/__tests__/bench. The numbers come from one machine, so run the suite on yours before deciding on speed alone.

Prompt · knotkit/static-filter
Use knotkit/static-filter for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/static-filter'.

Exports:
- `binaryFuse8StaticFilter` → `StaticFilter`: Immutable 3-wise Binary Fuse filter with 8-bit fingerprints, built once from a known set of Uint8Array keys hashed with XXH64; repeated keys count once.
- `binaryFuse16StaticFilter` → `StaticFilter`: The same filter with 16-bit fingerprints: twice the bytes for a false-positive rate near 2^-16.

Pick the layout by these rules:
- `binaryFuse8StaticFilter` (kind 'binary-fuse-8') when the key set is complete before the first query, never changes, and about one false positive per 256 absent-key probes fits the read budget
- `binaryFuse16StaticFilter` (kind 'binary-fuse-16') when the key set is complete before the first query, never changes, and one false positive per 256 absent-key probes exceeds the read budget, one per 65,536 fits, and memory allows two bytes per slot

Inputs and their sources:
- seed, defaulting to `0n`, that selects the XXH64 identity every key and probe is hashed under and the first construction attempt; the same keys and seed build byte-identical filters: `bigint` from `knotkit/hash`

Use something else when:
- add keys one at a time after the filter is built, or merge filters from several partitions → knotkit/scalar-sketch
- an exact set, where a false positive is unacceptable → Set
- read back, list, or count the keys that were stored → knotkit/sorted-block
- count distinct keys or estimate how often a key occurs → knotkit/scalar-sketch
- membership against an adversary who can choose keys to collide, or a signed proof of membership → a cryptographic accumulator or a Merkle tree

Errors are StaticFilterInvalidInputError or StaticFilterParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/static-filter/wire` (serializeStaticFilter, deserializeStaticFilter).

Full page: https://knotkit.jkomyno.dev/modules/static-filter.md
Types: node_modules/knotkit/static-filter/ and https://knotkit.jkomyno.dev/reference/knotkit/static-filter/