# Incremental Top-K Collections

> 2-level Chunked Sorted Block Index with deterministic tie-breaking and O(1) Top-K boundary pruning across TypeScript and Rust.

Sorting tens of thousands of rows inside a derived selector on every update wastes CPU and triggers downstream re-renders even when the visible Top-K rows did not change.

`@zwire/core/collections` and `zwire-collections` provide a **2-level Chunked Sorted Block Index** (`BLOCK_TARGET = 128`, split `> 256`, merge `< 32`) with deterministic key tie-breaking and **`O(1)` Top-K boundary pruning**.

## Try it live

Build a 10,000- or 50,000-row collection in your browser, apply 1,000 random row updates, and observe `O(1)` boundary pruning keep the Top-5 leaderboard updated in sub-microsecond average latency:

## TypeScript (`@zwire/core/collections`)

`createCollection` indexes rows by stable ID (`getId`) and user comparator (`compare`), wrapping the comparator with deterministic key tie-breaking so equal scores always have a total order:

```ts
import { createScope, effect } from '@zwire/core';
import { createCollection } from '@zwire/core/collections';

interface Order {
  id: number;
  price: number;
  qty: number;
}

const scope = createScope();
const bids = createCollection<Order, number>({
  scope,
  getId: (o) => o.id,
  compare: (a, b) => b.price - a.price,
});

bids.insert({ id: 1, price: 100, qty: 10 });
bids.insert({ id: 2, price: 120, qty: 5 });

const top5 = bids.topK(5);
effect(() => {
  console.log('Top bids:', top5.get());
}, { scope });

// Updating a row outside the Top-5 boundary is pruned in O(1) without firing `top5`!
bids.upsert({ id: 99, price: 42, qty: 1 });
```

### Query & transactional collections

- **`createQueryCollection`**: Adds reactive filtered/sliced range views (`range(offset, limit, { filter })`) on top of the sorted index.
- **`createTransactionalCollection`**: Integrates with `@zwire/core/tx` optimistic layers and STM drafts so uncommitted mutations reflect cleanly in collection views.
- **UI adapter hooks**: `@zwire/{react,vue,solid,svelte}/collections` expose `useCollectionTopK`, `useCollectionRange`, `useCollectionItem`, and `useCollectionSize`.

## Rust (`zwire-collections` & `zwire`)

Rust provides both standalone `#![no_std]` data structures (`Collection`, `KeyedCollection` backed by `BTreeSet<(S, K, u32)>`) and scope-integrated reactive wrappers in the `zwire` umbrella crate:

- **`ReactiveCollection` / `PureReactiveCollection`**: Single-threaded `Scope`-bound collections (`PureReactiveCollection` reaches `171.9 ns/op` on 50k upserts + Top-50).
- **`SyncReactiveCollection` / `SyncPureReactiveCollection`**: Thread-safe `SyncScope`-bound collections (`535.7 ns/op` under 4-thread contention). Mutations run under an `RwLock` and publish versioned immutable snapshots via `sync_publish_external_versioned` after releasing the lock—deadlock-free and monotonic under concurrent writers.
