Repository navigation
perf(r2rml): vectorized fused-aggregate fold + late-rendered decode seam (Gap-4 P1) - #1582
Conversation
…id dict
The GROUP BY fold allocated a fresh Vec<GKey> and cloned each string key every
row, then SipHashed a Vec<GKey> into HashMap<Vec<GKey>, Vec<Acc>>. On a 1M-row
scan grouping to 18 groups that is ~2M String clones + 1M SipHashes (Gap-4 P0
profile: GroupCol::key_at 14.4% + SipHash 7.5% of on-CPU wall).
Build the composite key BORROWED (GKeyRef — no per-row String clone / Vec alloc)
into a reused scratch, FxHash it, and intern to a dense id in a
hashbrown::HashTable; the owned key is materialized only when a new group is
inserted, and typed accumulators live in group_accs[id]. A HashTable (not a
HashMap + insert_hashed_nocheck) is used so the borrowed probe and the
resize-rehash share one hash function (hash_key_refs / gkeys_hash) — otherwise a
table grow re-buckets a key away from its probe and splits its group.
Preserves exactly: the exact-arithmetic domain (Dec{i128,scale} -> BigDecimal on
overflow, unchanged accumulate_*/Acc), every fold semantic, the memory-budget
group-growth checkpoint, and the whole decline/fallback surface (admission
untouched). f64 SUM stays bit-identical (each group folds its rows in the same
row order under both paths).
Gated by FLUREE_FUSED_VECTOR_FOLD (default on; off = byte-identical owned-key
fold). Tests: key_ref_at_matches_key_at (borrowed read == owned read for every
Column kind/null/coercion), key_hash_borrowed_matches_owned (resize-safety
invariant), and a resize-forcing vector_fold_grouping_matches_owned_map.
…umnValue intermediate The Arrow decode built a Vec<Option<ColumnValue>> per column (arrow_column_to_values) and then a second Column Vec<Option<T>> (build_columns_from_values) — a two-hop copy, and two String allocations per string cell. The Gap-4 P0 profile measured this decode seam at ~33-46% of on-CPU wall on the fused GROUP BY family (46% on the 1M-row cq027). Add arrow_column_to_column, which builds the Column directly from the Arrow array in one hop. Its fast arms cover the cases where the Arrow physical type matches the target field type (each value-identical to the old composition); every other pair — cross-type coercions, timestamp unit-scaling, unhandled types, and schema-evolution-absent columns — falls back to the exact old mapping via the extracted column_from_values, so behavior is unchanged there. Gated by FLUREE_ARROW_DIRECT_DECODE (default on; off = byte-identical two-hop path). Differential test direct_decode_matches_two_hop asserts the two paths produce identical Columns across every fast type + nulls + NaN + the cross-type fallbacks.
…-fold Brings family-C's widened filter-over-join admission and #1529's keep-min parent-index change under the vectorized fold. merge-tree verified conflict-free; the semantic interaction (family-C shapes now folded through the borrowed-key dense-id path) is re-verified by the P1 differential and the fused_aggregate suite at this merged head.
…ame has a non-target branch The parity-gate-failure path drops the WHOLE ledger name (every branch, DropMode::Hard, no --force), but the build's freshness refusal is branch-scoped, so `--into existing-ledger:new-branch` initializes cleanly and a later gate failure — which can fire on a correct twin (CRITICAL-3) — then purges every other branch of that ledger too, irreversibly. Refuse before building unless the twin's ledger NAME is fresh apart from the target branch (a live, non-retracted non-target branch blocks), restoring by construction the invariant docs/cli/materialize.md rests on. Pure predicate blocking_existing_branch is unit-tested (live non-target blocks; empty / target-only / retracted-other allow).
… of hanging The driver held its own Arc<Mutex<work_rx>> for the whole wave, so SyncSender::send could never observe all receivers gone: the consumer_gone escape hatch was dead code and an all-workers-dead pool (a full spool disk, or one panic poisoning the shared lock and cascading) left the driver blocked in send forever and the consumer blocked in recv forever — a silent permanent hang. - drop(work_rx) right after spawn so a dead pool disconnects the channel and work_tx.send errors (making the consumer_gone break reachable); - lock the shared receiver with unwrap_or_else(PoisonError::into_inner) so one worker panic doesn't cascade into the rest; - run the scan/dispatch under a scoped future and drop(work_tx) + JOIN the workers UNCONDITIONALLY (happy path and error path) before propagating, so no detached worker is left writing spool files into a dir the failing import is about to clean up. Test worker_failure_errors_not_hangs drives a poison mapping (empty subject map => hard emit error in every worker) and asserts the build ERRORS within a timeout rather than hanging.
…n full verify
The N-Triples export writer hardcoded xsd:double in its Double arm while the
source renders the DECLARED datatype (xsd:float), so every triple from a float
column compared "v"^^xsd:float (source) against "v"^^xsd:double (twin) — one
missing + one extra per triple — and --verify full hard-dropped an otherwise
correct twin (which then arms CRITICAL-1 on correct data).
- canonicalize_value_nt folds the datatype IRI xsd:float -> xsd:double; both
sides flow through this canonicalizer (source render + the twin export via
CanonicalizingLineWriter), and the lexical forms already collapse, so it never
masks a genuine float-vs-double VALUE difference.
- export.rs Double arm now resolves o_type like its Long/BigInt/Decimal
neighbors (falling back to xsd:double) instead of silently re-typing.
- the count:{class} checks carry COUNT_MULTISET_NOTE explaining that a
multiset-source vs set-twin count can mismatch on a non-unique subject
template even on a faithful twin (the full-triple diff is authoritative).
The durable structural fix (one shared renderer both sides + count-distinct
subjects source-side) is tracked, not in this phase. Test
float_and_double_same_value_canonicalize_equal pins the fold + non-masking.
The operator built its parent lookup index keyed in parent-name-sorted column order but probed it with the child key in DECLARED order. Whenever the two orderings of the same condition pairs disagree (a composite FK), the probe key was transposed, the lookup silently missed, and the virtual query dropped the FK edge as if dangling — while the materialize enumerator (which uses canonical_join) was correct, so twin and virtual genuinely diverged on that shape. Single-column FKs (the whole current corpus) were unaffected. - export canonical_join from fluree-db-r2rml (parent columns ordered deterministically, child columns positionally aligned); - use it at both operator sites (parent-lookup build + materialize_pom_object probe, incl. the ref-shortcut zip), so index and probe agree on column order. Engine-level test composite_fk_disagreeing_name_order_resolves_via_canonical_join constructs a composite FK whose child-declared order disagrees with its parent-sorted order and asserts the edge resolves (it was dropped before). Also updates the it_graph_source_r2rml count-mismatch assertion to ignore the new CheckOutcome::Mismatch note field added in CRITICAL-3.
…ouse single-table fallback MAJOR-2 (#1529 review): on the Direct path the pin is a 2s metadata cache and on REST with the loadTable cache off pinning is a documented no-op, so a source that commits mid-build yields a twin whose stamped watermark does not describe its contents. Cheap-loud fix: - IcebergCatalogSession.record_snapshot now records a table that yields a SECOND DISTINCT metadata_location into snapshot_conflicts (first-writer-wins still picks the pin); - R2rmlProvider gains a defaulted verify_build_snapshot_integrity (mock/test providers stay Ok); FlureeR2rmlProvider refuses when the loadTable cache is disabled and when any table moved snapshots; - drive_virtual_import calls it at build start (cache) and again before the completion stamp (conflicts), so no untrustworthy twin is ever stamped. MAJOR-3 (#1529 review): the warehouse-root detector splits the leaf on the FIRST '.', misrouting legitimate single-table Direct locations whose leaf dir does not name the table (a suffixed table dir, or a dir literally 'DW.FACT_ORDER'). When match_warehouse_table_dir misses AND the listing has a metadata/ child (every Iceberg table dir has one), treat it as a single table and return the location unchanged. Tests: record_snapshot_flags_second_distinct_metadata_location, listing_is_single_table_detects_metadata_child.
…p minors MAJOR-4 (#1529 review): two per-row/per-edge alloc sites O4 missed. - emit_batch: FK-edge counts accumulate in a per-POM Vec (a bare += 1), folded into stats.ref_edges ONCE per batch — the old per-edge entry((tm.iri.clone(), predicate.to_string())) did two heap allocs + a composite-String hash on every edge (and defeated the Cow::Borrowed hoist); templated ref predicates keep the per-edge path. - ParentIndexSet::index_batch: pre-create each col-set map once (get_mut by borrow in the row loop) instead of entry(cols.clone()) per row; pass the join key by value and re-read it only on the rare distinct-subject collision. MAJOR-5 (#1529 review): three verification gaps. - parent_index_budget_guard_trips_on_a_populated_index (the failure arm — the 'fails loud rather than OOM' promise was untested). - build_parent_lookup_keeps_min_subject_on_duplicate_join_key (the live-query keep-min semantics; last-wins would pick the other subject). - verify_twin_full_passes_on_multi_chunk_twin now asserts build.t > 1 so it's genuinely multi-chunk. Cheap minors adjacent to touched files: dupParentKeys read warns on a malformed (present) payload instead of reading back CLEAN (fail-open); verify spool dir gets a per-process atomic suffix (concurrent same-source verifies no longer share/delete each other's runs); the pack drop instruction + docs use the whole-ledger id + --force; the --memory-budget-mb 0=auto doc line corrected to the 512MB co-resident default; ImportConfig marked #[non_exhaustive].
…keys A GROUP BY on a referenced parent IRI (crt_highcard: GROUP BY ?c where ?c is edw:customer) declined the fused fold — scalar_column_for_var admits only a scalar column, so ?c fell to the generic per-row materialize path, which mints an RDF IRI for EVERY fact row (~58% of wall + the 8.7x RSS at SF1). Admit it in the single-table resolve_at_open: resolve the RefObjectMap, build an FK->IRI resolver by scanning the parent dimension ONCE (minting each parent subject via materialize_subject_from_batch exactly as build_parent_lookup does, with deterministic keep-min on a duplicate parent join key), then fold on that IRI through the existing Dim-sourced group-key machinery and emit it as an IRI term at output (new GKind::Iri => Binding::iri). The per-fact-row minting is gone — the mint cost moves to the O(dim) resolver build the generic path already pays — so the fold is byte-identical to the generic ?c binding while collapsing RSS. Design (team-lead approved, deviating from the charter's fold-on-FK/decline sketch where value-identity requires it): fold on the exact minted IRI (dodges the Decimal-lexical stringification-drift class of fold-on-FK), keep-min not decline (the generic query path resolves dup parent keys by keep-min post-#1529, so keep-min IS parity — declining would be slower parity). At most one ref group key (+ any fact-column keys via the mixed W4-2 model); >=2 ref keys decline as follow-on. A null/dangling FK drops the row, matching materialize_pom_object. #1583 (RefObjectMap fan-out) will change group multiplicity — a comment at the admission site flags that it must revisit this fusion IN THE SAME change. Tests (hermetic, end-to-end via open+next_batch over a mock provider): value-identity + dangling-FK drop; keep-min on a duplicate parent key (asserts the lexicographically smaller subject wins, byte-identical to build_parent_lookup); ~100k distinct-IRI cardinality exercising the dense-id dict.
…ne-only)
The structural half of P3 (the multi-fact branching-star join, crt_join_reorder
class), landed decline-only and byte-identical so the soundness core lands
separately.
order_chain admits only a LINEAR fact→dim chain and explicitly declines a branch,
which is why crt_join_reorder (FactOrderLine branching to edw:order→FactOrder→
customer[Enterprise] AND edw:product→DimProduct[isCurrent]→category) is uncovered
(the 917×/DNF gap). This adds:
- FLUREE_FUSED_R2RML_MULTIFACT kill switch (default on; off = pre-P3 wholesale).
- Typed branch model (Branch / JoinBranch{GroupKey|SemiJoin} / BranchingStar) — a
LIST even though v1 admits exactly one of each, so K-branch generalization is
additive rather than a per-shape rewrite.
- decompose_branching_star: recovers the fact root + classifies each linear FK
branch (GROUP-KEY = binds a GROUP BY var; SEMI-JOIN = pure membership/constraint),
declining every non-admitted shape (merge, cycle, nested branch, disconnected,
non-branching root, not {one group-key + one semi-join}).
resolve_join_at_open recognizes a branching star (gated) for the follow-on but
still returns Ok(None) — behavior is byte-identical to pre-P3 (all 1343 query
tests pass; crt_join_reorder still declines to the generic pipeline).
The soundness core — the semi-join branch's KEEP-MIN-THEN-FILTER membership build
(budget-charged, typed fail-loud) + the fold probe + the differential fixtures
(value-identity, budget-fail, switch-off, dup-ORDER_KEY keep-min-then-filter) —
is the tracked next unit; the kept invariant is recorded. Test
decompose_branching_star_recognizes_crt_join_reorder_shape pins the decomposition.
…d-fold Puts the P3 soundness core on the true final tree. #1586 renamed the materialize spool tuple finish()->into_parts() (the #1529 x #1552 merge skew); this branch's pre-#1552 call sites are superseded by main's repaired versions (I never touched those lines, so git takes main's side cleanly). merge-tree verified conflict-free.
… (crt_join_reorder) Wire the branching-star success arm of the fused R2RML aggregate operator: a fact root with one GROUP-KEY branch and one SEMI-JOIN branch now FUSES instead of declining (the 917×/DNF crt_join_reorder class). - SEMI-JOIN membership built KEEP-MIN-THEN-FILTER: each hop resolves to the keep-min parent subject (byte-identical to build_parent_lookup / parent_key_insert_keep_min), then the kept row is filtered — so a duplicate intermediate key tests the keep-min row, matching the generic chained inner join. filter-then-union would wrongly admit a key whose keep-min row fails but a discarded dup passes. - GROUP-KEY branch resolves via the shared linear-chain resolver (resolve_linear_chain_at_open, extracted from resolve_join_at_open) with the SEMI-JOIN FK stripped from the fact's required objects and its child columns added to validity + projection. - Bounded: each membership level charges record_alloc + checkpoints per batch → typed MemoryBudgetExceeded (507) before OOM. - Fold probe drops a fact row on a membership miss before the group-key resolve. - Gated by FLUREE_FUSED_R2RML_MULTIFACT (default on; off = pre-P3 byte-identical decline). - #1583 cross-reference at the semi-join site: the semi-join≡inner-join equivalence rests on FK single-valuedness; a fan-out RefObjectMap must revisit it. Differentials: value-identity (integer + exact-decimal i128 SUM), the dup-ORDER_KEY keep-min discriminator + control, budget-exceeded typed fail, and the switch gate.
…nts, not only star_constraints Live validation (crt_join_reorder on substrate B) caught a silent SUM over-count: the fused result was ~6× DuckDB because the Enterprise semi-join applied NO filter. Root cause: the R2RML rewrite emits a subject's constant-object member as a STANDALONE const-object scan (predicate_filter + object_constant) when that subject has no var-object member (rewrite.rs, "const-object pattern stays a standalone scan"). The semi-join terminal `?c edw:segment "Enterprise"` is exactly that shape, so its constraint is NOT in star_constraints. build_semi_join_membership gathered constraints only from star_constraints, so the terminal filter was empty and every order was admitted. (The group-key branch's isCurrent DOES fold into star_constraints because its ?p has the var-object ?cat, which is why only the semi-join leaked.) Fix: resolve_semijoin_pattern_constraints gathers constraints as an OR over BOTH forms — folded star_constraints AND the standalone (predicate_filter + object_constant) — and declines the fuse if a standalone constraint cannot resolve to a scalar column (never silently ignored). Wired into the per-chain-pattern constraint build. Fixture fidelity: the crt differential fixtures now represent the segment constraint in the real standalone const-object form the rewrite produces (would have caught this), and a new test pins the folded star_constraints arm — so the OR gatherer is fixtured on both forms. The dup-ORDER_KEY discriminator, rewritten to the standalone form, is the strongest end-to-end guard. Live: crt_join_reorder now matches DuckDB exactly (10 rows, gate=exact).
…outputs) A high-cardinality fused GROUP BY (crt_highcard's 259k groups) materialized its ENTIRE output at once — all group rows built into one batch while the accumulator dict was still resident — the P2a output residual. Output-bounding drains the finalized rollup in bounded chunks (OUTPUT_BOUND_ROWS per next_batch call) across calls, popping from the back so each group's key + accumulators are freed as it is finalized (peak output-side memory = one chunk, not the whole result). One mechanism, shared by every fused GROUP BY consumer — single-table, the fact-dim join, and the P3 branching-star join — since they all reach the same emission. Gated by FLUREE_FUSED_R2RML_OUTPUT_BOUND (default on; off restores the single-batch emission wholesale, byte-identical — same rows, dict/map iteration order). An implicit (no-GROUP-BY) aggregate and the COUNT-manifest shortcut are one row and bypass bounding. Tests: a >OUTPUT_BOUND_ROWS rollup emits multiple batches each ≤ the bound with the union == the full result (switch on) and a single batch (switch off), same total both ways; the 100k-group high-cardinality test now drains all batches (multi-batch cover).
bplatz
left a comment
There was a problem hiding this comment.
Review of the fused vectorized fold + late-rendered decode seam. Overall this is careful work — the P3 keep-min discriminator pair (b / b-control) is exactly the right test shape, the 2500-key grow test genuinely guards the split-group hazard, the canonical_join transposition fix is a real latent-bug fix with a regression test, and CRITICAL-2's drop(work_rx) + unconditional join with a timeout-guarded hang test is properly done.
One blocking correctness issue (dangling FKs counted in an ungrouped aggregate over a RefObjectMap object var — verified locally, see inline), one soundness caveat worth documenting or gating, and a handful of smaller cleanups. Details inline.
| count_non_null_cols.push(col); | ||
| } | ||
| None => { | ||
| // P2a: a RefObjectMap object var (e.g. the `?c` group key) has no |
There was a problem hiding this comment.
Blocking — dangling FKs are counted when the ref object var is not a GROUP BY key.
This arm used to return Ok(None) for any non-scalar object; it now admits a RefObjectMap object var by pushing its FK child columns into validity_cols. The comment says "A present-but-dangling FK is dropped later by the resolver probe" — but group_resolver is only built when that ref var is an admitted GROUP BY key (ref_group_key). For a bare COUNT(*) / SUM over ?o :custRef ?c with no GROUP BY there is no resolver, so only null FKs drop and dangling FKs are folded in.
Verified on this branch with a throwaway test using the same data as ref_iri_group_key_folds_to_parent_iris_and_drops_dangling, only with group_by: [] and CountAll:
PROBE: fused ungrouped COUNT over a ref object var = Some(4) (generic = 3)
Order 4's CFK=99 has no customer row — the generic path yields no triple, the fused path counts it.
Suggested fix: decline unless v is the admitted ref_group_key var (cheap, and matches the comment's intent), or build the FK resolver for existence-only checking in the ungrouped case.
Secondary: those same columns land in count_non_null_cols, so a provider that proves them zero-null lets the manifest record_count shortcut fire with dangling FKs included.
Every P2a test currently has a GROUP BY — that's why this slipped through. Worth adding the ungrouped case to the fixtures regardless of which fix you pick.
There was a problem hiding this comment.
Great catch, and confirmed — this was a real over-count. You're exactly right that group_resolver only exists when the ref var is an admitted GROUP BY key (ref_group_key), so a bare COUNT(*)/SUM over ?o :custRef ?c with no GROUP BY reaches :2407, admits on FK-non-null validity, and nothing ever probes the parent — so a dangling FK folds in. I reproduced it on the same data as ref_iri_group_key_folds_to_parent_iris_and_drops_dangling but with group_by: [] + CountAll: fused = Some(4), generic = 3 (order 4's CFK=99 has no customer row). Fixed in 560fb1d4c by taking the cheap path you suggested — decline unless the ref object var is the admitted ref_group_key (if !self.group_by.contains(&v) { return Ok(None) }) — which also closes the secondary count_non_null_cols / record_count-shortcut hole you flagged, since a declined shape never reaches the manifest shortcut. Added the ungrouped case to the P2a fixtures so it can't creep back.
| /// many parents) would make a discarded-dup row a legitimate join partner, so a | ||
| /// membership *set* would then under-represent the fan-out; the fan-out follow-on must | ||
| /// revisit this site (mirrors the P2a #1583 caveat on the FK→IRI group key). | ||
| struct SemiJoinSet { |
There was a problem hiding this comment.
The keep-min-then-filter equivalence argument (and the b / b-control discriminator tests) covers duplicate join keys with distinct subjects. It does not cover duplicate keys with the same subject: parent_key_insert_keep_min treats an equal subject as a benign duplicate and keeps the first row, so if two dim rows share a key and mint the same subject but differ in a constraint column or their next-hop FK, this admits/rejects based on whichever row the scan hit first. The generic path effectively asks "does any row with that subject satisfy the constraint", and can also fan out to multiple join partners.
Not exotic for the shape being targeted: the fixture's Product is http://ex/prod/{PRODUCT_KEY} with an IS_CURRENT column — an SCD-2 dimension where multiple versions per key mint an identical subject is the normal case.
I believe GroupKeyResolver has the same modeling gap pre-PR so this isn't newly introduced, but P3 extends it to constraint evaluation, where the divergence becomes scan-order-dependent rather than just a fan-out difference. Minimum: document it here next to the #1583 caveat. Better: decline when a level observes a same-key/same-subject pair whose passes_own or next_fk differ — the key collision is already detected.
There was a problem hiding this comment.
Agreed, and you're right that the SCD-2 case (IS_CURRENT on Product, multiple versions per key minting the same subject) is the normal case for this shape, not exotic — so scan-order-dependent constraint evaluation is a real hazard, not just a fan-out difference. I took the decline rather than only documenting it: 0797bdc2a declines when a level observes a same-key/same-subject pair whose passes_own or next_fk differ (the key collision is already detected, so it's cheap). And you're right it's a pre-existing modeling gap in GroupKeyResolver — P3 is what extends it to constraint evaluation, where the divergence turns scan-order-dependent, so declining is the conservative call for what this PR actually introduces.
| /// byte-identical to the generic chained inner join on duplicate intermediate keys. | ||
| /// The dup-ORDER_KEY differential (kept row failing, discarded dup passing) guards any | ||
| /// drift between the two. | ||
| fn semijoin_subject_sort_key(term: &RdfTerm) -> &str { |
There was a problem hiding this comment.
This PR makes canonical_join pub precisely because two copies of one invariant had drifted — and then adds a local mirror of the private subject_sort_key (fluree-db-r2rml/src/materialize/graph.rs:226), plus a third hand-rolled keep-min (if iri < *cur) in the P2a resolver build below. Three copies of the same rule, two of them carrying "these MUST agree" comments.
parent_key_insert_keep_min is already pub and is exactly this logic; subject_sort_key could be exported the same way canonical_join just was. Suggest reusing one of them and deleting both copies — a comment is the weakest available enforcement, and this file has already paid for that once.
There was a problem hiding this comment.
Fair — and a little embarrassing, given this PR makes canonical_join pub precisely because two copies had drifted, then adds a third hand-rolled keep-min below. d8ad558cd exports subject_sort_key the same way canonical_join just was and single-sources the comparator across the three sites, so a comment isn't the only thing holding them together anymore. One caveat worth stating: the value types differ (parent_key_insert_keep_min stores RdfTerm, P2a stores Vec<GKey>, the semi-join stores KeptChainRow), so it's the sort-key comparator that's shared, not a single insert fn — but that's the part that was drifting, so it's enough.
| /// byte-identical pre-bounding path). Same total either way. Single-table ref-IRI | ||
| /// GROUP BY (one order per customer → one group per customer). | ||
| #[tokio::test] | ||
| async fn p3_output_bounding_chunks_high_card_and_off_single_batch() { |
There was a problem hiding this comment.
std::env::set_var from a test, with the switch read uncached under cfg(test) specifically to make this work. Rust test threads run in parallel within one process, so setenv/getenv race here — UB at the libc level, and set_var becomes unsafe in edition 2024.
Concretely: ref_iri_group_key_high_cardinality reads FLUREE_FUSED_R2RML_OUTPUT_BOUND while this test has it set to 0. It passes today only because that test drains all batches.
Also, the comments disagree with each other — multifact_enabled says "Only the gate test toggles this var (under a lock)", and p3_multifact_switch_gates_the_branching_path says "so no lock is needed". There is no lock either way.
Suggest making the switches operator fields defaulted from env at construction (testable without touching process state), or serializing the toggling tests behind a static Mutex.
There was a problem hiding this comment.
You're right, and this is the load-bearing one — thank you. Test threads share the process, so setenv/getenv race, and it's UB regardless of how carefully one switch is guarded (and set_var goes unsafe in edition 2024). 59d71e23a makes the four switches this PR owns (FLUREE_FUSED_VECTOR_FOLD, _OUTPUT_BOUND, _MULTIFACT, FLUREE_ARROW_DIRECT_DECODE) operator fields defaulted from env at construction, so the tests set a field and touch no process state — no lock, no cfg(test) uncached read. The same defect shows up in #1589 (its GEN_ENV_LOCK band-aid over only _MULTIFACT_GEN); that PR converts _MULTIFACT_GEN and drops the lock, so the stack lands the fix coherently rather than in half-measures. Also fixed the two comments that contradicted each other on whether a lock existed.
| ) { | ||
| hashbrown::hash_table::Entry::Occupied(o) => o.get().1, | ||
| hashbrown::hash_table::Entry::Vacant(v) => { | ||
| let id = group_accs.len() as u32; |
There was a problem hiding this comment.
group_accs.len() as u32 wraps silently past 4B groups and would corrupt accumulators rather than fail. The memory budget normally trips first, but it isn't set on every path — a debug_assert! or an explicit check here is free.
There was a problem hiding this comment.
Good cheap insurance — e5a56a51a adds a checked cast so group_accs.len() past u32::MAX fails loudly instead of wrapping and corrupting accumulators. Agreed the memory budget usually trips first, but it isn't set on every path, so the explicit check is worth the zero cost.
| /// refuse when the loadTable cache is disabled (pinning is then a no-op) or when | ||
| /// a table yielded a second distinct `metadata_location` mid-build (the source | ||
| /// committed and the twin's stamped watermark would not describe its contents). | ||
| fn verify_build_snapshot_integrity( |
There was a problem hiding this comment.
Result<(), String> on a public trait method conflicts with the project's stated error convention (thiserror, structured per-crate enums, not stringly errors). Both call sites immediately wrap the String back into R2rmlError::Materialization, so the type isn't buying anything.
Separately: this turns FLUREE_ICEBERG_LOADTABLE_CACHE=0 into a hard materialize failure. That's a user-visible behavior change and only docs/cli/materialize.md got updated — docs/operations/configuration.md documents that env var and should mention the new refusal.
There was a problem hiding this comment.
Agreed on both. 0db38cbec gives verify_build_snapshot_integrity a typed per-crate error instead of Result<(), String> — both call sites were just re-wrapping the String into R2rmlError::Materialization, so the type wasn't buying anything. And you're right that turning FLUREE_ICEBERG_LOADTABLE_CACHE=0 into a hard materialize failure is a user-visible change that only docs/cli/materialize.md had captured — I added the refusal to docs/operations/configuration.md in the same commit.
| let fluree: &'static Fluree = Box::leak(Box::new(context::build_fluree(dirs)?)); | ||
| let provider = Arc::new(FlureeR2rmlProvider::new(fluree)); | ||
|
|
||
| // CRITICAL-1 (#1529 review): a failed parity gate drops the WHOLE ledger NAME |
There was a problem hiding this comment.
This fixes the symptom rather than the cause. The actual hazard is that a failed parity gate performs a name-scoped DropMode::Hard across every branch. Refusing to build when the name has a live non-target branch closes it for the CLI, but the destructive drop stays unchanged and unguarded for anyone driving the API directly.
Scoping the drop to the branch the build created would make this guard belt-and-braces instead of the only thing between a user and losing unrelated branches. If that's out of scope here, worth a tracked issue linked from this comment.
There was a problem hiding this comment.
You've put your finger on the real hazard, and I want to be honest that this commit doesn't fully close it. The CLI-level up-front refusal (blocking_existing_branch, cli/materialize.rs:118-142) closes it for the CLI, but the destructive name-scoped DropMode::Hard — dropping every branch of the ledger name on a failed parity gate — is unchanged and still unguarded for anyone driving the API directly. Scoping the drop to the branch the build created is the right belt-and-braces fix, but it's more than this review's scope, so I took the tracked-issue option you offered: e9a1592b2 links #1592 from the comment. The CLI is the only driver today, so it's non-blocking now — but #1592 keeps the API-direct hazard from getting lost.
| let mut ambiguous_this_batch: Vec<Vec<String>> = Vec::new(); | ||
| { | ||
| let entry = self.index.entry(tm.iri.clone()).or_default(); | ||
| // MAJOR-4 (#1529 review): create each canonical col-set's map ONCE (one |
There was a problem hiding this comment.
Pre-creating every col-set's map means a col-set that never yields a key now leaves an empty map where previously there was no entry. Worth confirming no downstream get / contains_key distinguishes "absent" from "present but empty" — the perf win is right, this is just the one behavioral edge it introduces.
There was a problem hiding this comment.
Good edge to flag. I checked the downstream get/contains_key sites and none distinguish "absent" from "present but empty" — a col-set that never yields a key just leaves an empty map that reads the same as a miss. 88ee9a6a4 notes it's safe-by-construction next to the change so the reasoning is on the record; the perf win stands.
| /// restores the byte-identical two-hop `arrow_column_to_values` + | ||
| /// `build_columns_from_values` path. Read once per process (`OnceLock`, the family | ||
| /// idiom): set it at startup, not per query. | ||
| fn direct_decode_enabled() -> bool { |
There was a problem hiding this comment.
This hand-rolls the env parsing that env_switch_enabled does for the other three switches. Different crate so there's no direct reuse, but the family is now four switches with one odd one out — a small shared helper (or moving the parser somewhere both crates can see) would keep them from drifting on the next accepted-value tweak.
There was a problem hiding this comment.
Agreed — four switches with one odd one out is exactly how they drift on the next accepted-value tweak. Different crate, so there's no direct reuse of env_switch_enabled, but 94c097a55 adds a crate-local equivalent in fluree-db-iceberg so the arrow-decode switch parses the same way as the other three.
| /// Arrow direct decoder ([`crate::io::arrow_reader::arrow_column_to_column`]) can | ||
| /// reuse the EXACT same `ColumnValue` -> `Column` mapping for its cross-type | ||
| /// fallback — this keeps the direct decode path byte-identical to the two-hop path. | ||
| pub fn column_from_values(values: &[Option<ColumnValue>], field_type: &FieldType) -> Column { |
There was a problem hiding this comment.
Good extraction — this is the right way to keep the direct path from diverging. Minor: now that all the per-field work lives here and this is infallible, build_columns_from_values above still returns Result though it can no longer fail. Worth dropping the Result while the callers are being touched anyway.
There was a problem hiding this comment.
Agreed, good cleanup while the callers are already being touched. After the extraction build_columns_from_values only wraps an infallible column_from_values in Ok(...), so 8eeb80126 drops the Result. The two in-repo callers used ?; I confirmed no out-of-crate callers rely on the Result before changing the pub signature.
…rops dangling FKs (review id=3717339897) An ungrouped aggregate over a RefObjectMap object var (`?o :ref ?c` with no GROUP BY) reached the P2a admission arm and was admitted on FK-non-null validity alone. A group_resolver — whose per-row parent probe drops a present-but-dangling FK — is built ONLY for a RefObjectMap GROUP BY key, so the ungrouped shape folded in dangling FKs the generic inner join drops (over-count; the manifest count shortcut inherited it). Decline the fuse unless the ref object var is the admitted GROUP BY key. Adds the ungrouped P2a fixture the grouped tests all lacked.
…view id=3717398030) build_semi_join_membership projects only join/subject/constraint/next-FK columns and never consults a chain pattern's star_bindings, so a var-object member other than the next-hop FK (e.g. `?c :segment "Enterprise" ; :region ?r`) imposes a BGP existence requirement the membership build silently drops — over-admitting the root FK. Decline the fuse when any chain pattern carries a star_binding var that is not a branch join var (the only star_binding it may carry is its next-hop FK). Also covers the K>=2 cross-branch shared-var correlation case. Fixture uses the real two-forms representation (segment in star_constraints because the subject now carries the ?r var-object member).
…review id=3717339904) Two semi-join dim rows sharing the join key that mint the same subject but disagree on the constraint result (passes_own) or the next-hop FK are the normal SCD-2 case. keep-min discriminates only by subject, so it kept whichever row the scan hit first — a scan-order-dependent answer. Decline to the generic chained join (which materializes every version). The collision is already detected at the Occupied entry, so the check is nearly free. Documents it next to the #1583 fan-out caveat.
…review id=3717339907) Export subject_sort_key from fluree-db-r2rml (as canonical_join was) and reuse it at the P3 semi-join keep-min site, deleting the local semijoin_subject_sort_key mirror and its fragile 'MUST agree' comment. The P2a Vec<GKey> keep-min operates on already-extracted pure-IRI strings (a different value type), so it shares the comparator by construction — documented inline — since subject_sort_key on an RdfTerm::Iri is that same inner-string ordering. Removes the drift risk the two independent RdfTerm sort keys carried.
…ng (review id=3717339912) The back-pop drain reverses group order relative to the switch-off single-batch path; spell out that a bare LIMIT with no ORDER BY can therefore return a different prefix on vs off — permitted, since SPARQL leaves unsorted row order unspecified.
group_accs.len() as u32 would silently wrap past u32::MAX groups and corrupt accumulators. The memory-budget checkpoint normally trips far earlier but is not set on every caller/fixture path; add a debug_assert plus a checked try_from.
…layer, not a vacuous enum field (review id=3717339914) CheckOutcome::Mismatch always set note: Some(COUNT_MULTISET_NOTE) — a vacuous Option that also broke the public enum's derived PartialEq (forcing downstream matchers to spell the field). Drop the field; render the caveat in the CLI reporting layer (format_failures) for count:* mismatches only. Restores the it_graph_source_r2rml matcher to a clean assert_eq!.
…iew id=3717339915)
The cfg(test) poison-hang test built fluree-c2-test-{pid} with no per-run
suffix; apply the same VERIFY_DIR_SEQ atomic-suffix pattern the production
verify spool dir uses, so repeats/parallel runs never share a dir.
…c the refusal (review id=3717339918) The trait returned Result<(), String> and both call sites immediately wrapped the string back into a structured error — the stringly type bought nothing against the repo's thiserror convention. Add R2rmlError::BuildSnapshotIntegrity, return it from the trait + Iceberg override, and drop the string-wrap at both materialize call sites. Also document the FLUREE_ICEBERG_LOADTABLE_CACHE=0 materialize refusal in configuration.md (only cli/materialize.md had it).
… (review id=3717339921) MAJOR-4 leaves a present-but-empty inner map where the old per-row code left it absent; document that no consumer distinguishes empty from absent (resolve's chained ?.get(key), merge_from's extend, estimated_bytes all behave identically).
…from_values (review id=3717339925) After column_from_values was extracted (infallible), build_columns_from_values only wrapped it in Ok(...). Return Vec<Column> directly and drop the ? at the two in-crate call sites (no out-of-crate callers).
… drop (review id=3717339919) The gate-fail drop is name-scoped (DropMode::Hard hits every branch); the CLI is guarded up front by blocking_existing_branch, but a branch-scoped HARD purge for belt-and-braces (API drivers) does not exist today (drop_ledger is name-only, drop_branch is record-only). Filed #1592 and linked it from the comment.
…) env reads (review id=3717339910) output_bound_enabled/multifact_enabled read env UNCACHED under cfg(test) and the tests toggled process env with std::env::set_var/remove_var — concurrent setenv/getenv across parallel test threads is libc-level UB (set_var is unsafe in edition 2024). Make FLUREE_FUSED_VECTOR_FOLD/_OUTPUT_BOUND/_MULTIFACT operator fields defaulted from env at construction; delete the three switch functions; tests set the field instead of process env. Leaves the pattern extensible for #1589's _MULTIFACT_GEN (Phase 2) without touching it here.
…e switch (review id=3717339924) direct_decode_enabled hand-rolled the exact 0/false/off/no falsy-spelling match that fluree-db-query's env_switch_enabled performs. The crates can't share the symbol (fluree-db-query depends on fluree-db-iceberg, not the reverse), so add a crate-local env_switch_enabled twin once and call it from direct_decode_enabled. Keeps the OnceLock (this is a decode function, not a query operator — no operator-field conversion applies, and the OnceLock has no cfg(test)/set_var UB).
…n.md (review id=3717398050) Add FLUREE_FUSED_VECTOR_FOLD / _OUTPUT_BOUND / _MULTIFACT / FLUREE_ARROW_DIRECT_DECODE to the operator switch inventory and the Iceberg/R2RML tuning table, with each switch's kill-scope and read-timing (the three fused switches are read at operator construction per the id=3717339910 field refactor). FLUREE_FUSED_R2RML_MULTIFACT_GEN is left for #1589 (Phase 2).
…sed_mut) The B2 and SCD-2 decline tests call resolve_branching_star_at_open (&self) and never mutate the operator, so `let op` suffices.
…eview id=3717398030 refix) The prior B2 guard (46534f6) only inspected a semi-join chain pattern's star_bindings, but the rewrite's subject-star fold puts the FIRST var-object member in object_var and only ADDITIONAL members in star_bindings. The flagged single-member shape `?c :segment "Enterprise" ; :region ?r` is therefore emitted object_var=Some(?r)/star_bindings=[], so the guard was silent and the null-region customer was still over-admitted; the old hand-built fixture used star_bindings=[region] (a 2nd+-member-only shape) so it passed vacuously. Guard now declines when a chain pattern's object_var OR any star_binding is a non-join var — but NOT when object_var IS the next-hop FK (the rewrite folds a SOLE FK member into object_var too, so declining that would OVER-decline and break the clean crt fuse). The join_vars set is the discriminator; also closes the object_var cross-branch correlation case. Declines before the chain-constraint gather/projection, so neither needs object_var handling. Tests are generated THROUGH the actual rewrite (crt_rewritten) so members land in the real fields by construction, verified both directions: the leaf ?region shape DECLINES (RED on the old star_bindings-only guard, GREEN now) and the clean crt interior FK (folded into object_var, a join var) still FUSES (over-decline guard). Plus a fidelity-pin unit test on the emission.
…48c07a) Brings in Phase-1 blocking fixes from perf/fused-vectorized-fold, including the var-object semi-join decline (review id=3717398030) that fixes #1589's own blocking bug on the shared build_semi_join_membership, and the operator-field env-switch pattern. # Conflicts: # fluree-db-query/src/r2rml/fused_aggregate.rs
…d + configuration.md (review id=3717398050) Phase 1 (#1582) added the other four fused switches to both operator-facing switch inventories; the #1589-only MULTIFACT_GEN generality switch was missing from both. Add its row (gates ONLY the S1 K>=2 / S2 >=2-ref widening; OFF is byte-identical to #1582) and update the SWITCHES.md construction-field note to list it as the fourth construction-time operator-field fused switch.
…ctional fuse tests (review id=3717398038) crt_patterns/s1_patterns's segment_star / seg_star / dept_star = true arms hand-built star_constraints on a semi-join TERMINAL with an empty object_var AND empty star_bindings, a shape the rewrite never emits: the two-forms rule folds a const-object into star_constraints ONLY when a var-object member is present, and the SOLE var member lands in object_var, not star_bindings (pinned by rewrite_emits_single_var_member_semijoin_terminal_as_object_var). The three fuse tests over that shape (p3_crt_join_reorder_semijoin_constraint_star_constraints_form, s1_k2_semijoin_both_constraint_forms, s1_k2_semijoin_mixed_constraint_forms) asserted a fiction. Remove the toggle params (the fixtures always emit the emittable standalone const-object form) and delete the three tests. The REAL object_var representation and its decline/over-decline are covered by the #1582 refix's crt_rewritten (generate-through-rewrite) + p3_semijoin_chain_var_object_member_declines + p3_semijoin_interior_fk_in_object_var_still_fuses. The folded star_constraints READ path is covered by the product group-key branch (isCurrent=true drops OL5) via the shared resolve_star_constraint_checks, plus its direct unit tests (e2_resolve_star_constraint_checks_scalar_vs_ref). Removal loses no coverage.
…t the microbench s2_gen_switch_gates_only_the_widening built its one-ref 'still fuses' case from s2_two_ref_plan with group_by=[?c] but left productRef->?p in the fact's star_bindings. Post-B1 (id=3717339897) an un-grouped ref binding gets no resolver, so its dangling FKs can't be dropped and fusing would over-count — so that shape now correctly DECLINES (which is what the two_off assertion covers). The single-ref fuse assertion must use a genuine single-ref plan; strip the second, un-grouped ref before asserting is_some(). Surfaced only at the re-merged #1589 head — the per-task gates didn't run the full r2rml lib suite after the restack onto the corrected #1582 head. Also rustfmt the fk_probe_alloc microbench eprintln reflow (fmt --check).
|
Thanks for the thorough pass, @bplatz — genuinely good review, and two of the notes were real correctness findings rather than nits. Quick summary of what landed: The blocking one ( The load-bearing maintainability item was the Two honest notes so the record's straight: (1) the tmp-dir collision ( Re-requesting review when you have a moment — replies inline on each thread. |
main moved 114 commits ahead (incl. #1422 iceberg-materialize and #1591 import-fd-budget, both overlapping this PR's materialize domain). Two files conflicted, both in fluree-db-r2rml/src/materialize/: - graph.rs (emit_batch): #1422 refactored the inline per-row emit loop into emit_row / emit_row_terms behind a TmEmitContext; this PR had optimized the same inline loop (MAJOR-4: batched per-POM local_ref_edges fold for constant predicates). Took main's emit_row refactor verbatim — it is the go-forward structure the rest of #1422 depends on, and it is behavior-identical (the per-edge vs batched ref_edges counting yields the same totals). This DROPS MAJOR-4's constant-predicate allocation optimization on the bulk-materialize path; it is tangential to this PR's fused-aggregate QUERY-path core and can be re-applied inside emit_row_terms (a scratch-buffer param) as a follow-up if the materialize bulk-emit path perf warrants it. - mod.rs (pub use graph::{…}): union re-export — canonical_join + subject_sort_key (this PR, reused by the fused query path) plus emit_row + emit_row_terms + TmEmitContext (#1422). Verified on the merged tree: cargo check --all-targets (workspace) = clean; cargo fmt --all --check = clean; cargo clippy --all --all-features --all-targets -- -D warnings = clean; nextest seam crates (fluree-db-r2rml, fluree-db-query, --all-features) = green.
Brings the #1582 <-> main reconciliation (6b8b3c8) into #1589. One conflict, fluree-db-r2rml/src/materialize/mod.rs: the ColumnBatch term re-export — #1589 added fill_join_key_from_batch (#46 borrowed-scratch probe), main added batch_has_column / column_is_orderable / column_sort_key / column_string / materialize_graph_from_batch. Resolved to the union (all defined in term.rs). graph.rs auto-merged to #1582's already-reconciled emit_row form. Verified on the merged tree: fmt --all --check (main + testsuite-sparql) clean; clippy --all --all-features --all-targets -D warnings clean; nextest r2rml+query --all-features green (1609 passed).
…in branches Widen the #1582 branching-star fused aggregate beyond its exactly-one-of-each cut to admit ONE group-key branch plus K≥2 SEMI-JOIN branches (the multi-filter BI shape: e.g. tickets by product category where customer='Enterprise' AND agent.department='Support'). The typed JoinBranch list already carried any K; this makes the resolver and fold additive over it: - decompose_branching_star: admit {exactly 1 group-key, ≥1 semi-join}. K=1 is #1582's crt_join_reorder class (always admitted); K≥2 is gated behind the new FLUREE_FUSED_R2RML_MULTIFACT_GEN switch, so an OFF run declines a K≥2 star to the generic pipeline byte-identically to #1582 (the #1582 switches remain independently killable underneath). - Resolved.semi_join: Option<SemiJoinSet> -> semi_joins: Vec<SemiJoinSet>; one membership set per semi-join branch. resolve_branching_star_at_open builds all of them (keep-min-then-filter each) and strips every semi-join branch's root FK var; the fold ANDs the probes (row survives iff a member of EVERY set) via the new row_passes_semi_joins helper. K sets compose exactly as K chained inner joins; #1583 (each FK single-valued) applies per set. Differentials (fused == generic inner join): K=2 value-identity integer + exact-i128 decimal; both const-object constraint forms at both semi-join sites (the 6x over-count regression class, now guarded at the 2nd site); keep-min-then- filter EXCLUDES + control INCLUDES on the NEW agent branch (discarded-dup soundness); decompose recognition; GEN switch gates only the widening (K=1 still admits with GEN off).
What & why
Gap-4 program, P1 — the fused-tail fix (the first gated PR family from the adjudicated slate). The external-engine A/B measured the fused R2RML/Iceberg aggregate family 6–52× behind DuckDB at scale, and a co-resident CPU profile spike (P0) settled where that time goes. On the genuinely-fused pairs (cq014, cq027) RDF term-minting is 0.0% of on-CPU wall — the fused fold never mints — refuting "late materialization is the cure." The tail is two costs, co-primary:
(For contrast, the shapes that decline the fuse — cq038, crt_highcard — are 58–83% minting; that is an admission/coverage problem, out of scope here.)
This PR attacks exactly those two costs, corridor-only (r2rml/iceberg), each behind a default-on kill switch whose OFF path is byte-identical to today.
Mechanisms
N1 — vectorized fused-aggregate fold (
fluree-db-query/src/r2rml/fused_aggregate.rs). The GROUP BY fold allocated a freshVec<GKey>and cloned each string key every row, then hashed aVec<GKey>through SipHash into aHashMap<Vec<GKey>, Vec<Acc>>— on cq027 that is 2MStringclones + 1M SipHashes to map 1M rows onto 18 groups (GroupCol::key_at14.4% + SipHash 7.5%, P0). New path: build the composite key borrowed (GKeyRef, no per-rowStringclone /Vecalloc) into a reused scratch, hash withFxHasher, and intern it to a dense id in ahashbrown::HashTable<(Vec<GKey>, u32)>; the owned key is materialized only when a new group is inserted. Typed accumulators live ingroup_accs[id].HashTable(notHashMap+insert_hashed_nocheck) is deliberate: the borrowed probe and the resize-rehash go through the SAME hash function (hash_key_refs/gkeys_hash, kept in lockstep), so a table grow can never re-bucket a key away from its probe. (An earlierHashMap+insert_hashed_nocheckdraft did split groups on resize — the live A/B differential caught it before commit; the grouping test is now hardened to force grows.)Preserved exactly: the exact-arithmetic domain (
Dec{i128,scale}→BigDecimalon overflow, unchangedaccumulate_*/Acc), every fold semantic, the memory-budget group-growth checkpoint, and the whole decline/fallback surface (admission untouched). f64SUMstays bit-identical because each group's rows fold in the same row order under both paths.N2 — direct Arrow→Column decode (
fluree-db-iceberg/src/io/{arrow_reader,parquet}.rs). Decode was a two-hop copy: Arrow array →Vec<Option<ColumnValue>>(arrow_column_to_values) →Column'sVec<Option<T>>(build_columns_from_values) — a full intermediate allocation per column, and twoStringallocations per string cell. Newarrow_column_to_columnbuilds theColumndirectly from the Arrow array (one hop; one string alloc). Its fast arms cover only the case where the Arrow physical type matches the field type — each provably value-identical to the old composition — and every other (cross-type coercion, timestamp unit-scaling, unhandled type, schema-evolution-absent column) falls back to the exact old mapping via the extractedcolumn_from_values. So behavior is unchanged everywhere; only the hot common path is shortened.Switch inventory (both default ON; OFF = byte-identical old path)
FLUREE_FUSED_VECTOR_FOLD— N1. Off restores the owned-keyHashMap<Vec<GKey>, Vec<Acc>>fold.FLUREE_ARROW_DIRECT_DECODE— N2. Off restores the two-hoparrow_column_to_values+build_columns_from_valuespath.Gates
direct_decode_matches_two_hop— assertsarrow_column_to_column== the two-hop path (Debug-equal) across every fast type + nulls + NaN + cross-type fallbacks.key_ref_at_matches_key_at— the borrowed key read equals the owned read for every Column kind, null, out-of-bounds, wrong-type, and the NUMBER(n,0) physical-Decimal integer coercion (None⟺GKey::Null).vector_fold_grouping_matches_owned_map— the dense dict partitions + counts a key sequence identically to the owned-key map.fluree-db-query,fluree-db-iceberg). clippy--all-targets --no-depsdiff-clean on both crates (no new warnings introduced by this change).fluree-db-query,fluree-db-iceberg --all-features,fluree-db-api(featureless + iceberg) — all green.Live yardstick (Substrate B, SF0.1, warm; same binary, old switches OFF vs new ON)
Median of 7 warm reps, fresh process/rep, local MinIO+REST fixture (macOS, co-resident host — absolute ms are noisier than the EC2 Wave-C rows and not host-comparable to them; the OFF→ON ratio on one binary is the acceptance evidence). DuckDB column is the EC2 Wave-C SF0.1 number for context only.
Results are byte-identical (sorted) between OFF and ON on every pair — kill-criterion-1 satisfied. The movers are the single-table fused GROUP BYs the P0 profile fingered (cq014, cq027). cq008 is join-resolution-dominated (its fold/decode are a small share, so ~flat); crt_minmax uses a different fast path; crt_highcard declines to the generic path (no movement by design — see below). An earlier draft that split groups on table resize was caught by this very differential and fixed before commit.
Why crt_highcard does NOT move here (expected, by design)
crt_highcard(GROUP BY ?cwhere?c = edw:customer) declines the fuse — its group key is aRefObjectMap/IRI, andscalar_column_for_varadmits onlyObjectMap::Column— so it runs the generic per-rowmaterialize_batchpath. The P0 profile confirms it is a minting shape (term-mint 58.2%, viaexpand_template_from_batch+ regex), not a fold/decode shape, so P1 correctly shows ~no movement on it (its small decode-seam share, 3.6%, is all N2 can touch). It becomes a mover only after admission widening (P2 / N3): admit aRefObjectMapgroup key by folding on the FK column value and minting the group-key IRI once per group at output — i.e. this PR's dict + late-materialize-only-on-emit substrate extended to IRI keys. That is the designed follow-up; it is deliberately not built here.Scope / non-goals
Corridor-only: the engine-wide
hash_join.rs/group_aggregate.rs(native, Binding-based) are untouched, so native legs are byte-identical for the mechanical reason they never enter this path. Minting on the un-fused shapes (cq038/crt_highcard) is the next program step (admission widening, N3), not this PR. MIN/MAX is a separate fast path, not this fold.2026-08-03 addendum — scope expansion: post-merge #1529 review fixes + main merge-up
This branch merged current
main(96370dd10, post-#1554/#1529 — conflict-free; the P1 value-identity differentials re-proven at the merged head since family-C's widened admission now feeds the vectorized fold). It then became the fix vehicle for a high-rigor post-merge review of #1529 (the findings arrived after that PR merged; per the maintainers' consolidation preference they land here rather than in a new PR). Every finding was independently re-verified against the merged tree before fixing — all eight substantive findings CONFIRMED:--into existing:branch+ failed gate purged every branch)6a5403ff6)fade7a0ae)--verify fullfalse-rejected every twin with anxsd:floatcolumn (export writer hardcodedxsd:double)c83c67bc6); durable single-renderer restructure trackedcanonical_joinshared from fluree-db-r2rml into both operator sites + a disagreeing-name-order composite test (757a54868)metadata_locationobserved for a table fails the build; cache-off refuses (2d1a1d407)metadata/child (2d1a1d407)index_batch(b6387a6a6)b6387a6a6)Cheap minors folded in the same commit (dupParentKeys malformed-payload warn, verify-spool dir suffix, corrected drop instructions and
0 = autodoc line,ImportConfig#[non_exhaustive]); the remaining review minors are enumerated as explicitly-deferred in the audit record. Phase B of this PR (the named-gap perf items: IRI group-key admission and the bounded multi-fact columnar join) follows on this same branch.2026-08-04 — Phase B COMPLETE (named-gap perf items)
Phase B lands the two named-gap perf items plus a shared output-bounding mechanism on this branch, each gated + differential-verified, corridor-only (r2rml/iceberg). Live numbers are Substrate B (SF0.1, local MinIO + Iceberg REST, macOS co-resident host,
/usr/bin/time -lpeak RSS, fresh process per cold rep, timing boundary = query_exec_serialize); the DuckDB column is the same-host local yardstick (~/bin/duckdb, arch -arm64). Load stayed ~5 throughout.P2a — high-cardinality RefObjectMap (IRI) GROUP BY fusion — DONE (
537a18613). AGROUP BY ?con a referenced parent IRI (crt_highcard) now fuses: the FK→IRI resolver is built by scanning the parent dim once (deterministic keep-min on a duplicate parent key, byte-identical tobuild_parent_lookup), the fold runs through the existing Dim group-key machinery + the N1 dict, and the key emits as an IRI term (GKind::Iri). Hermetic tests: value-identity + dangling-FK drop, keep-min on a duplicate parent key, ~100k-group cardinality (now drained across multiple output batches). Gated byFLUREE_FUSED_R2RML_AGG_JOIN; off byte-identical.P3 — bounded multi-fact branching-star join (crt_join_reorder class) — DONE (
de0f2b921scaffolding,82ff82940soundness core,59c4f06b7const-object fix). A fact root that branches to one GROUP-KEY dim chain AND one SEMI-JOIN dim chain — crt_join_reorder = FactOrderLine → {edw:order→FactOrder→edw:customer[segment=Enterprise]} + {edw:product→DimProduct[isCurrent]→category},SUM(quantity) GROUP BY category— now FUSES instead of declining (the 917×/DNF gap). The GROUP-KEY branch resolves through the shared linear-chain resolver (resolve_linear_chain_at_open, extracted fromresolve_join_at_open, byte-identical on the pure-linear path) with the SEMI-JOIN FK stripped from the fact's required objects. The SEMI-JOIN branch resolves to a KEEP-MIN-THEN-FILTER membership set: each hop resolves to the keep-min parent subject (byte-identical toparent_key_insert_keep_min), THEN the kept row is filtered — so on a duplicate intermediate key it tests the keep-min row, matching the generic chained inner join (filter-then-union would wrongly admit a key whose keep-min row fails but a discarded duplicate passes). Constraint gathering is an OR over BOTH rewrite forms — foldedstar_constraintsAND the standalone const-object (predicate_filter+object_constant) the rewrite emits for a subject with no var-object member — declining if a constraint can't resolve to a scalar column. The membership build is budget-charged (record_alloc+checkpoint) → typedMemoryBudgetExceeded(507) before OOM. Gated byFLUREE_FUSED_R2RML_MULTIFACT(default on; off = pre-P3 byte-identical decline).P3 live (Substrate B, SF0.1, same-host before/after, N=5 cold): crt_join_reorder goes from the DNF/decline class to fused — wall ~83,000 → ~1,020 ms (~81×), peak RSS ~1.4 GB → ~260 MB (~5.4×), result EXACT-matches DuckDB (10 rows; DuckDB same-host ~250 ms). "Before" = the current-main baseline binary, which declines and materializes the 4-table join at ~83 s / 1.2–1.4 GB. Hermetic differentials (mock-provider
open()/next_batch()): value-identity (integer + exact-decimal i128 SUM), the dup-ORDER_KEY keep-min-then-filter discriminator plus a subject-swapped control (proving keep-min — not "any duplicate" — decides), built so a filter-then-union implementation FAILS it; budget-exceeded typed fail; switch-off decline; and both constraint forms.Output-bounding — DONE (
5bd3d52dc). A high-cardinality fused GROUP BY materialized its entire output in onenext_batchbatch; output-bounding drains the finalized rollup in bounded chunks (OUTPUT_BOUND_ROWS= 8192 per call, popped from the back so each group's key + accumulators are freed as it is finalized), one mechanism shared by the single-table fold, the fact-dim join, and the P3 branching-star join (they all reach the same emission). Gated byFLUREE_FUSED_R2RML_OUTPUT_BOUND(default on; off = single-batch, byte-identical — same rows, dict/map order). Hermetic: a >8192-group rollup emits multiple ≤8192-row batches whose union is the full result (on) vs one batch (off), same total; the 100k-group cardinality test now drains all batches.Output-bounding as an attribution experiment — correcting the P2a residual hypothesis. The earlier P2a yardstick attributed crt_highcard's ~1.1 GB residual to the 259k-row grouped output materialization (serialize +
ORDER BY). The output-bounding ON/OFF flip is the cleanest attribution experiment the program has run, and it REFUTES that hypothesis: a switch that removes the full output materialization moves NOTHING — crt_highcard ON 1139–1432 / OFF 1140–1149 MB, wall ~1410 ms both, 259,418 rows EXACT (DuckDB same-host ~350 ms / 138 MB). So the residual is not output-bound; it lives in the scan + 259k-group accumulator/resolver state — the peak is reached before emission, and a downstreamORDER BYSort re-collects every row regardless of how the operator batches its output. This re-points the next RSS lever at the Gap-3 columnar accumulator-state work (compact / columnar accumulators, SYNTHESIS N1), now filed — a better-targeted follow-up than an output-materialization drop would have been, with an experiment behind it rather than an assumption. Output-bounding is kept on its own merits: correct, gated (off = byte-identical), hermetic chunking proof, no regression on the shared fold+join output path, and it does bound output-heavy shapes that lack a blocking Sort and aidLIMITearly-termination — it is simply not the crt_highcard RSS lever.Regression / yardstick columns (Substrate B, SF0.1, N=5 cold, fused ON)
No regression on the existing fused pairs: cq027/cq014/cq008 are unchanged (P3 only adds the branching-star arm; output-bounding is off-byte-identical and these fit one batch), and crt_join_reorder was re-run on the output-bounding binary (which touches the shared emission) to confirm it stays ~1,020 ms and EXACT.
Honesty notes (reviewer's non-blocking items + the fixture-fidelity lesson)
star_constraints, but the rewrite emits it as a standalone const-object pattern, so the semi-join applied no filter and admitted every order. The live DuckDB oracle caught it (fused Apparel 325,586 vs 54,606). Fix: the OR-gatherer handles both forms, and the fixtures now use the real const-object representation (would have caught it). Hand-built fixtures must match the rewrite's actual emission shape.Acc::Exactfinalize the fold uses, pinning the i128 → BigDecimal path bit-for-bit.FLUREE_FUSED_R2RML_MULTIFACTand_OUTPUT_BOUNDread uncached under#[cfg(test)]; resolver tests call the resolver methods directly (no env), and only the gate tests toggle env.Follow-ups (final state)