Skip to content

perf: packed histograms skip empty subtrees when scanning counts - #69

Merged
alexvictoor merged 2 commits into
masterfrom
perf/packed-nonzero-iteration
Nov 15, 2026
Merged

alexvictoor merged 2 commits into
masterfrom
perf/packed-nonzero-iteration

Conversation

@alexvictoor

@alexvictoor alexvictoor commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

Summary

Scanning a PackedHistogram visited every virtual index, so its cost was proportional to the virtual length even when only a few hundred counts were populated. Packed scans now jump from one populated leaf group to the next.

 getValueAtPercentile / add / subtract / encode / establishInternalTackingValues
   for i in [lowestNonZeroIndex, highestNonZeroIndex]     # bounds from #70
+    i = nextNonZeroIndex(i)        # packed: skip the empty subtrees
+    if i < 0 or i > bound: break
     getCountAtIndex(i)

The primitive, in both implementations (assembly/packedarray, src/packedarray):

flowchart TD
    S["PackedArray.nextNonZeroIndex(from)"] --> U{"context unpacked? (storage full, #66)"}
    U -- yes --> L["linear scan of the long array"]
    U -- no --> T["PackedArrayContext.nextIndexWithLeaf(from): descend the set-0 tree"]
    T --> P["at each entry visit only the slots flagged in its bitmask (slot = popcount of the lower bits)"]
    P --> G["first leaf group at or after from"]
    G --> R{"any of its 8 counts non-zero? (read through the leaf cache)"}
    R -- yes --> I["return that index"]
    R -- no --> N["continue from the next group"] --> T
Loading

Why set 0 is enough: sets are populated in order 0..7, so any group with a leaf in any set has a set-0 leaf. The set-0 leaf can still be all zero (a count of 256 has byte 0 = 0 under byte 1 = 1), hence the per-group check.

Consumers:

  • AssemblyScript Histogram: nextNonZeroIndex dispatched at compile time via idof<T>(); the jump is inserted in the scalar loops, guarded by !isFlatStorage<T>(), so the SIMD kernels of flat histograms are untouched. encoding.ts measures zero runs with it.
  • JS: JsHistogram.nextNonZeroIndex (@internal, linear by default), overridden by PackedHistogram (tree walk) and TypedArrayHistogram (direct _counts read). PackedHistogram also overrides getValueAtPercentile. Rebased on perf: bound counts scans by min and max recorded values #70: add / subtract loops use a new nextNonZeroIndexInRange(from, last) that combines the min/max bounds with the jump.

No public API change.

Evidence

  • Before: src/bench/histogram-sparse-packed.bench.ts (new: 300 values over the safe-integer range, 3 significant digits) run on master 2b0e3ed.
    After: same bench on this branch. ops/s, higher is better.
Bench Histogram master branch
get value at percentile (p99) Packed (JS) 7,899 17,689 2.2x
WASM Packed 36,915 54,131 1.5x
Int32 (JS) 27,516 91,826 3.3x *
add (JS) Packed 6,243 11,597 1.9x
Int32 65,731 157,500 2.4x
encoding (compressed base64) Packed (JS) 2,498 8,621 3.4x
WASM Packed 6,168 17,311 2.8x
Int32 (JS) 8,773 12,055 1.4x

* PackedHistogram now overrides getValueAtPercentile, so the base JsHistogram method's getCountAtIndex call site stays monomorphic for typed-array histograms in a process that also uses packed ones.

  • Before: no test covered the jump.
    After: assembly/__tests__/PackedArrayIteration.test.ts and fast-check properties in src/packedarray/PackedArray.fc.spec.ts compare the walk against a brute-force scan (sparse, dense, byte-0-zero values, set back to 0, resize, unpacked fallback); src/PackedHistogram.spec.ts compares a sparse packed histogram with Int32 / Float64 twins (percentiles, encoded bytes incl. after subtract, add / subtract across layouts) and WASM packed with JS packed. npm run astest:ci: 15377/15377. npm test: 284 passed.

Merge Danger

Door: two-way

Internal hooks only; a plain git revert restores the linear scans. The encoded bytes are unchanged (the encoder only uses the hook to measure zero runs, and the tests compare them against the flat histograms).

Blast Radius: scans

Every packed-histogram scan (percentiles, add, subtract, encode, re-establishing min/max/total after subtract) and, on the JS side, the nextNonZeroIndex hook used by add / subtract for typed-array histograms. A wrong jump would silently skip counts, which is what the brute-force and twin comparisons guard against.

🤖 Generated with Claude Code

Scanning a PackedHistogram's counts (percentile lookup, add, subtract,
re-establishing min/max/total, encoding) used to visit every virtual index
and walk the set trees for each group of 8, so the cost grew with the
counts array length rather than with the values actually recorded.

PackedArray now exposes nextNonZeroIndex(fromIndex): on a packed context it
walks only the populated slots of the set-0 tree (sets are populated in
order 0..7, so any group holding a non-zero value has a set-0 leaf) and
reads the 8 values of each candidate group; on an unpacked context it scans
the longs linearly. Both the AssemblyScript and the JS histograms use it in
their packed-specific scan paths, through a nextNonZeroIndex hook on the
histogram (default: linear scan, TypedArrayHistogram reads its counts
directly). Outputs are unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…ions

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@alexvictoor
alexvictoor marked this pull request as ready for review November 15, 2026 19:12
@alexvictoor
alexvictoor merged commit bdfa37d into master Nov 15, 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