# knotkit/snapshot-set

> Keeps every snapshot readable for the lifetime of the set, at O(1) mutation and snapshot cost

## Use

```ts
import { snapshotSet } from 'knotkit/snapshot-set'

const set = snapshotSet(['a'])

const s1 = set.createSnapshot()
set.delete('a')

set.has('a') // false
set.hasAt(s1, 'a') // true — the snapshot is unaffected by the later delete
```

```ts
const s = snapshotSet<string>()

s.add('a') // true
s.add('a') // false, already present
s.add('b')
s.add('c')
s.delete('b') // true
s.delete('z') // false, never present
s.add('b')
;[...s.values()] // ['a', 'b', 'c'] — 'b' keeps its original position
```

## What it solves

* read a set as it was at an earlier point, while it keeps changing
* answer whether a value was present at a given moment, for an audit trail or a change log
* serve MVCC reads: older readers keep their view while a writer mutates
* keep an undo stack over membership, or time-travel debug a collection, without cloning it per step
* report when each value joined and left a live set, as of any snapshot taken earlier

## Choose a layout

| Factory                           | Choose when                                                                                                                                                                                          | Cost                                                                                                                                                                                                                                          |
| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `snapshotSet`kind `version-chain` | the caller mints snapshots and later mutations must not change any answer derived from an id already minted, and mutation plus snapshot cost must stay O(1) rather than cloning the set per snapshot | one immutable version entry per effective toggle and one Set insert per minted id; \`hasAt\` binary-searches that value's toggles, and \`valuesAt\` pays O(r log h) over every value registered by the snapshot, not just the ones it returns |

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

## Worked example

Set size1287Reset

* Original checkpoint has key 0: true. Current set has key 0: false.
* After 12 checkpoints, full copies write 1536 memberships. The version chain records 24 membership changes.
* The work model counts membership history after initialization.

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

## API

| Export                                                                  | Returns          | Does                                                                                                                       |
| ----------------------------------------------------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------- |
| [`snapshotSet`](/reference/knotkit/snapshot-set/functions/snapshotset/) | `SnapshotSet<T>` | Mutable set whose snapshots are O(1) ids over a per-value toggle-version history, so a minted id never changes its answer. |

Cost per member. Open a row for every operation.

`snapshotSet` 8 members

| Member           | Cost                      |
| ---------------- | ------------------------- |
| `size`           | O(1)                      |
| `has`            | O(1) average              |
| `add`            | O(1) amortized            |
| `delete`         | O(1) average              |
| `values`         | O(1) per step, O(n) total |
| `createSnapshot` | O(1)                      |
| `hasAt`          | O(log h)                  |
| `valuesAt`       | O(r log h)                |

## What you pass in

| Input                                                                         | Type                             | Get one from                     |
| ----------------------------------------------------------------------------- | -------------------------------- | -------------------------------- |
| value encoding for a binary artifact, which no artifact carries back          | `ElementCodec<T>`                | [`knotkit/wire`](/modules/wire/) |
| value validation for a JSON artifact, whose projection carries no value types | `(value: unknown) => value is T` | `the caller`                     |

## Errors

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

* `FOREIGN_SNAPSHOT_SET` `SNAPSHOT_ID_NOT_MINTED` `MISSING_ELEMENT_CODEC` `INVALID_CODEC_RESULT` `NON_INJECTIVE_CODEC` `SERIALIZATION_LIMIT_EXCEEDED` `INVALID_SHAPE` `UNSUPPORTED_SCHEMA_VERSION` `UNKNOWN_KIND` `MISSING_VALUES` `MISSING_HISTORY` `VALUES_HISTORY_LENGTH_MISMATCH` `INVALID_SNAPSHOTS` `INVALID_VERSION` `INVALID_HISTORY_ENTRY` `EMPTY_HISTORY_ENTRY` `HISTORY_NOT_STRICTLY_INCREASING` `HISTORY_EXCEEDS_VERSION` `HISTORY_ORDER_VIOLATION` `SNAPSHOT_EXCEEDS_VERSION` `DUPLICATE_VALUE` `INVALID_VALUE` `INVALID_MAGIC` `UNSUPPORTED_ENVELOPE_VERSION` `UNSUPPORTED_PAYLOAD_VERSION` `INVALID_SECTION_GEOMETRY` `NONZERO_PADDING` `MISALIGNED_SECTION` `TRUNCATED_PAYLOAD` `DECODE_BUDGET_EXCEEDED` `UNSTABLE_BUFFER` `WRONG_FORMAT` `INTEGRITY_MISMATCH` `INVALID_PACKAGE_HEADER`

## Save and restore

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

* Functions

  `serializeSnapshotSet`, `deserializeSnapshotSet`, `serializeSnapshotSetJson`, `deserializeSnapshotSetJson`

* Formats

  binary, json

* Compatibility

  schema-versioned, envelope v1

## When not to use it

| If you need to…                                                  | Use instead                                                                                               |
| ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| a plain set with no history                                      | Set                                                                                                       |
| keep every version of a keyed value, not just membership         | a persistent data-structure library such as immutable.js, or structuredClone per version                  |
| record which elements belong to the same group, and merge groups | [`knotkit/disjoint-set`](/modules/disjoint-set/)                                                          |
| reclaim the memory a snapshot holds once nobody reads it         | drop the id and rebuild the set from your own change log, because a snapshot lives for the set's lifetime |
| serialize identically-behaving sets to identical bytes           | your own canonical projection, because a snapshot-set artifact records the mutation path it took          |

## Performance

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

## Prompt an agent

Prompt · knotkit/snapshot-setCopy prompt

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

Exports:
- `snapshotSet` → `SnapshotSet<T>`: Mutable set whose snapshots are O(1) ids over a per-value toggle-version history, so a minted id never changes its answer.

Pick the layout by these rules:
- `snapshotSet` (kind 'version-chain') when the caller mints snapshots and later mutations must not change any answer derived from an id already minted, and mutation plus snapshot cost must stay O(1) rather than cloning the set per snapshot

Inputs and their sources:
- value encoding for a binary artifact, which no artifact carries back: `ElementCodec<T>` from `knotkit/wire`
- value validation for a JSON artifact, whose projection carries no value types: `(value: unknown) => value is T` from `the caller`

Use something else when:
- a plain set with no history → Set
- keep every version of a keyed value, not just membership → a persistent data-structure library such as immutable.js, or structuredClone per version
- record which elements belong to the same group, and merge groups → knotkit/disjoint-set
- reclaim the memory a snapshot holds once nobody reads it → drop the id and rebuild the set from your own change log, because a snapshot lives for the set's lifetime
- serialize identically-behaving sets to identical bytes → your own canonical projection, because a snapshot-set artifact records the mutation path it took

Errors are SnapshotSetInvalidInputError or SnapshotSetParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/snapshot-set/wire` (serializeSnapshotSet, deserializeSnapshotSet, serializeSnapshotSetJson, deserializeSnapshotSetJson).

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

## See also

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