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
28 changes: 16 additions & 12 deletions docs/semantic-input.md
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,8 @@ invariants, and caller policies constrain both event populations.
Entity, event and time dimensions may map to source expressions, and output
identifiers retain quoting. The two-event path follows Python's last-declared
time-dimension selection; the multi-step path uses its default/first time
dimension. Joined populations, graph-scoped conversion metrics and calculated
dimension. A graph-scoped conversion metric can declare its owner or use an
entity dimension unique to one model. Joined populations and calculated
wrappers retain route-specific restrictions.

### Multi-step conversion
Expand All @@ -442,10 +443,12 @@ Entity and time dimensions can map to row-local source expressions. Step predica
refer to physical source columns; query and metric filters resolve declared dimensions.
All steps read the same policy-, invariant-, query-, and metric-filtered population.
The strict wrapper validates expressions and projects internal source columns before
calling the existing sequential generator. Graph-scoped metrics, mixed metrics,
joined populations, aggregate/window/subquery source expressions, colliding output
names (including dimensions named `entity` or `step_N_ts`) and rollup routing
remain gated. Null-default metadata retains Python's inert behavior.
calling the existing sequential generator. Query filters may use `{model}` for
the funnel's source, including the resolved owner of a graph-scoped funnel.
Mixed metrics, joined populations, aggregate/window/subquery source expressions
and rollup routing remain gated. Public output names must be unique ignoring case. Grouping dimensions
can be named `entity` or `step_N_ts` because each step carries their values in
separate internal columns. Null-default metadata retains Python's inert behavior.

## PostgreSQL policy output

Expand Down Expand Up @@ -498,8 +501,8 @@ junction declaration. Measures retain their source-key grain across duplicate
junction rows. Inactive relationships remain excluded.
### Source-local cohorts

