Skip to content

Commit feaf623

Browse files
committed
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.
1 parent 66652f6 commit feaf623

16 files changed

Lines changed: 250 additions & 7 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-python-front/src/native_host/_helpers/consumption_state.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ pub(crate) fn ensure_table(
125125
}
126126

127127
/// Whether the warehouse catalog lists the consumption table in `location`.
128-
fn table_exists(
128+
pub(crate) fn table_exists(
129129
adapter: &Bound<'_, PyAny>,
130130
connection: &Bound<'_, PyAny>,
131131
location: &Location,
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
//! Leave relations replaced outside a recorded build without a completed consumption record.
2+
3+
use std::collections::BTreeMap;
4+
5+
use pyo3::prelude::{Bound, PyAny, PyResult};
6+
use sqlbuild_state::consumption::main::replaced_append::replaced_append;
7+
use sqlbuild_state::consumption::models::{ConsumptionAppend, NodeKey, RelationKey};
8+
use uuid::Uuid;
9+
10+
use crate::native_host::_helpers::consumption_state::{append, table_exists};
11+
use crate::native_host::models::Location;
12+
13+
/// Append a never-completed execution for each of `replaced` where its schema has a consumption table.
14+
pub fn append_replaced_consumption(
15+
(adapter, connection): (&Bound<'_, PyAny>, &Bound<'_, PyAny>),
16+
run_id: &str,
17+
replaced: Vec<(NodeKey, RelationKey)>,
18+
) -> PyResult<()> {
19+
let mut rows: BTreeMap<Location, Vec<ConsumptionAppend>> = BTreeMap::new();
20+
for (node, relation) in replaced {
21+
let execution_id: String = Uuid::now_v7().to_string();
22+
rows.entry(Location::of(&relation))
23+
.or_default()
24+
.push(replaced_append((node, relation), (&execution_id, run_id)));
25+
}
26+
for (location, rows) in rows {
27+
if table_exists(adapter, connection, &location)? {
28+
append(adapter, connection, &location, &rows)?;
29+
}
30+
}
31+
Ok(())
32+
}

‎crates/sqlbuild-python-front/src/native_host/main/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
pub mod append_observations;
2+
pub mod append_replaced_consumption;
23
pub mod execute;
34
pub mod fixed_state_table_sql;
45
pub mod integer_literal;

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ use sqlbuild_host::entries::models::ExecutorHost;
1919
use crate::bindings::_helpers::build_command::invocation::BuildContext;
2020
use crate::bindings::_helpers::build_command::policies::build_command_error;
2121
use crate::bindings::_helpers::build_command::policies::enforce_model_execution_limit_binding;
22+
use crate::bindings::_helpers::clone::clone_execution::forget_replaced_consumption;
2223
use crate::bindings::_helpers::clone::clone_pipeline::run_clone_pipeline_with_options;
2324
use crate::bindings::_helpers::dbt_interop::reference_resolver::resolve_external_sql_reference_resolver;
2425
use sqlbuild_python_base::boundary::main::call_with::call_with;
@@ -455,7 +456,7 @@ fn clone_boundaries<'py>(
455456
call_with(
456457
&host_entry(py, ExecutorHost::CopyCloneFingerprints)?,
457458
&[
458-
("result", result),
459+
("result", result.clone()),
459460
(
460461
"origin_model_entries",
461462
native_field(&pipeline, "origin_model_entries")?,
@@ -481,7 +482,7 @@ fn clone_boundaries<'py>(
481482
),
482483
],
483484
)?;
484-
Ok(())
485+
forget_replaced_consumption((&prephase.adapter, connection), &pipeline, &result)
485486
}
486487

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

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

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Execute the prepared clone plan and propagate fingerprints.
22
3-
use std::collections::HashMap;
3+
use std::collections::{HashMap, HashSet};
44
use std::time::Instant;
55

66
use pyo3::prelude::{Bound, Py, PyAny, PyAnyMethods, PyResult, Python};
@@ -13,6 +13,7 @@ use crate::bindings::_helpers::clone::clone_command::Invocation;
1313
use crate::bindings::_helpers::clone::clone_progress::{
1414
CloneFingerprintReporter, CloneItemPrinter,
1515
};
16+
use sqlbuild_analysis::fingerprint_storage::constants::{NODE_TYPE_MODEL, NODE_TYPE_SEED};
1617
use sqlbuild_python_base::boundary::main::call_with::call_with;
1718
use sqlbuild_python_base::boundary::main::within::within;
1819
use sqlbuild_python_base::native_host::main::host_entry::host_entry;
@@ -23,7 +24,10 @@ use sqlbuild_python_base::records::main::fields::field::field as native_field;
2324
use sqlbuild_python_base::records::main::fields::mapping_items::mapping_items;
2425
use sqlbuild_python_base::records::types::RecordId;
2526
use sqlbuild_python_front::contracts::main::resolve_target_config::resolve_target_config;
27+
use sqlbuild_python_front::native_host::main::append_replaced_consumption::append_replaced_consumption;
2628
use sqlbuild_python_output::result_output::models::ExecutionEventWriter;
29+
use sqlbuild_python_planner::consumption::main::relation::relation;
30+
use sqlbuild_state::consumption::models::{NodeKey, RelationKey};
2731

2832
const DESTINATION_ENTRY_GROUPS: [&str; 4] = [
2933
"destination_source_entries",
@@ -37,6 +41,13 @@ const ORIGIN_ENTRY_GROUPS: [&str; 3] = [
3741
"origin_seed_entries",
3842
];
3943

44+
/// A clone item that finished cleanly.
45+
const SUCCESS_STATUS: &str = "success";
46+
/// Clone actions that replace the destination relation with the origin's data.
47+
const REPLACING_ACTIONS: [&str; 2] = ["cloned", "copied"];
48+
/// The materialization of a model the clone recreates as a view rather than replacing.
49+
const VIEW_MATERIALIZATION: &str = "view";
50+
4051
/// The pipeline's plan entries of `groups`, in order.
4152
fn entries<'py>(pipeline: &Bound<'py, PyAny>, groups: &[&str]) -> PyResult<Vec<Bound<'py, PyAny>>> {
4253
let mut found: Vec<Bound<'py, PyAny>> = Vec::new();
@@ -310,6 +321,57 @@ fn copy_fingerprints<'py>(
310321
Ok(())
311322
}
312323

