Skip to content

perf: packed arrays write through the leaf cache - #68

Merged
alexvictoor merged 1 commit into
masterfrom
perf/packed-write-leaf-cache
Nov 14, 2026
Merged

alexvictoor merged 1 commit into
masterfrom
perf/packed-write-leaf-cache

Conversation

@alexvictoor

@alexvictoor alexvictoor commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

Summary

PackedArray.add(), increment() and set() now go through the leaf cache from #63 (only get() used it before), in both the TS and the AssemblyScript implementations. The 8 indexes of a group share one leaf per byte set, so writes on nearby indexes skip the set-tree walk (3-5 dependent reads per set) and write directly at leafIndex * 8 + (index & 7).

Cache state: for the cached group, leafIndexBySet[0 .. knownSets) holds a leaf or NO_LEAF; sets from knownSets upwards are not looked up yet. get/add/set resolve sets from byte 0 upwards without skipping one, so the known sets are always a prefix and one counter describes them.

 cacheGroupOf(index)
   if group != cachedGroup                 // miss
     cachedGroup = group
-    for b in 0..7: leafIndexBySet[b] = UNKNOWN_LEAF   // 8 writes
+    knownSets = 0                                     // 1 write
+    // bound checked by getPackedIndex(), always called for set 0 after a miss
-  check index < virtualLength             // every call
+  else if index >= virtualLength          // hit only: no walk to check it
+    throw

 add / set / get, for byteNum from 0 upwards
-  leaf = leafIndexBySet[byteNum]
+  leaf = byteNum < knownSets ? leafIndexBySet[byteNum] : UNKNOWN_LEAF
   if leaf < 0
     walk set tree (insert for writes, probe for get / set 0)
     record leaf or NO_LEAF
+    knownSets = max(knownSets, byteNum + 1)
   read / write byte at leaf * 8 + (index & 7)

Why the counter: latency recordings land on scattered buckets, so a miss is the common case for recordValue. Resetting 8 entries per miss made random writes up to ~9% slower than master; the counter makes eviction a single write without adding a load on the hit path (a per-entry generation stamp would have).

Correctness:

Evidence

Tests: npm test 238 passed, npm run typecheck clean, npm run astest 15291/15291.

New specs: fast-check properties in PackedArray.fc.spec.ts (interleaved get/add/increment/set on 4 groups, cached writes while storage fills up and unpacks), AS cases in PackedArrayAccess.test.ts, out-of-bound access after a cached access in PackedArray.spec.ts.

Mutations run against the JS specs, each caught:

cacheGroupOf: drop `knownSets = 0` on a miss      -> 9 failing tests
cacheGroupOf: drop the bound check on a hit       -> 1 failing test
add: wrong byte offset in the cached leaf         -> caught (first iteration)
get: treat a not-looked-up set as NO_LEAF         -> caught (first iteration)

Benchmarks: A/B/C on the same Apple Silicon machine, 3 alternating rounds, median in M ops/s (higher is better). "latency values" = log-normal around 3 ms in µs, the realistic recordValue workload.

bench master before this fix (c6ee2a2) this PR
JS PackedHistogram, latency values 5.63 5.44 5.72
WASM PackedHistogram, latency values 23.10 22.89 23.12
JS PackedHistogram, random values over full range 4.09 4.25 4.10
WASM PackedHistogram, random values over full range 24.75 25.65 (noisy: 17-33) 24.99
WASM PackedHistogram, sequential values 23.95 31.48 31.42 (+31%)
JS PackedArray, sequential add 8.30 23.71 23.94 (2.9x)
JS PackedArray, random add 31.05 31.65 33.15
JS PackedArray, random set 39.38 36.36 40.51
JS PackedArray, random set(i, 0) 36.82 33.58 32.84 (noisy: 31-40)

Recording latency values is on par with master in WASM and ~2% faster in JS; sequential writes (Histogram.add, decoding) keep the 2.9x / +31% gain. set(i, 0) on a bare array stays the one inconclusive row; histograms do not hit it on the recording path.

Merge Danger

Door: two-way

Internal to PackedArray, no API or encoding change; a revert restores the previous behaviour.

Blast Radius: packed histograms

A cache bug would return wrong counts for packed histograms (JS and WASM), silently. Covered by the model-based fast-check properties and the mutations above. The prefix rule is an invariant future edits must keep: a code path that resolves a set without resolving the lower ones first would break it, which the class comment states.

🤖 Generated with Claude Code

@alexvictoor
alexvictoor force-pushed the perf/packed-write-leaf-cache branch 4 times, most recently from bdc333c to b510adb Compare November 14, 2026 20:08
add(), increment() and set() used to walk the set trees for every byte
they touched (getPackedIndex with insertAsNeeded), and only refreshed the
leaf cache afterwards. They now take the leaf of the cached group
directly and descend only for sets the cache has no leaf for, so
sequential writes (histogram add, decoding, recordValue runs) mostly
skip the descents.

For the cached group, leafIndexBySet[0 .. knownSets) holds a leaf or
NO_LEAF; sets from knownSets upwards are not looked up yet. get(), add()
and set() resolve sets from byte 0 upwards without skipping one, so the
known sets always form a prefix and evicting a group is a single
knownSets = 0 instead of a reset of every entry. A miss, the common case
for random recordValue such as latency recordings, therefore costs no
more than before the cache: a write looks up only the sets it touches,
get() resolves the remaining ones on demand.

The write fast path skips getPackedIndex(), which held the only
virtualLength check of the packed path, so a cache hit now checks the
bound in cacheGroupOf(); a miss leaves it to getPackedIndex(), called for
set 0 by every access after a miss.

Correctness rests on the same invariants as the read cache: a leaf never
moves once created (entries are only appended, resizeArray copies them in
place), every write that creates a leaf records it so a known NO_LEAF is
always current, and anything rebuilding the context invalidates the
cache. The unpacked fallback is unchanged: the fast path only runs on a
packed context, and unpack() is still reached from the inserting
descents.

Both the TypeScript and the AssemblyScript implementations change the
same way, with property-based (fast-check) and as-test cases covering
interleaved get/add/set/increment within a group, carries across cached
and uncached sets, sets to smaller values, out-of-range indexes in a
cached group, and the unpacked fallback after cached writes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@alexvictoor
alexvictoor force-pushed the perf/packed-write-leaf-cache branch from b510adb to 0b2e54a Compare November 14, 2026 20:12
@alexvictoor
alexvictoor marked this pull request as ready for review November 14, 2026 20:16
@alexvictoor
alexvictoor merged commit 2b0e3ed into master Nov 14, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant