Skip to content

knotkit/snapshot-set

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

import {
function snapshotSet<T>(values?: Iterable<T>): SnapshotSet<T>

Create a

SnapshotSet

backed by one toggle-version history per value, optionally pre-populated from an iterable.

Diverges from knotkit/disjoint-set's growable factories: a duplicate value in the initial iterable is a silent no-op, matching add's no-op-on-present rule, rather than a throw.

@param ― values - Values to insert, in iteration order.

snapshotSet
} from 'knotkit/snapshot-set'
const
const set: SnapshotSet<string>
set
=
snapshotSet<string>(values?: Iterable<string> | undefined): SnapshotSet<string>

Create a

SnapshotSet

backed by one toggle-version history per value, optionally pre-populated from an iterable.

Diverges from knotkit/disjoint-set's growable factories: a duplicate value in the initial iterable is a silent no-op, matching add's no-op-on-present rule, rather than a throw.

@param ― values - Values to insert, in iteration order.

snapshotSet
(['a'])
const
const s1: number
s1
=
const set: SnapshotSet<string>
set
.
SnapshotSet<string>.createSnapshot: () => number

Mint an id denoting the set's state at this moment. O(1); nothing is copied.

Shares its counter with add/delete, so two createSnapshot() calls with no intervening mutation return different ids that answer identically for every value. Ids are strictly increasing across the structure's lifetime.

createSnapshot
()
const set: SnapshotSet<string>
set
.
SnapshotSet<string>.delete: (value: string) => boolean

Delete a value. O(1) average.

A no-op when the value is not present.

@returns ― true when the value was present and is now removed.

delete
('a')
const set: SnapshotSet<string>
set
.
SnapshotSet<string>.has: (value: string) => boolean

Return true when the value is currently present. O(1) average.

has
('a') // false
const set: SnapshotSet<string>
set
.
SnapshotSet<string>.hasAt: (id: number, value: string) => boolean

Return true when the value was present at the given snapshot. O(log h), where h is the number of times that value has toggled.

@throws ― {SnapshotSetInvalidInputError} When id was never returned by createSnapshot().

hasAt
(
const s1: number
s1
, 'a') // true — the snapshot is unaffected by the later delete
snapshot-set.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
  • 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
FactoryChoose whenCost
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 snapshotone 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

{"v":1,"box":[58.1806,94.1597,1043,437.3555],"x":{"s":"log","lim":[0.803850990743,159.233491622],"inv":false,"g":0,"t":"Members exchanged between checkpoints","tk":[[1,"1"],[2,"2"],[4,"4"],[8,"8"],[16,"16"],[32,"32"],[64,"64"],[128,"128"]],"b":10},"y":{"s":"log","lim":[1.60770198149,318.466983244],"inv":false,"g":0,"tk":[[2,"2"],[4,"4"],[8,"8"],[16,"16"],[32,"32"],[64,"64"],[128,"128"],[256,"256"]],"b":10},"ti":"A version chain writes 2 records per exchange: 64× under a copy at 1, equal at 64","a":[{"k":"line","c":"#1d5fa6","s":"x","d":[1,2,2,4,4,8,8,16,16,32,32,64,64,128,128,256],"p":[98.84,423.19,227.91,378.21,356.98,333.23,486.05,288.25,615.13,243.27,744.2,198.29,873.27,153.31,1002.34,108.33]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"line","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#5c5c57"}],"lg":[]} 1 2 4 8 16 32 64 128 Members exchanged between checkpoints 2 4 8 16 32 64 128 256 Full copy: 128 records, whatever changed Membership records written per checkpoint A version chain writes 2 records per exchange: 64× under a copy at 1, equal at 64
{"v":1,"box":[58.1806,150.6246,595,437.3555],"x":{"s":"log","lim":[0.803850990743,159.233491622],"inv":false,"g":0,"t":"Members exchanged between checkpoints","tk":[[1,"1"],[2,"2"],[4,"4"],[8,"8"],[16,"16"],[32,"32"],[64,"64"],[128,"128"]],"b":10},"y":{"s":"log","lim":[1.60770198149,318.466983244],"inv":false,"g":0,"tk":[[2,"2"],[4,"4"],[8,"8"],[16,"16"],[32,"32"],[64,"64"],[128,"128"],[256,"256"]],"b":10},"ti":"A version chain writes 2 records per\nexchange: 64× under a copy at 1, equal at\n64","a":[{"k":"line","c":"#1d5fa6","s":"x","d":[1,2,2,4,4,8,8,16,16,32,32,64,64,128,128,256],"p":[80.34,425.52,150.7,387.94,221.06,350.36,291.41,312.78,361.77,275.2,432.12,237.62,502.48,200.04,572.84,162.46]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"line","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#5c5c57"}],"lg":[]} 1 2 4 8 16 32 64 128 Members exchanged between checkpoints 2 4 8 16 32 64 128 256 Full copy: 128 records, whatever changed Membership records written per checkpoint A version chain writes 2 records per exchange: 64× under a copy at 1, equal at 64
  • 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 against knotkit/snapshot-set in your browser; the defaults reproduce the README figure.

ExportReturnsDoes
snapshotSetSnapshotSet<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
MemberCost
sizeO(1)
hasO(1) average
addO(1) amortized
deleteO(1) average
valuesO(1) per step, O(n) total
createSnapshotO(1)
hasAtO(log h)
valuesAtO(r log h)
InputTypeGet one from
value encoding for a binary artifact, which no artifact carries backElementCodec<T>knotkit/wire
value validation for a JSON artifact, whose projection carries no value types(value: unknown) => value is Tthe caller

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

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
If you need to…Use instead
a plain set with no historySet
keep every version of a keyed value, not just membershipa persistent data-structure library such as immutable.js, or structuredClone per version
record which elements belong to the same group, and merge groupsknotkit/disjoint-set
reclaim the memory a snapshot holds once nobody reads itdrop 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 bytesyour own canonical projection, because a snapshot-set artifact records the mutation path it took

Measured by the suite in 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.

Prompt · knotkit/snapshot-set
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/