Skip to content

Commit 4c4ffb0

Browse files
authored
feat(plan): say how to fix missing upstreams, and rebuild cloned tables with --changed (#1562)
* fix(clone): leave replaced tables without a completed consumption record sqb clone (and a build's --defer-clone-from) replaced a destination table but kept its consumption rows, which describe the build the clone overwrote, so --changed could treat the cloned table as up to date with inputs it never read. A clone now appends a 'replaced' row for each table and seed it replaces; --changed reads that as no completed record and rebuilds the table once, and a later build supersedes the marker. * feat(plan): say how to fix missing upstreams in S301 and list them all S301 named at most five missing upstreams and stopped. It now lists the first five, says how many more there are, and offers each fix: defer to or clone from every target configured as a clone origin for this one (with a copyable `sqb clone` command naming every missing resource), or build them with `+`. Origins come from configuration only. `sqb plan --json` lists every missing name in `error.missing`, and the plan page shows the message as printed with a copy button per clone command. * fix: keep S301 when its hints fail and mark partly cloned boundaries as replaced A default target that does not resolve no longer turns S301 into an unknown-target error; the clone command then names its destination. --defer-to is offered only for project targets and not when the plan already defers. A defer clone that fails for one boundary still marks the boundaries it replaced. A failed marker write still fails the command, but only after fingerprints are copied, and a defer clone's C411 is reported first.
1 parent 2f0ef09 commit 4c4ffb0

36 files changed

Lines changed: 993 additions & 77 deletions

File tree

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
MODEL (description "Customers no clone touches, so --changed keeps skipping them.", materialized table);
2+
3+
SELECT 101 AS customer_id
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
MODEL (description "Orders a clone replaces in the destination target.", materialized table);
2+
3+
SELECT 1 AS order_id
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
MODEL (description "Orders read downstream of the cloned table.", materialized table);
2+
3+
SELECT order_id FROM __ref("fact_orders")

‎crates/sqlbuild-analysis/src/planner_identity/main/missing_upstream_message.rs‎

Lines changed: 117 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,16 @@
33
use std::collections::HashMap;
44

55
use crate::planner_identity::constants::MISSING_MESSAGE_ITEM_LIMIT;
6-
use crate::planner_identity::models::{GraphKey, MissingUpstream};
6+
use crate::planner_identity::models::{GraphKey, MissingUpstream, MissingUpstreamFixes};
77

8-
/// Missing lineage upstreams by name and, when only an audit or hook read requires one, that read's origin.
8+
/// Missing lineage upstreams with how to fix them and, when only an audit or hook read requires one, that read's origin.
99
pub fn missing_upstream_message(
1010
missing: &[MissingUpstream],
1111
edge_origins: &HashMap<(GraphKey, GraphKey), String>,
12+
fixes: &MissingUpstreamFixes,
1213
) -> String {
13-
let mut lineage_missing: Vec<&MissingUpstream> = Vec::new();
14+
let mut lineage_missing: Vec<&str> = Vec::new();
15+
let mut kinds: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
1416
let mut read_names: Vec<&str> = Vec::new();
1517
for entry in missing {
1618
let origins: Vec<&str> = entry
@@ -23,7 +25,8 @@ pub fn missing_upstream_message(
2325
})
2426
.collect();
2527
if origins.len() < entry.required_by.len() {
26-
lineage_missing.push(entry);
28+
lineage_missing.push(entry.key.name.as_str());
29+
kinds.insert(entry.key.kind.as_str());
2730
continue;
2831
}
2932
for origin in origins {
@@ -32,39 +35,121 @@ pub fn missing_upstream_message(
3235
}
3336
}
3437
}
35-
let mut parts: Vec<String> = Vec::new();
36-
if !lineage_missing.is_empty() {
37-
let names: Vec<&str> = lineage_missing
38+
let reads: Option<String> = audit_reads_text(&read_names);
39+
if lineage_missing.is_empty() {
40+
return format!("cannot build selected scope: {}", reads.unwrap_or_default());
41+
}
42+
let mut text: String = lineage_text(&lineage_missing, &kinds, fixes);
43+
if let Some(reads) = reads {
44+
text.push_str(&format!("\n\n Also, {reads}"));
45+
}
46+
text
47+
}
48+
49+
/// The missing lineage upstreams, a few by name, then how to read, clone or build them.
50+
fn lineage_text(
51+
names: &[&str],
52+
kinds: &std::collections::BTreeSet<&str>,
53+
fixes: &MissingUpstreamFixes,
54+
) -> String {
55+
let one: bool = names.len() == 1;
56+
let noun: String = match kinds.iter().collect::<Vec<_>>().as_slice() {
57+
[kind] if one => (*kind).to_string(),
58+
[kind] => format!("{kind}s"),
59+
_ => "models and seeds".to_owned(),
60+
};
61+
let place: String = fixes.target.as_ref().map_or_else(
62+
|| "the warehouse".to_owned(),
63+
|target| format!("target '{target}'"),
64+
);
65+
let mut lines: Vec<String> = vec![format!(
66+
"{} upstream {noun} this build reads {} exist in {place}",
67+
names.len(),
68+
if one { "doesn't" } else { "don't" }
69+
)];
70+
lines.extend(
71+
names
3872
.iter()
3973
.take(MISSING_MESSAGE_ITEM_LIMIT)
40-
.map(|entry| entry.key.name.as_str())
41-
.collect();
42-
parts.push(format!(
43-
"{} missing upstream dependencies ({})",
44-
lineage_missing.len(),
45-
names.join(", ")
74+
.map(|name| format!(" {name}")),
75+
);
76+
if names.len() > MISSING_MESSAGE_ITEM_LIMIT {
77+
lines.push(format!(
78+
" ... {} more (sqb plan --json lists all)",
79+
names.len() - MISSING_MESSAGE_ITEM_LIMIT
4680
));
4781
}
48-
if let [name] = read_names.as_slice() {
49-
parts.push(format!(
50-
"{name}, which is not selected and does not exist in the warehouse; select it or build it first"
51-
));
52-
} else if !read_names.is_empty() {
53-
let shown: String = read_names
54-
.iter()
55-
.take(MISSING_MESSAGE_ITEM_LIMIT)
56-
.copied()
57-
.collect::<Vec<&str>>()
58-
.join("; ");
59-
let more: &str = if read_names.len() > MISSING_MESSAGE_ITEM_LIMIT {
60-
"; ..."
82+
lines.push(String::new());
83+
let (exists, them): (&str, &str) = if one {
84+
("it exists", "it")
85+
} else {
86+
("they exist", "them")
87+
};
88+
let read_label: String = format!("read {them} from it for this run:");
89+
let copy_label: String = format!("copy {them} into this target:");
90+
let build_label: String = format!(
91+
"{} {them} too:",
92+
if fixes.origins.is_empty() {
93+
"Build"
6194
} else {
62-
""
63-
};
64-
parts.push(format!(
65-
"{} audit reads are not selected and do not exist in the warehouse ({shown}{more}); select them or build them first",
66-
read_names.len()
95+
"Or build"
96+
}
97+
);
98+
let width: usize = if fixes.origins.is_empty() {
99+
build_label.len() + 2
100+
} else {
101+
(read_label.len() + 4).max(copy_label.len() + 4)
102+
}
103+
.max(build_label.len() + 2);
104+
let to: String = fixes
105+
.clone_to
106+
.as_ref()
107+
.map(|target| format!(" --to {target}"))
108+
.unwrap_or_default();
109+
for origin in &fixes.origins {
110+
lines.push(format!(" If {exists} in {origin}:"));
111+
if fixes.deferrable.contains(origin) {
112+
lines.push(format!(
113+
" {read_label:<0$} --defer-to {origin}",
114+
width - 4
115+
));
116+
}
117+
lines.push(format!(
118+
" {copy_label:<0$} sqb clone --from {origin}{to} -s {1}",
119+
width - 4,
120+
names.join(" ")
67121
));
68122
}
69-
format!("cannot build selected scope: {}", parts.join("; "))
123+
lines.push(format!(
124+
" {build_label:<0$} add + before your selection",
125+
width - 2
126+
));
127+
lines.join("\n")
128+
}
129+
130+
/// The audit and hook reads that need a missing upstream, a few by name.
131+
fn audit_reads_text(read_names: &[&str]) -> Option<String> {
132+
match read_names {
133+
[] => None,
134+
[name] => Some(format!(
135+
"{name}, which is not selected and does not exist in the warehouse; select it or build it first"
136+
)),
137+
_ => {
138+
let shown: String = read_names
139+
.iter()
140+
.take(MISSING_MESSAGE_ITEM_LIMIT)
141+
.copied()
142+
.collect::<Vec<&str>>()
143+
.join("; ");
144+
let more: &str = if read_names.len() > MISSING_MESSAGE_ITEM_LIMIT {
145+
"; ..."
146+
} else {
147+
""
148+
};
149+
Some(format!(
150+
"{} audit reads are not selected and do not exist in the warehouse ({shown}{more}); select them or build them first",
151+
read_names.len()
152+
))
153+
}
154+
}
70155
}

‎crates/sqlbuild-analysis/src/planner_identity/models.rs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,19 @@ pub struct AvailableUpstreams {
8787
pub deferred_relations: Option<HashSet<String>>,
8888
}
8989

90+
/// What a missing-upstream message offers to fix the misses with, all from configuration.
91+
#[derive(Clone, Debug, Default, PartialEq, Eq)]
92+
pub struct MissingUpstreamFixes {
93+
/// The active target, named as where the upstreams are missing.
94+
pub target: Option<String>,
95+
/// Targets the active target may clone from, to defer to or clone the upstreams from.
96+
pub origins: Vec<String>,
97+
/// The origins `--defer-to` accepts: project targets, offered only when this plan does not defer already.
98+
pub deferrable: Vec<String>,
99+
/// The clone command's `--to`, needed when the active target is not the default one.
100+
pub clone_to: Option<String>,
101+
}
102+
90103
/// One upstream dependency missing from both scope and warehouse, with its dependents.
91104
#[derive(Clone, Debug, PartialEq, Eq)]
92105
pub struct MissingUpstream {

‎crates/sqlbuild-analysis/src/planner_identity/tests/test_planner_identity.rs‎

Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ use crate::planner_identity::main::missing_upstreams::missing_upstreams;
1010
use crate::planner_identity::main::stale_upstream_warning_message::stale_upstream_warning_message;
1111
use crate::planner_identity::main::topological_order::topological_order;
1212
use crate::planner_identity::models::{
13-
AvailableUpstreams, FunctionFingerprintFields, GraphKey, MissingUpstream, StaleWarning,
14-
StalenessNames,
13+
AvailableUpstreams, FunctionFingerprintFields, GraphKey, MissingUpstream, MissingUpstreamFixes,
14+
StaleWarning, StalenessNames,
1515
};
1616
use crate::planner_identity::tests::helpers::{
1717
chain_head_hash, chain_identity_graph, chain_staleness_graph, cyclic_identity_graph,
@@ -406,11 +406,58 @@ fn given_selected_keys_when_checking_buildability_then_reports_missing_upstreams
406406
..AvailableUpstreams::default()
407407
},
408408
origins: HashMap::new(),
409+
fixes: MissingUpstreamFixes::default(),
409410
expected_missing: vec![MissingUpstream {
410411
key: model("raw"),
411412
required_by: vec![model("a"), model("b")],
412413
}],
413-
expected_message: "cannot build selected scope: 1 missing upstream dependencies (raw)",
414+
expected_message: concat!(
415+
"1 upstream model this build reads doesn't exist in the warehouse\n",
416+
" raw\n",
417+
"\n",
418+
" Build it too: add + before your selection",
419+
),
420+
},
421+
BuildabilityTestCase {
422+
description: "more misses than shown, with clone origins and a non-default target",
423+
selected: vec![model("report")],
424+
upstream: HashMap::from([(
425+
model("report"),
426+
["f", "a", "e", "b", "d", "c"]
427+
.map(model)
428+
.into_iter()
429+
.chain([key("seed", "codes")])
430+
.collect(),
431+
)]),
432+
available: AvailableUpstreams::default(),
433+
origins: HashMap::new(),
434+
fixes: MissingUpstreamFixes {
435+
target: Some("dev".to_owned()),
436+
origins: vec!["prod".to_owned(), "staging".to_owned()],
437+
deferrable: vec!["prod".to_owned()],
438+
clone_to: Some("dev".to_owned()),
439+
},
440+
expected_missing: ["a", "b", "c", "d", "e", "f"]
441+
.map(model)
442+
.into_iter()
443+
.chain([key("seed", "codes")])
444+
.map(|key| MissingUpstream {
445+
key,
446+
required_by: vec![model("report")],
447+
})
448+
.collect(),
449+
expected_message: concat!(
450+
"7 upstream models and seeds this build reads don't exist in target 'dev'\n",
451+
" a\n b\n c\n d\n e\n",
452+
" ... 2 more (sqb plan --json lists all)\n",
453+
"\n",
454+
" If they exist in prod:\n",
455+
" read them from it for this run: --defer-to prod\n",
456+
" copy them into this target: sqb clone --from prod --to dev -s a b c d e f codes\n",
457+
" If they exist in staging:\n",
458+
" copy them into this target: sqb clone --from staging --to dev -s a b c d e f codes\n",
459+
" Or build them too: add + before your selection",
460+
),
414461
},
415462
BuildabilityTestCase {
416463
description: "only an audit read requires the upstream",
@@ -421,6 +468,7 @@ fn given_selected_keys_when_checking_buildability_then_reports_missing_upstreams
421468
(model("a"), model("lookup")),
422469
"audit 'check' on 'a' reads 'lookup'".to_owned(),
423470
)]),
471+
fixes: MissingUpstreamFixes::default(),
424472
expected_missing: vec![MissingUpstream {
425473
key: model("lookup"),
426474
required_by: vec![model("a")],
@@ -436,7 +484,7 @@ fn given_selected_keys_when_checking_buildability_then_reports_missing_upstreams
436484
);
437485
assert_eq!(
438486
(
439-
missing_upstream_message(&missing, &test_case.origins),
487+
missing_upstream_message(&missing, &test_case.origins, &test_case.fixes),
440488
missing
441489
),
442490
(

‎crates/sqlbuild-analysis/src/planner_identity/tests/test_types.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet};
22

33
use crate::planner_identity::models::{
44
AvailableUpstreams, FunctionFingerprintFields, GraphKey, IdentityGraph, MissingUpstream,
5-
StaleWarning, StalenessGraph,
5+
MissingUpstreamFixes, StaleWarning, StalenessGraph,
66
};
77
use crate::planner_identity::types::IdentityHashes;
88

@@ -31,6 +31,7 @@ pub(super) struct BuildabilityTestCase {
3131
pub(super) upstream: HashMap<GraphKey, Vec<GraphKey>>,
3232
pub(super) available: AvailableUpstreams,
3333
pub(super) origins: HashMap<(GraphKey, GraphKey), String>,
34+
pub(super) fixes: MissingUpstreamFixes,
3435
pub(super) expected_missing: Vec<MissingUpstream>,
3536
pub(super) expected_message: &'static str,
3637
}

‎crates/sqlbuild-python-base/src/records/_helpers/compiler_errors/constants.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -398,7 +398,7 @@ pub(crate) const COMPILER_ERRORS: &[ErrorSpec] = &[
398398
doc: "Raised when planner inputs cannot be resolved safely.",
399399
class_attributes: &[("code", ClassValue::Text("S000"))],
400400
required: &[],
401-
optional: &[],
401+
optional: &["missing"],
402402
fixed: &[],
403403
},
404404
ErrorSpec {

‎crates/sqlbuild-python-base/src/records/_helpers/native_classes/construct.rs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,17 @@ pub(crate) fn new_error(
6060
pub(crate) fn exception_from(
6161
class: PyResult<Bound<'_, PyAny>>,
6262
message: &str,
63+
keywords: (Option<&str>, Option<&str>),
64+
) -> PyErr {
65+
exception_with_fields(class, message, keywords, &[])
66+
}
67+
68+
/// The exception `class` with `message`, the given `code` and `help`, and its declared `fields`, or the error raising it.
69+
pub(crate) fn exception_with_fields<'py>(
70+
class: PyResult<Bound<'py, PyAny>>,
71+
message: &str,
6372
(code, help): (Option<&str>, Option<&str>),
73+
fields: &[(&str, Bound<'py, PyAny>)],
6474
) -> PyErr {
6575
class
6676
.and_then(|class| {
@@ -71,6 +81,9 @@ pub(crate) fn exception_from(
7181
if let Some(help) = help {
7282
keywords.set_item("help", help)?;
7383
}
84+
for (name, value) in fields {
85+
keywords.set_item(*name, value)?;
86+
}
7487
class.call((message,), Some(&keywords))
7588
})
7689
.map_or_else(|error| error, PyErr::from_value)

‎crates/sqlbuild-python-base/src/records/main/construct/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ pub mod error_class;
44
pub mod exception_from;
55
pub mod new_annotated_error;
66
pub mod new_error;
7+
pub mod new_error_with_fields;
78
pub mod new_plain_error;
89
pub mod new_record;
910
pub mod new_record_with;

0 commit comments

Comments
 (0)