324+
/// Mark each table and seed the clone replaced as having no completed consumption record, so `--changed` rebuilds it once.
325+
pub(crate) fn forget_replaced_consumption(
326+
(adapter, connection): (&Bound<'_, PyAny>, &Bound<'_, PyAny>),
327+
pipeline: &Bound<'_, PyAny>,
328+
result: &Bound<'_, PyAny>,
329+
) -> PyResult<()> {
330+
let mut replaced_names: HashSet<String> = HashSet::new();
331+
for item in native_field(result, "item_results")?.try_iter()? {
332+
let item: Bound<'_, PyAny> = item?;
333+
let status: String = native_field(&native_field(&item, "status")?, "value")?.extract()?;
334+
let action: String = native_field(&native_field(&item, "action")?, "value")?.extract()?;
335+
if status == SUCCESS_STATUS && REPLACING_ACTIONS.contains(&action.as_str()) {
336+
replaced_names.insert(native_field(&item, "name")?.extract()?);
337+
}
338+
}
339+
let mut replaced: Vec<(NodeKey, RelationKey)> = Vec::new();
340+
for (group, kind) in [
341+
("destination_model_entries", NODE_TYPE_MODEL),
342+
("destination_seed_entries", NODE_TYPE_SEED),
343+
] {
344+
for entry in native_field(pipeline, group)?.try_iter()? {
345+
let entry: Bound<'_, PyAny> = entry?;
346+
let name: String = native_field(&entry, "name")?.extract()?;
347+
let destination: Bound<'_, PyAny> = native_field(&entry, "destination")?;
348+
let view: bool = kind == NODE_TYPE_MODEL
349+
&& native_field(&native_field(&entry, "materialization_type")?, "value")?
350+
.extract::<String>()?
351+
== VIEW_MATERIALIZATION;
352+
if view
353+
|| !replaced_names.contains(&name)
354+
|| native_field(&destination, "schema")?.is_none()
355+
{
356+
continue;
357+
}
358+
replaced.push((
359+
NodeKey {
360+
kind: kind.to_owned(),
361+
name,
362+
},
363+
relation(&destination)?,
364+
));
365+
}
366+
}
367+
let project: Bound<'_, PyAny> = native_field(pipeline, "destination_project")?;
368+
append_replaced_consumption(
369+
(adapter, connection),
370+
&native_field(&project, "run_id")?.extract::<String>()?,
371+
replaced,
372+
)
373+
}
374+
313375
/// Execute the clone, streaming items, then copy fingerprints; returns the result and elapsed seconds.
314376
pub(crate) fn execute_clone_plan<'py>(
315377
request: &Bound<'py, PyAny>,
@@ -352,5 +414,6 @@ pub(crate) fn execute_clone_plan<'py>(
352414
let result: Bound<'py, PyAny> = executed?;
353415
closed?;
354416
copy_fingerprints(invocation, (pipeline, connection), &result)?;
417+
forget_replaced_consumption((&invocation.adapter, connection), pipeline, &result)?;
355418
Ok((result, started.elapsed().as_secs_f64()))
356419
}

