Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 40 additions & 15 deletions src/boring_semantic_layer/calc_compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,7 @@ def attach_calc_totals(
calc_specs: dict[str, Any],
classifications: dict[str, CalcExprAnalysis],
totals_prefix: str = TOTALS_PREFIX,
lifted_calc_specs: dict[str, tuple[Any, Any, Any] | None] | None = None,
):
"""Compute ``__bsl_totals__<calc_name>`` columns for calc-of-calc-AllOf chains.

Expand Down Expand Up @@ -800,20 +801,40 @@ def attach_calc_totals(
continue
cm = calc_specs[calc_name]
fn = cm.expr if hasattr(cm, "expr") else cm
try:
scope = _TotalsResolvingScope(real_agg_tbl, totals_prefix)
if hasattr(fn, "_resolver") and hasattr(fn, "resolve"):
totals_expr = fn.resolve(scope)
elif callable(fn):
totals_expr = fn(scope)
else:
totals_expr = fn
except Exception as exc:
raise TotalsNotAvailableError(
f"Could not evaluate totals for calc measure {calc_name!r}; "
"a skipped totals column would silently substitute the "
"per-group value for the grand total."
) from exc
lifted = (lifted_calc_specs or {}).get(calc_name)
if lifted is not None:
lifted_expr, lifted_vt, lifted_totals_vt = lifted
lifted_op = _to_op(lifted_expr)
real_op = _to_op(real_agg_tbl)
real_cols = set(getattr(real_agg_tbl, "columns", ()))
subs: dict = {}
for src_vt in (lifted_vt, lifted_totals_vt):
if src_vt is None:
continue
src_vt_op = _to_op(src_vt)
src_schema = getattr(src_vt_op, "schema", None)
if src_schema is not None:
for col_name in src_schema.items():
c = col_name[0]
prefixed = f"{totals_prefix}{c}"
if prefixed in real_cols:
subs[Field(src_vt_op, c)] = Field(real_op, prefixed)
totals_expr = lifted_op.replace(subs).to_expr()
else:
try:
scope = _TotalsResolvingScope(real_agg_tbl, totals_prefix)
if hasattr(fn, "_resolver") and hasattr(fn, "resolve"):
totals_expr = fn.resolve(scope)
elif callable(fn):
totals_expr = fn(scope)
else:
totals_expr = fn
except Exception as exc:
raise TotalsNotAvailableError(
f"Could not evaluate totals for calc measure {calc_name!r}; "
"a skipped totals column would silently substitute the "
"per-group value for the grand total."
) from exc
col = f"{totals_prefix}{calc_name}"
real_agg_tbl = real_agg_tbl.mutate(**{col: totals_expr})

Expand Down Expand Up @@ -1189,7 +1210,11 @@ def _remap(piece, _subs=key_subs):
else:
intermediate = op

field_subs = {r: Field(new_vt_op, reduction_to_name[id(r)]) for r in base_reductions}
field_subs: dict = {
vt_op: new_vt_op,
totals_vt_op: new_totals_vt_op,
**{r: Field(new_vt_op, reduction_to_name[id(r)]) for r in base_reductions},
}
new_op = intermediate.replace(field_subs)

lifted_aggs = {anon: r.to_expr() for anon, r in name_to_reduction.items()}
Expand Down
46 changes: 19 additions & 27 deletions src/boring_semantic_layer/ops/_compile_deferred.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@

from __future__ import annotations

from ..calc_compiler import apply_calc_measures
from ..measure_scope import MeasureScope
from ._core import (
SemanticJoinOp,
SemanticTableOp,
_augment_dimensions_with_raw_columns,
_build_aggregation_plan,
_compile_aggregation,
_DeferrableJoin,
_get_merged_fields,
_JoinTreeInfo,
Expand Down Expand Up @@ -134,32 +134,24 @@ def strip_deferred(node):
tbl=core_tbl,
)

# Execute aggregation on core table
if plan.group_by_cols:
gb_exprs = []
for col in plan.group_by_cols:
if col in core_tbl.columns:
gb_exprs.append(core_tbl[col])
elif col in merged_dimensions:
dim_fn = merged_dimensions[col]
gb_exprs.append(dim_fn(core_tbl).name(col))

agg_exprs = {name: fn(core_tbl) for name, fn in plan.agg_specs.items()}
result = core_tbl.group_by(gb_exprs).aggregate(**agg_exprs)
else:
agg_exprs = {name: fn(core_tbl) for name, fn in plan.agg_specs.items()}
result = core_tbl.aggregate(**agg_exprs)

# Handle calculated measures
if plan.calc_specs:
known = frozenset(merged_base_measures) | frozenset(merged_calc_measures)
result = apply_calc_measures(
result,
core_tbl,
dict(plan.calc_specs),
known,
agg_specs=dict(plan.agg_specs),
)
# Execute aggregation and calc compilation via _compile_aggregation so
# inline reductions, windowed t.all(...) totals, and calc-of-calc chains
# behave identically to the non-deferred path (#314).
known = (
frozenset(merged_base_measures)
| frozenset(merged_calc_measures)
| frozenset(plan.agg_specs)
| frozenset(plan.calc_specs)
)
result = _compile_aggregation(
core_tbl,
list(plan.group_by_cols),
dict(plan.agg_specs),
dict(plan.calc_specs),
known_measures=known,
requested_measures=None,
is_post_agg=False,
)

# --- 3. LEFT JOIN deferred dimension tables ---
for d in deferrable:
Expand Down
30 changes: 26 additions & 4 deletions src/boring_semantic_layer/ops/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1738,7 +1738,7 @@ def _compile_aggregation(
)
analysis = analyze_calc_expr(
new_expr,
known_measures=known_measures,
known_measures=known_measures | frozenset(lifted),
base_table_op=base_op,
totals_vt_op=_to_op(new_totals_vt),
)
Expand Down Expand Up @@ -1887,7 +1887,13 @@ def _compile_aggregation(
# each needed calc lambda against the totals columns to derive the
# calc's totals value (constant across rows).
if calc_specs and totals_arbitrary_specs:
real_agg_tbl = attach_calc_totals(real_agg_tbl, calc_specs, classifications, TOTALS_PREFIX)
real_agg_tbl = attach_calc_totals(
real_agg_tbl,
calc_specs,
classifications,
TOTALS_PREFIX,
lifted_calc_specs=lifted_calc_specs,
)

# --- Apply calc measures -----------------------------------------
if calc_specs:
Expand Down Expand Up @@ -2523,10 +2529,26 @@ def walk(node):
if not entity_dims:
return

# Check: no measures from right table are used in aggregation
for agg_name in agg_names:
# Check: no measures (or calc measure deps) from right table are used in aggregation
merged_calc_measures = _get_merged_fields(all_roots, "calc_measures", source=join_op)
for agg_name, agg_fn in agg_names.items():
if agg_name.startswith(f"{right_name}."):
return # Right table has measures in agg → can't defer
cm = merged_calc_measures.get(agg_name)
if isinstance(cm, CalcMeasure) and any(
dep.startswith(f"{right_name}.") for dep in cm.depends_on
):
return
unwrapped = _unwrap(agg_fn)
if _detect_bare_name_lambda(unwrapped) is None and callable(unwrapped):
# Inline agg/calc expression: check if it references right_name
try:
right_tbl_check = _to_untagged(right)
ext = _extract_columns_from_callable(unwrapped, right_tbl_check)
if ext.is_success() and ext.columns:
return
except Exception:
pass

# Get join keys for the right table
right_join_keys = join_tree_info.table_join_keys.get(right_name, set())
Expand Down
43 changes: 43 additions & 0 deletions src/boring_semantic_layer/tests/test_calc_compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ def test_multiple_allof_calcs_share_one_totals_per_measure():
``OVER (...)`` window per AllOf-referenced measure. Locking the
"one totals per measure" property guards against an O(n²) regression.
"""

