Skip to content

perf(r2rml): multi-fact fused-join generality (K≥2 semi-joins, multi ref group keys) - #1589

Merged
aaj3f merged 16 commits into
mainfrom
perf/multifact-generality
Aug 11, 2026
Merged

aaj3f merged 16 commits into
mainfrom
perf/multifact-generality

Conversation

@aaj3f

@aaj3f aaj3f commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Multi-fact fused-join generality (Unit 1 of the DuckDB-cold-parity program)

Generalizes the #1582 branching-star fused aggregate beyond its exactly-one-of-each cut. The bar (maintainer directive): wherever DuckDB satisfies a common enterprise join-aggregate COLD, un-materialized, in tolerable time/memory, the virtual path must too. #1582 fused exactly {one group-key branch, one semi-join branch} (the crt_join_reorder class); everything one step beyond that shape DNF'd. This widens the admission additively over the typed JoinBranch list.

Stacked on perf/fused-vectorized-fold (#1582); base auto-retargets to main when #1582 merges.

Review: CLEAN — no blocking findings (audit-2026-07/gap4-adjudication/REVIEW-1589.md); three coverage-gap pins added in 683bc893b (mixed const-forms, fact-column interleave, same-table semi-branches).

Switch table

Switch Default Off effect
FLUREE_FUSED_R2RML_AGG / _AGG_JOIN on #1582 — disables the fused aggregate / its join path wholesale
FLUREE_FUSED_R2RML_MULTIFACT on #1582 — disables the branching (multi-fact) path wholesale
FLUREE_FUSED_R2RML_MULTIFACT_GEN on NEW — declines ONLY the generality increment: K≥2 semi-join branches (S1) and ≥2 ref-IRI group keys (S2). With it off, behavior is byte-identical to #1582 (K=1 / 1-ref still fuse).

The umbrella rides ON TOP of the #1582 switches, which remain independently killable underneath — turning either of those off declines the whole family regardless of the umbrella. The umbrella gates only the widening, so an OFF run reproduces #1582 exactly.

S1 — K≥2 semi-join branches (LANDED)

The multi-filter BI shape: a fact with one group-key branch and multiple pure-membership (semi-join) branches — "tickets by product category where customer='Enterprise' AND agent.department='Support'".

Why FactSupportTicket, not FactOrderLine: the illustrative example is order-lines, but FactOrderLine has only two FKs (order, product), and a supplier branch there would have to hang off product — colliding with the product group-key branch (branches must be disjoint). FactSupportTicket (customer, product, agent) is the only ≥3-FK fact in the SF01 schema and is the better enterprise exemplar (a support-ops rollup with two population filters).

Differentials (fused == generic inner join, in the rewrite's real representation): K=2 value-identity integer + exact-i128 decimal (covers Acc::Exact in the K≥2 shape); both const-object constraint forms at both semi-join sites (the 6× 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; the GEN switch gates only the widening.

S2 — Multiple ref-IRI group keys (LANDED)

GROUP BY two+ referenced-entity IRIs (e.g. events by customer AND product) — a single-table fold over a fact whose group keys are FKs to different dims.

  • Resolved.group_resolver: Option<GroupKeyResolver> → group_resolvers: Vec<GroupKeyResolver>, indexed by KeySource::Dim.resolver; KeySource::Dim(slot) → Dim { resolver, slot }. The join path pushes exactly one resolver (the terminal dim's map, resolver: 0) — the Vec model with N=1, no behavior change. S2's single-table path builds one FK→IRI resolver per ref key, each probed by its own FK.
  • The fold hot loop probes EVERY resolver by its own FK into a reused per-batch dim_probes scratch (no per-row alloc); a miss on ANY drops the row — the AND of K independent inner-join existence tests. Keep-min on a duplicate parent join key is unchanged from P2a, applied per resolver.
  • resolve_at_open lifts the ≥2-ref decline (P2a's follow-on scope) behind the umbrella: OFF declines the 2nd ref key exactly as P2a did (byte-identical); ON admits it.

Differentials: two-ref value-identity integer + exact-i128 decimal (Acc::Exact under a composite IRI key); dangling FK on EITHER key drops (inner join); keep-min on the SECOND resolver (distinct subjects, smaller wins); the GEN switch gates only the widening (one ref key still fuses with GEN off). The assemble_group_key unit test is migrated to the multi-resolver dim_probes form.

S3 — Row-returning multi-fact joins (DESIGN ONLY — recommended as its own unit)

The sized design for S3 (a row-returning, non-aggregate multi-fact virtual join — a
corridor-architecture item, not an admission-widening of this fold operator) has moved
out of this PR body to a standalone design doc: docs/design/virtual-multifact-row-corridor.md (linked from docs/SUMMARY.md). S1 + S2 alone meet this unit's bar; S3's implementation is explicitly out of #1589's scope.

Decline-completeness

Everything not admitted still declines cleanly (Ok(None) → the generic materialize pipeline), preserving the #1582/P2a discipline — no shape is silently mis-answered. Residual decline set (unchanged from #1582/P2a except where noted):

Branching-star (S1): more than one GROUP-KEY branch; zero SEMI-JOIN branches (that is the pure fact⋈dim linear fold); a nested branch inside a branch (interior out-degree > 1); a merge (a pattern referenced by > 1 parent); a cycle or disconnected pattern; a multi-column FK on any hop (single-column only, the 6b constraint); a semi-join constraint not reducible to a scalar-column equality; a fan-out RefObjectMap (#1583 — semi-join ≡ inner join rests on each FK being single-valued; a fan-out would under-represent multiplicity and MUST flip the fused and generic paths together); and, with FLUREE_FUSED_R2RML_MULTIFACT or the umbrella off, the whole path / the K≥2 increment respectively.

Ref-IRI group keys (S2): a ref group key whose parent subject is a blank node or literal (the fold emits an IRI term); ref group keys reached through a JOIN rather than a direct fact FK (S2 is single-table — the join-path group keys remain scalar-attribute only); a multi-column FK; and, with the umbrella off, the ≥2-ref increment. (Correction, id=3717398047: a duplicate (non-PK) parent join key on a ref-IRI key does NOT decline — it is resolved by keep-min (the lexicographically smaller parent IRI wins, byte-identical to the generic parent_key_insert_keep_min). Declining on a duplicate is the DISTINCT attribute-group-key JOIN path — insert_dim_gkeys — not this ref-IRI path; the prior text conflated the two policies.)

Bench pairs

Two A/B pairs (one per admitted shape) on bench/multifact-pairs (@ 077bbe151, off bench/duckdb-ab), manifest-gated pending_engine (+ --include-pending in run_pair.py/check_pair.py) so #1570's default run set never runs a pair that DNFs on shipped binaries until this lands.

Yardstick — substrate B, SF0.1, EC2 c7g.4xlarge (aarch64, quiet), N=5 cold

Correctness gate PASS both pairs, both binaries, vs real DuckDB (s1=10 rows, s2=28105). duckdb v1.5.5; fluree-1589 = this branch; fluree-before = 99e9656d9 (#1582 head, declines S1/S2 → generic path). Raw + writeup in bench-external-ab/results/.

pair duckdb-iceberg fluree-1589 fluree-before 1589 RSS DNF
s1 (K=2 semi-joins) 64 ms 832 ms (13×) 3000 ms 177 MB 0/5
s2 (2 ref-IRI keys) 49 ms 978 ms (20×) 965 ms 187 MB 0/5

Bar assessment (stated honestly). no DNF — MET (0/5 both). RSS < 2 GB — MET (177/187 MB, ~11× under). ≤5× DuckDB cold — NOT met at SF0.1 (13×/20×). The completion goal the maintainer's directive names ("tolerable time/memory") is met: ~0.8–1.0 s cold, <200 MB, zero DNF, exact-correct, and S1 is 3.6× faster than the materialize twin (832 ms vs 3000 ms); S2 is at wall-clock parity with the twin at this scale but leaner and structurally bounded.

Known ceilings on this approach (id=3717398042, next to the RSS). Two structural costs of the keep-min-then-filter membership design are real and un-fixed here (non-blocking): (1) duplicate dim scan — two SEMI-JOIN branches touching the SAME dim table each scan it independently and hold their own keep-min map. Unlike the ref-IRI group-key dedup this PR does add (shared Arc'd map when a dim map is fully determined by (parent_tm, parent_cols)), a semi-join membership SET's contents also depend on the branch's own constraints (the s1_same_table shape filters buyer='Enterprise' vs seller='SMB' on one Customer table), so a (parent_tm, parent_cols) share is NOT sound; a sound dedup needs a full-signature key or a scan-once-build-N refactor — a tracked follow-on, not folded in. (2) no ScanFilter pushdown on the membership scan — keep-min must see ALL rows to pick the min parent subject BEFORE the constraint filter, so each membership scan is a full resident dim scan with a fully resident keep-min map (pushing the terminal const down would be the unsound filter-then-keep-min order). Both bound RSS/scan on wide dims and belong beside the 177/187 MB numbers above.

Why the residual is the shared floor, not this unit's join logic — basis corrected per review (id=3717398040). The earlier wording inferred this from the single-table cq027 pair being 6.8×, and bplatz correctly flagged that cq027 has no semi-join sets and one resolver, so it cannot observe the one cost this PR actually adds: the per-fact-row FK probes (K semi-join membership + R resolver = K+R probes/row). So that cost was measured directly rather than inferred. A release microbench (fk_probe_alloc_microbench, 300k rows × 3 probes, in-process A/B) puts the FK-key probe at 69.6 ns/probe on the old fresh-Vec form and 48.6 ns/probe on the borrowed-scratch form this PR now uses — a 21 ns/probe, 30% saving, ≈63 ns/row on the s1 K+R=3 shape. Two things follow, stated plainly: (1) the alloc was real and cq027-invisible, so the cq027 inference was the wrong basis and the review was right to flag it; (2) it is already removed in this PR by the borrowed-scratch fix (d6eaa782c), so the residual profile going forward no longer contains it. What the microbench does not establish is what share of the 13×/20× those ~63 ns/row represent — that depends on the s1 per-row decode + IRI-mint floor, which needs the s1 substrate (EC2), not an in-process A/B; s1 was not re-timed end-to-end. On the numbers in hand — cold floor (p1, no scan) = 22 ms (overhead negligible), cold ≈ warm (s1 832→786, s2 978→922 ⇒ compute-bound on the R2RML scan), and the fold itself vectorized (N1, in #1582) — the remaining residual is directionally the shared fused-family virtual-scan/decode + per-row IRI-mint floor (SYNTHESIS N2 decode-seam + Gap-3 accumulators = the parity program's already-scheduled Unit 2). Per the established scale trend (ratio widens with scale) an SF1 run would not bring it under 5×, so it was not run.

aaj3f added 3 commits August 3, 2026 22:55
…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).
…oup keys

Widen P2a's single RefObjectMap (IRI) group key to K≥2, so a single-table fused
aggregate can GROUP BY multiple referenced-entity IRIs (e.g. events by customer
AND product). Generalizes the one FK→IRI resolver to a Vec, keyed per group key.

- Resolved.group_resolver: Option<GroupKeyResolver> -> group_resolvers:
  Vec<GroupKeyResolver>, indexed by KeySource::Dim.resolver. KeySource::Dim(slot)
  -> Dim { resolver, slot }. The join path pushes exactly one resolver (the
  terminal dim's FK->GKey map, resolver 0); S2's single-table path builds one
  FK->IRI resolver PER ref key, each probed by its own FK.
- The fold hot loop probes EVERY resolver by its own FK into a reused per-batch
  dim_probes scratch (no per-row alloc); a miss on ANY resolver drops the row —
  the AND of K independent inner-join existence tests. Each resolver keeps
  keep-min on a duplicate parent join key, unchanged from P2a.
- resolve_at_open lifts the ≥2-ref decline to a Vec, gated by
  FLUREE_FUSED_R2RML_MULTIFACT_GEN: OFF declines the 2nd ref key exactly as P2a
  did (byte-identical); ON admits it.

Differentials: two-ref value-identity integer + exact-i128 decimal (Acc::Exact
under a composite IRI key); dangling FK on EITHER key drops (inner join);
keep-min on the SECOND ref resolver (distinct subjects, smaller wins); GEN switch
gates only the widening (one ref key still fuses with GEN off). assemble_group_key
unit test migrated to the multi-resolver dim_probes form.
…rleave, same-table semi-branches

Three coverage-gap differentials the #1589 reviewer flagged (pins, not redesigns):

- s1_k2_semijoin_mixed_constraint_forms: the two S1 semi-join branches in DIFFERENT
  const-object forms in one query (customer star_constraints + agent standalone) —
  the other S1 tests were form-symmetric; pins resolve_semijoin_pattern_constraints
  gathering each branch's form independently in the same fuse.
- s2_fact_col_interleaved_with_two_ref_keys: GROUP BY (device[Fact], customer[ref],
  product[ref]) — a fact-column key interleaved with two ref-IRI keys; two events
  sharing (customer,product) but differing in device land in different groups, pinning
  the positional lockstep between group_key_plan positions and their sources.
- s1_same_table_semi_branches_independent: two semi-join branches on the SAME dim
  table (#Customer via BUYER_KEY/SELLER_KEY, segment=Enterprise / segment=SMB) enforced
  independently — each membership set built from its own scan+FK+constraint, not
  conflated.

63/63 in the module; fmt + query clippy (-D uninlined-format-args) clean. event mapping
gains a harmless DEVICE column for the interleave key.
aaj3f added a commit that referenced this pull request Aug 4, 2026
…ey fix

Yardstick for db #1589 (S1 K>=2 semi-joins, S2 >=2 ref-IRI group keys) on substrate B,
EC2 c7g.4xlarge, SF0.1, N=5 cold. Correctness PASS both pairs/both binaries vs real
DuckDB answers (s1=10 rows, s2=28105).

Headline (cold median, RSS): both shapes FUSE + COMPLETE, no DNF, RSS 177/187 MB (<2GB).
s1 832ms (3.6x faster than the 3000ms materialize twin); s2 978ms (parity w/ twin at
this scale, leaner). fluree-1589/duckdb-iceberg = 13x (s1) / 20x (s2) cold.

The <=5x bar is NOT met at SF0.1: it's the shared virtual-scan/decode floor (single-table
fused cq027 is already 6.8x here; fluree cold floor 22ms; cold~=warm => compute-bound on
the R2RML scan + per-row IRI minting, SYNTHESIS N2), NOT the fold generality. Details +
mechanism in RESULTS-multifact-generality.md.

Also: s2 SQL reconstructs the entity IRIs (cq040 convention) so both engines' keys reduce
to the same trailing-key token; a bare integer key mis-compared against Fluree's IRI.
@aaj3f
aaj3f marked this pull request as ready for review August 4, 2026 12:58
@aaj3f
aaj3f requested a review from bplatz August 4, 2026 13:37

@bplatz bplatz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of the multi-fact generality unit. The production change is a clean mechanical generalization — Option<SemiJoinSet> → Vec, Option<GroupKeyResolver> → Vec, Dim(slot) → Dim { resolver, slot }, plus the umbrella switch. 63 tests pass, clippy clean at --all-features --all-targets. The K-sets-AND soundness argument is correct for independent single-valued FKs; dim_probes is cleared per row and continues before use on a partial fill, so a miss can't read a stale slice. Choosing FactSupportTicket over the illustrative FactOrderLine because the latter's branches would collide is the right instinct and worth having in the body. And the bench section states plainly that the ≤5× bar was not met rather than reframing it.

One blocking finding though — the "no shape is silently mis-answered" claim in decline-completeness does not hold: a semi-join branch's var-object members are ignored, and I reproduced a wrong answer on this branch. Details inline, along with a hot-loop allocation issue that I think bears on the bench attribution.

On the S3 section: it's a genuinely good sized design — the late-materialization corridor, the reuse/new split, the unbounded-survivor risk, the SYNTHESIS §4 tie-in. It will be unfindable in a PR description six weeks from now. Suggest moving it to docs/design/, linking from docs/SUMMARY.md, and leaving a two-line pointer here.

/// pure-linear path, a no-op byte-identical to pre-P3). Each set is probed with the
/// same `get_join_key_from_batch` stringification the membership build used, so both
/// sides encode the join value identically.
fn row_passes_semi_joins(sets: &[SemiJoinSet], batch: &ColumnBatch, row: usize) -> bool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking — a semi-join branch's var-object members are silently ignored, so this probe over-admits.

build_semi_join_membership applies only constant-object constraints (resolve_semijoin_pattern_constraints reads star_constraints plus the standalone predicate_filter/object_constant form). It never looks at star_bindings. There is no validity_cols equivalent on the semi-join side, so the "this column must be non-null for the var-object triple to exist" row-drop that the fact-side fold enforces everywhere else is simply absent on a branch chain.

Reproduced on this branch — crt fixture with a :region ?r member added to the customer terminal (?c :segment "Enterprise" ; :region ?r), REGION null for every customer, so the generic BGP binds no ?r and the join is empty:

PROBE: fused FUSED with a var-object semi-join member; rows = [
    ("Lit { val: String(\"Widgets\") ... }", "Lit { val: Long(12) ... }"),
    ("Lit { val: String(\"Gadgets\") ... }", "Lit { val: Long(3) ... }"),
]  (generic = empty, ?r never binds)

The same hole breaks cross-branch correlation: two semi-join branches whose terminals bind the same variable are correlated in the generic join and independent in this AND-of-memberships. decompose_branching_star prevents two branches sharing a pattern, not a variable.

Fix is either to decline when any semi-join chain pattern has non-empty star_bindings, or to extend the per-level checks with a non-null requirement per var-object column — with the correlation case handled separately.

Inherited from the K=1 path, but this is the PR that widens the admission and carries the CLEAN verdict, so it should be resolved here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking and correct — thank you, this was the important one. You're right that build_semi_join_membership applies only constant-object constraints and never looks at star_bindings, and that there's no validity_cols equivalent on the semi-join side, so the var-object row-drop the fact-side fold enforces everywhere is simply absent on a branch chain. I reproduced your exact case (?c :segment "Enterprise" ; :region ?r, REGION null for every customer): fused returns rows, generic is empty because ?r never binds. Declined it in 46534f669.

One honest note I'd rather flag than bury: my first cut of that guard was incomplete. It checked only star_bindings, but the rewrite emits a single var-object member in object_var (only the 2nd+ members spill to star_bindings), so the exact single-member shape you flagged went straight through the first guard. b8e5c2f75 is the real fix — the guard checks object_var and star_bindings for a non-join var, with join-var membership as the discriminator (so an interior FK carried in object_var still fuses; that stays-green case has its own over-decline test). I also generated the decline fixture through the rewrite instead of hand-building it, and added an emission-pin test, because this is the third time a hand-built fixture in a shape the rewrite never emits let a bug through on this exact line. You're right it's inherited from the K=1 path — but this is the PR that widens the admission and carried the CLEAN verdict, so it's resolved here. (Both fixes sit on the #1582 base since the code lives there; #1589 inherits them via the restack.)

/// OR gatherer is fixtured on BOTH forms at BOTH sites (standalone const-object = the
/// live rewrite shape and the over-count regression guard; star_constraints = the
/// folded form).
fn s1_patterns(seg_star: bool, dept_star: bool) -> [R2rmlPattern; 4] {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Related to the var-object finding above, and the reason the const-forms coverage pin didn't catch it.

The doc on crt_patterns says star_constraints is what the rewrite emits "when the subject also has a var-object member." But both seg_star and dept_star here produce star_constraints on a terminal with no var-object member — a configuration the rewrite can't actually emit. So the true arms fixture a shape that doesn't occur, while the shape that does occur (var-object member alongside the folded constraint) is exactly the one that's mishandled.

Worth adding a var-object member to the *_star: true arms — that alone would have turned the pin red.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're exactly right, and this is why the const-forms pin didn't catch the var-object bug above. The doc on crt_patterns says star_constraints is what the rewrite emits "when the subject also has a var-object member," but both seg_star and dept_star produce star_constraints on a terminal with no var-object member — a config the rewrite can't emit. Rather than add a var-object member to the true arms (which would just fixture a different not-quite-real shape), a8b8c6fd5 drops those unemittable arms and their fictional fuse tests outright — the real shape (var-object member alongside the folded constraint) is the one the blocking fix and its generated-through-rewrite fixture now cover. Better no test than a green test for a shape that doesn't occur.

// K independent inner-join existence tests.
dim_probes.clear();
let mut resolver_miss = false;
for resolver in &resolved.group_resolvers {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hot-loop allocation — and I think it bears on the bench attribution.

get_join_key_from_batch builds a fresh Vec<String> plus a String per FK column, per row, per set. Both this resolver loop and row_passes_semi_joins call it. N1 existed specifically to remove per-row String/Vec allocation from the group key; the FK probe was left as-is, and this PR turns 1 probe/row into K+R probes/row.

Cheap fix with no soundness surface: keep one reusable Vec<String> scratch per batch and probe borrowed — HashSet<Vec<String>>::contains(scratch.as_slice()) and HashMap<Vec<String>, _>::get(scratch.as_slice()) both work via Borrow<[String]>. That removes the Vec allocation outright; interning or encoding FK keys to a fixed-width tuple would remove the Strings too.

Why it matters for the write-up: the body attributes the 13×/20× residual to the shared virtual-scan/decode + per-row IRI-minting floor and defers it to Unit 2. That rests on the single-table cq027 pair being 6.8× — but cq027 has no semi-join sets and one resolver, so it cannot observe this cost at all. A profile of the s1 pair before deferring seems worth the ten minutes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on both, and the second half is the more important one. d6eaa782c takes your cheap suggestion: one reusable Vec<String> scratch per batch, probed borrowed via Borrow<[String]> (HashSet::contains(scratch.as_slice()) / HashMap::get(scratch.as_slice())), so the per-row Vec alloc is gone on both the semi-join and resolver probes.

On the attribution — you're right that the body leaned on cq027's 6.8×, and that cq027 has no semi-join sets and one resolver, so it structurally cannot observe this cost. So I measured it instead of inferring it: 9517f22e6 adds a release microbench (fk_probe_alloc_microbench, 300k rows × 3 probes, in-process A/B, answer-identical assert). Old fresh-Vec = 69.6 ns/probe; new borrowed-scratch = 48.6 ns/probe; saved = 21 ns/probe (30%), ≈63 ns/row on the s1 K+R=3 shape. So the alloc was real and cq027-invisible — you were right to flag the basis — and it's removed in this PR. I corrected the PR-body paragraph to rest on that number rather than the cq027 inference. The one thing I want to be honest the microbench does not establish: what share of the 13×/20× those 63 ns/row are — that needs the s1 substrate end-to-end (it's on the EC2 bench branch; I didn't re-time it), not an in-process A/B. On the numbers in hand (cold ≈ warm ⇒ compute-bound on the scan, cold floor 22 ms) the remaining residual is directionally the shared scan/decode + IRI-mint floor = the already-scheduled Unit 2, but I've stopped short of claiming the precise share.

// not scalar/group objects.
let mut semi_joins: Vec<SemiJoinSet> = Vec::with_capacity(semi_branches.len());
let mut strip: Vec<VarId> = Vec::with_capacity(semi_branches.len());
for semi_branch in &semi_branches {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each semi-join branch builds its membership independently, so two branches whose chains touch the same table — the shape s1_same_table_semi_branches covers — scan it twice and hold two maps. Same for two S2 ref group keys onto the same dim (shipTo/billTo → Customer, a common case). Deduping by (parent_tm_iri, parent_cols) and sharing the map would halve both.

Worth stating alongside it in the write-up: keep-min-then-filter forbids pushing the terminal constraint down as a ScanFilter — that would be filter-then-keep-min, the exact unsound order the design warns about. So every semi-branch is a full dim scan with a fully resident keep-min map, by construction. That's a real ceiling on this approach and belongs next to the RSS numbers.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two parts, and I split them because only one is soundly shareable. The ref-IRI group-key dedup is in acc7c9dd6: when two ref keys resolve to the same parent TM on the same join columns (shipTo/billTo → Customer), they now share one Arc'd keep-min map keyed by (parent_tm, parent_cols). The two-semi-branches-same-table dedup I did not implement, and I want to be explicit why: a semi-join membership set's contents also depend on the branch's own constraints (s1_same_table filters buyer='Enterprise' on one branch, seller='SMB' on the other, same Customer table), so (parent_tm, parent_cols) does not fully determine the set — sharing by that key would be unsound (it would merge two different memberships). A sound dedup needs a full-signature key or a scan-once-build-N refactor, which is more than a contained change — so it's a documented ceiling (code comment at the build loop + a "Known ceilings" note in the body), not folded in.

And your keep-min-then-filter point is dead on and now sits next to the RSS numbers: keep-min must see all rows before the constraint filter, so pushing the terminal const down as a ScanFilter would be the unsound filter-then-keep-min order — every membership scan is a full resident dim scan by construction. That's a real ceiling on the approach and belongs beside the 177/187 MB.

// probe miss then folds "dangling FK" and "null parent" into one drop, exactly as
// the generic path does. The resolvers are built in `ref_group_keys` order, so
// resolver index `i` matches the `KeySource::Dim { resolver: i, .. }` plan above.
let mut group_resolvers: Vec<GroupKeyResolver> = Vec::with_capacity(ref_group_keys.len());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same dedupe point as the semi-join build: one full parent scan + one resident map per ref key, even when two ref keys resolve to the same parent TM on the same join columns. Keying the built resolvers by (parent_tm_iri, parent_cols) and pointing both KeySource::Dim entries at a shared index would avoid the duplicate scan.

(The keep-min inline here is correct for the IRI case — it mirrors build_parent_lookup, so no fan-out and no decline is needed. But the decline-completeness section credits S2's duplicate-key handling to insert_dim_gkeys, which this path doesn't call. Worth correcting the text so the two policies stay distinguishable: attribute group keys decline on a duplicate, ref-IRI keys keep-min.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The dedup half is the ref-key sharing in acc7c9dd6 above (same (parent_tm, parent_cols) key, both KeySource::Dim entries pointed at the shared index). On the text — you're right, and thanks for catching it: the keep-min inline here mirrors build_parent_lookup (no fan-out, no decline needed for the IRI case), but the decline-completeness section wrongly credited S2's duplicate-key handling to insert_dim_gkeys, which this path doesn't call. I fixed the body so the two policies stay distinguishable: attribute group keys decline on a duplicate (insert_dim_gkeys); ref-IRI keys keep-min. They were conflated; they're separate now.

/// killable underneath — turning either of those off declines the whole family
/// regardless of this flag. Read once per process (test reads live, as the sibling
/// switches do).
fn multifact_gen_enabled() -> bool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

docs/audit/2026-07-virtual-dataset-perf/SWITCHES.md maintains a table of every fused switch (default / off-effect / introduced-in) and contains none of the five added across this stack — FLUREE_FUSED_VECTOR_FOLD, _OUTPUT_BOUND, _MULTIFACT, FLUREE_ARROW_DIRECT_DECODE, and _MULTIFACT_GEN here. Neither does docs/operations/configuration.md. Per the repo's docs mandate these belong in the same changeset; the switch table in the PR body is most of the content already.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed — the switch table in the body was most of the content already, so this belonged in the same changeset per the docs mandate. 508074304 inventories the four #1582 switches (FLUREE_FUSED_VECTOR_FOLD, _OUTPUT_BOUND, _MULTIFACT, FLUREE_ARROW_DIRECT_DECODE) and 4a71154a4 adds _MULTIFACT_GEN — both in SWITCHES.md and docs/operations/configuration.md, each with default / off-effect / introduced-in.

/// admission gate in `decompose_branching_star` reads it live under cfg(test), so the
/// switch test's set/remove window must not race a concurrent K≥2 decompose. Held
/// ONLY around the (synchronous) `decompose` call — never across an `.await`.
static GEN_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This lock is a real improvement over the unguarded toggling in the base branch, and every reader in tests takes it. Two gaps keep it from actually closing the race:

  1. It covers _MULTIFACT_GEN only. FLUREE_FUSED_R2RML_OUTPUT_BOUND and _MULTIFACT are still toggled unlocked, and OUTPUT_BOUND is read uncached by every grouped fold — including all the new S1/S2 tests. Concurrent setenv/getenv is UB regardless of how well one of the three is locked, so this makes the race rarer rather than absent (and set_var becomes unsafe in edition 2024).
  2. The doc says the lock is "Held ONLY around the (synchronous) decompose call — never across an .await", but s2_gen_switch_gates_only_the_widening does hold it across awaits (see the #[allow] there).

The durable fix is to make these switches operator fields defaulted from env at construction — then the tests need no process state and no lock.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right the lock only made the race rarer, not absent: it covered _MULTIFACT_GEN only, OUTPUT_BOUND was still read uncached by every grouped fold, and concurrent setenv/getenv is UB regardless. And you caught that s2_gen_switch_gates_only_the_widening held the lock across awaits, contradicting the lock's own doc. 03d5ac665 does the durable fix you pointed to: _MULTIFACT_GEN becomes an operator field defaulted from env at construction, GEN_ENV_LOCK is gone, and the tests set the field (no process state, no lock, no across-await hold). Combined with #1582's 59d71e23a converting the other four, the whole switch family is operator fields now — no test touches process env.

/// while a ONE-ref-key fold (P2a) STILL fuses — so OFF is byte-identical to P2a. Holds
/// the GEN lock (shared with the run helpers) across the reads.
#[tokio::test]
#[allow(clippy::await_holding_lock)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Holding a std::sync::Mutex guard across .await under an #[allow], which contradicts GEN_ENV_LOCK's own doc comment ("never across an .await"). It's safe today only because #[tokio::test] defaults to a current-thread runtime — on a multi-thread runtime another task needing the lock on the same worker would deadlock.

If the switch stays env-based, tokio::sync::Mutex would at least make the hold legitimate. Better is to drop the env dependence for the reason in the GEN_ENV_LOCK comment.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same root cause, same fix — dropping the env dependence (03d5ac665) removes the across-.await std::sync::Mutex hold entirely, so there's no lock to hold legitimately or otherwise. You're right it was only safe today because #[tokio::test] defaults to a current-thread runtime; on a multi-thread runtime another task needing the lock on the same worker would deadlock. Gone now.

aaj3f added a commit that referenced this pull request Aug 6, 2026
…) 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.
aaj3f added a commit that referenced this pull request Aug 6, 2026
…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).
aaj3f added 10 commits August 6, 2026 14:30
…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
… a cfg(test) env read (review id=3717398054, id=3717398056)

multifact_gen_enabled read FLUREE_FUSED_R2RML_MULTIFACT_GEN live under cfg(test);
tests toggled it with std::env::set_var/remove_var behind a GEN_ENV_LOCK band-aid,
holding the lock across .await (allow(clippy::await_holding_lock)). Concurrent
setenv/getenv across parallel test threads is libc-level UB (set_var is unsafe in
edition 2024). Mirror Phase 1's pattern for the other four switches: multifact_gen
is now an operator field defaulted from env at construction. The static
decompose_branching_star (no self receiver) takes the K>=2 gate flag as a bool
argument threaded from self.multifact_gen; the >=2-ref gate reads the field
directly. Tests set the field / pass the bool; GEN_ENV_LOCK and every
await-holding-lock hold are removed.
…emi-join/resolver probes (review id=3717398040)

get_join_key_from_batch allocates a fresh Vec<String> per call; S1/S2 turned the
K=1 single probe/row into K+R allocating probes/row (K semi-join membership sets
plus R group resolvers). Add fill_join_key_from_batch, which fills a caller-owned
buffer reused across rows, and probe the HashSet/HashMap by scratch.as_slice()
(Vec<String>: Borrow<[String]>), so no owned key Vec is built per fact row per
probe. The fold hot loop allocates one fk_scratch per batch alongside N1's scratch
and S2's dim_probes; row_passes_semi_joins takes it as a param. get_join_key_from_batch
is single-sourced through the fill helper and kept for the BUILD path (which inserts
the owned key into a map). Component Strings still allocate per fill; interning the
FK key to a fixed-width tuple to remove those too is a deferred follow-on.
…dim (review id=3717398042)

Two ref-IRI GROUP-BY keys to the SAME dim on the SAME parent join cols (shipTo/billTo
to Customer) built an identical keep-min parent-key to IRI map and scanned the dim
twice. The map's contents depend only on (parent TM, parent cols), never on the
fact-side FK, so cache it by that pair and share it: GroupKeyResolver.map is now an
Arc<HashMap> and the second key reuses the first's scan + map (its own fact_fk_cols).
The per-fact-row probe derefs through the Arc unchanged.

The symmetric SEMI-JOIN case (two branches to the same dim) is left as a DOCUMENTED
known ceiling: a membership set's contents also depend on the branch's own constraints
(s1_same_table filters buyer='Enterprise' vs seller='SMB' on one Customer table), so a
(parent_tm, parent_cols) share is NOT sound there; a sound dedup needs a full-signature
key or a scan-once-build-N refactor, more than this contained change. Also noted at the
build site: the ScanFilter-pushdown ceiling (keep-min must see ALL rows before the
constraint filter, so each membership scan is a full resident dim scan by construction).
…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.
…t of the PR body (review top-level)

The #1589 PR body carried the full sized design for S3 (a row-returning multi-fact
virtual join). Per the review's top-level suggestion, move it to a standalone design
doc (docs/design/virtual-multifact-row-corridor.md) and link it from docs/SUMMARY.md
and docs/design/README.md; the PR body keeps a two-line pointer. Content is the same
sized design reframed as a standalone document; implementation stays out of #1589's
scope.
…8e5c2f)

Brings in the #1582 B2 refix: the object_var-aware var-object decline guard and its
generate-through-rewrite fixture.
…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.
…ratch fix (review id=3717398040)

Reviewer's point: the residual-attribution deferral leaned on the single-table
cq027 pair (6.8x), which has no semi-join sets and one resolver and so cannot
observe the per-fact-row FK-probe alloc this PR adds (K membership + R resolver
= K+R probes/row). Measure it directly instead of inferring it.

In-process A/B over 300k rows x 3 probes, answer-identical assert, release:
  OLD fresh-Vec probe        69.6 ns/probe
  NEW borrowed-scratch probe 48.6 ns/probe
  saved                      21.0 ns/probe (30%), ~63 ns/row on the s1 K+R=3 shape

#[ignore]d (perf microbench); the number is now reproducible and the PR-body
attribution is corrected to rest on it, not on cq027.
…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).
@aaj3f

aaj3f commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, @bplatz — the var-object semi-join finding (:1397) was the important catch, and it was real. Summary:

The blocking one: build_semi_join_membership ignored star_bindings entirely, so a semi-join branch with a var-object member over-admitted (reproduced with your :region ?r case — fused returns rows, generic is empty). I declined it — and I want to flag honestly that my first guard was incomplete: it checked only star_bindings, but the rewrite emits a single var-object member in object_var, so the exact shape you flagged slipped through. b8e5c2f75 is the real fix, checking object_var + star_bindings for a non-join var, with the fixture generated through the rewrite and an emission pin so this class can't recur. (Both fixes are on the #1582 base since the code lives there; #1589 inherits via the restack.)

On the bench attribution you pushed back on — you were right that cq027 can't observe the FK-probe alloc, so I measured it rather than inferring it. Microbench (9517f22e6): 21 ns/probe saved (30%), ≈63 ns/row on the s1 shape, and the borrowed-scratch fix (d6eaa782c) removes it in this PR. I corrected the body to rest on that number, and I've been explicit that the microbench does not establish the share of the 13×/20× — that needs the s1 substrate end-to-end, which I didn't re-time.

The two dedup points split: the ref-key dedup is sound and implemented (acc7c9dd6, shared Arc'd map); the two-semi-branches-same-table dedup is unsound to share by (parent_tm, parent_cols) (the branches carry different constraints), so it's a documented ceiling alongside the no-ScanFilter-pushdown one, next to the RSS numbers. The switch/lock UB is fixed by the same operator-field conversion as #1582 (03d5ac665, GEN_ENV_LOCK gone). Docs, the decline-text correction, and moving the S3 corridor design out of the body all landed too.

Re-requesting review — replies inline on each thread.

@bplatz bplatz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good! There is ci/cd issue but you'll need to reconcile after the stacked PR merges regardless.

aaj3f added 2 commits August 10, 2026 12:25
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).
…xity (CI -D warnings)

CI clippy (--all --all-features --all-targets -- -D warnings) fails on the
id=3717398042 ref-key dedup cache type at fused_aggregate.rs — a warning locally,
a hard error under -D warnings, which is why #1589's clippy job was red.
Introduce SharedDimMap + DimMapCache aliases and use them at the cache decl and
GroupKeyResolver.map. No behavior change.
Base automatically changed from perf/fused-vectorized-fold to main August 10, 2026 16:43
@aaj3f
aaj3f merged commit 732b6c9 into main Aug 11, 2026
15 checks passed
@aaj3f
aaj3f deleted the perf/multifact-generality branch August 11, 2026 18:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants