# knotkit/sorted-block

> Packs byte-keyed entries, given in ascending key order, into one immutable prefix-compressed block with point reads, seeks, and range scans

## Use

```ts
import { encodeKeyTuple } from 'knotkit/key-encoding'
import { restartPointSortedBlock } from 'knotkit/sorted-block'

const encoder = new TextEncoder()
const key = (user: string, version: bigint): Uint8Array =>
  encodeKeyTuple([
    { kind: 'string', value: user },
    { kind: 'uint64', value: version, direction: 'descending' },
  ])

// Entries must already ascend under compareBytes: here, each user's newest version first.
const block = restartPointSortedBlock(
  [
    [key('ada', 2n), encoder.encode('engineer')],
    [key('ada', 1n), encoder.encode('student')],
    [key('grace', 1n), encoder.encode('admiral')],
  ],
  { restartInterval: 16 },
)

block.size // 3
block.get(key('ada', 1n)) // the bytes of 'student'
block.has(key('ada', 3n)) // false

// A user's key prefix sorts before every one of its versions, so the ceiling is the newest one.
const ada = encodeKeyTuple([{ kind: 'string', value: 'ada' }])
const [, latest] = block.ceiling(ada) ?? []
new TextDecoder().decode(latest) // 'engineer'

// Every entry from user 'ada' up to, not including, user 'grace'.
const grace = encodeKeyTuple([{ kind: 'string', value: 'grace' }])
const versions = [...block.entries(ada, grace)].length // 2
```

```ts
import { compareBytes } from 'knotkit/key-encoding'
import { restartPointSortedBlock, type SortedBlockEntry } from 'knotkit/sorted-block'
import { mergeSorted } from 'knotkit/sorted-merge'

const key = Uint8Array.of(1)
const newest = restartPointSortedBlock([[key, Uint8Array.of(20)]])
const oldest = restartPointSortedBlock([[key, Uint8Array.of(10)]])

function* firstPerKey(entries: Iterable<SortedBlockEntry>) {
  let previous: Uint8Array | undefined
  for (const entry of entries) {
    if (previous === undefined || compareBytes(previous, entry[0]) !== 0) {
      previous = entry[0]
      yield entry
    }
  }
}

const merged = mergeSorted<SortedBlockEntry>((a, b) => compareBytes(a[0], b[0]), [newest, oldest])
const compacted = restartPointSortedBlock(firstPerKey(merged))
compacted.get(key) // Uint8Array [20]
```

## What it solves

* build the data or index block of a sorted string table from key-value pairs already in key order
* store many sorted Uint8Array keys that share long prefixes in fewer bytes than an array of pairs
* look up, seek to the first key at or above a bound, or scan a key range in a block built once
* persist a sorted run as bytes and reload it with every offset, varint, and key order validated
* trade block size against lookup cost by choosing how often a key is stored whole

## Choose a layout

| Factory                                       | Choose when                                                                                                                     | Cost                                                                                                                                                                                                                 |
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `restartPointSortedBlock`kind `restart-point` | the entries are known up front, arrive in strictly ascending compareBytes key order, and are only read after the block is built | three varints, the unshared key bytes, and the value per entry, 4 bytes per restart point, and an 8-byte trailer; 385,963 bytes at restartInterval 16 for 10,000 23-byte keys with 32-byte values, 550,000 bytes raw |

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

## API

| Export                                                                                          | Returns       | Does                                                                                                                                                                                                 |
| ----------------------------------------------------------------------------------------------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`restartPointSortedBlock`](/reference/knotkit/sorted-block/functions/restartpointsortedblock/) | `SortedBlock` | Immutable block of entries in strictly ascending compareBytes key order, each key prefix-compressed against the previous one except at every restartInterval-th entry, a restart point stored whole. |

Cost per member. Open a row for every operation.

`restartPointSortedBlock` 8 members

| Member     | Cost                                                                                     |
| ---------- | ---------------------------------------------------------------------------------------- |
| `build`    | O(total key and value bytes)                                                             |
| `size`     | O(1)                                                                                     |
| `firstKey` | O(k)                                                                                     |
| `lastKey`  | O(k)                                                                                     |
| `get`      | O(k log(n / r) + r k + v), including v returned value bytes                              |
| `has`      | O(k log(n / r) + r k)                                                                    |
| `ceiling`  | O(k log(n / r) + r k + v), including v returned value bytes                              |
| `entries`  | O(k log(n / r) + r k) to start, then O(k + v) per entry including v returned value bytes |

## Errors

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

* `SortedBlockInvalidInputError`

  `INVALID_RESTART_INTERVAL` `INVALID_ENTRY` `UNSORTED_KEY` `DUPLICATE_KEY` `MAX_CAPACITY_EXCEEDED`

* `SortedBlockParseError`

  `INVALID_KEY` `INVALID_RANGE` `FOREIGN_SORTED_BLOCK` `INVALID_PACKAGE_HEADER` `UNKNOWN_KIND` `CORRUPT_BLOCK_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/sorted-block/wire`, so code that never saves a structure never loads a parser.

* Functions

  `serializeSortedBlock`, `deserializeSortedBlock`

* Formats

  binary

* Compatibility

  schema-versioned, envelope v1

## When not to use it

| If you need to…                                                                             | Use instead                                                     |
| ------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| insert, update, or delete keys after the structure is built                                 | [`knotkit/ordered-map`](/modules/ordered-map/)                  |
| turn integers, strings, or tuples into byte keys whose order matches the values             | [`knotkit/key-encoding`](/modules/key-encoding/)                |
| merge several sorted runs before building a block (resolve equal keys in the merged stream) | [`knotkit/sorted-merge`](/modules/sorted-merge/)                |
| look up keys by exact match only, with no order, seek, or range scan                        | Map                                                             |
| a whole persistent store with writes, compaction, and crash recovery                        | an embedded key-value store such as SQLite, LevelDB, or RocksDB |

## Performance

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

## Prompt an agent

Prompt · knotkit/sorted-blockCopy prompt

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

Exports:
- `restartPointSortedBlock` → `SortedBlock`: Immutable block of entries in strictly ascending compareBytes key order, each key prefix-compressed against the previous one except at every restartInterval-th entry, a restart point stored whole.

Pick the layout by these rules:
- `restartPointSortedBlock` (kind 'restart-point') when the entries are known up front, arrive in strictly ascending compareBytes key order, and are only read after the block is built

Use something else when:
- insert, update, or delete keys after the structure is built → knotkit/ordered-map
- turn integers, strings, or tuples into byte keys whose order matches the values → knotkit/key-encoding
- merge several sorted runs before building a block (resolve equal keys in the merged stream) → knotkit/sorted-merge
- look up keys by exact match only, with no order, seek, or range scan → Map
- a whole persistent store with writes, compaction, and crash recovery → an embedded key-value store such as SQLite, LevelDB, or RocksDB

Errors are SortedBlockInvalidInputError or SortedBlockParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/sorted-block/wire` (serializeSortedBlock, deserializeSortedBlock).

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

## See also

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