from boring_semantic_layer import to_semantic_table

con = xo.duckdb.connect()
Expand Down Expand Up @@ -260,6 +261,7 @@ def test_multiple_allof_calcs_share_one_totals_per_measure():

def test_apply_calc_measures_join_with_mean_totals():
"""Joined model: t.all over a non-sum measure recomputes totals from base."""

from boring_semantic_layer import to_semantic_table

con = xo.duckdb.connect()
Expand Down Expand Up @@ -318,6 +320,7 @@ def test_apply_calc_measures_non_sum_totals(reducer, expected_total, per_group):
common non-sum reductions: per-group sums-of-medians or sum-of-mins
would be obviously wrong.
"""

from boring_semantic_layer import to_semantic_table

con = xo.duckdb.connect()
Expand Down Expand Up @@ -368,6 +371,7 @@ def test_cast_to_float_survives_int_measure_substitution():
behavior end-to-end with a count-style integer measure and a
``cast('float64')``-using calc.
"""

from boring_semantic_layer import to_semantic_table

con = xo.duckdb.connect()
Expand Down Expand Up @@ -419,6 +423,7 @@ def test_joined_model_totals_via_windowed_aggregation():
``arbitrary()``. There is no cross-join, so the shared-ancestor
optimization can't kick in.
"""

from boring_semantic_layer import to_semantic_table

con = xo.duckdb.connect()
Expand Down Expand Up @@ -480,6 +485,7 @@ def test_joined_model_totals_does_not_emit_cross_join():
this in SQL prevents a regression to the shared-ancestor cross-join
pattern that would silently return zero rows on some backends.
"""

from boring_semantic_layer import to_semantic_table

