Skip to content

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.

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.

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.

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.

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.

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.

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 with the raw per-repeat timings in 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.

{"v":1,"box":[58.1806,94.1597,845.1333,437.3555],"x":{"s":"log","lim":[0.77916457966,328.557029776],"inv":false,"g":0,"t":"Results requested","tk":[[1,"1"],[4,"4"],[16,"16"],[64,"64"],[256,"256"]],"b":10},"y":{"s":"log","lim":[0.77916457966,328.557029776],"inv":false,"g":0,"tk":[[1,"1"],[4,"4"],[16,"16"],[64,"64"],[256,"256"]],"b":10},"ti":"A 16-result prefix reads 19 of 256 IDs, only 3 beyond the prefix itself","a":[{"k":"line","c":"#fffff8","s":"x","d":[1,1,2,2,4,4,8,8,16,16,32,32,64,64,128,128,256,256],"p":[90.67,423.19,180.92,383.83,271.16,344.47,361.41,305.11,451.66,265.76,541.9,226.4,632.15,187.04,722.4,147.69,812.64,108.33]},{"k":"line","c":"#5b6b7c","s":"x","d":[1,1,2,2,4,4,8,8,16,16,32,32,64,64,128,128,256,256],"p":[90.67,423.19,180.92,383.83,271.16,344.47,361.41,305.11,451.66,265.76,541.9,226.4,632.15,187.04,722.4,147.69,812.64,108.33]},{"k":"line","c":"#fffff8","s":"x","d":[1,4,2,5,4,7,8,11,16,19,32,35,64,67,128,131,256,256],"p":[90.67,344.47,180.92,331.8,271.16,312.7,361.41,287.03,451.66,256,541.9,221.31,632.15,184.44,722.4,146.37,812.64,108.33]},{"k":"line","c":"#1d5fa6","s":"x","d":[1,4,2,5,4,7,8,11,16,19,32,35,64,67,128,131,256,256],"p":[90.67,344.47,180.92,331.8,271.16,312.7,361.41,287.03,451.66,256,541.9,221.31,632.15,184.44,722.4,146.37,812.64,108.33]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"line","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#5b6b7c"},{"k":"annotation","c":"#1d5fa6"}],"lg":[]} 1 4 16 64 256 Results requested 1 4 16 64 256 Materialize and sort: all 256 16 results: 19 reads Input IDs the lazy merge reads from 4 sorted lists One read per result Lazy merge A 16-result prefix reads 19 of 256 IDs, only 3 beyond the prefix itself
{"v":1,"box":[58.1806,122.3921,397.1333,437.3555],"x":{"s":"log","lim":[0.77916457966,328.557029776],"inv":false,"g":0,"t":"Results requested","tk":[[1,"1"],[4,"4"],[16,"16"],[64,"64"],[256,"256"]],"b":10},"y":{"s":"log","lim":[0.77916457966,328.557029776],"inv":false,"g":0,"tk":[[1,"1"],[4,"4"],[16,"16"],[64,"64"],[256,"256"]],"b":10},"ti":"A 16-result prefix reads 19 of 256 IDs,\nonly 3 beyond the prefix itself","a":[{"k":"line","c":"#fffff8","s":"x","d":[1,1,2,2,4,4,8,8,16,16,32,32,64,64,128,128,256,256],"p":[72.17,424.35,111.04,388.23,149.92,352.11,188.79,315.99,227.66,279.87,266.53,243.75,305.4,207.63,344.27,171.51,383.14,135.4]},{"k":"line","c":"#5b6b7c","s":"x","d":[1,1,2,2,4,4,8,8,16,16,32,32,64,64,128,128,256,256],"p":[72.17,424.35,111.04,388.23,149.92,352.11,188.79,315.99,227.66,279.87,266.53,243.75,305.4,207.63,344.27,171.51,383.14,135.4]},{"k":"line","c":"#fffff8","s":"x","d":[1,4,2,5,4,7,8,11,16,19,32,35,64,67,128,131,256,256],"p":[72.17,352.11,111.04,340.49,149.92,322.95,188.79,299.4,227.66,270.92,266.53,239.08,305.4,205.25,344.27,170.31,383.14,135.4]},{"k":"line","c":"#1d5fa6","s":"x","d":[1,4,2,5,4,7,8,11,16,19,32,35,64,67,128,131,256,256],"p":[72.17,352.11,111.04,340.49,149.92,322.95,188.79,299.4,227.66,270.92,266.53,239.08,305.4,205.25,344.27,170.31,383.14,135.4]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"line","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#5b6b7c"},{"k":"annotation","c":"#1d5fa6"}],"lg":[]} 1 4 16 64 256 Results requested 1 4 16 64 256 Materialize and sort: all 256 16 results: 19 reads Input IDs the lazy merge reads from 4 sorted lists One read per result Lazy merge A 16-result prefix reads 19 of 256 IDs, only 3 beyond the prefix itself
  • 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 against knotkit/sorted-merge.

  • 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.
  • You need insert and remove of independent items. That is a queue or heap, not a merge — knotkit/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.

ExportReturnsDoes
mergeSortedGenerator<A, void, unknown>Merges a finite collection of sorted iterables by pulling from the last emitted item's source.
mergeSortedAsyncAsyncGenerator<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
MemberCost
first nextO(k) time and space for k sources
subsequent nextO(log(k + 1)) time plus one iterator advance
returnO(k) plus input cleanup
mergeSortedAsync 3 members
MemberCost
first nextO(k) time and space for k sources, with the k first reads awaited concurrently
subsequent nextO(log(k + 1)) time plus one awaited iterator advance
returnO(k) plus input cleanup, awaited one source at a time
Prompt · knotkit/sorted-merge
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/