# knotkit/scalar-sketch

> Provides reducible Bloom filter, HyperLogLog, Count-Min Sketch, and MinHash sketches over four scalar domains

## Use

```ts
import { stringSplitBlockBloomFilter } from 'knotkit/scalar-sketch'

const filter = stringSplitBlockBloomFilter({
  expectedEntries: 10_000,
  targetFalsePositiveProbability: 0.01,
  seed: 7n,
})

filter.update('alpha')
filter.mightContain('alpha') // true — no false negatives
filter.mightContain('omega') // almost always false
filter.blockCount // 512 — a power of two, chosen by the model
```

```ts
import { stringSplitBlockBloomFilter } from 'knotkit/scalar-sketch'
import { deserializeScalarSketch, serializeScalarSketch } from 'knotkit/scalar-sketch/wire'

const options = { expectedEntries: 10_000, seed: 7n }
const shard = stringSplitBlockBloomFilter(options)
const other = stringSplitBlockBloomFilter(options)

shard.update('alpha')
other.update('beta')
shard.merge(other) // union in place; `other` is untouched

const smaller = shard.reduce(shard.blockCount / 2) // half the state, a higher error model
const restored = deserializeScalarSketch(serializeScalarSketch(smaller))
if (restored.kind === 'split-block-bloom-filter' && restored.scalarKind === 'string') {
  restored.mightContain('alpha') // true
}
```

## What it solves

* count distinct visitors without storing every visitor
* check whether an id or URL was already processed, with a small false-positive rate and no false negatives
* find the heavy hitters of a stream without keeping a counter per key
* estimate how much two large sets overlap without holding both of them
* answer those questions per partition and merge the answers afterwards
* keep the answer in a fixed-size summary that is serialized now and queried later

## Choose a layout

