From cffccb0630f20c7f0d58161eb3f502ab5be98480 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:26:23 +0000 Subject: [PATCH 1/2] fix: a microbatch rebuild left by a failed run is rebuilt, never published A microbatch first build or full refresh builds aside into a rebuild relation and swaps it in once every batch has run. When a later batch failed, the rebuild relation stayed behind for inspection. The next build found it without a live table, took it for an interrupted swap and renamed it to the live name, publishing the batches before the failure as the model. Later incremental runs then never filled the batches that were missing. A rebuild relation records nothing that says it is complete, so the next build now always drops it and starts again from the first batch. A swap interrupted on an adapter without transactional DDL costs one rebuild; the previous generation is kept. --- .../_helpers/materializations/microbatch.py | 70 ++++--------------- .../cli/commands/main/build/_test_types.py | 19 +++++ .../cli/commands/main/build/helpers.py | 26 +++++-- .../build/test_microbatch_batch_window.py | 51 ++++++++++++++ 4 files changed, 106 insertions(+), 60 deletions(-) diff --git a/src/sqlbuild/executor/run/_helpers/materializations/microbatch.py b/src/sqlbuild/executor/run/_helpers/materializations/microbatch.py index 3bb0f19512..72c8ceec02 100644 --- a/src/sqlbuild/executor/run/_helpers/materializations/microbatch.py +++ b/src/sqlbuild/executor/run/_helpers/materializations/microbatch.py @@ -520,14 +520,22 @@ def execute_microbatch_entry( **_microbatch_result_fields(history=history_context, succeeded=False), ) if full_refresh_relations is not None: - preparation_failure: ModelExecutionResult | None = _prepare_full_refresh_rebuild( - context=context, - state=state, - relations=full_refresh_relations, - ) - if preparation_failure is not None: + try: + context.adapter.drop_table( + connection=context.connection, + destination=full_refresh_relations.rebuild_qualified, + statement_recorder=state.statement_recorder, + ) + except Exception as exc: return replace( - preparation_failure, + build_failed_result( + entry=context.entry, + phase=ExecutionPhase.STAGING, + error=exc, + warnings=state.warnings, + audit_results=state.audit_results, + statement_recorder=state.statement_recorder, + ), **_microbatch_result_fields(history=history_context, succeeded=False), ) batch_outcome: MicrobatchPhaseOutcome = _execute_microbatch_batches( @@ -3156,54 +3164,6 @@ def _complete_microbatch_batch( ) -def _prepare_full_refresh_rebuild( - *, - context: ModelMaterializationContext, - state: MicrobatchLifecycleState, - relations: FullRefreshRelations, -) -> ModelExecutionResult | None: - """Inspect or initialize the deterministic full-refresh rebuild relation.""" - - try: - live_exists: bool = relation_exists( - adapter=context.adapter, - connection=context.connection, - database=context.entry.destination.database, - schema=context.entry.destination.schema, - name=relations.target_name, - ) - rebuild_exists: bool = relation_exists( - adapter=context.adapter, - connection=context.connection, - database=context.entry.destination.database, - schema=context.entry.destination.schema, - name=relations.rebuild_name, - ) - if not live_exists and rebuild_exists: - context.adapter.rename( - connection=context.connection, - origin=relations.rebuild_qualified, - destination=relations.target_qualified, - statement_recorder=state.statement_recorder, - ) - elif rebuild_exists: - context.adapter.drop_table( - connection=context.connection, - destination=relations.rebuild_qualified, - statement_recorder=state.statement_recorder, - ) - except Exception as exc: - return build_failed_result( - entry=context.entry, - phase=ExecutionPhase.STAGING, - error=exc, - warnings=state.warnings, - audit_results=state.audit_results, - statement_recorder=state.statement_recorder, - ) - return None - - def _promote_microbatch_full_refresh( *, context: ModelMaterializationContext, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/_test_types.py index 5881c1b68f..7dd50fff42 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/_test_types.py @@ -1864,6 +1864,25 @@ class BatchWindowTestCase: expected_refusal: str = "[R012]" +@dataclass(frozen=True) +class PartialRebuildStep: + """One build of a partial-rebuild case: the model's value expression and the table after it.""" + + description: str + output_value: str + expected_exit_code: int + expected_values: tuple[int, ...] | None + + +@dataclass(frozen=True) +class PartialRebuildTestCase: + """A rolling-window first build whose later batch fails, built again step by step.""" + + description: str + steps: tuple[PartialRebuildStep, ...] + expected_failure: str = "Conversion Error" + + @dataclass(frozen=True) class ReplayWindowTestCase: """A cursor delete_insert model read by order day and replaced by delivery day, step by step.""" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/helpers.py index 6a4e371202..9fc781d03a 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/helpers.py @@ -1964,7 +1964,7 @@ def snapshot_validity_project(tmp_path: Path, strategy_config: str) -> Path: ), ); - SELECT {output_ts} AS ts, value + SELECT {output_ts} AS ts, {output_value} AS value FROM __seed("events") WHERE ts >= __cursor_start() AND ts < __cursor_end() """ @@ -1984,14 +1984,30 @@ def prepare_batch_window_project(*, tmp_path: Path, today: date, output_ts: str) "seeds:\n- name: events\n description: Events.\n columns:\n" " - name: ts\n type: TIMESTAMP\n - name: value\n type: INTEGER\n" ), - "sql/models/daily_events.sql": _BATCH_WINDOW_MODEL.format( - start=today - timedelta(days=4), output_ts=output_ts - ) - + "\n", + "sql/models/daily_events.sql": _batch_window_model( + today=today, output_ts=output_ts, output_value="value" + ), }, ) +def write_batch_window_model(*, project_dir: Path, today: date, output_value: str) -> None: + """Rewrite the model so it writes `output_value` as its value and its input's ts unchanged.""" + + (project_dir / "sql/models/daily_events.sql").write_text( + _batch_window_model(today=today, output_ts="ts", output_value=output_value) + ) + + +def _batch_window_model(*, today: date, output_ts: str, output_value: str) -> str: + return ( + _BATCH_WINDOW_MODEL.format( + start=today - timedelta(days=4), output_ts=output_ts, output_value=output_value + ) + + "\n" + ) + + def write_batch_window_events(*, project_dir: Path, today: date, events: int) -> None: """Seed `events` events at noon, one a day from four days ago, valued 1, 2, 3 and so on.""" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_batch_window.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_batch_window.py index fea894210b..5b0039af02 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_batch_window.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_microbatch_batch_window.py @@ -9,6 +9,8 @@ from tests.e2e.src.sqlbuild.cli.commands.main.build._test_types import ( BatchWindowStep, BatchWindowTestCase, + PartialRebuildStep, + PartialRebuildTestCase, ReplayWindowTestCase, ) from tests.e2e.src.sqlbuild.cli.commands.main.build.helpers import ( @@ -17,12 +19,16 @@ prepare_batch_window_project, prepare_delivery_window_project, write_batch_window_events, + write_batch_window_model, write_delivery_window_rows, ) from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import run_sqb _BUILD: tuple[str, ...] = ("--no-color", "build") _FULL_REFRESH: tuple[str, ...] = ("--no-color", "build", "--full-refresh") +_FAILS_ON_FOURTH_DAY: str = ( + "CAST(CASE WHEN value = 4 THEN 'x' ELSE CAST(value AS VARCHAR) END AS INTEGER)" +) @pytest.mark.parametrize( @@ -124,3 +130,48 @@ def test_given_cursor_rows_outside_the_replay_window_when_building_then_the_repl step.description ) assert delivery_window_ids(project_dir=project_dir) == step.expected_values, output + + +@pytest.mark.parametrize( + "test_case", + [ + PartialRebuildTestCase( + description="a first build that failed partway is rebuilt, never published", + steps=( + PartialRebuildStep( + "the fourth batch fails the first build", _FAILS_ON_FOURTH_DAY, 1, None + ), + PartialRebuildStep( + "the next build fails again and publishes nothing", + _FAILS_ON_FOURTH_DAY, + 1, + None, + ), + PartialRebuildStep( + "once fixed, every batch is built once", "value", 0, (1, 2, 3, 4, 5) + ), + ), + ), + ], + ids=lambda case: case.description, +) +def test_given_a_first_build_failed_at_a_later_batch_when_building_again_then_no_partial_table_is_published( + test_case: PartialRebuildTestCase, tmp_path: Path +) -> None: + today: date = datetime.now(UTC).date() + project_dir: Path = prepare_batch_window_project(tmp_path=tmp_path, today=today, output_ts="ts") + write_batch_window_events(project_dir=project_dir, today=today, events=5) + + step: PartialRebuildStep + for step in test_case.steps: + write_batch_window_model( + project_dir=project_dir, today=today, output_value=step.output_value + ) + result: subprocess.CompletedProcess[str] = run_sqb(command=_BUILD, project_dir=project_dir) + output: str = result.stdout + result.stderr + + assert result.returncode == step.expected_exit_code, output + assert (test_case.expected_failure in output) == (step.expected_exit_code == 1), ( + step.description + ) + assert batch_window_values(project_dir=project_dir) == step.expected_values, output From 3e64e11a27d99e2577e2868e8540d5b4ad593eec Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:42:34 +0000 Subject: [PATCH 2/2] fix: a microbatch rebuild is dropped only when a failed run left one Checking the cached relation listing first keeps a full refresh with no leftover rebuild at its earlier statement count. --- .../run/_helpers/materializations/microbatch.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/sqlbuild/executor/run/_helpers/materializations/microbatch.py b/src/sqlbuild/executor/run/_helpers/materializations/microbatch.py index 72c8ceec02..7003aeaea9 100644 --- a/src/sqlbuild/executor/run/_helpers/materializations/microbatch.py +++ b/src/sqlbuild/executor/run/_helpers/materializations/microbatch.py @@ -521,11 +521,18 @@ def execute_microbatch_entry( ) if full_refresh_relations is not None: try: - context.adapter.drop_table( + if relation_exists( + adapter=context.adapter, connection=context.connection, - destination=full_refresh_relations.rebuild_qualified, - statement_recorder=state.statement_recorder, - ) + database=context.entry.destination.database, + schema=context.entry.destination.schema, + name=full_refresh_relations.rebuild_name, + ): + context.adapter.drop_table( + connection=context.connection, + destination=full_refresh_relations.rebuild_qualified, + statement_recorder=state.statement_recorder, + ) except Exception as exc: return replace( build_failed_result(