‎crates/sqlbuild-state/src/consumption/_helpers/decision.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,11 @@ fn execution_changes(node: &NodeFacts, context: &Context<'_>, window: &Window<'_
235235
let mut changes: Vec<Change> = Vec::new();
236236
for execution in window.executions {
237237
if !execution.complete {
238-
return vec![always(RunReason::Unfinished)];
238+
return vec![always(if execution.replaced {
239+
RunReason::NoRecord
240+
} else {
241+
RunReason::Unfinished
242+
})];
239243
}
240244
if execution.version_hash.as_deref() != Some(node.version_hash.as_str()) {
241245
changes.push(definition(RunReason::DefinitionChanged));

‎crates/sqlbuild-state/src/consumption/_helpers/history.rs‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
33
use std::collections::{BTreeMap, BTreeSet, HashMap};
44

5-
use crate::consumption::constants::{ORDER_SKEW_MICROS, SUCCEEDED_PHASE};
5+
use crate::consumption::constants::{ORDER_SKEW_MICROS, REPLACED_PHASE, SUCCEEDED_PHASE};
66
use crate::consumption::models::{
77
ConsumedInput, ConsumptionHistory, ConsumptionRow, Execution, RelationHistory, RelationKey,
88
};
@@ -18,7 +18,7 @@ struct ExecutionRows<'a> {
1818
/// A retried append repeats a row: its execution, phase and the input it records.
1919
type RowIdentity<'a> = (&'a str, &'a str, Option<(&'a str, &'a str, &'a str)>);
2020

21-
/// Recent executions per relation, from rows read newest first with at most `limit` per relation.
21+
/// Recent executions per relation (rows newest first, at most `limit` each); a replacement marker counts only while newest.
2222
pub(crate) fn build_history(rows: &[ConsumptionRow], limit: usize) -> ConsumptionHistory {
2323
let mut relations: HashMap<RelationKey, RelationHistory> = HashMap::new();
2424
for (relation, execution) in executions_of(rows) {
@@ -33,6 +33,13 @@ pub(crate) fn build_history(rows: &[ConsumptionRow], limit: usize) -> Consumptio
3333
(right.started_at, &right.execution_id).cmp(&(left.started_at, &left.execution_id))
3434
});
3535
history.truncated = history.executions.len() >= limit;
36+
let newest: Option<String> = history
37+
.executions
38+
.first()
39+
.map(|execution| execution.execution_id.clone());
40+
history.executions.retain(|execution| {
41+
!execution.replaced || Some(&execution.execution_id) == newest.as_ref()
42+
});
3643
}
3744
ConsumptionHistory {
3845
relations,
@@ -124,6 +131,7 @@ fn execution(execution_id: &str, rows: &ExecutionRows<'_>) -> Execution {
124131
execution_id: execution_id.to_owned(),
125132
started_at: rows.earliest,
126133
complete,
134+
replaced: rows.rows.iter().all(|row| row.row.phase == REPLACED_PHASE),
127135
version_hash: (versions.len() == 1)
128136
.then(|| versions.first().map(|version| (*version).to_owned()))
129137
.flatten(),

0 commit comments

Comments
 (0)