| Factory                                                      | Choose when                                                                                                                                                                                                                                                | Cost                                                                                                                                     |
| ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `stringSplitBlockBloomFilter`kind `split-block-bloom-filter` | the question is membership, a rare false positive is acceptable, and \`expectedEntries\` is known before the first update; the \`string\`, \`bytes\`, \`uint32\`, and \`uint64\` factories are this one layout over four value domains                     | \`blockCount\` 256-bit blocks, a power of two, 16 KiB at \`expectedEntries\` 10,000 and a 0.01 target rate; one block touched per update |
| `stringHyperLogLog`kind `hyperloglog`                        | the question is how many distinct values there are, the reported \`relativeStandardError\` of \`1.04 / sqrt(registerCount)\` is acceptable, and the values themselves need not be retained; the four domain factories differ only in how a value is hashed | one byte per register over \`2 \*\* precision\` registers, 16 KiB at the default precision 14 for a 0.8% relative standard error         |
| `stringCountMinSketch`kind `count-min-sketch`                | the question is how often each value occurred, an overestimate is acceptable, and the reported \`epsilon\` and \`confidence\` bounds fit the caller's tolerance; the four domain factories differ only in how a value is hashed                            | \`width \* depth\` 32-bit counters, 4096 columns and 5 rows at the default \`epsilon\` 0.001 and \`confidence\` 0.99, 80 KiB             |
| `stringMinHash`kind `minhash`                                | the question is how much two sets overlap, as an estimated Jaccard index, one signature per set fits where the sets do not, and \`maximumStandardError\` of \`1 / (2 \* sqrt(signatureSize))\` is acceptable                                               | \`signatureSize\` 64-bit coordinate minima, 1 KiB at the default 128 coordinates, and one digest per coordinate per value                |
| `string*`kind `string`                                       | values are JavaScript strings and the caller accepts O(length) hashing per operation, which every string-domain sketch pays on \`update\` and on the query that takes a value                                                                              | one XXH64 digest over the UTF-8 bytes, so time and cache pressure scale with string length rather than with state size                   |
| `bytes*`kind `bytes`                                         | values are \`Uint8Array\` byte sequences, such as digests or serialized records, and hashing those exact bytes is what the caller wants                                                                                                                    | one XXH64 digest over the raw bytes, O(length) per operation                                                                             |
| `uint32*`kind `uint32`                                       | values are integers in \`0..2^32 - 1\`, so every operation hashes in O(1) with no encoding step                                                                                                                                                            | one XXH64 digest of four bytes per operation, independent of state size                                                                  |
| `uint64*`kind `uint64`                                       | values are \`bigint\`s in \`0n..2^64 - 1n\`, so every operation hashes in O(1) and the full 64-bit domain survives                                                                                                                                         | one XXH64 digest of eight bytes per operation, independent of state size                                                                 |

[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/scalar-sketch/README.md#performance)

## Try it

Seed77Reset

* Membership can return a false positive. The rate rises when a filter fills past its design load.
* Choose the sketch by the question: membership, distinct count, frequency, or similarity.

Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/scalar-sketch/demo.ts) against `knotkit/scalar-sketch` in your browser; the defaults reproduce the README figure.

## API

| Export                                                                                                   | Returns                       | Does                                                                                                                     |
| -------------------------------------------------------------------------------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| [`stringSplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/functions/stringsplitblockbloomfilter/) | `StringSplitBlockBloomFilter` | String membership with no false negatives. \`expectedEntries\` is required; the block count rounds up to a power of two. |
| [`bytesSplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/functions/bytessplitblockbloomfilter/)   | `BytesSplitBlockBloomFilter`  | Membership over \`Uint8Array\` values, hashing the raw bytes.                                                            |
| [`uint32SplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/functions/uint32splitblockbloomfilter/) | `Uint32SplitBlockBloomFilter` | Membership over integers in \`0..2^32 - 1\`, hashed without an encoding step.                                            |
| [`uint64SplitBlockBloomFilter`](/reference/knotkit/scalar-sketch/functions/uint64splitblockbloomfilter/) | `Uint64SplitBlockBloomFilter` | Membership over \`bigint\` values in \`0n..2^64 - 1n\`.                                                                  |
| [`stringHyperLogLog`](/reference/knotkit/scalar-sketch/functions/stringhyperloglog/)                     | `StringHyperLogLog`           | Distinct-count estimate over strings, by Ertl's improved raw estimator over one-byte registers.                          |
| [`bytesHyperLogLog`](/reference/knotkit/scalar-sketch/functions/byteshyperloglog/)                       | `BytesHyperLogLog`            | Distinct-count estimate over \`Uint8Array\` values; \`precision\` defaults to 14 and may be reduced exactly.             |
| [`uint32HyperLogLog`](/reference/knotkit/scalar-sketch/functions/uint32hyperloglog/)                     | `Uint32HyperLogLog`           | Distinct-count estimate over integers in \`0..2^32 - 1\`.                                                                |
| [`uint64HyperLogLog`](/reference/knotkit/scalar-sketch/functions/uint64hyperloglog/)                     | `Uint64HyperLogLog`           | Distinct-count estimate over \`bigint\` values in \`0n..2^64 - 1n\`.                                                     |
| [`stringCountMinSketch`](/reference/knotkit/scalar-sketch/functions/stringcountminsketch/)               | `StringCountMinSketch`        | Per-value frequency over strings; the minimum counter across rows never underestimates an accepted stream.               |
| [`bytesCountMinSketch`](/reference/knotkit/scalar-sketch/functions/bytescountminsketch/)                 | `BytesCountMinSketch`         | Per-value frequency over \`Uint8Array\` values; weights are unsigned 32-bit integers and zero is a no-op.                |
| [`uint32CountMinSketch`](/reference/knotkit/scalar-sketch/functions/uint32countminsketch/)               | `Uint32CountMinSketch`        | Per-value frequency over integers in \`0..2^32 - 1\`.                                                                    |
| [`uint64CountMinSketch`](/reference/knotkit/scalar-sketch/functions/uint64countminsketch/)               | `Uint64CountMinSketch`        | Per-value frequency over \`bigint\` values in \`0n..2^64 - 1n\`.                                                         |
| [`stringMinHash`](/reference/knotkit/scalar-sketch/functions/stringminhash/)                             | `StringMinHash`               | Jaccard-estimate signature over strings: \`signatureSize\` ordered coordinate minima, prefix-stable under \`reduce\`.    |
| [`bytesMinHash`](/reference/knotkit/scalar-sketch/functions/bytesminhash/)                               | `BytesMinHash`                | Jaccard-estimate signature over \`Uint8Array\` values; \`signatureSize\` defaults to 128.                                |
| [`uint32MinHash`](/reference/knotkit/scalar-sketch/functions/uint32minhash/)                             | `Uint32MinHash`               | Jaccard-estimate signature over integers in \`0..2^32 - 1\`.                                                             |
| [`uint64MinHash`](/reference/knotkit/scalar-sketch/functions/uint64minhash/)                             | `Uint64MinHash`               | Jaccard-estimate signature over \`bigint\` values in \`0n..2^64 - 1n\`.                                                  |

Cost per member. Open a row for every operation.

`stringSplitBlockBloomFilter` 4 members

| Member         | Cost          |
| -------------- | ------------- |
| `update`       | O(length)     |
| `mightContain` | O(length)     |
| `merge`        | O(blockCount) |
| `reduce`       | O(blockCount) |

`bytesSplitBlockBloomFilter` 4 members

| Member         | Cost          |
| -------------- | ------------- |
| `update`       | O(length)     |
| `mightContain` | O(length)     |
| `merge`        | O(blockCount) |
| `reduce`       | O(blockCount) |

`uint32SplitBlockBloomFilter` 4 members

| Member         | Cost          |
| -------------- | ------------- |
| `update`       | O(1)          |
| `mightContain` | O(1)          |
| `merge`        | O(blockCount) |
| `reduce`       | O(blockCount) |

`uint64SplitBlockBloomFilter` 4 members

| Member         | Cost          |
| -------------- | ------------- |
| `update`       | O(1)          |
| `mightContain` | O(1)          |
| `merge`        | O(blockCount) |
| `reduce`       | O(blockCount) |

`stringHyperLogLog` 4 members

| Member     | Cost                                                    |
| ---------- | ------------------------------------------------------- |
| `update`   | O(length)                                               |
| `estimate` | O(registerCount) after a write, O(1) for repeated reads |
| `merge`    | O(registerCount)                                        |
| `reduce`   | O(registerCount)                                        |

`bytesHyperLogLog` 4 members

| Member     | Cost                                                    |
| ---------- | ------------------------------------------------------- |
| `update`   | O(length)                                               |
| `estimate` | O(registerCount) after a write, O(1) for repeated reads |
| `merge`    | O(registerCount)                                        |
| `reduce`   | O(registerCount)                                        |

`uint32HyperLogLog` 4 members

| Member     | Cost                                                    |
| ---------- | ------------------------------------------------------- |
| `update`   | O(1)                                                    |
| `estimate` | O(registerCount) after a write, O(1) for repeated reads |
| `merge`    | O(registerCount)                                        |
| `reduce`   | O(registerCount)                                        |

`uint64HyperLogLog` 4 members

| Member     | Cost                                                    |
| ---------- | ------------------------------------------------------- |
| `update`   | O(1)                                                    |
| `estimate` | O(registerCount) after a write, O(1) for repeated reads |
| `merge`    | O(registerCount)                                        |
| `reduce`   | O(registerCount)                                        |

`stringCountMinSketch` 4 members

| Member     | Cost               |
| ---------- | ------------------ |
| `update`   | O(depth \* length) |
| `estimate` | O(depth \* length) |
| `merge`    | O(width \* depth)  |
| `reduce`   | O(width \* depth)  |

`bytesCountMinSketch` 4 members

| Member     | Cost               |
| ---------- | ------------------ |
| `update`   | O(depth \* length) |
| `estimate` | O(depth \* length) |
| `merge`    | O(width \* depth)  |
| `reduce`   | O(width \* depth)  |

`uint32CountMinSketch` 4 members

| Member     | Cost              |
| ---------- | ----------------- |
| `update`   | O(depth)          |
| `estimate` | O(depth)          |
| `merge`    | O(width \* depth) |
| `reduce`   | O(width \* depth) |

`uint64CountMinSketch` 4 members

| Member     | Cost              |
| ---------- | ----------------- |
| `update`   | O(depth)          |
| `estimate` | O(depth)          |
| `merge`    | O(width \* depth) |
| `reduce`   | O(width \* depth) |

`stringMinHash` 5 members

| Member       | Cost                       |
| ------------ | -------------------------- |
| `update`     | O(signatureSize \* length) |
| `snapshot`   | O(signatureSize)           |
| `similarity` | O(signatureSize)           |
| `merge`      | O(signatureSize)           |
| `reduce`     | O(signatureSize)           |

`bytesMinHash` 5 members

| Member       | Cost                       |
| ------------ | -------------------------- |
| `update`     | O(signatureSize \* length) |
| `snapshot`   | O(signatureSize)           |
| `similarity` | O(signatureSize)           |
| `merge`      | O(signatureSize)           |
| `reduce`     | O(signatureSize)           |

`uint32MinHash` 5 members

| Member       | Cost             |
| ------------ | ---------------- |
| `update`     | O(signatureSize) |
| `snapshot`   | O(signatureSize) |
| `similarity` | O(signatureSize) |
| `merge`      | O(signatureSize) |
| `reduce`     | O(signatureSize) |

`uint64MinHash` 5 members

| Member       | Cost             |
| ------------ | ---------------- |
| `update`     | O(signatureSize) |
| `snapshot`   | O(signatureSize) |
| `similarity` | O(signatureSize) |
| `merge`      | O(signatureSize) |
| `reduce`     | O(signatureSize) |

## What you pass in

| Input                                                                                                                                    | Type                                      | Get one from                     |
| ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | -------------------------------- |
| hash identity, the seeded XXH64 instance that produces every digest and decides whether two sketches may merge                           | `bigint seed selecting an XXH64 identity` | [`knotkit/hash`](/modules/hash/) |
| seed, defaulting to \`0n\` and folded into merge compatibility; an invalid seed surfaces \`HashInvalidInputError\` from \`knotkit/hash\` | `bigint`                                  | [`knotkit/hash`](/modules/hash/) |

## Errors

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

* `ScalarSketchInvalidInputError`

  `INVALID_PROBABILITY` `INVALID_DIMENSION` `INVALID_PRECISION` `INVALID_SIGNATURE_SIZE` `STATE_TOO_LARGE`

* `ScalarSketchParseError`

  `FOREIGN_STRUCTURE` `WRONG_FAMILY` `INCOMPATIBLE_SKETCH` `INVALID_REDUCTION` `INVALID_WEIGHT` `CAPACITY_EXCEEDED` `COUNTER_OVERFLOW` `INVALID_SHAPE` `INVALID_ENVELOPE` `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` `INVALID_PACKAGE_HEADER` `UNKNOWN_KIND` `UNKNOWN_SCALAR_KIND` `UNSUPPORTED_WIRE_VERSION` `UNSUPPORTED_PRODUCER_VERSION` `UNSUPPORTED_SCHEDULE` `INVALID_STATE`

## Save and restore

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

* Functions

  `serializeScalarSketch`, `deserializeScalarSketch`, `serializeScalarSketchJson`, `deserializeScalarSketchJson`

* Formats

  binary, json

* Compatibility

  schema-versioned, envelope v1

## When not to use it

| If you need to…                                                                                        | Use instead                                        |
| ------------------------------------------------------------------------------------------------------ | -------------------------------------------------- |
| an exact set, where a false positive is unacceptable                                                   | Set, Map                                           |
| the exact count of a value, or a count that never exaggerates                                          | Map\<K, number>                                    |
| read back the values that were observed                                                                | [`knotkit/snapshot-set`](/modules/snapshot-set/)   |
| keep a bounded random sample of the stream instead of a summary of it                                  | [`knotkit/sampling`](/modules/sampling/)           |
| test membership in a key set that is complete before the first query and never changes, in fewer bytes | [`knotkit/static-filter`](/modules/static-filter/) |

## Performance

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

## Prompt an agent

Prompt · knotkit/scalar-sketchCopy prompt

```
Use knotkit/scalar-sketch for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/scalar-sketch'.

