# 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

## Use

```ts
import { binaryFuse8StaticFilter } from 'knotkit/static-filter'

const encoder = new TextEncoder()
const keys = ['user:1', 'user:2', 'user:3', 'user:2'].map((key) => encoder.encode(key))

const filter = binaryFuse8StaticFilter(keys, { seed: 42n })

filter.size // 3: the repeated key counts once
filter.mightContain(encoder.encode('user:2')) // true, for every key the filter was built from
filter.mightContain(encoder.encode('user:404')) // false, except for about 1 key in 256
filter.byteLength // 12: one byte per slot
```

## What it solves

* 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

## Choose a layout

| Factory                                         | Choose when                                                                                                                                                                                        | Cost                                                                                                               |
| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| `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 budget                                                         | 1 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 slot | 2 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](https://github.com/jkomyno/knotkit/blob/main/packages/static-filter/README.md#performance)

## API

| Export                                                                                             | Returns        | Does                                                                                                                                                     |
| -------------------------------------------------------------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`binaryFuse8StaticFilter`](/reference/knotkit/static-filter/functions/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`](/reference/knotkit/static-filter/functions/binaryfuse16staticfilter/) | `StaticFilter` | The 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

| Member         | Cost                                           |
| -------------- | ---------------------------------------------- |
| `build`        | O(n) expected, plus O(total key bytes) hashing |
| `mightContain` | O(key length) hash plus 3 slot reads           |
| `size`         | O(1)                                           |

`binaryFuse16StaticFilter` 3 members

| Member         | Cost                                           |
| -------------- | ---------------------------------------------- |
| `build`        | O(n) expected, plus O(total key bytes) hashing |
| `mightContain` | O(key length) hash plus 3 slot reads           |
| `size`         | O(1)                                           |

## What you pass in

| Input                                                                                                                                                                                   | Type     | Get 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 filters | `bigint` | [`knotkit/hash`](/modules/hash/) |

## Errors

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`

## Save and restore

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

## When not to use it

| If you need to…                                                                                 | Use instead                                        |
| ----------------------------------------------------------------------------------------------- | -------------------------------------------------- |
| add keys one at a time after the filter is built, or merge filters from several partitions      | [`knotkit/scalar-sketch`](/modules/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`](/modules/sorted-block/)   |
| count distinct keys or estimate how often a key occurs                                          | [`knotkit/scalar-sketch`](/modules/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       |

## Performance

Measured by the suite in [`packages/static-filter/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/static-filter/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.

## Prompt an agent

Prompt · knotkit/static-filterCopy prompt

```
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/
```

## See also

* [API reference](/reference/knotkit/static-filter/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/static-filter/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/static-filter/knotkit.capability.json)suggest a change to the source record
