# knotkit/sorted-merge

> Lazily merges sorted iterables in comparator order, preserving duplicates and source order on ties.

`mergeSorted` turns any number of independently sorted iterables into one ordered stream, one item at a time. It reads one head per source to start, and after that pulls only from the source it last emitted from. Nothing is buffered beyond one item per source, so a 32-item prefix of eight posting lists reads about 32 items — not the 32,768 the lists hold. `mergeSortedAsync` applies the same plan to async streams.

time O(k) to open, then O(log(k + 1)) per item · space O(k), one cursor per source · excluding comparator cost and the input's own reads

The bound is the reason the module exists. Materializing the input makes the cost of the *input*, not the cost of the *answer*.

## One call

```ts
import { numberOrder } from 'knotkit/heap'
import { mergeSorted } from 'knotkit/sorted-merge'

const merged = mergeSorted(numberOrder, [
  [1, 4, 4],
  [2, 4, 7],
])

Array.from(merged) // [1, 2, 4, 4, 4, 7]
```

Duplicates are kept, and an item equal to another keeps its source order — the earlier source wins the tie. That is what makes the merge usable for log-structured storage: pass newer runs first and the first record for a key is the newest one.

## Read a prefix, pay for a prefix

```ts
const stream = mergeSorted(numberOrder, postingLists)

const prefix: number[] = []
for (const id of stream) {
  prefix.push(id)
  if (prefix.length === 32) {
    break // closes every unfinished source through its own return()
  }
}
```

A `break` closes the opened inputs. The merge calls `return()` once on each unfinished iterator that exposes it, and if the comparator or an input throws, it still tries to close the rest — the first cleanup error surfaces only when the merge was otherwise returning normally. That contract is what makes an early exit safe rather than merely fast.

## Merge async streams

`mergeSortedAsync` is the same merge for sources that arrive over the network — SSTable blocks streamed from object storage during a compaction or a range scan. Each source can be an `AsyncIterable` or a plain `Iterable`, mixed in one call, and the result is an `AsyncGenerator` consumed with `for await`. When a source supplies a promise-valued item, the order receives the promise. The generator yields its resolved value and closes the remaining sources if the item rejects.

```ts
import { numberOrder } from 'knotkit/heap'
import { mergeSortedAsync } from 'knotkit/sorted-merge'

async function* remoteBlock(ids: readonly number[]): AsyncGenerator<number> {
  for (const id of ids) {
    await Promise.resolve() // stands in for a network read
    yield id
  }
}

const merged = mergeSortedAsync(numberOrder, [remoteBlock([1, 4, 4]), [2, 4, 7]])

await Array.fromAsync(merged) // [1, 2, 4, 4, 4, 7]
```

Order, tie-breaking, and duplicates match `mergeSorted` item for item, and at most one item per source is held at a time, so no run is ever buffered whole. Two things differ because the reads are awaited:

* **The first advance primes every source at once.** It opens the sources in order, then awaits all their first reads together with `Promise.allSettled`, so eight remote runs cost one round trip to start, not eight. Every later advance awaits only the source whose item was just emitted.
* **Failures wait for in-flight reads.** If a first read rejects, the merge still lets the others settle, then awaits `return()` on every opened source that has not ended and rethrows the rejection from the earliest source. A `break` awaits `return()` once per unfinished source, one source at a time, with the same cleanup-error rule as the sync merge.

## Watch the reads

Slide the prefix and the sources; both sides of the comparison are counted on the same generated data. The merge’s “items pulled” is the number of `next()` calls it actually made, so it is a count of work, not an estimate.

Sorted sources 88Items per source 409612Prefix to read 3232

* Items pulled

  —

* Comparisons

  —

* Baseline reads

  —

* Baseline compares

  —

Input is generated with `splitmix32(42)` from `knotkit/prng`, so the panel is reproducible. Both sides are counted on the same data. The published timing for this case, with its machine and workload, is in the repository at `evidence/benchmarks/results.json` under `sorted-merge`; this panel makes no timing claim of its own.

The published timing for this workload — a 32-ID prefix across eight lists holding 32,768 IDs — is **408× faster than materializing and sorting**, and it lives at [`packages/sorted-merge/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/sorted-merge/__tests__/bench) with the raw per-repeat timings in [`evidence/benchmarks/results.json`](https://github.com/jkomyno/knotkit/blob/main/evidence/benchmarks/results.json). It is an algorithmic-class comparison: the baseline does more work by design. The panel above makes no timing claim at all; it counts reads, which is the part that holds on any machine.

* Read the smallest record IDs across four sorted posting lists.
* The first 16 results pull 19 of 256 input IDs.
* The merge keeps one pending ID per active list and advances the list that supplied the last result.

Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/sorted-merge/demo.ts) against `knotkit/sorted-merge`.

## When not to reach for it

* **The input is not sorted.** `mergeSorted` does not order anything; it merges under an order every input already satisfies. Sorting one input is `Array.from(input).toSorted(order)`.
* **You need a keyed store.** Keeping one item per key is a `Map`; keeping keys ordered while they change is [`knotkit/ordered-map`](/modules/ordered-map/).
* **You need insert and remove of independent items.** That is a queue or heap, not a merge — [`knotkit/heap`](/modules/heap/).

The order must be a stable total order, and the values being compared must not change while the merge is active. Both requirements are inherited from the underlying heap rather than invented here; the module README states them in full.

## API

| Export                                                                            | Returns                                     | Does                                                                                                                                                   |
| --------------------------------------------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [`mergeSorted`](/reference/knotkit/sorted-merge/functions/mergesorted/)           | `Generator<A, void, unknown>`               | Merges a finite collection of sorted iterables by pulling from the last emitted item's source.                                                         |
| [`mergeSortedAsync`](/reference/knotkit/sorted-merge/functions/mergesortedasync/) | `AsyncGenerator<Awaited<A>, void, unknown>` | Merges a finite collection of sorted async or sync iterables, priming every source concurrently and then awaiting only the last emitted item's source. |

Cost per member. Open a row for every operation.

`mergeSorted` 3 members

| Member            | Cost                                         |
| ----------------- | -------------------------------------------- |
| `first next`      | O(k) time and space for k sources            |
| `subsequent next` | O(log(k + 1)) time plus one iterator advance |
| `return`          | O(k) plus input cleanup                      |

`mergeSortedAsync` 3 members

| Member            | Cost                                                                           |
| ----------------- | ------------------------------------------------------------------------------ |
| `first next`      | O(k) time and space for k sources, with the k first reads awaited concurrently |
| `subsequent next` | O(log(k + 1)) time plus one awaited iterator advance                           |
| `return`          | O(k) plus input cleanup, awaited one source at a time                          |

## Prompt an agent

Prompt · knotkit/sorted-mergeCopy prompt

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

Exports:
- `mergeSorted` → `Generator<A, void, unknown>`: Merges a finite collection of sorted iterables by pulling from the last emitted item's source.
- `mergeSortedAsync` → `AsyncGenerator<Awaited<A>, void, unknown>`: Merges a finite collection of sorted async or sync iterables, priming every source concurrently and then awaiting only the last emitted item's source.

Inputs and their sources:
- item order: `Order<A>` from `knotkit/heap`

Use something else when:
- order an input whose items arrive unsorted → Array.from(input).toSorted(order)
- keep one item per key from a stream of unsorted arrivals → Map
- insert and remove independent items from an ordered queue → knotkit/heap

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

## See also

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