Exports:
- `stringSplitBlockBloomFilter` → `StringSplitBlockBloomFilter`: String membership with no false negatives. `expectedEntries` is required; the block count rounds up to a power of two.
- `bytesSplitBlockBloomFilter` → `BytesSplitBlockBloomFilter`: Membership over `Uint8Array` values, hashing the raw bytes.
- `uint32SplitBlockBloomFilter` → `Uint32SplitBlockBloomFilter`: Membership over integers in `0..2^32 - 1`, hashed without an encoding step.
- `uint64SplitBlockBloomFilter` → `Uint64SplitBlockBloomFilter`: Membership over `bigint` values in `0n..2^64 - 1n`.
- `stringHyperLogLog` → `StringHyperLogLog`: Distinct-count estimate over strings, by Ertl's improved raw estimator over one-byte registers.
- `bytesHyperLogLog` → `BytesHyperLogLog`: Distinct-count estimate over `Uint8Array` values; `precision` defaults to 14 and may be reduced exactly.
- `uint32HyperLogLog` → `Uint32HyperLogLog`: Distinct-count estimate over integers in `0..2^32 - 1`.
- `uint64HyperLogLog` → `Uint64HyperLogLog`: Distinct-count estimate over `bigint` values in `0n..2^64 - 1n`.
- `stringCountMinSketch` → `StringCountMinSketch`: Per-value frequency over strings; the minimum counter across rows never underestimates an accepted stream.
- `bytesCountMinSketch` → `BytesCountMinSketch`: Per-value frequency over `Uint8Array` values; weights are unsigned 32-bit integers and zero is a no-op.
- `uint32CountMinSketch` → `Uint32CountMinSketch`: Per-value frequency over integers in `0..2^32 - 1`.
- `uint64CountMinSketch` → `Uint64CountMinSketch`: Per-value frequency over `bigint` values in `0n..2^64 - 1n`.
- `stringMinHash` → `StringMinHash`: Jaccard-estimate signature over strings: `signatureSize` ordered coordinate minima, prefix-stable under `reduce`.
- `bytesMinHash` → `BytesMinHash`: Jaccard-estimate signature over `Uint8Array` values; `signatureSize` defaults to 128.
- `uint32MinHash` → `Uint32MinHash`: Jaccard-estimate signature over integers in `0..2^32 - 1`.
- `uint64MinHash` → `Uint64MinHash`: Jaccard-estimate signature over `bigint` values in `0n..2^64 - 1n`.

