Skip to content

Commit 6ea74e6

Browse files
committed
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 834cbb3 commit 6ea74e6

9 files changed

Lines changed: 169 additions & 13 deletions

File tree

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

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -108,10 +108,12 @@ fn lineage_text(
108108
.unwrap_or_default();
109109
for origin in &fixes.origins {
110110
lines.push(format!(" If {exists} in {origin}:"));
111-
lines.push(format!(
112-
" {read_label:<0$} --defer-to {origin}",
113-
width - 4
114-
));
111+
if fixes.deferrable.contains(origin) {
112+
lines.push(format!(
113+
" {read_label:<0$} --defer-to {origin}",
114+
width - 4
115+
));
116+
}
115117
lines.push(format!(
116118
" {copy_label:<0$} sqb clone --from {origin}{to} -s {1}",
117119
width - 4,

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,8 @@ pub struct MissingUpstreamFixes {
9494
pub target: Option<String>,
9595
/// Targets the active target may clone from, to defer to or clone the upstreams from.
9696
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>,
9799
/// The clone command's `--to`, needed when the active target is not the default one.
98100
pub clone_to: Option<String>,
99101
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -434,6 +434,7 @@ fn given_selected_keys_when_checking_buildability_then_reports_missing_upstreams
434434
fixes: MissingUpstreamFixes {
435435
target: Some("dev".to_owned()),
436436
origins: vec!["prod".to_owned(), "staging".to_owned()],
437+
deferrable: vec!["prod".to_owned()],
437438
clone_to: Some("dev".to_owned()),
438439
},
439440
expected_missing: ["a", "b", "c", "d", "e", "f"]
@@ -454,7 +455,6 @@ fn given_selected_keys_when_checking_buildability_then_reports_missing_upstreams
454455
" read them from it for this run: --defer-to prod\n",
455456
" copy them into this target: sqb clone --from prod --to dev -s a b c d e f codes\n",
456457
" If they exist in staging:\n",
457-
" read them from it for this run: --defer-to staging\n",
458458
" copy them into this target: sqb clone --from staging --to dev -s a b c d e f codes\n",
459459
" Or build them too: add + before your selection",
460460
),

‎crates/sqlbuild-python-planner/src/planner_phases/_helpers/outputs/buildability.rs‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ pub(crate) fn check_selected_scope_buildability<'py>(
7777
let message = missing_upstream_message(
7878
&missing,
7979
&origins,
80-
&missing_upstream_fixes(runtime, &project)?,
80+
&missing_upstream_fixes(runtime, &project, available.deferred_relations.is_some())?,
8181
);
8282
let names = missing.iter().map(|entry| entry.key.name.as_str());
8383
return Err(new_error_with_fields(
@@ -98,10 +98,11 @@ pub(crate) fn check_selected_scope_buildability<'py>(
9898
)
9999
}
100100

101-
/// The active target, the targets it may clone from, and the clone `--to` it needs, from configuration only.
101+
/// The active target, its clone or deferral origins, and the clone `--to` it needs (also when the default target is unknown).
102102
fn missing_upstream_fixes(
103103
runtime: &Bound<'_, PyAny>,
104104
project: &Bound<'_, PyAny>,
105+
deferring: bool,
105106
) -> PyResult<MissingUpstreamFixes> {
106107
let py: Python<'_> = runtime.py();
107108
let target: Option<String> = native_field(project, "effective_target_name")?.extract()?;
@@ -123,22 +124,29 @@ fn missing_upstream_fixes(
123124
native_field(&native_field(&config, "clone")?, flag)?.is_truthy()
124125
};
125126
let mut origins: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
127+
let mut deferrable: Vec<String> = Vec::new();
126128
if allows(&active, "allow_as_clone_destination")? {
127-
for config in [&configs.0, &configs.1] {
129+
for (config, project_targets) in [(&configs.0, true), (&configs.1, false)] {
128130
for name in native_field(config, "targets")?.try_iter()? {
129131
let name: String = name?.extract()?;
130132
if name != active && allows(&name, "allow_as_clone_origin")? {
133+
if project_targets && !deferring {
134+
deferrable.push(name.clone());
135+
}
131136
origins.insert(name);
132137
}
133138
}
134139
}
135140
}
136141
let default: Option<String> =
137-
resolve_target_name(py, &configs.0, &configs.1, &py.None().into_bound(py))?
138-
.map(|name| name.to_string());
142+
match resolve_target_name(py, &configs.0, &configs.1, &py.None().into_bound(py)) {
143+
Ok(name) => name.map(|name| name.to_string()),
144+
Err(_) => None,
145+
};
139146
Ok(MissingUpstreamFixes {
140147
clone_to: (default.as_deref() != Some(active.as_str())).then(|| active.clone()),
141148
target,
142149
origins: origins.into_iter().collect(),
150+
deferrable,
143151
})
144152
}

‎crates/sqlbuild-python/src/bindings/_helpers/build_command/defer_clone.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -441,6 +441,8 @@ fn clone_boundaries<'py>(
441441
),
442442
)?;
443443
let result: Bound<'py, PyAny> = executed_clone(context, prephase, (&pipeline, connection))?;
444+
let marked: PyResult<()> =
445+
forget_replaced_consumption((&prephase.adapter, connection), &pipeline, &result);
444446
let failed: Vec<String> = failed_items(&result)?;
445447
if !failed.is_empty() {
446448
return Err(user_error(
@@ -482,7 +484,7 @@ fn clone_boundaries<'py>(
482484
),
483485
],
484486
)?;
485-
forget_replaced_consumption((&prephase.adapter, connection), &pipeline, &result)
487+
marked
486488
}
487489

488490
/// Clone the selected boundary relations from the origin before build planning.

‎crates/sqlbuild-python/src/bindings/_helpers/clone/clone_execution.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -413,7 +413,9 @@ pub(crate) fn execute_clone_plan<'py>(
413413
let closed: PyResult<Bound<'py, PyAny>> = event_writer.call_method0("close");
414414
let result: Bound<'py, PyAny> = executed?;
415415
closed?;
416+
let marked: PyResult<()> =
417+
forget_replaced_consumption((&invocation.adapter, connection), pipeline, &result);
416418
copy_fingerprints(invocation, (pipeline, connection), &result)?;
417-
forget_replaced_consumption((&invocation.adapter, connection), pipeline, &result)?;
419+
marked?;
418420
Ok((result, started.elapsed().as_secs_f64()))
419421
}

‎tests/e2e/src/sqlbuild/cli/commands/main/clone/_test_types.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,3 +104,22 @@ class MissingUpstreamFixesE2ETestCase:
104104
destination_allowed: bool
105105
expected_fragments: tuple[str, ...]
106106
unexpected_fragments: tuple[str, ...]
107+
108+
109+
@dataclass(frozen=True)
110+
class PartialDeferCloneE2ETestCase:
111+
"""A defer clone with one boundary missing in the origin, and what `plan --changed` says."""
112+
113+
description: str
114+
dropped_origin_table: str
115+
expected_fragments: tuple[str, ...]
116+
117+
118+
@dataclass(frozen=True)
119+
class UnwritableConsumptionDeferCloneE2ETestCase:
120+
"""A partly failed defer clone whose destination consumption table rejects writes."""
121+
122+
description: str
123+
dropped_origin_table: str
124+
before_clone: tuple[str, ...]
125+
expected_fragments: tuple[str, ...]

‎tests/e2e/src/sqlbuild/cli/commands/main/clone/helpers.py‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,11 @@
77
from pathlib import Path
88
from textwrap import dedent
99

10-
from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import prepare_inline_project, run_sqb
10+
from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import (
11+
execute_duckdb,
12+
prepare_inline_project,
13+
run_sqb,
14+
)
1115

1216
PROJECT_FILES: dict[str, str] = {
1317
"sqlbuild_project.toml": dedent(
@@ -245,3 +249,50 @@ def plan_missing_upstreams(
245249
plan_command,
246250
run_sqb(command=plan_command, project_dir=project_dir),
247251
)
252+
253+
254+
def defer_clone_with_missing_origin(
255+
*, tmp_path: Path, dropped_origin_table: str, before_clone: tuple[str, ...] = ()
256+
) -> tuple[subprocess.CompletedProcess[str], subprocess.CompletedProcess[str]]:
257+
"""Defer-clone `report` with one of its boundaries dropped in `prod`, then `plan --changed`."""
258+
259+
project_dir: Path = prepare_inline_project(
260+
tmp_path=tmp_path,
261+
project_name="partial_defer_clone_project",
262+
repo_files={
263+
"sqlbuild_project.toml": (
264+
'name = "partial_defer_clone_project"\nadapter = "duckdb"\n'
265+
'default_target = "dev"\n\n[connection]\ndatabase = "shop.duckdb"\n\n'
266+
'[targets.prod]\nschema = "prod"\n\n'
267+
"[targets.prod.clone]\nallow_as_clone_origin = true\n\n"
268+
'[targets.dev]\nschema = "dev"\n\n'
269+
"[targets.dev.clone]\nallow_as_clone_destination = true\n"
270+
),
271+
"models/orders.sql": (
272+
"MODEL (description 'Orders.', materialized table);\n\nSELECT 1 AS id\n"
273+
),
274+
"models/customers.sql": (
275+
"MODEL (description 'Customers.', materialized table);\n\nSELECT 1 AS id\n"
276+
),
277+
"models/report.sql": (
278+
"MODEL (description 'Report.', materialized table);\n\n"
279+
'SELECT o.id FROM __ref("orders") AS o JOIN __ref("customers") AS c USING (id)\n'
280+
),
281+
},
282+
)
283+
for target in ("dev", "prod"):
284+
built: subprocess.CompletedProcess[str] = run_sqb(
285+
command=("--no-color", "build", "--target", target), project_dir=project_dir
286+
)
287+
assert built.returncode == 0, built.stdout + built.stderr
288+
for sql in (f"DROP TABLE prod.{dropped_origin_table}", *before_clone):
289+
execute_duckdb(db_path=project_dir / "shop.duckdb", sql=sql)
290+
cloned: subprocess.CompletedProcess[str] = run_sqb(
291+
command=("--no-color", "build", "--select", "report", "--defer-clone-from", "prod"),
292+
project_dir=project_dir,
293+
)
294+
planned: subprocess.CompletedProcess[str] = run_sqb(
295+
command=("--no-color", "plan", "--changed", "--select", "orders", "customers"),
296+
project_dir=project_dir,
297+
)
298+
return cloned, planned

‎tests/e2e/src/sqlbuild/cli/commands/main/clone/test_clone.py‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,12 @@
1919
ClonePolicyErrorTestCase,
2020
ClonePythonFunctionE2ETestCase,
2121
MissingUpstreamFixesE2ETestCase,
22+
PartialDeferCloneE2ETestCase,
23+
UnwritableConsumptionDeferCloneE2ETestCase,
2224
)
2325
from tests.e2e.src.sqlbuild.cli.commands.main.clone.helpers import (
2426
MISSING_UPSTREAMS,
27+
defer_clone_with_missing_origin,
2528
plan_missing_upstreams,
2629
)
2730
from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import (
@@ -1050,6 +1053,13 @@ def test_given_missing_upstreams_when_planning_then_s301_lists_them_with_fixes(
10501053
expected_clone_command="sqb clone --from prod --to dev -s "
10511054
+ " ".join(MISSING_UPSTREAMS),
10521055
),
1056+
CloneMissingUpstreamE2ETestCase(
1057+
description="a default target that does not exist still yields a runnable clone",
1058+
default_target="retired",
1059+
target_args=("--target", "dev"),
1060+
expected_clone_command="sqb clone --from prod --to dev -s "
1061+
+ " ".join(MISSING_UPSTREAMS),
1062+
),
10531063
],
10541064
ids=lambda case: case.description,
10551065
)
@@ -1077,3 +1087,63 @@ def test_given_missing_upstreams_when_running_printed_clone_then_plan_succeeds(
10771087
assert printed == [test_case.expected_clone_command], refused.stdout + refused.stderr
10781088
assert cloned.returncode == 0, cloned.stdout + cloned.stderr
10791089
assert planned.returncode == 0, planned.stdout + planned.stderr
1090+
1091+
1092+
@pytest.mark.parametrize(
1093+
"test_case",
1094+
[
1095+
PartialDeferCloneE2ETestCase(
1096+
description="a boundary cloned before another failed still rebuilds",
1097+
dropped_origin_table="customers",
1098+
expected_fragments=(
1099+
"orders no completed record",
1100+
"Unchanged (1): skipped by --changed",
1101+
),
1102+
),
1103+
],
1104+
ids=lambda case: case.description,
1105+
)
1106+
def test_given_partly_failed_defer_clone_when_planning_changed_then_cloned_boundary_rebuilds(
1107+
test_case: PartialDeferCloneE2ETestCase,
1108+
tmp_path: Path,
1109+
) -> None:
1110+
cloned, planned = defer_clone_with_missing_origin(
1111+
tmp_path=tmp_path, dropped_origin_table=test_case.dropped_origin_table
1112+
)
1113+
1114+
assert cloned.returncode == 1, cloned.stdout + cloned.stderr
1115+
assert "error[C411]" in cloned.stdout + cloned.stderr
1116+
assert planned.returncode == 0, planned.stdout + planned.stderr
1117+
assert all(fragment in planned.stdout for fragment in test_case.expected_fragments), (
1118+
planned.stdout
1119+
)
1120+
1121+
1122+
@pytest.mark.parametrize(
1123+
"test_case",
1124+
[
1125+
UnwritableConsumptionDeferCloneE2ETestCase(
1126+
description="the failed boundary is reported, not the consumption write",
1127+
dropped_origin_table="customers",
1128+
before_clone=(
1129+
"DROP TABLE dev._sqlbuild_consumption",
1130+
"CREATE TABLE dev._sqlbuild_consumption (unexpected INTEGER)",
1131+
),
1132+
expected_fragments=("error[C411]", "customers: missing in origin environment"),
1133+
),
1134+
],
1135+
ids=lambda case: case.description,
1136+
)
1137+
def test_given_unwritable_consumption_table_when_defer_clone_partly_fails_then_c411_is_reported(
1138+
test_case: UnwritableConsumptionDeferCloneE2ETestCase,
1139+
tmp_path: Path,
1140+
) -> None:
1141+
cloned, _ = defer_clone_with_missing_origin(
1142+
tmp_path=tmp_path,
1143+
dropped_origin_table=test_case.dropped_origin_table,
1144+
before_clone=test_case.before_clone,
1145+
)
1146+
1147+
output: str = cloned.stdout + cloned.stderr
1148+
assert cloned.returncode == 1, output
1149+
assert all(fragment in output for fragment in test_case.expected_fragments), output

0 commit comments

Comments
 (0)