con = xo.duckdb.connect()
Expand Down Expand Up @@ -549,6 +555,7 @@ def test_attach_calc_totals_handles_calc_of_calc():
helper should add ``__bsl_totals__avg`` computed from
``__bsl_totals__total_distance / __bsl_totals__total_count``.
"""

from boring_semantic_layer import to_semantic_table

con = xo.duckdb.connect()
Expand Down Expand Up @@ -645,3 +652,39 @@ def test_lift_inline_reductions_routes_window_to_totals():
assert new_totals_id in rels_for_anon, (
"expected Field(new_totals_vt, anon) for the windowed reduction"
)


def test_calc_measure_mixing_inline_reduction_and_measure_ref():
"""Mixing an inline reduction with a measure reference must not raise IntegrityError (#314)."""
import ibis

from boring_semantic_layer import to_semantic_table

tbl = ibis.memtable({"amount": [10, 20, 30], "cat": ["a", "b", "a"]})
model = (
to_semantic_table(tbl, name="s")
.with_dimensions(cat=lambda t: t.cat)
.with_measures(
n=lambda t: t.count(),
r=lambda t: t.amount.sum() / t.n,
r_all_n=lambda t: t.amount.sum() / t.all(t.n),
n_over_all_amount=lambda t: t.n / t.all(t.amount.sum()),
)
.with_measures(
share_of_r=lambda t: t.r / t.all(t.r),
)
)

df = (
model.group_by("cat").aggregate("r", "r_all_n", "n_over_all_amount", "share_of_r").execute()
)
df = df.sort_values("cat").reset_index(drop=True)
# cat='a': amount=40, n=2 -> r=20.0; cat='b': amount=20, n=1 -> r=20.0
# overall: amount=60, n=3 -> r=20.0
assert df["r"].tolist() == pytest.approx([20.0, 20.0])
assert df["r_all_n"].tolist() == pytest.approx([40.0 / 3.0, 20.0 / 3.0])
assert df["n_over_all_amount"].tolist() == pytest.approx([2.0 / 60.0, 1.0 / 60.0])
assert df["share_of_r"].tolist() == pytest.approx([1.0, 1.0])

ungrouped = model.aggregate("r").execute()
assert ungrouped["r"].iloc[0] == pytest.approx(20.0)
62 changes: 62 additions & 0 deletions src/boring_semantic_layer/tests/test_deferred_join.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,3 +481,65 @@ def test_prefixed_filter_prevents_deferral(self, lookup_tables):
# Only NYC cost center (101 = Engineering): user 1 (2 logins), user 3 (1 login)
assert list(result["users.user_id"]) == [1, 3]
assert list(result["users.login_count"]) == [2, 1]


class TestDeferredJoinTotalsAndInlineReductions:
"""t.all(...) totals and mixed inline reductions work on the deferred-join path (#314)."""

def test_deferred_join_inline_all_totals_and_mixed_reduction(self, con):
users_tbl = con.create_table(
"dj_users_314",
pd.DataFrame(
{
"user_id": [1, 1, 2, 2, 3],
"cost_center_id": [101, 101, 102, 102, 101],
"amount": [10, 20, 30, 40, 50],
}
),
)
cc_tbl = con.create_table(
"dj_cc_314",
pd.DataFrame({"cc_id": [101, 102], "cc_name": ["Engineering", "Marketing"]}),
)

def make_joined(with_entity: bool):
users = (
to_semantic_table(users_tbl, name="users")
.with_dimensions(
user_id=Dimension(expr=lambda t: t.user_id, is_entity=True),
cost_center_id=lambda t: t.cost_center_id,
)
.with_measures(
login_count=lambda t: t.count(),
)
.with_measures(
login_share=lambda t: t.login_count / t.all(t.login_count),
inline_pct=lambda t: t.amount.sum() / t.all(t.amount.sum()),
avg_amt=lambda t: t.amount.sum() / t.login_count,
)
)
cc = to_semantic_table(cc_tbl, name="cost_centers").with_dimensions(
cc_id=Dimension(expr=lambda t: t.cc_id, is_entity=with_entity),
cc_name=lambda t: t.cc_name,
)
return users.join_one(cc, on=lambda u, c: u.cost_center_id == c.cc_id)

deferred_df = (
make_joined(with_entity=True)
.group_by("users.user_id", "cost_centers.cc_name")
.aggregate("users.login_share", "users.inline_pct", "users.avg_amt")
.execute()
.sort_values("users.user_id")
.reset_index(drop=True)
)
standard_df = (
make_joined(with_entity=False)
.group_by("users.user_id", "cost_centers.cc_name")
.aggregate("users.login_share", "users.inline_pct", "users.avg_amt")
.execute()
.sort_values("users.user_id")
.reset_index(drop=True)
)
pd.testing.assert_frame_equal(deferred_df, standard_df)
assert deferred_df["users.inline_pct"].sum() == pytest.approx(1.0)
assert deferred_df["users.avg_amt"].tolist() == pytest.approx([15.0, 35.0, 50.0])