Pick the layout by these rules:
- `stringSplitBlockBloomFilter` (kind 'split-block-bloom-filter') when the question is membership, a rare false positive is acceptable, and `expectedEntries` is known before the first update; the `string`, `bytes`, `uint32`, and `uint64` factories are this one layout over four value domains
- `stringHyperLogLog` (kind 'hyperloglog') when the question is how many distinct values there are, the reported `relativeStandardError` of `1.04 / sqrt(registerCount)` is acceptable, and the values themselves need not be retained; the four domain factories differ only in how a value is hashed
- `stringCountMinSketch` (kind 'count-min-sketch') when the question is how often each value occurred, an overestimate is acceptable, and the reported `epsilon` and `confidence` bounds fit the caller's tolerance; the four domain factories differ only in how a value is hashed
- `stringMinHash` (kind 'minhash') when the question is how much two sets overlap, as an estimated Jaccard index, one signature per set fits where the sets do not, and `maximumStandardError` of `1 / (2 * sqrt(signatureSize))` is acceptable
- `string*` (kind 'string') when values are JavaScript strings and the caller accepts O(length) hashing per operation, which every string-domain sketch pays on `update` and on the query that takes a value
- `bytes*` (kind 'bytes') when values are `Uint8Array` byte sequences, such as digests or serialized records, and hashing those exact bytes is what the caller wants
- `uint32*` (kind 'uint32') when values are integers in `0..2^32 - 1`, so every operation hashes in O(1) with no encoding step
- `uint64*` (kind 'uint64') when values are `bigint`s in `0n..2^64 - 1n`, so every operation hashes in O(1) and the full 64-bit domain survives