Direct model cohort metrics and graph metrics with an explicit `metric_owners`
entry can aggregate source rows per entity, apply `having`
Direct model cohort metrics and graph metrics with a resolved owner
can aggregate source rows per entity, apply `having`
to declared inner result columns, and aggregate the surviving groups. Query and
entity dimensions are carried through both levels, including explicit time
buckets. Outer `count` counts inner groups (including a qualifying null-entity
Expand All @@ -509,11 +512,12 @@ apply before the inner aggregation, with each predicate parenthesized.

This subset requires row-local scalar source expressions. Subqueries, windows,
and aggregates hidden in source dimensions, inner SQL or row filters are
rejected. Graph cohorts require their declared source owner; entity or output
column names do not infer ownership. The declared owner also determines the
mandatory restrictions applied to the source population. Joined populations,
unowned graph cohorts and calculated wrappers remain gated. HAVING and outer expressions must reference
available inner columns; other aggregate contexts are not silently inferred.
rejected. Graph cohorts use the declared owner or the unique model containing
their entity dimension. The owner determines the mandatory restrictions on
the source population. Joined populations and calculated wrappers remain gated.
Both `having` and the outer aggregate read named columns from the grouped
result. Applying `having` at this boundary lets a computed dimension share
a name with its physical source column.

The WASM SQL parser has a host-specific admission limit of 16 nested
parenthesis/bracket/brace/CASE constructs, 32 operators per expression chain,
Expand Down
149 changes: 149 additions & 0 deletions sqlctx-duckdb/test/test_semantic_input_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,155 @@ def call(query=None, source=None, sql=None, context=None, error=False):
return result if error else result[0]["sql"]


@pytest.mark.parametrize("expression", [False, True])
def test_graph_window_identity_shadows_same_named_local_aggregate(expression):
source = {
"version": 1,
"input_dialect": "duckdb",
"models": [
{
"name": "events",
"sql": """
select * from (values
(1, date '2024-01-01', 10, 900), (2, date '2024-01-02', 20, 800)
) events(id, day, amount, shadow)
""",
"primary_key": "id",
"dimensions": [{"name": "day", "type": "time", "granularity": "day"}],
"metrics": [
{"name": "total", "agg": "sum", "sql": "amount"},
{"name": "running", "agg": "sum", "sql": "shadow"},
],
}
],
"metrics": [
{
"name": "events.running",
"type": "cumulative",
**({"window_expression": "SUM(base.total)"} if expression else {"sql": "total"}),
}
],
"metric_owners": {"events.running": "events"},
}
compiled = call(
source=source,
query={"metrics": ["events.running"], "dimensions": ["events.day"], "order_by": ["events.day"]},
)
assert execute(compiled) == [
{"day": "2024-01-01", "total": "10", "events.running": "10"},
{"day": "2024-01-02", "total": "20", "events.running": "30"},
]


def test_computed_time_identity_stays_unbucketed_for_join_and_fanout():
source = {
"version": 1,
"input_dialect": "duckdb",
"models": [
{
"name": "events",
"sql": """
select * from (values
('2026-01-01 01:00:00', 3), ('2026-01-01 02:00:00', 4),
('2026-01-02 01:00:00', 8)
) events(raw_time, amount)
""",
"primary_key": "event_time",
"dimensions": [
{
"name": "event_time",
"type": "time",
"granularity": "day",
"sql": "cast(raw_time as timestamp)",
}
],
"metrics": [
{"name": "amount", "agg": "sum", "sql": "amount"},
{"name": "people", "agg": "count_distinct"},
],
},
{
"name": "logs",
"sql": """
select * from (values
(1, '2026-01-01 01:00:00', 'x'), (2, '2026-01-01 01:00:00', 'x'),
(3, '2026-01-01 02:00:00', 'x'), (4, '2026-01-02 01:00:00', 'y')
) logs(id, raw_time, category)
""",
"primary_key": "id",
"dimensions": [
{
"name": "event_ref",
"type": "time",
"granularity": "day",
"sql": "cast(raw_time as timestamp)",
},
{"name": "category", "type": "categorical"},
],
"relationships": [{"name": "events", "type": "many_to_one", "foreign_key": "event_ref"}],
},
],
}
compiled = call(
source=source,
query={
"metrics": ["events.amount", "events.people"],
"dimensions": ["events.event_time__day", "logs.category"],
"order_by": ["events.event_time__day", "logs.category"],
},
)
assert execute(compiled) == [
{"event_time__day": "2026-01-01", "category": "x", "amount": "7", "people": 2},
{"event_time__day": "2026-01-02", "category": "y", "amount": "8", "people": 1},
]


@pytest.mark.parametrize("rewrite", [False, True])
@pytest.mark.parametrize("suffix", ["", " ASC NULLS LAST", " DESC NULLS FIRST"])
def test_fanout_null_ordering_precedes_pagination(rewrite, suffix):
source = {
"version": 1,
"input_dialect": "duckdb",
"models": [
{
"name": "facts",
"sql": "select * from (values (1, 10), (2, 20), (3, 30)) facts(id, amount)",
"primary_key": "id",
"metrics": [{"name": "total", "agg": "sum", "sql": "amount"}],
"relationships": [{"name": "items", "type": "one_to_many", "foreign_key": "fact_id"}],
},
{
"name": "items",
"sql": """
select * from (values (1, 1, NULL), (2, 1, NULL), (3, 2, 'a'), (4, 3, 'b'))
items(id, fact_id, label)
""",
"primary_key": "id",
"dimensions": [{"name": "label", "type": "categorical"}],
},
],
}
if rewrite:
compiled = call(
source=source,
sql=f"select items.label, facts.total from metrics order by label{suffix} limit 1",
context={},
)
else:
compiled = call(
source=source,
query={
"metrics": ["facts.total"],
"dimensions": ["items.label"],
"order_by": ["items.label" + suffix],
"limit": 1,
},
)
# Structured queries default to NULLS FIRST; semantic SQL keeps DuckDB's NULLS LAST.
nulls_first = suffix.endswith("FIRST") or (not rewrite and not suffix)
assert execute(compiled) == [{"label": None, "total": "10"} if nulls_first else {"label": "a", "total": "20"}]


def test_retention_table_keeps_inactive_cohort_members_in_denominator():
source = {
"version": 1,
Expand Down
2 changes: 1 addition & 1 deletion sqlctx-rs/src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pub use parameter::{Parameter, ParameterType};
pub use policy::{AccessRule, PolicyError, PreparedPolicies, SecurityPolicy};
pub(crate) use preaggregation::{
materialization_sql as preaggregation_materialization_sql, replace_model_placeholder,
source_expression as preaggregation_source_expression,
replace_model_placeholder_in_dialect, source_expression as preaggregation_source_expression,
};
pub(crate) use relative_date::bigquery_trunc_part;
pub use relative_date::RelativeDate;
Expand Down
15 changes: 13 additions & 2 deletions sqlctx-rs/src/core/preaggregation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,19 @@ pub(crate) fn materialization_sql(

/// Rewrite only actual placeholder tokens, leaving literal and subquery text intact.
pub(crate) fn replace_model_placeholder(sql: &str, owner: Option<&str>) -> Result<String> {
use polyglot_sql::{dialects::Dialect, DialectType, TokenType};
let tokens = Dialect::get(DialectType::DuckDB)
replace_model_placeholder_in_dialect(sql, owner, polyglot_sql::DialectType::DuckDB)
}

pub(crate) fn replace_model_placeholder_in_dialect(
sql: &str,
owner: Option<&str>,
dialect: polyglot_sql::DialectType,
) -> Result<String> {
use polyglot_sql::{dialects::Dialect, TokenType};
if !sql.contains("{model}") {
return Ok(sql.to_owned());
}
let tokens = Dialect::get(dialect)
.tokenize(sql)
.map_err(|error| SqlctxError::SqlParse(error.to_string()))?;
// Token spans are character offsets, including for Unicode input.
Expand Down
2 changes: 2 additions & 0 deletions sqlctx-rs/src/python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,8 @@ fn semantic_input_error(py: Python<'_>, error: SqlctxError) -> PyErr {
}
SqlctxError::Validation(_)
| SqlctxError::ValidationIssue { .. }
| SqlctxError::AmbiguousReference { .. }
| SqlctxError::AmbiguousJoinPath { .. }
| SqlctxError::NoJoinPath { .. }
| SqlctxError::SqlParse(_) => QueryValidationError::new_err(error.to_string()),
SqlctxError::InvalidConfig(_) => PyValueError::new_err(error.to_string()),
Expand Down
82 changes: 77 additions & 5 deletions sqlctx-rs/src/semantic_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1233,6 +1233,31 @@ fn query_input(query: &str) -> Result<QueryInput> {
runtime_request(query, "query")
}

fn population_filter_owner(query: &QueryInput, graph: &SemanticGraph) -> Result<Option<String>> {
let [reference] = query.metrics.as_slice() else {
return Ok(None);
};
let is_population = |metric: &Metric| {
use crate::core::MetricType::{Cohort, Conversion, Retention};
matches!(metric.r#type, Cohort | Conversion | Retention)
};
if let Some(metric) = graph.get_metric(reference) {
return if is_population(metric) {
graph.population_metric_owner(reference, metric).map(Some)
} else {
Ok(None)
};
}
let Ok((owner, name, _)) = graph.parse_reference(reference) else {
return Ok(None);
};
Ok(graph
.get_model(&owner)
.and_then(|model| model.get_metric(&name))
.filter(|metric| is_population(metric))
.map(|_| owner))
}

fn prepare_query_input(mut query: QueryInput, input: &mut SemanticInput) -> Result<QueryInput> {
let dialect = query
.query_dialect
Expand All @@ -1242,15 +1267,33 @@ fn prepare_query_input(mut query: QueryInput, input: &mut SemanticInput) -> Resu
.unwrap_or(input.input_dialect);
query.filters = interpolate_query_filters_with_dialect(
&input.graph,
query.filters,
std::mem::take(&mut query.filters),
&query.parameter_values,
dialect,
)
.map_err(|error| invalid("query.parameter_values", error))?
.iter()
.map(|sql| {
fragments::validate_request_expression(sql, dialect, false)?;
dialects::fragment(sql, dialect, dialects::Fragment::Scalar)
.into_iter()
.map(|mut sql| {
// Bind a population filter to its declared or inferred source before
// request validation and policy discovery.
if sql.contains("{model}")
&& crate::core::replace_model_placeholder_in_dialect(&sql, Some(""), dialect)? != sql
{
if let Some(owner) = population_filter_owner(&query, &input.graph)? {
let quoted = polyglot_sql::dialects::Dialect::get(dialect)
.generate(&polyglot_sql::Expression::Identifier(
polyglot_sql::expressions::Identifier::quoted(owner),
))
.map_err(|error| invalid("query.filters", error))?;
sql = crate::core::replace_model_placeholder_in_dialect(
&sql,
Some(&quoted),
dialect,
)?;
}
}
fragments::validate_request_expression(&sql, dialect, false)?;
dialects::fragment(&sql, dialect, dialects::Fragment::Scalar)
})
.collect::<Result<Vec<_>>>()?;
let known_names: Vec<_> = query
Expand Down Expand Up @@ -1670,6 +1713,35 @@ mod tests {
})
}

#[test]
fn multistep_query_filter_binds_source_placeholder_before_validation() {
let mut source = input();
source["models"][0]["dimensions"] = json!([
{"name":"person", "type":"categorical"},
{"name":"region", "type":"categorical"},
{"name":"occurred", "type":"time"}
]);
source["models"][0]["metrics"] = json!([{
"name":"funnel", "type":"conversion", "entity":"person",
"steps":["kind = 'signup'", "kind = 'view'", "kind = 'purchase'"]
}]);
for dialect in ["duckdb", "mysql", "bigquery"] {
let query = json!({
"metrics":["orders.funnel"],
"filters":["{model}.region = '{model}.a'"],
"query_dialect":dialect
});
assert!(
validate_with_semantic_input(&source.to_string(), &query.to_string())
.unwrap()
.is_empty()
);
let sql = compile_with_semantic_input(&source.to_string(), &query.to_string()).unwrap();
assert!(sql.contains("'{model}.a'"), "{sql}");
assert!(!sql.contains("{model}.region"), "{sql}");
}
}

#[test]
fn unloaded_relationship_targets_do_not_block_local_queries() {
let mut source = input();
Expand Down
Loading
Loading