Repository navigation
feat(stats): fluree-db-stats kernel and on-demand column profiling - #1789
Conversation
…iling New crate `fluree-db-stats` holds mergeable sketches shared by every place that summarises a column of values: a const-generic HyperLogLog, exact Welford/Chan moments, a merging t-digest, and Misra-Gries heavy hitters, composed into `ColumnProfile` and a bounded-group `GroupedProfile`. The `findings` module derives group baselines, concentration, per-group constancy and scale drift for quality rules; the `tabular` feature adds a face over `fluree-db-tabular` column batches. The indexer's `HllSketch256` is now a re-export of the kernel's `Hll256`. Register layout and the 256-byte persisted form are unchanged, so existing sketches load and merge as before. `fluree-db-api` gains `Fluree::profile_ledger` (properties at the current `t`, novelty included, optionally grouped by other properties) and, under the `iceberg` feature, `Fluree::profile_table` (lake columns streamed through the graph-source scan, pinned to the current snapshot). Both report the same `ProfileReport` shape.
…e text values The t-digest kept its extremes as ±infinity, which serde_json writes as null and refuses to read back into an f64, so any column profile with no numeric values (a text or ref column) could not be deserialised. The extremes are now options, like the moments already were. A bytes cell was folded to one placeholder, so a bytes column profiled as a single constant value. Bytes now hash on their content under their own kind and report a hex sample. The text extremes compared incoming values against truncated samples, which mis-ordered strings that share a prefix longer than the sample. The whole value is kept for the comparison and truncated only in the summary. Text lengths count characters rather than bytes. `ProfileValue::to_text` replaces the three copies of the display match. The stats crate takes xxhash-rust from the workspace. On the API side, group keys are interned so the subject-to-key map costs one pointer per subject; the module doc states that the ledger face holds one property's flakes in memory per pass and that neither face applies view policy. Table profiling reads the schema first, so an empty table still reports missing columns and rejects an unknown group-by column, and the accumulators no longer depend on a first batch arriving.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz as a design idea to move this to its own crate & kernel seems very good to me and I have no pushback there. My only investigations were into memory performance (sizing) against that kernel. With Claude's assistance I found what I think may be some significant items worth addressing before merge:
This is a genuinely good kernel: const-generic Hll<M> with the indexer's Hll256 as an instantiation, exact Welford/Chan moments, a merging t-digest with the k_1 scale, Misra–Gries with the Agarwal merge and an honest decrements error bar, and every summary merges — which is what makes shard-parallel profiling and incremental refresh possible later. The thing I checked hardest was the persisted-sketch claim, and it holds: the deleted hll256.rs copied verbatim beside the new Hll256 and driven with the same 1 M hashes is byte-identical on registers, estimates, merges, every estimator branch and every error path in both directions, the indexer's hash lives in hashing.rs (untouched), and the per-flake insert is the same #[inline] code as before. Commit 2's fixes (Option extremes, whole-value text comparison, bytes on content, character lengths, schema-first table profiling) all check out under the crate's own tests, and no server route or tool reaches the two faces yet, so the "no view policy" statement is not a bypass — just a constraint for whoever wires them.
The two I have to block on: findings::scale_drift panics on a group with a negative median — ratio.ln() is NaN, partial_cmp falls back to Equal, and std's sort panics on the non-transitive comparator (reproduced on 1.97 with 200 groups, every third negative; a caller cannot guard it from outside the library) — and a ColumnProfile is sized for a column, not a group: an inline Hll4096, a HeavyHitters map that allocates ~5 KB eagerly in new, and t-digest capacity that is never shrunk come to 11–30 KB per group measured, times a 100,000-group default per column, so the per-(part, division) baseline the module doc advertises is 1.1–2.9 GiB per profiled column. Each fix is a few lines (skip median <= 0 and sort with total_cmp; HashMap::new(), shrink_to_fit, a smaller or lazy per-group HLL, a 10k default).
Fold-ins alongside, all inline: the lake face rebuilds the group key per row per profiled column with an allocation per key cell; profile_table loads the table three times so snapshot_id isn't structurally the snapshot scanned; the single-key subject map is deep-cloned while its source is alive; sum is the one bare float left that overflows to inf and breaks the round-trip; and a max_values guard on profile_ledger until a streaming walk exists (that walk needs a core API — genuinely separate scope, and I'd name it as such). Optional: SipHash over already-hashed keys, seven quantile() compress-clones per summary, an unclamped compression on deserialise, and one indexer-side monotonicity assert so the indexer's own tests can see a broken sketch merge.
Adherence to repo commitments:
- Patterns/abstractions: ✔ one kernel every column summary shares; the indexer re-exports rather than duplicates;
[lints] workspace = true, workspace version/license,tabularas an optional feature, zerounsafe. - Performance (speed first, memory second): ✔ indexer per-flake path unchanged (no bench budget needed); ✖ CRITICAL on memory for grouped profiling as shipped (per-group cost × default cap);
⚠️ N × K key allocations per row on the lake face, whole-property materialisation on the ledger face. - Testing: ✔ 47 kernel tests, 4 ledger-face and 2 lake-face integration tests wired into run targets (
grp_ledger, the[[test]]withrequired-features), CI green; ✖ the negative-median panic and the memory cliff are untested;⚠️ the indexer's tests don't detect a broken HLL merge. - Conventions: ✔ two thorough commits; module docs state the memory model and the no-policy caveat;
⚠️ struct docs /#[must_use]thin on the kernel's public API.
Verified locally at branch HEAD 71727bf69: compatibility proof by scratch test against the base commit's file (deleted after); cargo test -p fluree-db-stats 47, -p fluree-db-indexer stats 24 + hll 1, -p fluree-db-api --features iceberg,native --test grp_ledger profile 4 (+1 scratch novelty-retraction test), --test it_iceberg_local_fs 2; cargo fmt --all -- --check and cargo clippy -p fluree-db-stats -p fluree-db-indexer --all-targets --no-deps -- -D warnings clean; the panic, the memory numbers (counting allocator) and the sum round-trip failure reproduced; HLL merge mutation restored; worktree clean.
Just be sure to get the sort guard and the per-group sizing in before this merges — #1791 and #1792 rebase underneath it — and I'd rather see the fold-ins here than in the backlog.
| }) | ||
| }) | ||
| .collect(); | ||
| out.sort_by(|a, b| { |
There was a problem hiding this comment.
Blocking — scale_drift panics on a group with a negative median. ratio = median / overall (:201) is guarded only for overall <= 0 (:189). A group whose median is negative gives ratio < 0, ln = NaN, partial_cmp → None → Equal, and with NaN and non-NaN elements mixed the comparator is non-transitive, so std's sort (≥ 1.81) panics: "user-provided comparison function does not correctly implement a total order" (core/src/slice/sort/shared/smallsort.rs).
Reproduced on rustc 1.97: 200 groups × 5 values, every third group at -10-i, the rest at 10+i (overall median 59.5) → panic instead of a sorted Vec<ScaleDrift>. Any column of deltas, balances, adjustments or temperatures grouped by anything hits it, and the caller (a quality rule) cannot guard it from outside the library.
Fix: skip groups with median <= 0.0 — log-ratio drift is undefined there, which is what the overall guard already encodes — and sort on a precomputed |ln ratio| with f64::total_cmp so a NaN can never reach sort_by. Add the negative-median group as a test.
There was a problem hiding this comment.
Fixed in 7860eb0, but kept the group rather than skipping it — a negative median against a positive overall is the drift the rule exists to find. Sort key is precomputed and compared with total_cmp; a non-positive ratio sorts first. The test pins the misordering rather than the panic, since driftsort's detection is best-effort (it did not fire at 200 elements).
| config: ProfileConfig, | ||
| count: u64, | ||
| kinds: [u64; 9], | ||
| distinct: Hll4096, |
There was a problem hiding this comment.
CRITICAL (memory) — a ColumnProfile is sized for a column, not a group, and the grouped default makes 100,000 of them per column. Measured with a counting global allocator: 100,000 groups × 1 value = 1,081 MiB (11.3 KB per group); 10,000 groups × 600 values = 288 MiB (30 KB per group); size_of::<ColumnProfile>() = 4,536 B.
Where it goes: this inline Hll4096 (4,096 B in every profile, including a one-value group); HeavyHitters::new's HashMap::with_capacity(capacity + 1) (heavy_hitters.rs:57), which hashbrown rounds to 128 slots ≈ 5 KB allocated eagerly before the first observe; and the t-digest's Vec::with_capacity(points.len()) (tdigest.rs:116) sized for ~600 inputs but holding ~100 centroids, plus the emptied 500-slot buffer keeping its allocation (:112) — a digest that has seen ≥ 500 values holds ≈ 18 KB. DEFAULT_MAX_GROUPS = 100_000 (grouped.rs:18) is the API default (fluree-db-api/src/profile.rs:62), and profile_ledger builds one accumulator per requested column — so the "per-(part, division) baseline" the module doc advertises, over 10 properties and ≥ 100k parts, allocates 10 × 1.1–2.9 GiB before overflow starts pooling. GroupedProfile::merge (grouped.rs:107) clones whole Groups as well.
Four independent, cheap fixes: HashMap::new() in HeavyHitters::new (a one-value group then costs ~100 B); shrink_to_fit after compress and drop the emptied buffer; a smaller or lazily allocated per-group HLL (Hll256 / Hll1024, or Option/Box allocated on first insert) with Hll4096 kept for total; and a 10,000 default with the per-group cost documented beside it so max_groups is the knob callers reach for.
There was a problem hiding this comment.
Three of four in 7860eb0: HashMap::new(), centroid shrink_to_fit, default to 10,000 with the arithmetic beside it. Measured 11,334 → 6,250 B/group; the default worst case goes 1,081 MiB → 73.9 MiB. examples/memcheck.rs is the harness — it reproduced your 1,081/288 exactly. Per-group HLL sizing deferred: it needs ColumnProfile generic over M plus a cross-M merge into total. GroupedProfile::merge has no caller on the API path, so left as a note.
There was a problem hiding this comment.
Now done in bc57499, by a different route than sizing: the per-group Hll4096 is allocated only once the group's frequent-value table fills (64 distinct values), seeded from the counters' hashes while they are all still there, and fed every hash after, so its registers are byte-identical to an eager one (pinned by a test). Below that the distinct count was already exact from the counters and the sketch was never read. memcheck per one-value group: 6,250 B → 881 B; the 10,000-group default 73.9 MiB → 9.9 MiB per column. Merge builds the sketch before the frequent-value trim can drop a hash. Groups are also keyed on the key text now rather than its hash.
| .iter() | ||
| .filter_map(|k| batch.column_by_name(k)) | ||
| .collect(); | ||
| for (name, acc) in names.iter().zip(accs.iter_mut()) { |
There was a problem hiding this comment.
Should-fix (performance, lake face). The group key is rebuilt inside the per-column loop — once per row per profiled column — and tabular::display_at (tabular.rs:44-46, value_at(col,row).to_text()) allocates a String per key cell even for a Column::String where a borrow would do. That is N profiled columns × K key columns allocations per row for keys that are identical across the N columns: 20 columns, one key, 100 M rows → 2 × 10⁹ allocations. profile_column_grouped in tabular.rs:57-69 has the same shape.
Build the batch's keys once (a Vec<String> per batch, or one arena with offsets) and run the column loop over &keys[row]; let to_text return Cow<str> so a string cell borrows.
There was a problem hiding this comment.
Done in 303da9e — keys built once per batch into buffers reused across batches, and ProfileValue::write_text appends into a caller's string so a key cell no longer allocates. profile_column_grouped too. Left to_text returning String: once the N× factor is gone, the Cow change touches the public surface of both faces to save one allocation per key cell.
| use futures::StreamExt; | ||
|
|
||
| let provider = crate::graph_source::FlureeR2rmlProvider::new(self); | ||
| let snapshot_id = provider |
There was a problem hiding this comment.
Should-fix. profile_table resolves the table three times: current_snapshot_id and table_column_names each go through prepare_iceberg_scan (graph_source/r2rml.rs:933: nameservice lookup + catalog loadTable), then scan_table (:419-421) goes through the session-cached load_table_context. A commit landing between the calls makes the report say snapshot X and profile snapshot Y — the doc at :349-351 promises "at the table's current snapshot" — and each call pays two extra REST loadTables (priced at ~1–3 s each in the comment at r2rml.rs:2430).
Resolve metadata once (the session-pinned load_table_context), read current_snapshot() and the schema from that TableMetadata, and drive the scan from the same pinned context. Also: when every requested column is unknown the projection is empty (:403-411) and the scan still reads the whole table for nothing — short-circuit when no accumulator exists.
There was a problem hiding this comment.
Both halves in 303da9e. pinned_snapshot_and_columns reads the snapshot and the schema off one load_table_context, whose pin the following scan_table resolves to, so the reported snapshot is the scanned one. Short-circuit added with a test. table_column_names had no callers left and is removed.
| } | ||
| maps.push(map); | ||
| } | ||
| let keys: Option<HashMap<Sid, Arc<str>>> = match maps.as_slice() { |
There was a problem hiding this comment.
Should-fix (memory, ledger face). [single] => Some(single.clone()) deep-clones the whole HashMap<Sid, Arc<str>> while maps is still alive — 2× peak for the common one-key case — and each entry is a cloned Sid (24 B) plus a 16 B Arc<str> plus hashbrown overhead, ≈ 56–64 B per subject rather than the "one pointer per subject" the commit says (the interning does make the string one-per-distinct-key, which is the useful part). maps.into_iter().next() / std::mem::take for the single case; build the joined map by draining first.
Related and larger: property_flakes (:207-224) materialises every current assertion of the property as Vec<Flake> with no cap — the module doc says so, and no streaming range API exists yet, so it's a stated scope decision — but a max_values on ProfileRequest that probes with RangeOptions::with_flake_limit(limit + 1) and refuses would turn an OOM into an error today, with the streaming walk as the tracked follow-up (naming it: needs a core API, genuinely separate scope).
There was a problem hiding this comment.
Maps taken by value in 5129480. The max_values cap is deferred to a follow-up with the streaming walk — it is a new public request field and a new error path.
There was a problem hiding this comment.
max_values is now in a6603e5 rather than deferred: the range runs with a flake limit one past the cap and the property is refused, grouping properties included; the check runs before the retraction filter so a surviving retraction can only refuse earlier. Default stays unbounded. The same commit adds the indexed-path test: every existing profile test ran on the genesis overlay-only arm, so this one publishes an index, then retracts, rewrites and adds in novelty without reindexing, and asserts the counts and group keys net out through the provider. The streaming walk is filed as #1795.
| pub max: f64, | ||
| pub mean: f64, | ||
| pub stddev: Option<f64>, | ||
| pub sum: f64, |
There was a problem hiding this comment.
Should-fix (serde edge). sum is the one bare float left that can be non-finite: two Float(1e308) observations overflow it to inf, serde_json writes "sum":null, and from_str::<ColumnSummary> then fails — the report no longer round-trips, which is exactly what commit 2 fixed for the extremes. mean is Welford-safe and min/max are finite. Make it Option<f64> (None when non-finite), or serialise with a helper that nulls non-finite AND reads back as Option.
There was a problem hiding this comment.
Wider than sum, fixed in 7860eb0. observe had no finiteness guard at all, so an inf/NaN Parquet cell poisoned min/max/mean too. And mean is not Welford-safe: x - mean overflows on mixed extreme magnitudes of opposite sign, then goes NaN — f64::MAX/f64::MIN reproduces it. Every derived float now goes through one finite helper; mean and sum are Option, min/max stay bare since the ingest guard proves them finite.
| /// that formats the value lazily. | ||
| #[inline] | ||
| pub fn observe(&mut self, hash: u64, sample: impl FnOnce() -> String) { | ||
| if let Some(c) = self.counters.get_mut(&hash) { |
There was a problem hiding this comment.
Optional (perf on the profiling path). HashMap<u64, Counter> with the default hasher re-hashes an xxh3 key on every observe, merge and count_of; a ten-line NoHash BuildHasher removes ~15–20 ns per value. And when the table is full and the value is unseen, the retain at :81-86 runs over every counter per value — Misra–Gries' known cost, amortised O(1) for a mostly-unique column but O(capacity) per singleton when ~64 heavy values persist; worth a comment. Also a doc line on top(): empty under !is_exact() means "nothing provably frequent" — the equal-shard merge correctly drops every counter (decrements = 10, bound holds), which reads like a bug until you know.
There was a problem hiding this comment.
Both doc lines added in f6c7b5b, and HashMap::new() came with the memory thread. Skipped NoHash: ~15–20 ns against an HLL insert and a digest add on the same path.
| if self.total == 0.0 { | ||
| return None; | ||
| } | ||
| if !self.buffer.is_empty() { |
There was a problem hiding this comment.
Optional (perf). quantile() clones and compresses the digest (a sort of ≤ 600 centroids) on every call while the buffer is non-empty, and summary() (profile.rs:305-311) calls it seven times per column per group; findings::baseline_of and scale_drift repeat it per group. Compress once in summary (clone once, read all seven) or expose quantiles(&[f64]). Related: compression is clamped to ≥ 10 only in new (:48-50) — a digest deserialised with "compression":0.0 never merges (q_limit is NaN; 5,000 points → 5,000 centroids); a deserialize_with clamp closes it.
There was a problem hiding this comment.
Both done in 7860eb0. compressed() compresses once and summary reads all seven quantiles from it; compression is clamped on deserialize as well as in new.
| self.count += other.count; | ||
| self.values_hll.merge_inplace(&other.values_hll); | ||
| self.subjects_hll.merge_inplace(&other.subjects_hll); | ||
| self.values_hll.merge(&other.values_hll); |
There was a problem hiding this comment.
Praise, and the thing I checked hardest. The compatibility claim is true, and it was proven rather than read: the deleted hll256.rs was copied verbatim from the base commit into a scratch test beside the new Hll256 and both were driven with the same 1 M hashes — byte-identical registers, identical estimates and merges, identical behaviour on every estimator branch and every from_bytes_versioned error path, in both directions. The indexer never hashed inside that file (insert_hash takes the u64 from stats/hashing.rs, untouched), and this merge is the only edit on the refresh path; the per-flake insert_hash at :447-448 is the same #[inline] fixed-array code as before. One coverage note: flipping the kernel's merge max to min reddens two kernel tests and none of the 390 indexer tests — a single estimate-monotonicity assert on the merge_from test would let the indexer see its own sketch break.
There was a problem hiding this comment.
Took the coverage note in f6c7b5b — merge_from_unions_the_sketches, and the max→min flip now reddens the indexer (4630 + 4980 -> 3248). One thing it turned up: the sketch needs a properly mixed hash. Seeded with i * 0x9E3779B97F4A7C15 it reads 18,416 against a true 10,000, so the test feeds subject_hash and says why.
| /// Hash a value under its kind's domain. Nulls have no hash; callers | ||
| /// count them separately and never call this for them. | ||
| #[inline] | ||
| pub fn value_hash(value: &ProfileValue<'_>) -> Option<u64> { |
There was a problem hiding this comment.
Praise. Domain-separated hashing with integral-float folding (7 == 7.0 == 7.00, -0.0 == 0.0, "7" ≠ 7 ≠ <7>) is the right definition of "the same value" for a profile, and it is entirely separate from the indexer's persisted-sketch hash, which is why the compatibility question was moot.
…file
`scale_drift` ordered groups by `ratio.ln().abs()` through `partial_cmp`,
answering `Equal` when the log was NaN. A group whose median is negative
gives a negative ratio and so a NaN, and a comparator that calls a NaN
equal to everything is not a total order: the groups came back in
arbitrary order, and `sort_by` is entitled to panic on it. The distance
is now precomputed and compared with `total_cmp`, and a non-positive
ratio sorts first rather than being dropped -- a group at -5 against an
overall 60 is the drift the rule exists to find.
Non-finite floats had three ways into a report that then would not read
back, since serde_json writes them as null and a bare f64 refuses null:
- An infinity or NaN in the input reached the moments and the digest,
poisoning min, max, mean and sum together. A Parquet double column
can carry both. `observe` now keeps them out of the aggregates and
counts them, so they are visible rather than silently dropped.
- `sum` overflowed to infinity on wholly finite input; two cells at
1e308 are enough.
- `mean` overflowed the same way. Welford's increment is
`mean += (x - mean) / n`, and `x - mean` overflows when a column
mixes extreme magnitudes of opposite sign, after which the running
mean is NaN.
Every derived float the summary reports now goes through one `finite`
helper and is absent rather than unreadable, which makes `mean` and
`sum` options; `min` and `max` stay bare, being observed values that the
ingest guard has already proved finite. A group whose baseline overflowed
is omitted like a group with no numeric values, since a `RatioRule`
against a NaN centre answers false anyway.
A deserialised digest kept whatever compression it was given. At zero the
centroid limit is NaN, no two centroids ever merge, and the digest
silently stops being a sketch -- 5,000 points, 5,000 centroids. The clamp
in `new` now also runs on the way in.
A `ColumnProfile` is sized for a column, but `GroupedProfile` keeps one
per group, so the slack in it is paid per group and the default kept
100,000 of them. Measured with a counting allocator, 100,000 groups of
one value cost 1,081 MiB, or 11,334 B per group:
- `HeavyHitters::new` reserved a table for `capacity` counters before
the first observation. It is now unreserved; growth to the same
table is amortised over the first `capacity` inserts anyway.
- `compress` left the centroid vector sized for every input point
while holding around a hundred survivors, so it now shrinks.
- `summary` compressed a clone of the digest once per quantile, seven
times per column per group. `compressed` does it once for all seven.
Together those bring a group to 6,250 B, and the default group cap drops
to 10,000 with the arithmetic documented beside it -- 1,081 MiB to
73.9 MiB for the default. Keys beyond the cap still pool into overflow
rather than being lost. The remaining 4,096 B is the per-group HLL, which
needs `ColumnProfile` to become generic over its register count and a
cross-size merge to fold into `total`; that is left as a follow-up.
`examples/memcheck.rs` is the harness these numbers come from.
Joining the group-by maps cloned the whole subject-to-key map in the one-key case, which is the common one, holding two of them at once for no reason. The maps are taken by value instead. `profile_table` with only unknown column names built no accumulators but still scanned: an empty projection means every column to the scan, so it read the whole table to produce a report of nothing but skips. It now returns that report without scanning.
`profile_table` resolved the table three times. `current_snapshot_id` and the schema read each went through `prepare_iceberg_scan`, which is uncached -- a nameservice lookup, a fresh catalog client and a `loadTable` apiece -- and then the scan resolved a third time through the session-pinned `load_table_context`. So the report could name one snapshot and profile another, against a doc that promises the table's current snapshot, and paid two catalog round trips for the privilege. `pinned_snapshot_and_columns` reads both off one `load_table_context`, whose pin the following `scan_table` resolves to, so the reported snapshot is the scanned one. `table_column_names`, added earlier in this branch for the schema read, has no callers left and goes. The group key was rebuilt inside the per-column loop, once per row per profiled column, though a row's key is the same whichever column is being folded. It is now built once per batch, into buffers reused across batches. `ProfileValue::write_text` appends into a caller's string, so assembling a key no longer allocates one `String` per key cell: twenty columns over one key column and a hundred million rows came to two billion allocations for keys that were computed twenty times over. `tabular::profile_column_grouped` takes the same treatment.
The HLL the property-stats refresh persists is now the kernel's, and no indexer test covered its merge: flipping the kernel's register-wise max to a min reddened two kernel tests and none of the indexer's 398. `merge_from_unions_the_sketches` asserts the merge cannot lower the estimate and that the union of two disjoint halves lands near the true cardinality, which that flip breaks. The test feeds `subject_hash` rather than a counter on purpose. The sketch takes an already-mixed 64-bit hash, and a value with structure left in it inflates the estimate by most of a factor of two -- an `i * odd` sequence reads 18,416 against a true 10,000. Two notes on the frequent-value sketch that cost a reader time: the decrement pass is O(capacity) per unseen value while a set of heavy values keeps the table full, amortising to O(1) only over a mostly unique column; and an empty `top()` under `!is_exact()` means "nothing provably frequent", which is why merging equal shards correctly drops every counter.
…te columns Every hash the sketch sees is 64 bits, so the raw estimator holds past 2^32/30. The inherited correction read 2.3% high near 200M distinct and returned zero once the raw estimate passed 2^32, since it took the log of a negative number. Registers and the persisted form are unchanged. A column whose only numeric kind is temporal now reports no sum: a total of epoch milliseconds means nothing, while its mean, extremes and quantiles are still dates. The decimal-through-f64 loss is documented on both faces.
The ledger face holds a property's flakes whole, so a large property was an out-of-memory waiting for a route. `ProfileRequest::max_values` ranges one flake past the cap and refuses the property, grouping properties included; the check runs before retractions are filtered so a surviving retraction can only refuse earlier. Every existing profile test seeded one insert into a memory ledger and never built an index, so `range_with_overlay` took the genesis overlay-only arm each time and the binary-index path was untested. The new test publishes an index, then retracts, rewrites and adds in novelty without reindexing, and asserts the counts, extremes and group keys net out through the provider.
…e fills A `ColumnProfile` carried a 4 KB HLL from birth, and a grouped profile keeps one profile per group, so ten thousand groups of a few values each paid 40 MB of registers nobody read: below the frequent-value table's capacity the distinct count is exact from the counters. The sketch is now absent until the table reaches capacity, seeded from the counters' hashes while they are all still there, and fed every hash after, so its registers are byte-identical to an eager one. A merge builds it before the frequent-value trim can drop a hash, and two exact tables that fit together stay exact without one. Measured with the memcheck example, per group: 6,250 B to 881 B for one-value groups, 22.9 KB to 20.3 KB for 600-value groups; the 10,000-group default goes from 73.9 MiB to 9.9 MiB per column. Groups are now keyed on the key text rather than its hash, so two keys are one group only when they are the same string; only the overflow key sketch reduces a key to a hash. `key_candidate` says on the field what its test already did: the sketch could not disprove a key, and only an exact probe proves one.
Summary
Adds a
fluree-db-statscrate holding the mergeable sketches every column summary in Fluree can share, and two on-demand profiling entry points influree-db-apibuilt on it. Nothing here runs at index time: the indexer's only change is that its existing 256-register HLL is now the kernel'sHll256.The kernel (
fluree-db-stats):Hll<M>: const-generic HyperLogLog.Hll256is the indexer's existing per-(graph, property) sketch,Hll4096the profiling default. No large-range correction: every hash is 64 bits, so the raw estimator holds past2^32/30.Moments: exact count / mean / variance / min / max / sum (Welford single-stream, Chan merge).TDigest: merging t-digest with thek_1scale function; tight at the tails.HeavyHitters: Misra–Gries frequent values with the Agarwal et al. merge; exact when distinct ≤ capacity, bounded undercount otherwise, and every answer carries its own error bar.ColumnProfilecomposes the four over one column. Its cardinality sketch is allocated only once the frequent-value table fills; below that the distinct count is exact from the counters.GroupedProfilekeeps one profile per group key, keyed on the key text, with a bounded group count and an overflow pool.findings: group baselines, ratio and z-score rules, concentration, per-group constancy, scale drift.tabularfeature: a face overfluree-db-tabularcolumn batches.Every summary merges: two profiles over disjoint shards fold into the profile of the union, exactly for counts and moments, within stated error for the sketches.
The indexer re-exports the kernel's
Hll256asHllSketch256. Register layout, the per-flakeinsert_hash, and the 256-byte persisted form are unchanged, so existing sketches load and merge as before; the only call-site change wasmerge_inplace→merge. The indexer now has its own test that reddens if the kernel's merge regresses under it.The API gains:
Fluree::profile_ledger: properties at the currentt, novelty included, optionally grouped by one or more other properties.ProfileRequest::max_valuesrefuses a property past the cap instead of ranging it into memory.Fluree::profile_table(featureiceberg): lake columns streamed through the graph-source scan, pinned to the current snapshot, optionally grouped by other columns.Both return the same
ProfileReportshape.Since the first review
HashMap::new()inHeavyHitters, centroidshrink_to_fit, one compression per summary,compressionclamped on deserialise, every derived float through onefinitehelper, keys built once per batch on the lake face, oneload_table_contextfor the pinned snapshot, maps taken by value on the ledger face.a2fcf1bb9: the inherited 32-bit large-range HLL correction removed (it read 2.3% high near 200M distinct and returned zero past2^32); nosumfor a temporal-only column; decimal-through-f64 loss documented.a6603e5e7:max_valuescap on the ledger face, and a test through the binary index with novelty retractions, rewrites and additions on top of it. Every earlier profile test had run on the genesis overlay-only arm.bc5749902: lazy per-group cardinality sketch.memcheckper one-value group 6,250 B → 881 B; the 10,000-group default 73.9 MiB → 9.9 MiB per column. Groups keyed on the key text, so two keys are one group only when they are the same string.key_candidatedocumented as "the sketch could not disprove a key".Limitations stated in the docs
max_valuesis set. The table face is bounded by the scan batch.Follow-ups
max_valuesa soft limit.Test plan
cargo fmt --all --checkcargo clippy -p fluree-db-stats -p fluree-db-indexer -p fluree-db-api --features fluree-db-api/iceberg --all-targets --no-depscargo test -p fluree-db-stats --all-features(62 tests: sketch error bounds at both HLL sizes, no zero estimate past2^32, merge-equals-whole for every sketch, lazy sketch register-identical to an eager one across allocation and the three merge shapes, JSON round trips including empty digests and text-only profiles, whole-value text extremes, bytes by content, negative-median scale drift ordering)cargo test -p fluree-db-indexer --lib stats(25) and--test hll_testcargo test -p fluree-db-api --test grp_ledger it_profile_ledger(6: flat, grouped, two-key grouping with constancy, unknown group property, indexed base with novelty retractions,max_valuesat and past the cap)cargo test -p fluree-db-api --features iceberg --test it_iceberg_local_fs local_table_profiles(all columns, grouped with a missing column, every column unknown)cargo run -p fluree-db-stats --release --example memcheckbefore and after the lazy sketch.