Inputs and their sources:
- hash identity, the seeded XXH64 instance that produces every digest and decides whether two sketches may merge: `bigint seed selecting an XXH64 identity` from `knotkit/hash`
- seed, defaulting to `0n` and folded into merge compatibility; an invalid seed surfaces `HashInvalidInputError` from `knotkit/hash`: `bigint` from `knotkit/hash`

Use something else when:
- an exact set, where a false positive is unacceptable → Set, Map
- the exact count of a value, or a count that never exaggerates → Map<K, number>
- read back the values that were observed → knotkit/snapshot-set
- keep a bounded random sample of the stream instead of a summary of it → knotkit/sampling
- test membership in a key set that is complete before the first query and never changes, in fewer bytes → knotkit/static-filter

Errors are ScalarSketchInvalidInputError or ScalarSketchParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/scalar-sketch/wire` (serializeScalarSketch, deserializeScalarSketch, serializeScalarSketchJson, deserializeScalarSketchJson).

Full page: https://knotkit.jkomyno.dev/modules/scalar-sketch.md
Types: node_modules/knotkit/scalar-sketch/ and https://knotkit.jkomyno.dev/reference/knotkit/scalar-sketch/
```

## See also

* [API reference](/reference/knotkit/scalar-sketch/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/scalar-sketch/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/scalar-sketch/knotkit.capability.json)suggest a change to the source record
