Skip to content

Commit e074bd1

Browse files
authored
feat(native): build fast column lineage natively behind the preview engine (#1029)
* feat(native): build fast column lineage natively behind the preview engine * fix(native): run fast lineage on the analysis pool and walk set operations linearly
1 parent dd3690f commit e074bd1

35 files changed

Lines changed: 3181 additions & 5 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
pub(crate) mod parsed_lineage;
2+
pub(crate) mod projections;
3+
pub(crate) mod python_payload;
4+
pub(crate) mod references;
5+
pub(crate) mod stars;
Lines changed: 231 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
1+
//! Python's `_build_polyglot_fast_model_column_lineage`: the parse fallback without compact facts.
2+
3+
use std::collections::{HashMap, HashSet};
4+
5+
use polyglot_sql::{ComplexityGuardOptions, Dialect, DialectType, Expression, ParseOptions};
6+
7+
use crate::lineage::_helpers::projections::{
8+
UnreadableExpression, classify_transform, is_star, projection_output_name,
9+
projection_upstream_columns, set_expression_selects, table_alias_map, unaliased,
10+
};
11+
use crate::lineage::_helpers::references::{PhysicalResource, normalized_sql, physical_resources};
12+
use crate::lineage::_helpers::stars::star_lineage;
13+
use crate::lineage::constants::{KIND_SELECT, KIND_UNION, MAX_FUNCTION_CALL_DEPTH};
14+
use crate::lineage::models::{
15+
FastLineageOutcome, LineageColumn, LineageConfidence, LineageDeferral, LineageResourceType,
16+
LineageSource, LineageTransformKind,
17+
};
18+
19+
/// The parse options SQLBuild's Polyglot proxy gives `parse_one`, decoded as the wheel does.
20+
pub(crate) fn proxy_parse_options() -> Result<ParseOptions, serde_json::Error> {
21+
let guard: ComplexityGuardOptions = serde_json::from_value(serde_json::json!({
22+
"maxFunctionCallDepth": MAX_FUNCTION_CALL_DEPTH,
23+
}))?;
24+
Ok(ParseOptions {
25+
complexity_guard: Some(guard),
26+
})
27+
}
28+
29+
/// Python's `parse_one(dialect=dialect or "generic")` dialect, if this parser build carries it.
30+
pub(crate) fn lineage_dialect(name: Option<&str>) -> Option<DialectType> {
31+
let name = name.filter(|name| !name.is_empty()).unwrap_or("generic");
32+
let Ok(dialect) = name.parse::<DialectType>() else {
33+
return None;
34+
};
35+
matches!(
36+
dialect,
37+
DialectType::Generic
38+
| DialectType::PostgreSQL
39+
| DialectType::BigQuery
40+
| DialectType::Snowflake
41+
| DialectType::DuckDB
42+
| DialectType::TSQL
43+
| DialectType::Databricks
44+
)
45+
.then_some(dialect)
46+
}
47+
48+
pub(crate) struct ParsedModel<'a> {
49+
pub(crate) query_sql: &'a str,
50+
pub(crate) inferred_names: &'a [String],
51+
pub(crate) schema: &'a HashMap<String, Vec<String>>,
52+
pub(crate) dialect: Option<DialectType>,
53+
pub(crate) options: &'a Result<ParseOptions, serde_json::Error>,
54+
}
55+
56+
pub(crate) fn parsed_model_lineage(model: &ParsedModel<'_>) -> FastLineageOutcome {
57+
let Some(dialect) = model.dialect else {
58+
return FastLineageOutcome::Deferred(LineageDeferral::UnsupportedDialect);
59+
};
60+
let Ok(options) = model.options else {
61+
return FastLineageOutcome::Deferred(LineageDeferral::NativeFailure);
62+
};
63+
let physical = physical_resources(model.query_sql);
64+
let sql = normalized_sql(model.query_sql);
65+
let mut statements = match Dialect::get(dialect).parse_with_options(&sql, options) {
66+
Ok(statements) => statements,
67+
Err(error) => return FastLineageOutcome::Unparsed(error.to_string()),
68+
};
69+
if statements.len() != 1 {
70+
return FastLineageOutcome::Unparsed(format!(
71+
"Expected 1 statement, found {}",
72+
statements.len()
73+
));
74+
}
75+
let parsed = statements.remove(0);
76+
let built = match parsed.variant_name() {
77+
KIND_UNION => union_lineage(&parsed, model, &physical),
78+
KIND_SELECT => select_lineage(&parsed, model, &physical),
79+
_ => Ok(None),
80+
};
81+
match built {
82+
Ok(Some((columns, has_star))) => FastLineageOutcome::Built { columns, has_star },
83+
Ok(None) => FastLineageOutcome::Omitted,
84+
Err(UnreadableExpression) => FastLineageOutcome::Deferred(LineageDeferral::NativeFailure),
85+
}
86+
}
87+
88+
type BuiltLineage = Option<(Vec<LineageColumn>, bool)>;
89+
90+
fn select_lineage(
91+
parsed: &Expression,
92+
model: &ParsedModel<'_>,
93+
physical: &[PhysicalResource],
94+
) -> Result<BuiltLineage, UnreadableExpression> {
95+
let alias_map = table_alias_map(parsed, physical);
96+
let unqualified = alias_map.single_resource();
97+
let mut lineages: Vec<LineageColumn> = Vec::new();
98+
let mut has_star = false;
99+
for (index, projection) in parsed.get_expressions().iter().enumerate() {
100+
if is_star(projection) {
101+
has_star = true;
102+
continue;
103+
}
104+
let inner = unaliased(projection)?;
105+
if is_star(inner) {
106+
has_star = true;
107+
continue;
108+
}
109+
let Some(output_column) = projection_output_name(projection, index, model.inferred_names)
110+
else {
111+
continue;
112+
};
113+
let (upstream_columns, confidence) =
114+
projection_upstream_columns(projection, &alias_map, unqualified)?;
115+
let transform_kind = classify_transform(inner, &upstream_columns);
116+
let confidence =
117+
if !upstream_columns.is_empty() || transform_kind == LineageTransformKind::Constant {
118+
confidence
119+
} else {
120+
LineageConfidence::Unknown
121+
};
122+
lineages.push(LineageColumn {
123+
output_column,
124+
transform_kind,
125+
confidence,
126+
upstream_columns,
127+
});
128+
}
129+
Ok(Some(with_star_columns(lineages, has_star, model, physical)))
130+
}
131+
132+
fn union_lineage(
133+
parsed: &Expression,
134+
model: &ParsedModel<'_>,
135+
physical: &[PhysicalResource],
136+
) -> Result<BuiltLineage, UnreadableExpression> {
137+
let selects: Vec<Expression> = set_expression_selects(parsed)?;
138+
if selects.is_empty() {
139+
return Ok(None);
140+
}
141+
let alias_maps: Vec<_> = selects
142+
.iter()
143+
.map(|select| table_alias_map(select, physical))
144+
.collect();
145+
let max_projection_count = selects
146+
.iter()
147+
.map(|select| select.get_expressions().len())
148+
.max()
149+
.unwrap_or(0);
150+
let mut lineages: Vec<LineageColumn> = Vec::new();
151+
let mut has_star = false;
152+
for index in 0..max_projection_count {
153+
let mut output_column = model.inferred_names.get(index).cloned();
154+
let mut upstream_columns: Vec<LineageSource> = Vec::new();
155+
let mut seen: HashSet<(LineageResourceType, String, String)> = HashSet::new();
156+
let mut confidence = LineageConfidence::High;
157+
let mut transform_kind = LineageTransformKind::Direct;
158+
for (select, alias_map) in selects.iter().zip(&alias_maps) {
159+
let Some(projection) = select.get_expressions().get(index) else {
160+
continue;
161+
};
162+
if is_star(projection) {
163+
has_star = true;
164+
continue;
165+
}
166+
let inner = unaliased(projection)?;
167+
if is_star(inner) {
168+
has_star = true;
169+
continue;
170+
}
171+
if output_column.is_none() {
172+
output_column = projection_output_name(projection, index, model.inferred_names);
173+
}
174+
let (branch_upstream, branch_confidence) =
175+
projection_upstream_columns(projection, alias_map, alias_map.single_resource())?;
176+
if branch_confidence == LineageConfidence::Unknown {
177+
confidence = LineageConfidence::Unknown;
178+
} else if branch_confidence == LineageConfidence::Medium
179+
&& confidence == LineageConfidence::High
180+
{
181+
confidence = LineageConfidence::Medium;
182+
}
183+
let branch_transform = classify_transform(inner, &branch_upstream);
184+
if branch_transform != LineageTransformKind::Direct {
185+
transform_kind = branch_transform;
186+
}
187+
for source in branch_upstream {
188+
let key = (
189+
source.resource_type,
190+
source.resource_name.clone(),
191+
source.column_name.clone(),
192+
);
193+
if seen.insert(key) {
194+
upstream_columns.push(source);
195+
}
196+
}
197+
}
198+
let Some(output_column) = output_column else {
199+
continue;
200+
};
201+
if upstream_columns.is_empty() && transform_kind != LineageTransformKind::Constant {
202+
confidence = LineageConfidence::Unknown;
203+
}
204+
lineages.push(LineageColumn {
205+
output_column,
206+
transform_kind,
207+
confidence,
208+
upstream_columns,
209+
});
210+
}
211+
Ok(Some(with_star_columns(lineages, has_star, model, physical)))
212+
}
213+
214+
fn with_star_columns(
215+
mut lineages: Vec<LineageColumn>,
216+
has_star: bool,
217+
model: &ParsedModel<'_>,
218+
physical: &[PhysicalResource],
219+
) -> (Vec<LineageColumn>, bool) {
220+
if has_star {
221+
let star_columns = star_lineage(
222+
model.schema,
223+
physical,
224+
lineages
225+
.iter()
226+
.map(|lineage| lineage.output_column.as_str()),
227+
);
228+
lineages.extend(star_columns);
229+
}
230+
(lineages, has_star)
231+
}

0 commit comments

Comments
 (0)