From 72d6511ba2e22f259d1f8033610772da11cfcd3a Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Sun, 6 Dec 2026 10:28:04 +0000 Subject: [PATCH 1/8] feat: report a load's committed rows as each commit lands --- Cargo.lock | 34 +++++------ Cargo.toml | 4 +- .../src/bindings/_helpers/loader_binding.rs | 12 ++-- .../src/bindings/_helpers/run_binding.rs | 21 ++++++- .../src/runs/main/run_project.rs | 6 +- pyproject.toml | 2 +- src/sqlbuild/_native.pyi | 8 ++- .../executor/build/_helpers/load_node.py | 10 ++++ .../executor/load/main/_run_on_engine.py | 14 +++++ src/sqlbuild/executor/loads/main/_run_load.py | 7 ++- .../cli/commands/main/loads/_test_types.py | 9 +++ .../commands/main/loads/test_load_build.py | 46 ++++++++++++++ .../load_sessions/main/_test_types.py | 8 +++ .../executor/load_sessions/main/helpers.py | 35 +++++++++++ .../main/test_open_load_session.py | 60 ++++++++++++++++++- uv.lock | 8 +-- 16 files changed, 247 insertions(+), 37 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 908fee5b1d..abe7896dc4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1997,7 +1997,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -3194,7 +3194,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cde48f36530cbd91b65f050101e6c056d6eb743cea2a8f0f19beef69c6742ff8" dependencies = [ "scopeguard", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4654,7 +4654,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6e4d69d0fa3e7f6f9cf6b53a0e83e4fc99ba3586f65ce166cff30bd13bb4ad2" dependencies = [ "heck", - "itertools 0.15.0", + "itertools 0.14.0", "log", "multimap", "petgraph", @@ -4675,7 +4675,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ad9c5423459fa2f729b8d9235fab810aa29628b171467744fc86d21460ad70d" dependencies = [ "anyhow", - "itertools 0.15.0", + "itertools 0.14.0", "proc-macro2", "quote", "syn 2.0.119", @@ -4930,7 +4930,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -5582,7 +5582,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -5640,7 +5640,7 @@ dependencies = [ "security-framework 3.7.0", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -6214,7 +6214,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -7126,9 +7126,9 @@ dependencies = [ [[package]] name = "sqlload" -version = "0.91.1" +version = "0.92.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37a28d4f9a7f2f2c4002759a2de6a64047d27cd599e4af4e2b7f70233212b079" +checksum = "e6f2b40ac3cd5cab5d4140fa180c38bdf05d06a15fbfd2f0ecbf922f306008de" dependencies = [ "aes 0.8.4", "arrow-array", @@ -7200,9 +7200,9 @@ dependencies = [ [[package]] name = "sqlload-python-host" -version = "0.91.1" +version = "0.92.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "543c9b1e63e2ad1dc65db740dec3e3bdb36308b8942cc354f4a4de99c23fe4f5" +checksum = "5d96dd96cd02dea4e4cf189d8665c7c3cbf198dcd323818f3c8a34f7614da969" dependencies = [ "arrow-array", "arrow-pyarrow", @@ -7365,7 +7365,7 @@ dependencies = [ "cfg-if", "libc", "psm", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -7493,7 +7493,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -7948,7 +7948,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -8344,7 +8344,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.48.0", ] [[package]] @@ -8959,7 +8959,7 @@ dependencies = [ "memchr", "nix 0.31.3", "typed-path", - "windows-sys 0.61.2", + "windows-sys 0.60.2", "zeroize", "zopfli", ] diff --git a/Cargo.toml b/Cargo.toml index 9e55702912..d1bfe24ddc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -170,8 +170,8 @@ reqwest = { version = "0.13", default-features = false, features = ["json", "que # The ring provider that `sqlbuild_orchestration::tls` installs before any client is built. rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } # The loading engine behind loads, loaders and sinks: its library, without its CLI or its own DuckDB. -sqlload = { version = "=0.91.1", default-features = false } -sqlload-python-host = { version = "=0.91.1", default-features = false } +sqlload = { version = "=0.92.0", default-features = false } +sqlload-python-host = { version = "=0.92.0", default-features = false } arrow-array = { version = "60", default-features = false } arrow-schema = { version = "60", default-features = false } serde = { version = "1", features = ["derive"] } diff --git a/crates/sqlbuild-python-load/src/bindings/_helpers/loader_binding.rs b/crates/sqlbuild-python-load/src/bindings/_helpers/loader_binding.rs index 0c9ee3683e..3c9941003a 100644 --- a/crates/sqlbuild-python-load/src/bindings/_helpers/loader_binding.rs +++ b/crates/sqlbuild-python-load/src/bindings/_helpers/loader_binding.rs @@ -3,22 +3,24 @@ use std::sync::Arc; use pyo3::exceptions::{PyRuntimeError, PyValueError}; -use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, pyfunction}; +use pyo3::prelude::{Bound, Py, PyAny, PyAnyMethods, PyResult, pyfunction}; use pyo3::types::PyDict; +use sqlload::committed_rows::types::CommittedRows; use sqlload::loader::models::{PlanOptions, TypedCursors}; use sqlload::python_sources::models::PythonSource; use sqlload::python_sources::types::PythonHost; -use crate::bindings::_helpers::run_binding::{run_report, session_connections}; +use crate::bindings::_helpers::run_binding::{committed_rows, run_report, session_connections}; use crate::runs::main::run_project::run_project; use crate::runs::models::LoaderHost; -/// Load `loader` (an `EngineLoaderRun`: its project text, Python source, reload and cursor window, typed by family or in the cursor's own type) through `sessions`; the report `run_sqlload_project` gives. +/// Load `loader` (an `EngineLoaderRun`: its project text, Python source, reload and cursor window, typed by family or in the cursor's own type) through `sessions`; the report `run_sqlload_project` gives, calling `on_rows` with the rows committed so far after each commit. #[pyfunction] -#[pyo3(signature = (*, loader, sessions))] +#[pyo3(signature = (*, loader, sessions, on_rows = None))] pub(crate) fn run_sqlload_loader( loader: &Bound<'_, PyAny>, sessions: &Bound<'_, PyDict>, + on_rows: Option>, ) -> PyResult { let text = |name: &str| -> PyResult> { loader.getattr(name)?.extract() }; let source: PythonSource = @@ -39,6 +41,7 @@ pub(crate) fn run_sqlload_loader( }; let project: String = loader.getattr("project")?.extract()?; let connections = session_connections(sessions)?; + let committed: Option = on_rows.map(committed_rows); let host: Arc = Arc::new(LoaderHost { run: loader.clone().unbind(), }); @@ -49,6 +52,7 @@ pub(crate) fn run_sqlload_loader( (&project, vec![source], Some(host)), connections, (options, Vec::new()), + committed, ) }) .map_err(PyRuntimeError::new_err)?; diff --git a/crates/sqlbuild-python-load/src/bindings/_helpers/run_binding.rs b/crates/sqlbuild-python-load/src/bindings/_helpers/run_binding.rs index 3e4ceca119..87e990b163 100644 --- a/crates/sqlbuild-python-load/src/bindings/_helpers/run_binding.rs +++ b/crates/sqlbuild-python-load/src/bindings/_helpers/run_binding.rs @@ -3,10 +3,11 @@ use std::collections::BTreeMap; use pyo3::exceptions::{PyKeyError, PyRuntimeError}; -use pyo3::prelude::{Bound, Py, PyAny, PyResult, pyfunction}; +use pyo3::prelude::{Bound, Py, PyAny, PyResult, Python, pyfunction}; use pyo3::types::{PyAnyMethods, PyDict, PyDictMethods}; use serde_json::{Value, json}; use sqlload::adapters::session::models::SessionConnection; +use sqlload::committed_rows::types::CommittedRows; use sqlload::loader::models::PlanOptions; use crate::bindings::constants::{ADAPTER, DATABASE, DESCRIPTION, OPENER}; @@ -14,15 +15,17 @@ use crate::runs::main::run_project::run_project; use crate::runs::models::ProjectRun; use crate::sessions::main::session_connection::session_connection; -/// Load `project` (SQLLoad TOML) through `sessions`; `{tables, planned, missing}` JSON, nothing loaded when `require` misses. +/// Load `project` (SQLLoad TOML) through `sessions`, calling `on_rows` with the rows committed so far after each commit; `{tables, planned, missing}` JSON, nothing loaded when `require` misses. #[pyfunction] -#[pyo3(signature = (*, project, sessions, tables, reload = false))] +#[pyo3(signature = (*, project, sessions, tables, reload = false, on_rows = None))] pub(crate) fn run_sqlload_project( project: &str, sessions: &Bound<'_, PyDict>, tables: (Vec, Vec), reload: bool, + on_rows: Option>, ) -> PyResult { + let committed: Option = on_rows.map(committed_rows); let run: ProjectRun = detached_load( (project, sessions), (tables, reload), @@ -31,6 +34,7 @@ pub(crate) fn run_sqlload_project( (&project, Vec::new(), None), connections, (options, require), + committed, ) }, )?; @@ -56,6 +60,17 @@ pub(crate) fn run_report(run: ProjectRun) -> String { json!({"tables": rows, "planned": run.planned, "missing": run.missing}).to_string() } +/// `on_rows` as SQLLoad's committed-rows callback, called from the committing table's thread with the interpreter attached only for the call; an error it raises is reported as unraisable and the load goes on. +pub(crate) fn committed_rows(on_rows: Py) -> CommittedRows { + std::sync::Arc::new(move |total: u64| { + Python::attach(|py| { + if let Err(error) = on_rows.call1(py, (total,)) { + error.write_unraisable(py, None); + } + }); + }) +} + /// SQLLoad's connections, plan options and required tables for one plan or run from Python. pub(crate) type LoadRequest = ( BTreeMap, diff --git a/crates/sqlbuild-python-load/src/runs/main/run_project.rs b/crates/sqlbuild-python-load/src/runs/main/run_project.rs index 32f4f8a4da..32095d177f 100644 --- a/crates/sqlbuild-python-load/src/runs/main/run_project.rs +++ b/crates/sqlbuild-python-load/src/runs/main/run_project.rs @@ -3,6 +3,7 @@ use std::collections::BTreeMap; use sqlload::adapters::session::models::SessionConnection; +use sqlload::committed_rows::types::CommittedRows; use sqlload::loader::main::apply_project::apply_project; use sqlload::loader::main::connect_targets::connect_targets; use sqlload::loader::main::load_tables::load_tables; @@ -20,11 +21,12 @@ use crate::runs::_helpers::tables::{ }; use crate::runs::models::{LoadedTable, ProjectRun}; -/// Each selected table's load of the project `text` with the `python` sources `host` runs; nothing loads when the plan lacks a `required` table. +/// Each selected table's load of the project `text` with the `python` sources `host` runs, `committed` hearing the rows it has committed after each commit; nothing loads when the plan lacks a `required` table. pub fn run_project( (text, python, host): (&str, Vec, Option>), sessions: BTreeMap, (options, required): (PlanOptions, Vec), + committed: Option, ) -> Result { let warehouse = sessions.values().next().map(|session| session.warehouse); let mut project = parse_python_project(text, &|_| None, (&python, sessions)) @@ -59,7 +61,7 @@ pub fn run_project( options: &options, }; let mut tables: Vec = Vec::new(); - for outcome in load_tables(&run, &plan, None).await { + for outcome in load_tables(&run, &plan, None, committed.clone()).await { let (loaded, changes, warnings) = match outcome.loaded { Ok(loaded) => (Ok(loaded.rows), loaded.changes, loaded.warnings), Err(error) => ( diff --git a/pyproject.toml b/pyproject.toml index 14b51fa478..cf1814a9c9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,7 +20,7 @@ dependencies = [ "PyYAML>=6.0.2", "sqlbuild-cli==0.308.0", # x-release-please-version # Release Please rewrites the pin above; this line keeps its bumps from conflicting with edits below. - "sqlload-api==0.91.1", + "sqlload-api==0.92.0", "sqlbabel==0.41.0", ] diff --git a/src/sqlbuild/_native.pyi b/src/sqlbuild/_native.pyi index 2e472a9a53..a6ede30a86 100644 --- a/src/sqlbuild/_native.pyi +++ b/src/sqlbuild/_native.pyi @@ -4126,6 +4126,7 @@ def run_sqlload_project( sessions: dict[str, dict[str, object]], tables: tuple[list[str], list[str]], reload: bool = False, + on_rows: Callable[[int], None] | None = None, ) -> str: ... def loader_projects( *, @@ -4134,7 +4135,12 @@ def loader_projects( target: str | None = None, schema: str | None = None, ) -> dict[str, tuple[str, str]]: ... -def run_sqlload_loader(*, loader: object, sessions: dict[str, dict[str, object]]) -> str: ... +def run_sqlload_loader( + *, + loader: object, + sessions: dict[str, dict[str, object]], + on_rows: Callable[[int], None] | None = None, +) -> str: ... def plan_sqlload_project( *, project: str, diff --git a/src/sqlbuild/executor/build/_helpers/load_node.py b/src/sqlbuild/executor/build/_helpers/load_node.py index c7a3cc7e72..9eb97d53ff 100644 --- a/src/sqlbuild/executor/build/_helpers/load_node.py +++ b/src/sqlbuild/executor/build/_helpers/load_node.py @@ -41,6 +41,14 @@ def execute_build_load_node( start: float = time.monotonic() tables: tuple[LoadedTable, ...] = () raised: LoadRunError | RuntimeError | KeyError | None = None + # The rows the load has committed so far; a load that raises reports these. + committed: list[int] = [] + + def on_rows(total: int) -> None: + committed.append(total) + if callbacks.on_rows_written is not None: + callbacks.on_rows_written(f"load:{entry.name}", total) + rows_affected: int | None = None try: tables = run_load( @@ -51,10 +59,12 @@ def execute_build_load_node( connection_config=connection_config, base_connection=connection, database=runtime.default_database, + on_rows=on_rows, ) rows_affected = sum(table.rows or 0 for table in tables) except (LoadRunError, RuntimeError, KeyError) as error: raised = error + rows_affected = max(committed, default=None) failures: list[str] = [f"{table.table}: {table.error}" for table in tables if table.error] fields: dict[str, Any] = { "source_name": entry.name, diff --git a/src/sqlbuild/executor/load/main/_run_on_engine.py b/src/sqlbuild/executor/load/main/_run_on_engine.py index 5ea7b23a23..95ca5ef00e 100644 --- a/src/sqlbuild/executor/load/main/_run_on_engine.py +++ b/src/sqlbuild/executor/load/main/_run_on_engine.py @@ -4,6 +4,7 @@ import json import time +from collections.abc import Callable from typing import Any from sqlbuild._native import CostContext, DiscoveredLoaderFunction, SourceEntry, run_sqlload_loader @@ -52,6 +53,7 @@ def run_on_engine( else runtime.default_database ), ), + on_rows=_rows_reporter(source_entry=source_entry, runtime=runtime), ) ) result: LoadExecutionResult = engine_result( @@ -60,3 +62,15 @@ def run_on_engine( if runtime.on_rows_written is not None and result.rows_affected: runtime.on_rows_written(f"source:{source_entry.name}", result.rows_affected) return result + + +def _rows_reporter( + *, source_entry: SourceEntry, runtime: LoadRuntimeParams +) -> Callable[[int], None] | None: + """Report the loader's committed rows to the build as each commit lands.""" + + on_rows_written: Callable[[str, int], None] | None = runtime.on_rows_written + if on_rows_written is None: + return None + key: str = f"source:{source_entry.name}" + return lambda total: on_rows_written(key, total) diff --git a/src/sqlbuild/executor/loads/main/_run_load.py b/src/sqlbuild/executor/loads/main/_run_load.py index 11ce1941db..d6262caa8b 100644 --- a/src/sqlbuild/executor/loads/main/_run_load.py +++ b/src/sqlbuild/executor/loads/main/_run_load.py @@ -3,7 +3,7 @@ from __future__ import annotations import json -from collections.abc import Mapping +from collections.abc import Callable, Mapping from typing import Any from sqlbuild._native import LoadPlanEntry, SourceEntry, run_sqlload_project @@ -27,8 +27,10 @@ def run_load( connection_config: dict[str, object], base_connection: Any, database: str | None, + on_rows: Callable[[int], None] | None = None, ) -> tuple[LoadedTable, ...]: - """Each table `entry` loads; nothing loads when its plan leaves out a source's table.""" + """Each table `entry` loads, `on_rows` hearing the rows committed so far after each commit; + nothing loads when its plan leaves out a source's table.""" report: dict[str, Any] = json.loads( run_sqlload_project( project=project.text, @@ -44,6 +46,7 @@ def run_load( required_tables(entry=entry, source_map=source_map), ), reload=entry.is_reload, + on_rows=on_rows, ) ) if report["missing"]: diff --git a/tests/integration/src/sqlbuild/cli/commands/main/loads/_test_types.py b/tests/integration/src/sqlbuild/cli/commands/main/loads/_test_types.py index c286dc2571..046bcc886e 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/loads/_test_types.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/loads/_test_types.py @@ -137,3 +137,12 @@ class CaseOnlyColumnTestCase: expected_exit: int expected_fragments: tuple[str, ...] unexpected_fragments: tuple[str, ...] = () + + +@dataclass(frozen=True) +class RaisedAfterCommitTestCase: + """A load whose run raises after its rows committed, and the rows its failure reports.""" + + description: str + landed: tuple[tuple[str, str], ...] + expected_rows_loaded: int diff --git a/tests/integration/src/sqlbuild/cli/commands/main/loads/test_load_build.py b/tests/integration/src/sqlbuild/cli/commands/main/loads/test_load_build.py index 57486c06f3..5f47641ff3 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/loads/test_load_build.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/loads/test_load_build.py @@ -1,11 +1,13 @@ from __future__ import annotations +import base64 import json from pathlib import Path from typing import Any import pytest +import sqlbuild.executor.build._helpers.load_node as load_node_module from sqlbuild._native import COMPILE_REUSE_DISABLE_ENV_VAR, DELTA_COMPILE_VERIFY_ENV_VAR from tests.integration.src.sqlbuild.cli.commands.main.loads._test_types import ( AssetDependencyBuildTestCase, @@ -16,6 +18,7 @@ LoadPlanTestCase, MissingTableTestCase, PhysicalTableTestCase, + RaisedAfterCommitTestCase, UnmatchedTableTestCase, ) from tests.integration.src.sqlbuild.cli.commands.main.loads.helpers import ( @@ -580,3 +583,46 @@ def test_given_a_load_depends_on_when_an_unrelated_model_changes_then_compiling_ assert first.exit_code == 0, first.output assert second.exit_code == 0, second.output assert test_case.expected_line in second.output, second.output + + +@pytest.mark.parametrize( + "test_case", + [ + RaisedAfterCommitTestCase( + description="a load raising after two files committed reports their rows", + landed=(("a.csv", "id,name\n1,a\n"), ("b.csv", "id,name\n2,b\n")), + expected_rows_loaded=2, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_load_raising_after_rows_committed_when_building_then_it_reports_those_rows( + test_case: RaisedAfterCommitTestCase, + tmp_path: Path, + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + project_dir: Path = write_project( + root=tmp_path, sources_yml=_SOURCES, models={"order_names": _ORDER_NAMES} + ) + for name, text in test_case.landed: + land_file(root=tmp_path, name=name, text=text) + loaded: Any = load_node_module.run_load + + def raising_after_load(**arguments: Any) -> Any: + _ = loaded(**arguments) + raise RuntimeError("connection lost after the commit") + + monkeypatch.setattr(load_node_module, "run_load", raising_after_load) + + run: CliRun = run_sqb(project_dir=project_dir, args=("build",), capsys=capsys) + rows: list[tuple[Any, ...]] = query( + project_dir=project_dir, + sql="SELECT status, metadata_json_b64 FROM dev._sqlbuild_node_results " + "WHERE node_type = 'load'", + ) + + assert run.exit_code == 1, run.output + assert [ + (status, json.loads(base64.b64decode(metadata))["rows_loaded"]) for status, metadata in rows + ] == [("failed", test_case.expected_rows_loaded)], run.output diff --git a/tests/unit/src/sqlbuild/executor/load_sessions/main/_test_types.py b/tests/unit/src/sqlbuild/executor/load_sessions/main/_test_types.py index 66e76f31df..24b5fac649 100644 --- a/tests/unit/src/sqlbuild/executor/load_sessions/main/_test_types.py +++ b/tests/unit/src/sqlbuild/executor/load_sessions/main/_test_types.py @@ -15,3 +15,11 @@ class UnsupportedAdapterTestCase: description: str adapter_name: str expected_error_fragment: str + + +@dataclass(frozen=True) +class CommittedRowsTestCase: + description: str + # Each source's one CSV file, as (source name, file text). + sources: tuple[tuple[str, str], ...] + expected_final_total: int diff --git a/tests/unit/src/sqlbuild/executor/load_sessions/main/helpers.py b/tests/unit/src/sqlbuild/executor/load_sessions/main/helpers.py index b49dbae7a8..4ba73c9e55 100644 --- a/tests/unit/src/sqlbuild/executor/load_sessions/main/helpers.py +++ b/tests/unit/src/sqlbuild/executor/load_sessions/main/helpers.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import threading from typing import Any from sqlbuild._native import run_sqlload_project @@ -32,3 +33,37 @@ def opener() -> LoadSession: ) ) return [table["error"] for table in report["tables"]] + + +def committed_totals( + *, project: str, adapter: BaseAdapter, base_connection: Any +) -> tuple[list[int], set[int]]: + """Load `project`: each committed total `on_rows` heard, in order, and the threads it heard + them on.""" + + totals: list[int] = [] + threads: set[int] = set() + + def on_rows(total: int) -> None: + totals.append(total) + threads.add(threading.get_ident()) + + def opener() -> LoadSession: + return open_load_session( + adapter=adapter, connection_config={}, base_connection=base_connection + ) + + _ = run_sqlload_project( + project=project, + sessions={ + "warehouse": { + "adapter": "duckdb", + "database": None, + "opener": opener, + "description": "a DuckDB file", + } + }, + tables=([], []), + on_rows=on_rows, + ) + return totals, threads diff --git a/tests/unit/src/sqlbuild/executor/load_sessions/main/test_open_load_session.py b/tests/unit/src/sqlbuild/executor/load_sessions/main/test_open_load_session.py index 79d9c7b83d..b74f0189e1 100644 --- a/tests/unit/src/sqlbuild/executor/load_sessions/main/test_open_load_session.py +++ b/tests/unit/src/sqlbuild/executor/load_sessions/main/test_open_load_session.py @@ -1,5 +1,6 @@ from __future__ import annotations +import threading from pathlib import Path from typing import Any @@ -9,11 +10,34 @@ from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter from sqlbuild.adapter.contract.models import QueryResult from tests.unit.src.sqlbuild.executor.load_sessions.main._test_types import ( + CommittedRowsTestCase, SessionLoadTestCase, UnsupportedAdapterTestCase, ) -from tests.unit.src.sqlbuild.executor.load_sessions.main.helpers import load_errors +from tests.unit.src.sqlbuild.executor.load_sessions.main.helpers import ( + committed_totals, + load_errors, +) + +_PROJECT_HEAD: str = """ +default_target = "dev" + +[connections.landing] +kind = "filesystem" +root = "{root}" +[targets.dev] +connection = "warehouse" +loader_schema = "raw" +""" +_APPEND_SOURCE: str = """ +[sources.{name}] +kind = "files" +connection = "landing" +path = "{name}/" +format = "csv" +write_strategy = "append" +""" _PROJECT: str = """ default_target = "dev" @@ -71,6 +95,40 @@ def test_given_csv_files_when_loading_through_a_load_session_then_the_table_hold assert result.rows == test_case.expected_rows, test_case.description +@pytest.mark.parametrize( + "test_case", + [ + CommittedRowsTestCase( + description="three tables' threads report one load's rising committed total", + sources=( + ("orders", "id,name\n1,a\n2,b\n3,c\n"), + ("customers", "id,name\n1,a\n2,b\n"), + ("products", "id,name\n1,a\n"), + ), + expected_final_total=6, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_load_of_several_tables_when_rows_commit_then_on_rows_hears_its_rising_total( + test_case: CommittedRowsTestCase, tmp_path: Path +) -> None: + adapter: BaseAdapter = resolve_adapter(adapter_name="duckdb") + connection: Any = adapter.connect({"database": str(tmp_path / "warehouse.duckdb")}) + project: str = _PROJECT_HEAD.format(root=(tmp_path / "landing").as_posix()) + for name, text in test_case.sources: + landing: Path = tmp_path / "landing" / name + landing.mkdir(parents=True) + (landing / "1.csv").write_text(text) + project += _APPEND_SOURCE.format(name=name) + + totals, threads = committed_totals(project=project, adapter=adapter, base_connection=connection) + + assert totals == sorted(totals), totals + assert totals[-1] == test_case.expected_final_total, totals + assert threading.get_ident() not in threads + + @pytest.mark.parametrize( "test_case", [ diff --git a/uv.lock b/uv.lock index d6fd94334c..216f206653 100644 --- a/uv.lock +++ b/uv.lock @@ -3806,7 +3806,7 @@ requires-dist = [ { name = "snowflake-connector-python", marker = "extra == 'snowflake'", specifier = ">=4.7.1,<5" }, { name = "sqlbabel", specifier = "==0.41.0" }, { name = "sqlbuild-cli", directory = "crates/sqlbuild-cli" }, - { name = "sqlload-api", specifier = "==0.91.1" }, + { name = "sqlload-api", specifier = "==0.92.0" }, ] provides-extras = ["dbt", "snowflake", "bigquery", "databricks", "dagster", "postgres", "sqlserver", "clickhouse", "rivers"] @@ -3838,11 +3838,11 @@ source = { directory = "crates/sqlbuild-cli" } [[package]] name = "sqlload-api" -version = "0.91.1" +version = "0.92.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/df/fd/467e0281690e6cd85795ab733e5d6bae79739bac0470f65511af55f0fa79/sqlload_api-0.91.1.tar.gz", hash = "sha256:092f4a0b6b5a8c9b17f13e4c13b991be3507b67ae5b52cf7937abec78147543d", size = 31995, upload-time = "2026-12-04T13:44:46.645Z" } +sdist = { url = "https://files.pythonhosted.org/packages/99/ad/93c2d980729f57d9662565250588f0cfe97335ff10f2dafb2904a3ef7a70/sqlload_api-0.92.0.tar.gz", hash = "sha256:2313cc9fb7256ba8cea5374eae43ceee0cf8c60c7d717888398272ccf51e329c", size = 31995, upload-time = "2026-12-06T10:06:27.835Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/47/d6/558189f21e069b15c647085f6cc4e6f8888d04edaa7791dba7fbc115565d/sqlload_api-0.91.1-py3-none-any.whl", hash = "sha256:0c4689a2492f6b01e7117b3a1037601a9f55112dedcb8ada7c743ace3b870386", size = 38350, upload-time = "2026-12-04T13:44:45.585Z" }, + { url = "https://files.pythonhosted.org/packages/5e/fa/3dac5839b20c6a22a1272e93babc9356768cb3b7cbfa07154b82405f40bd/sqlload_api-0.92.0-py3-none-any.whl", hash = "sha256:715a5f769bbbc820ebe50971ea88e4e5ceb58509160126c999bae323236c4424", size = 38347, upload-time = "2026-12-06T10:06:26.72Z" }, ] [[package]] From afb73b4e55c40739d2df2d859ea1c68881e6db22 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Sun, 6 Dec 2026 10:32:56 +0000 Subject: [PATCH 2/8] fix!: fail only the node whose own work raises an error BREAKING CHANGE: an error inside a node no longer stops the build; that node fails and the rest of the build runs. --- .../src/integration_results/constants.rs | 3 +- crates/sqlbuild-host/src/models.rs | 3 + .../src/tests/test_enum_values.rs | 1 + fensu.toml | 6 +- .../executor/build/_helpers/load_node.py | 77 ++- .../executor/build/_helpers/node_errors.py | 108 ++++ .../executor/build/classes/build_scheduler.py | 471 ++++++++++-------- src/sqlbuild/executor/build/constants.py | 2 +- src/sqlbuild/executor/build/exceptions.py | 7 + src/sqlbuild/executor/run/types.py | 1 + .../classes/connection_recovery.py | 14 +- .../publication/_test_types.py | 4 + .../publication/test_worker.py | 49 ++ .../sqlbuild/executor/build/_test_types.py | 44 ++ .../src/sqlbuild/executor/build/helpers.py | 173 +++++++ .../executor/build/test_node_errors.py | 232 +++++++++ .../executor/build/classes/_test_types.py | 10 + .../executor/build/classes/helpers.py | 43 ++ .../test_build_scheduler_unreported.py | 68 ++- 19 files changed, 1053 insertions(+), 263 deletions(-) create mode 100644 src/sqlbuild/executor/build/_helpers/node_errors.py create mode 100644 src/sqlbuild/executor/build/exceptions.py create mode 100644 tests/integration/src/sqlbuild/executor/build/test_node_errors.py diff --git a/crates/sqlbuild-core/src/integration_results/constants.rs b/crates/sqlbuild-core/src/integration_results/constants.rs index e78f90316a..5b329851d6 100644 --- a/crates/sqlbuild-core/src/integration_results/constants.rs +++ b/crates/sqlbuild-core/src/integration_results/constants.rs @@ -30,11 +30,12 @@ pub(crate) const CHECK_KINDS: [&str; 3] = [AUDIT_KIND, "python_check", "sql_test pub(crate) const EXTRA_RESOURCE_KINDS: [&str; 3] = ["audit", "check", "test"]; pub(crate) const MODEL_RESOURCE_KINDS: [&str; 5] = ["custom", "model", "snapshot", "table", "view"]; pub(crate) const ASSET_STATUSES: [&str; 4] = ["failed", "skipped", "success", "warning"]; -pub(crate) const FAILED_PHASES: [&str; 12] = [ +pub(crate) const FAILED_PHASES: [&str; 13] = [ "audit", "contract", "custom_materialization", "dml", + "execute", "fingerprint", "microbatch_state", "post_hook", diff --git a/crates/sqlbuild-host/src/models.rs b/crates/sqlbuild-host/src/models.rs index 1f9b5085fd..b2a63f61c2 100644 --- a/crates/sqlbuild-host/src/models.rs +++ b/crates/sqlbuild-host/src/models.rs @@ -48,6 +48,7 @@ impl ResultEnum for ExecutionStatus { /// The model phase a failure happened in. Mirrors `sqlbuild.executor.run.types.ExecutionPhase`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ExecutionPhase { + Execute, PreHook, Staging, SchemaChange, @@ -64,6 +65,7 @@ pub enum ExecutionPhase { impl ResultEnum for ExecutionPhase { const ALL: &'static [Self] = &[ + Self::Execute, Self::PreHook, Self::Staging, Self::SchemaChange, @@ -80,6 +82,7 @@ impl ResultEnum for ExecutionPhase { fn value(self) -> &'static str { match self { + Self::Execute => "execute", Self::PreHook => "pre_hook", Self::Staging => "staging", Self::SchemaChange => "schema_change", diff --git a/crates/sqlbuild-host/src/tests/test_enum_values.rs b/crates/sqlbuild-host/src/tests/test_enum_values.rs index 9f6e806efb..1d37383e1e 100644 --- a/crates/sqlbuild-host/src/tests/test_enum_values.rs +++ b/crates/sqlbuild-host/src/tests/test_enum_values.rs @@ -27,6 +27,7 @@ fn given_result_enums_when_read_by_value_then_they_match_the_python_members() { values: values::(), parsed: parsed::(), expected_values: vec![ + "execute", "pre_hook", "staging", "schema_change", diff --git a/fensu.toml b/fensu.toml index 5e1ed11dc6..f27a6a1d4e 100644 --- a/fensu.toml +++ b/fensu.toml @@ -1462,12 +1462,16 @@ reason = "PlatformEvent::event_type and RunChange::event_type each name their ow [[dupes.allowlist]] paths = ["crates/sqlbuild-host/src/models.rs", "crates/sqlbuild-orchestration/src/platform/models.rs"] -reason = "ExecutionPhase::value and PlatformEventKind::as_str each name their own enum's variants, one arm per variant, in crates that don't depend on each other; only the twelve-arm variant-to-string match shape is alike." +reason = "ExecutionPhase::value and PlatformEventKind::as_str each name their own enum's variants, one arm per variant, in crates that don't depend on each other; only the variant-to-string match shape is alike." [[dupes.allowlist]] paths = ["crates/sqlbuild-host/src/models.rs", "crates/sqlbuild-orchestration/src/runs/models.rs"] reason = "ExecutionPhase::value and NodeAction::as_str each name their own enum's stored strings, one arm per variant, in crates that don't depend on each other; only the variant-to-string match shape is alike." +[[dupes.allowlist]] +paths = ["crates/sqlbuild-discovery/src/models.rs", "crates/sqlbuild-host/src/models.rs"] +reason = "FailureKind::as_str and ExecutionPhase::value each name their own enum's stored strings, one arm per variant, in crates that don't depend on each other; only the variant-to-string match shape is alike." + [[dupes.allowlist]] paths = ["crates/sqlbuild-cli/src/person_login/main/read_past_runs.rs", "crates/sqlbuild-cli/src/person_login/main/read_sensor_events.rs", "crates/sqlbuild-cli/src/person_login/main/request_warehouse_sync.rs"] reason = "Each is the public entry for one request a saved `sqb login` session makes: it opens the session and calls its own transport request, which stays private to person_login. Only the open-session-then-call shape is alike; the requests, arguments and results differ." diff --git a/src/sqlbuild/executor/build/_helpers/load_node.py b/src/sqlbuild/executor/build/_helpers/load_node.py index c7a3cc7e72..6a4a88ce5b 100644 --- a/src/sqlbuild/executor/build/_helpers/load_node.py +++ b/src/sqlbuild/executor/build/_helpers/load_node.py @@ -3,6 +3,7 @@ from __future__ import annotations import time +from dataclasses import replace from itertools import chain from typing import Any @@ -11,7 +12,6 @@ from sqlbuild.compiler.python_nodes.types import SkipMode from sqlbuild.executor.build.models import BuildCallbacks, BuildRuntimeParams from sqlbuild.executor.load.models import LoadExecutionResult -from sqlbuild.executor.loads.exceptions import LoadRunError from sqlbuild.executor.loads.main._persist_load_result import persist_load_result from sqlbuild.executor.loads.main._run_load import run_load from sqlbuild.executor.loads.models import LoadedTable, LoadProject @@ -32,48 +32,48 @@ def execute_build_load_node( runtime: BuildRuntimeParams, callbacks: BuildCallbacks, ) -> LoadExecutionResult: - """Run `entry`'s load, record its node result, and report it as one load result.""" + """Run `entry`'s load as one load result; the node boundary fails it when it raises.""" if callbacks.on_progress is not None: callbacks.on_progress(f"load: {entry.name}") if callbacks.on_node_start is not None: callbacks.on_node_start(name=entry.name, resource_kind=ExecutionResourceKind.LOAD) start: float = time.monotonic() - tables: tuple[LoadedTable, ...] = () - raised: LoadRunError | RuntimeError | KeyError | None = None - rows_affected: int | None = None - try: - tables = run_load( - entry=entry, - project=LoadProject(*runtime.load_projects[entry.name]), - source_map=plan.source_map, - adapter=adapter, - connection_config=connection_config, - base_connection=connection, - database=runtime.default_database, - ) - rows_affected = sum(table.rows or 0 for table in tables) - except (LoadRunError, RuntimeError, KeyError) as error: - raised = error + tables: tuple[LoadedTable, ...] = run_load( + entry=entry, + project=LoadProject(*runtime.load_projects[entry.name]), + source_map=plan.source_map, + adapter=adapter, + connection_config=connection_config, + base_connection=connection, + database=runtime.default_database, + ) failures: list[str] = [f"{table.table}: {table.error}" for table in tables if table.error] fields: dict[str, Any] = { "source_name": entry.name, "loader_name": "", "target": entry.name, "resource_kind": ExecutionResourceKind.LOAD, - "rows_affected": rows_affected, + "rows_affected": sum(table.rows or 0 for table in tables), "duration_ms": int((time.monotonic() - start) * 1000), "result_payload": [_table_report(table=table) for table in tables], "result_metadata": {"tables": [table.table for table in tables]}, "warning_messages": tuple(chain.from_iterable(table.warnings for table in tables)), } - result: LoadExecutionResult = ( - failed_result( - LoadExecutionResult, reason="\n".join(failures) or None, error=raised, **fields - ) - if raised is not None or failures - else LoadExecutionResult(status=ExecutionStatus.SUCCESS, **fields) - ) + if failures: + return failed_result(LoadExecutionResult, reason="\n".join(failures), **fields) + return LoadExecutionResult(status=ExecutionStatus.SUCCESS, **fields) + + +def record_build_load_result( + *, + result: LoadExecutionResult, + adapter: BaseAdapter, + connection: Any, + runtime: BuildRuntimeParams, +) -> LoadExecutionResult: + """Record the load's node result row, whether the load finished or failed, and return it.""" + result_store: DirectNodeResultStore = build_direct_node_result_store( adapter=adapter, connection=connection, @@ -82,26 +82,25 @@ def execute_build_load_node( target_config=runtime.target_config, ) with CostContext.resource_scope( - resource_type="load", resource_name=entry.name, phase="finalize" + resource_type="load", resource_name=result.source_name, phase="finalize" ): persist_load_result(result_store=result_store, result=result, run_id=runtime.run_id) return result -def failed_load_result( - *, key: CompiledObjectKey, reason: str | None = None, error: BaseException | None = None +def own_failure_or_recorded( + *, result: LoadExecutionResult, recorded: LoadExecutionResult ) -> LoadExecutionResult: - """The failed result of the load `key`, so a load's failure handling applies.""" + """`recorded`, unless recording failed `result` that had already failed: then its own error.""" - return failed_result( - LoadExecutionResult, - reason=reason, - error=error, - source_name=key.name, - loader_name="", - target=key.name, - resource_kind=ExecutionResourceKind.LOAD, - rows_affected=None, + if recorded is result or result.status != ExecutionStatus.FAILED: + return recorded + return replace( + result, + warning_messages=( + *result.warning_messages, + f"Its node result row was not recorded: {recorded.error_message}", + ), ) diff --git a/src/sqlbuild/executor/build/_helpers/node_errors.py b/src/sqlbuild/executor/build/_helpers/node_errors.py new file mode 100644 index 0000000000..b9522027a5 --- /dev/null +++ b/src/sqlbuild/executor/build/_helpers/node_errors.py @@ -0,0 +1,108 @@ +"""The node boundary's rule: which errors fail one node and which stop the whole build.""" + +from __future__ import annotations + +import builtins +from types import TracebackType +from typing import Any + +from sqlbuild._native import CompiledObjectKey, CompiledResourceType, PlanOutput, SourceEntry +from sqlbuild.executor.build.constants import BUILD_WORKER_FAILED_CODE +from sqlbuild.executor.build.models import FunctionExecutionResult, SeedExecutionResult +from sqlbuild.executor.load.main._resource_kind import load_resource_kind +from sqlbuild.executor.load.models import LoadExecutionResult +from sqlbuild.executor.run.models import ModelExecutionResult +from sqlbuild.executor.run.types import ExecutionPhase +from sqlbuild.executor.scheduling.main._failed_result import failed_result +from sqlbuild.executor.testing.models import SqlTestExecutionResult +from sqlbuild.runtime.contracts.types import ExecutionResourceKind +from sqlbuild.runtime.execution_limits.exceptions import ExecutionDurationLimitError + +_OWN_PACKAGE: str = "sqlbuild" + + +def stops_build(error: BaseException) -> bool: + """Whether `error` ends the build: an interrupt, a control signal or the build's time limit.""" + + return not isinstance(error, Exception) or isinstance(error, ExecutionDurationLimitError) + + +def node_error_reason(error: BaseException) -> str | None: + """The text before a node error's message: its type, and where SQLBuild's own code raised it.""" + + name: str = type(error).__name__ + place: str | None = _own_code_place(error) + if place is not None: + return f"{name} raised in SQLBuild's own code at {place}" + return name if str(error).strip() else None + + +def failed_node_result( + *, + key: CompiledObjectKey, + plan: PlanOutput, + reason: str | None = None, + error: BaseException | None = None, + code: str = BUILD_WORKER_FAILED_CODE, + phase: ExecutionPhase | None = None, +) -> ( + ModelExecutionResult + | SeedExecutionResult + | FunctionExecutionResult + | SqlTestExecutionResult + | LoadExecutionResult +): + """The failed result of the node's own kind, so its kind's failure handling applies.""" + + said: dict[str, Any] = {"reason": reason, "error": error, "code": code, "phase": phase} + if key.resource_type == CompiledResourceType.SEED: + return failed_result(SeedExecutionResult, seed_name=key.name, **said) + if key.resource_type == CompiledResourceType.SOURCE: + source: SourceEntry = plan.source_map[key.name] + return failed_result( + LoadExecutionResult, + source_name=source.name, + loader_name=source.loader or "", + target=source.table or source.name, + resource_kind=load_resource_kind(source), + rows_affected=None, + **said, + ) + if key.resource_type == CompiledResourceType.LOAD: + return failed_result( + LoadExecutionResult, + source_name=key.name, + loader_name="", + target=key.name, + resource_kind=ExecutionResourceKind.LOAD, + rows_affected=None, + **said, + ) + if key.resource_type in {CompiledResourceType.UDF, CompiledResourceType.TABLE_FN}: + return failed_result( + FunctionExecutionResult, + function_name=key.name, + function_kind=str(key.resource_type), + **said, + ) + if key.resource_type == CompiledResourceType.SQL_TEST: + return failed_result(SqlTestExecutionResult, test_name=key.name, **said) + return failed_result(ModelExecutionResult, model_name=key.name, **said) + + +def _own_code_place(error: BaseException) -> str | None: + """`module:line` where SQLBuild's own code raised a built-in error other than `OSError`.""" + + if type(error) is not getattr(builtins, type(error).__name__, None) or isinstance( + error, OSError + ): + return None + traceback: TracebackType | None = error.__traceback__ + if traceback is None: + return None + while traceback.tb_next is not None: + traceback = traceback.tb_next + module: str = str(traceback.tb_frame.f_globals.get("__name__", "")) + if module != _OWN_PACKAGE and not module.startswith(f"{_OWN_PACKAGE}."): + return None + return f"{module}:{traceback.tb_lineno}" diff --git a/src/sqlbuild/executor/build/classes/build_scheduler.py b/src/sqlbuild/executor/build/classes/build_scheduler.py index 7105274992..6108f9c207 100644 --- a/src/sqlbuild/executor/build/classes/build_scheduler.py +++ b/src/sqlbuild/executor/build/classes/build_scheduler.py @@ -8,8 +8,9 @@ import threading import time from collections import deque -from collections.abc import Callable, Iterable, Mapping +from collections.abc import Callable, Iterable, Iterator, Mapping from concurrent.futures import FIRST_COMPLETED, CancelledError, Future, ThreadPoolExecutor, wait +from contextlib import contextmanager from contextvars import copy_context from functools import partial from itertools import chain @@ -39,6 +40,7 @@ WriteClaims, audit_resource_id, current_native_progress_projector, + error_code, output_node_scope, sql_test_resource_id, ) @@ -64,12 +66,18 @@ from sqlbuild.executor.build._helpers.indexes import build_execution_indexes from sqlbuild.executor.build._helpers.load_node import ( execute_build_load_node, - failed_load_result, + own_failure_or_recorded, + record_build_load_result, ) from sqlbuild.executor.build._helpers.model_timeouts import ( model_timeout_policy, timed_out_model_result, ) +from sqlbuild.executor.build._helpers.node_errors import ( + failed_node_result, + node_error_reason, + stops_build, +) from sqlbuild.executor.build._helpers.retention import ( apply_table_type_conversion, materialization_recreates_relation, @@ -88,8 +96,9 @@ BUILD_UNKNOWN_RESOURCE_FAILED_CODE, BUILD_WORKER_FAILED_CODE, CLAIM_POLL_SECONDS, - UNREPORTED_NODE_REASON, + SCHEDULER_FAILURE_REASON, ) +from sqlbuild.executor.build.exceptions import BuildSchedulerError from sqlbuild.executor.build.models import ( BuildCallbacks, BuildCustomizations, @@ -126,7 +135,7 @@ ModelExecutionResult, ModelMaterializationContext, ) -from sqlbuild.executor.run.types import MicrobatchBatchExecutor +from sqlbuild.executor.run.types import ExecutionPhase, MicrobatchBatchExecutor from sqlbuild.executor.scheduling.classes.recovering_connection_pool import RecoveringConnectionPool from sqlbuild.executor.scheduling.classes.session_warehouses import ( SessionWarehouses, @@ -152,7 +161,6 @@ from sqlbuild.provider.main.runtime import ProviderContainer from sqlbuild.runtime.contracts.types import ExecutionResourceKind, NodeStartCallback from sqlbuild.runtime.execution_limits.classes.connection_recovery import ConnectionRecovery -from sqlbuild.runtime.execution_limits.exceptions import ExecutionDurationLimitError from sqlbuild.runtime.execution_limits.main.enforce_execution_deadline import ( enforce_execution_deadline, ) @@ -177,6 +185,10 @@ def _test_result_authored_order(*, plan: PlanOutput, result: SqlTestExecutionRes return len(plan.test_entries) +def _node_label(key: CompiledObjectKey) -> str: + return f"{key.resource_type}:{key.name}" + + def _claim_key(key: CompiledObjectKey) -> str: """The `kind:name` key a write claim names `key` by.""" @@ -476,7 +488,7 @@ def _run_serial(self) -> None: self._wait_for_claims() continue key: CompiledObjectKey = next_key - if key.resource_type == CompiledResourceType.SOURCE: + with self._scheduler_step(step=f"dispatching {_node_label(key)}"): if self._verdicts.holds(key): self._record_skipped(key) self._mark_complete(key) @@ -484,24 +496,7 @@ def _run_serial(self) -> None: if not self._pre_dispatch(key): self._mark_complete(key) continue - try: - result: LoadExecutionResult = cast( - LoadExecutionResult, - self._execute_node(key=key, connection=connection), - ) - except Exception as error: - self._fail_unreported_node(key=key, error=error) - raise - self._handle_completion(key=key, result=result) - continue - if self._verdicts.holds(key): - self._record_skipped(key) - self._mark_complete(key) - continue - if not self._pre_dispatch(key): - self._mark_complete(key) - continue - try: + with self._scheduler_step(step=f"running {_node_label(key)}", key=key): result: ( ModelExecutionResult | SeedExecutionResult @@ -509,11 +504,9 @@ def _run_serial(self) -> None: | SqlTestExecutionResult | LoadExecutionResult ) = self._execute_node(key=key, connection=connection) - except Exception as error: - self._fail_unreported_node(key=key, error=error) - raise connection = self._connection_recovery.usable(connection) - self._handle_completion(key=key, result=result) + with self._scheduler_step(step=f"recording {_node_label(key)}'s result"): + self._handle_completion(key=key, result=result) finally: self._connection_pool.put(connection) @@ -521,90 +514,144 @@ def _run_concurrent(self) -> None: escaped: BaseException | None = None with ThreadPoolExecutor(max_workers=self._max_concurrency) as pool: self._report_scheduler_state() - while self._ready or self._in_flight: - enforce_execution_deadline() - if self._stop and not self._in_flight: - break + try: + escaped = self._dispatch_concurrently(pool) + except BuildSchedulerError as failure: + self._record_in_flight(failure) + raise + self._report_scheduler_state() + if escaped is not None: + raise escaped - self._update_microbatch_coordinator_demand() + def _dispatch_concurrently(self, pool: ThreadPoolExecutor) -> BaseException | None: + """Run ready nodes on `pool` until none is left; the first error that stops the build.""" - while self._ready and len(self._in_flight) < self._max_concurrency: - if self._stop: - break - next_key: CompiledObjectKey | None = self._take_ready_key() - if next_key is None: - break - key: CompiledObjectKey = next_key - if key.resource_type == CompiledResourceType.SOURCE: - if self._verdicts.holds(key): - self._record_skipped(key) - self._mark_complete(key) - continue - if not self._pre_dispatch(key): - self._mark_complete(key) - continue - self._start_in_flight(key) - pool.submit(copy_context().run, self._worker, key) - continue - if self._verdicts.holds(key): - self._record_skipped(key) - self._mark_complete(key) - continue - if self._is_concurrent_microbatch(key) and any( - not self._is_concurrent_microbatch(candidate) - and self._has_job_room(candidate) - for candidate in self._ready - ): - self._ready.append(key) - continue - if not self._pre_dispatch(key): - self._mark_complete(key) - continue - if self._is_concurrent_microbatch(key): - with self._microbatch_coordinator_lock: - if ( - len(self._microbatch_coordinators) + self._microbatch_subworkers - >= self._max_concurrency - ): - self._ready.appendleft(key) - break - self._microbatch_coordinators.add(key) - self._start_in_flight(key) - pool.submit( - copy_context().run, - self._concurrent_microbatch_worker, - key=key, - pool=pool, - ) - continue - self._start_in_flight(key) - pool.submit(copy_context().run, self._worker, key) + escaped: BaseException | None = None + while self._ready or self._in_flight: + enforce_execution_deadline() + if self._stop and not self._in_flight: + break - self._report_scheduler_state() - if not self._in_flight: - if not self._ready or self._stop: - break - self._wait_for_claims() - continue + self._update_microbatch_coordinator_demand() - try: - completion: NodeCompletion = self._completion_queue.get( - timeout=CLAIM_POLL_SECONDS if self._ready and self._write_claims else None - ) - except queue.Empty: + with self._scheduler_step(step="dispatching ready nodes"): + self._dispatch_ready(pool) + + self._report_scheduler_state() + if not self._in_flight: + if not self._ready or self._stop: + break + self._wait_for_claims() + continue + + try: + completion: NodeCompletion = self._completion_queue.get( + timeout=CLAIM_POLL_SECONDS if self._ready and self._write_claims else None + ) + except queue.Empty: + continue + self._finish_in_flight(completion.key) + if completion.error is not None: + self._stop = True + if escaped is None and not stops_build(completion.error): + raise self._scheduler_failure( + step=f"running {_node_label(completion.key)}", + error=cast(Exception, completion.error), + key=completion.key, + ) from completion.error + if escaped is None: + escaped = completion.error + continue + if completion.result is not None: + with self._scheduler_step(step=f"recording {_node_label(completion.key)}'s result"): + self._handle_completion(key=completion.key, result=completion.result) + return escaped + + def _dispatch_ready(self, pool: ThreadPoolExecutor) -> None: + while self._ready and len(self._in_flight) < self._max_concurrency: + if self._stop: + break + next_key: CompiledObjectKey | None = self._take_ready_key() + if next_key is None: + break + key: CompiledObjectKey = next_key + if key.resource_type == CompiledResourceType.SOURCE: + if self._verdicts.holds(key): + self._record_skipped(key) + self._mark_complete(key) continue - self._finish_in_flight(completion.key) - if completion.error is not None: - if escaped is None: - escaped = completion.error - self._stop = True - self._fail_unreported_node(key=completion.key, error=completion.error) + if not self._pre_dispatch(key): + self._mark_complete(key) continue - if completion.result is not None: - self._handle_completion(key=completion.key, result=completion.result) - self._report_scheduler_state() - if escaped is not None: - raise escaped + self._start_in_flight(key) + pool.submit(copy_context().run, self._worker, key) + continue + if self._verdicts.holds(key): + self._record_skipped(key) + self._mark_complete(key) + continue + if self._is_concurrent_microbatch(key) and any( + not self._is_concurrent_microbatch(candidate) and self._has_job_room(candidate) + for candidate in self._ready + ): + self._ready.append(key) + continue + if not self._pre_dispatch(key): + self._mark_complete(key) + continue + if self._is_concurrent_microbatch(key): + with self._microbatch_coordinator_lock: + if ( + len(self._microbatch_coordinators) + self._microbatch_subworkers + >= self._max_concurrency + ): + self._ready.appendleft(key) + break + self._microbatch_coordinators.add(key) + self._start_in_flight(key) + pool.submit( + copy_context().run, + self._concurrent_microbatch_worker, + key=key, + pool=pool, + ) + continue + self._start_in_flight(key) + pool.submit(copy_context().run, self._worker, key) + + @contextmanager + def _scheduler_step(self, *, step: str, key: CompiledObjectKey | None = None) -> Iterator[None]: + """Stop the build with a `BuildSchedulerError` naming `step` if its own work raises.""" + + try: + yield + except Exception as error: + if stops_build(error): + raise + self._stop = True + raise self._scheduler_failure(step=step, error=error, key=key) from error + + def _record_in_flight(self, failure: BuildSchedulerError) -> None: + """Record the result of each node still running, so none is left without one.""" + + while self._in_flight: + completion: NodeCompletion = self._completion_queue.get() + self._finish_in_flight(completion.key) + if completion.error is not None and not stops_build(completion.error): + escaped: BuildSchedulerError = self._scheduler_failure( + step=f"running {_node_label(completion.key)}", + error=cast(Exception, completion.error), + key=completion.key, + ) + failure.add_note("\n".join([str(escaped), *getattr(escaped, "__notes__", ())])) + if completion.result is None: + continue + try: + self._handle_completion(key=completion.key, result=completion.result) + except Exception as error: # noqa: BLE001 - the scheduler's first error escapes + failure.add_note( + f"Recording {_node_label(completion.key)}'s result also failed: {error}" + ) def _update_microbatch_coordinator_demand(self) -> None: """Count the running coordinators and the queued ones whose jobs would let them start.""" @@ -824,33 +871,44 @@ def _execute_concurrent_microbatch_node( on_statement_complete=self._on_statement_complete, ), ): - failure: str | None = self._switch_failure(key=key, connection=connection) - if failure is not None: - return failed_result( - ModelExecutionResult, - code=BUILD_WORKER_FAILED_CODE, - model_name=key.name, - reason=failure, - ) - return self._execute_model_node( + return self._at_node_boundary( key=key, connection=connection, - microbatch_batch_runner=lambda batches, concurrency, execute: ( - self._run_microbatch_subwork( - pool=pool, - jobs=self._node_jobs.get(key, ()), - warehouse=self._node_warehouses.get(key), - coordinator_connection=connection, - batches=batches, - concurrency=concurrency, - execute=execute, - ) + work=lambda: self._run_concurrent_microbatch_model( + key=key, pool=pool, connection=connection ), ) finally: with self._microbatch_coordinator_lock: self._microbatch_coordinators.discard(key) + def _run_concurrent_microbatch_model( + self, *, key: CompiledObjectKey, pool: ThreadPoolExecutor, connection: Any + ) -> ModelExecutionResult: + failure: str | None = self._switch_failure(key=key, connection=connection) + if failure is not None: + return failed_result( + ModelExecutionResult, + code=BUILD_WORKER_FAILED_CODE, + model_name=key.name, + reason=failure, + ) + return self._execute_model_node( + key=key, + connection=connection, + microbatch_batch_runner=lambda batches, concurrency, execute: ( + self._run_microbatch_subwork( + pool=pool, + jobs=self._node_jobs.get(key, ()), + warehouse=self._node_warehouses.get(key), + coordinator_connection=connection, + batches=batches, + concurrency=concurrency, + execute=execute, + ) + ), + ) + def _run_microbatch_subwork( self, *, @@ -900,14 +958,18 @@ def submit_one() -> tuple[Future[MicrobatchPhaseOutcome], BatchWindow]: submitted_future, submitted_batch = submit_one() in_flight[submitted_future] = submitted_batch coordinator_batch: BatchWindow = pending_batches.popleft() - coordinator_result: MicrobatchPhaseOutcome = execute( - coordinator_batch, coordinator_connection - ) + try: + coordinator_result: MicrobatchPhaseOutcome = execute( + coordinator_batch, coordinator_connection + ) + except BaseException: + self._cancel_microbatch_subworkers(futures=tuple(in_flight), jobs=jobs) + _ = wait(tuple(in_flight)) + raise results[coordinator_batch.index] = coordinator_result failed: bool = coordinator_result.failure is not None if failed: - for future in in_flight: - self._cancel_microbatch_subworker(future=future, jobs=jobs) + self._cancel_microbatch_subworkers(futures=tuple(in_flight), jobs=jobs) first_exception: BaseException | None = None while in_flight: completed, _ = wait(tuple(in_flight), return_when=FIRST_COMPLETED) @@ -921,14 +983,12 @@ def submit_one() -> tuple[Future[MicrobatchPhaseOutcome], BatchWindow]: if first_exception is None: first_exception = exc failed = True - for sibling in in_flight: - self._cancel_microbatch_subworker(future=sibling, jobs=jobs) + self._cancel_microbatch_subworkers(futures=tuple(in_flight), jobs=jobs) continue results[batch.index] = outcome if outcome.failure is not None: failed = True - for sibling in in_flight: - self._cancel_microbatch_subworker(future=sibling, jobs=jobs) + self._cancel_microbatch_subworkers(futures=tuple(in_flight), jobs=jobs) while ( not failed and pending_batches @@ -991,11 +1051,12 @@ def _release_microbatch_subworker(self, jobs: tuple[str, ...]) -> None: with self._job_lock: self._add_job_running(jobs=jobs, change=-1) - def _cancel_microbatch_subworker( - self, *, future: Future[MicrobatchPhaseOutcome], jobs: tuple[str, ...] + def _cancel_microbatch_subworkers( + self, *, futures: tuple[Future[MicrobatchPhaseOutcome], ...], jobs: tuple[str, ...] ) -> None: - if not future.cancelled() and future.cancel(): - self._release_microbatch_subworker(jobs) + for future in futures: + if not future.cancelled() and future.cancel(): + self._release_microbatch_subworker(jobs) def _pre_dispatch(self, key: CompiledObjectKey) -> bool: """Run pre-dispatch checks. Returns False if the node should be skipped.""" @@ -1177,7 +1238,28 @@ def _execute_node( | FunctionExecutionResult | SqlTestExecutionResult | LoadExecutionResult - ) = self._execute_node_with_cost_context(key=key, connection=connection) + ) = self._at_node_boundary( + key=key, + connection=connection, + work=lambda: self._execute_node_with_cost_context( + key=key, connection=connection + ), + ) + if key.resource_type == CompiledResourceType.LOAD: + load_result: LoadExecutionResult = cast(LoadExecutionResult, result) + result = own_failure_or_recorded( + result=load_result, + recorded=self._at_node_boundary( + key=key, + connection=connection, + work=lambda: record_build_load_result( + result=load_result, + adapter=self._adapter, + connection=connection, + runtime=self._runtime, + ), + ), + ) if _resource_result_failed(result): lifecycle.failed(error_code=getattr(result, "error_code", None)) elif getattr(result, "status", None) == ExecutionStatus.SKIPPED: @@ -1303,29 +1385,22 @@ def _enter_node_warehouse( failure: str | None = self._switch_failure(key=key, connection=connection) if failure is None: return None - return self._failed_node_result(key=key, reason=failure) + return failed_node_result(key=key, plan=self._plan, reason=failure) - def _fail_unreported_node(self, *, key: CompiledObjectKey, error: BaseException) -> None: - """Fail a node whose execution raised an `Exception`, other than the build's time limit.""" + def _at_node_boundary[ResultT]( + self, *, key: CompiledObjectKey, connection: Any, work: Callable[[], ResultT] + ) -> ResultT: + """The node boundary: `work`'s result, or the node's failure when its own work raises.""" - if not isinstance(error, Exception) or isinstance(error, ExecutionDurationLimitError): - return try: - self._handle_completion( - key=key, - result=self._failed_node_result( - key=key, reason=UNREPORTED_NODE_REASON, error=error - ), + return work() + except Exception as error: + return cast( + ResultT, self._node_error_result(key=key, connection=connection, error=error) ) - except Exception as recording_error: # noqa: BLE001 - the node's own error still escapes - error.add_note(f"Recording the node's failure also failed: {recording_error}") - def _failed_node_result( - self, - *, - key: CompiledObjectKey, - reason: str | None = None, - error: BaseException | None = None, + def _node_error_result( + self, *, key: CompiledObjectKey, connection: Any, error: Exception ) -> ( ModelExecutionResult | SeedExecutionResult @@ -1333,41 +1408,38 @@ def _failed_node_result( | SqlTestExecutionResult | LoadExecutionResult ): - """The failed result of the node's own kind, so its kind's failure handling applies.""" + """Node `key`'s failure for `error`, which escapes instead when it stops the build.""" - said: dict[str, Any] = {"reason": reason, "error": error} - if key.resource_type == CompiledResourceType.SEED: - return failed_result( - SeedExecutionResult, code=BUILD_WORKER_FAILED_CODE, seed_name=key.name, **said - ) - if key.resource_type == CompiledResourceType.SOURCE: - source: SourceEntry = self._plan.source_map[key.name] - return failed_result( - LoadExecutionResult, - source_name=source.name, - loader_name=source.loader or "", - target=source.table or source.name, - resource_kind=load_resource_kind(source), - rows_affected=None, - **said, - ) - if key.resource_type == CompiledResourceType.LOAD: - return failed_load_result(key=key, **said) - if key.resource_type in {CompiledResourceType.UDF, CompiledResourceType.TABLE_FN}: - return failed_result( - FunctionExecutionResult, - code=BUILD_WORKER_FAILED_CODE, - function_name=key.name, - function_kind=str(key.resource_type), - **said, - ) - if key.resource_type == CompiledResourceType.SQL_TEST: - return failed_result( - SqlTestExecutionResult, code=BUILD_WORKER_FAILED_CODE, test_name=key.name, **said - ) - return failed_result( - ModelExecutionResult, code=BUILD_WORKER_FAILED_CODE, model_name=key.name, **said + if stops_build(error): + raise error + self._connection_recovery.check_before_reuse(connection) + return failed_node_result( + key=key, + plan=self._plan, + reason=node_error_reason(error), + error=error, + code=error_code(error=error, fallback_code=BUILD_WORKER_FAILED_CODE), + phase=ExecutionPhase.EXECUTE, + ) + + def _scheduler_failure( + self, *, step: str, error: Exception, key: CompiledObjectKey | None = None + ) -> BuildSchedulerError: + """Stop the build at `step`, first failing node `key` when it has no result yet.""" + + reason: str = SCHEDULER_FAILURE_REASON.format(step=step) + failure: BuildSchedulerError = BuildSchedulerError( + f"{reason}: {type(error).__name__}: {error}" ) + if key is not None and key not in self._completed_keys: + try: + self._handle_completion( + key=key, + result=failed_node_result(key=key, plan=self._plan, reason=reason, error=error), + ) + except Exception as recording_error: # noqa: BLE001 - the scheduler's error escapes + failure.add_note(f"Recording the node's failure also failed: {recording_error}") + return failure def _execute_source_node( self, *, key: CompiledObjectKey, connection: Any @@ -1421,17 +1493,8 @@ def _execute_seed_node(self, *, key: CompiledObjectKey, connection: Any) -> Seed sqlbuild_phase="load", sqlbuild_kind="seed", ): - try: - if self._before_node_write is not None: - self._before_node_write(entry=seed_entry, connection=connection) - except Exception as error: - return failed_result( - SeedExecutionResult, - error=error, - code=BUILD_WORKER_FAILED_CODE, - seed_name=seed_entry.name, - duration_ms=int((time.monotonic() - start) * 1000), - ) + if self._before_node_write is not None: + self._before_node_write(entry=seed_entry, connection=connection) result: SeedExecutionResult = execute_seed( seed_entry=seed_entry, adapter=self._adapter, @@ -1687,11 +1750,9 @@ def _execute_model_node( ), ) except Exception as error: - result = failed_result( + result = cast( ModelExecutionResult, - error=error, - code=BUILD_WORKER_FAILED_CODE, - model_name=model_entry.name, + self._node_error_result(key=key, connection=connection, error=error), ) if deadline is not None and deadline.expired and result.status == ExecutionStatus.FAILED: result = timed_out_model_result(result=result, report=deadline.report()) diff --git a/src/sqlbuild/executor/build/constants.py b/src/sqlbuild/executor/build/constants.py index 0aca2c7336..b30c8544fe 100644 --- a/src/sqlbuild/executor/build/constants.py +++ b/src/sqlbuild/executor/build/constants.py @@ -26,4 +26,4 @@ BUILD_SOURCE_FRESHNESS_BLOCKED_CODE: str = "B005" BUILD_FIRST_BUILD_OVER_EXISTING_CODE: str = "B006" CLAIM_POLL_SECONDS: float = 2.0 -UNREPORTED_NODE_REASON: str = "execution ended before the node reported a result" +SCHEDULER_FAILURE_REASON: str = "the build scheduler failed while {step}" diff --git a/src/sqlbuild/executor/build/exceptions.py b/src/sqlbuild/executor/build/exceptions.py new file mode 100644 index 0000000000..d877cf5297 --- /dev/null +++ b/src/sqlbuild/executor/build/exceptions.py @@ -0,0 +1,7 @@ +"""Errors that end a build.""" + +from __future__ import annotations + + +class BuildSchedulerError(RuntimeError): + """The build scheduler's own work failed, so the build stopped.""" diff --git a/src/sqlbuild/executor/run/types.py b/src/sqlbuild/executor/run/types.py index d7ad567e24..db69a15c0d 100644 --- a/src/sqlbuild/executor/run/types.py +++ b/src/sqlbuild/executor/run/types.py @@ -51,6 +51,7 @@ class RuntimeCursorWatermarkMode(StrEnum): class ExecutionPhase(StrEnum): + EXECUTE = "execute" PRE_HOOK = "pre_hook" STAGING = "staging" SCHEMA_CHANGE = "schema_change" diff --git a/src/sqlbuild/runtime/execution_limits/classes/connection_recovery.py b/src/sqlbuild/runtime/execution_limits/classes/connection_recovery.py index 578aa01202..95988e6210 100644 --- a/src/sqlbuild/runtime/execution_limits/classes/connection_recovery.py +++ b/src/sqlbuild/runtime/execution_limits/classes/connection_recovery.py @@ -1,4 +1,4 @@ -"""Check connections a deadline interrupted before reuse, replacing those left unusable.""" +"""Check connections a deadline interrupted or a failed node left before reuse.""" from __future__ import annotations @@ -26,6 +26,11 @@ def __init__(self, *, adapter: Any, connect: Callable[[], Any]) -> None: self._broken: set[int] = set() self._lock: threading.Lock = threading.Lock() + def check_before_reuse(self, connection: Any) -> None: + """Probe `connection` before its next use, as a node's error may have left it unusable.""" + + interrupted_connections.mark(connection) + def usable(self, connection: Any) -> Any: """`connection` if healthy, else a replacement, else the original kept marked broken.""" @@ -51,12 +56,15 @@ def usable(self, connection: Any) -> Any: with self._lock: self._broken.add(id(connection)) _LOGGER.warning( - "A connection left unusable by a timed-out statement could not be replaced (%s); " + "A connection left unusable by a timed-out statement or a failed node could not be " + "replaced (%s); " "work that uses it will fail", error, ) return connection - _LOGGER.warning("A connection left unusable by a timed-out statement was replaced") + _LOGGER.warning( + "A connection left unusable by a timed-out statement or a failed node was replaced" + ) self._forget_broken(connection) with self._lock: self._replacements.append(replacement) diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/_test_types.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/_test_types.py index 91ae6779f1..021fce1ab7 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/_test_types.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/_test_types.py @@ -266,6 +266,10 @@ class GroupExecutionTestCase(WorkerExecutionTestCase): expected_marts_started: bool = True # How staging_job's status reason starts: a failed run names the node that failed. expected_staging_reason: str = "model:broken_orders failed" + # Python run at the start of every worker and build process, such as an injected failure. + sitecustomize: str = "" + # staging_job's nodes as (key, status, failed phase, error message), when the case checks them. + expected_staging_nodes: list[tuple[str, str, str | None, str | None]] | None = None # model:broken_orders in staging_job; None when it follows the group's outcome. expected_broken_orders: str | None = None diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_worker.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_worker.py index fa2967fc3b..f8760ff224 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_worker.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_worker.py @@ -130,6 +130,21 @@ } | REGION_PROVIDER_FILES # The status reason of a worker run that ended as its nodes did. +# Fails broken_orders' build with an OSError, as a dropped warehouse connection would. +_BROKEN_ORDERS_CONNECTION_RESET: str = """ +import sqlbuild.executor.build.classes.build_scheduler as scheduler + +_dispatch = scheduler._dispatch_model + + +def _dispatch_model(**arguments): + if arguments["context"].entry.name == "broken_orders": + raise OSError("connection reset by peer") + return _dispatch(**arguments) + + +scheduler._dispatch_model = _dispatch_model +""" _COMPLETED: str = "worker executor completed and closed its connections" # marts_job builds only what staging_job's failure skips, and gate_job reads none of it. @@ -282,6 +297,24 @@ ), }, ), + GroupExecutionTestCase( + "an OSError inside one member's node fails that node; its member's other nodes run", + "SELECT 17 AS amount", + "SELECT amount FROM orders", + "failed", + [(11,)], + expected_child_statuses={"staging_job": ("failed",), "marts_job": ("blocked",)}, + sitecustomize=_BROKEN_ORDERS_CONNECTION_RESET, + expected_staging_nodes=[ + ( + "model:broken_orders", + "failed", + "execute", + "OSError: connection reset by peer", + ), + ("model:stg_orders", "success", None, None), + ], + ), GroupExecutionTestCase( "a failed critical node stops nothing beyond the default policy", "WITH source(value) AS (VALUES ('invalid')) SELECT CAST(value AS INTEGER) AS amount FROM source", @@ -343,6 +376,12 @@ def test_given_a_scheduled_group_when_workers_execute_then_dependencies_and_fail | test_case.files, default_job_files={}, ) + extlib: Path = tmp_path / "extlib" + extlib.mkdir() + _ = (extlib / "sitecustomize.py").write_text(test_case.sitecustomize) + monkeypatch.setenv( + "PYTHONPATH", os.pathsep.join(filter(None, (str(extlib), os.environ.get("PYTHONPATH")))) + ) with scheduled_worker(tmp_path, monkeypatch, test_case) as worker: parent: dict[str, Any] = wait_for_run( worker.api, worker.process, worker.log, job_key="annual_orders_job_group" @@ -402,6 +441,16 @@ def test_given_a_scheduled_group_when_workers_execute_then_dependencies_and_fail test_case.expected_status, "failed" ), ) + staging_nodes: list[tuple[str, str, str | None, str | None]] = control.execute( + "SELECT n.node_key, n.status, " + "json_extract(e.payload, '$.change.change.phase'), " + "json_extract(e.payload, '$.change.change.error_message') " + "FROM sqb_run_nodes n JOIN recall_events e " + "ON e.storage_id=n.finished_storage_id " + "WHERE n.run_id=? AND n.kind='node' ORDER BY n.node_key", + (runs["staging_job"]["run_id"],), + ).fetchall() + assert test_case.expected_staging_nodes in (None, staging_nodes), staging_nodes assert control.execute("SELECT count(*) FROM sqb_write_claims").fetchone() == (0,) assert control.execute( "SELECT count(*) FROM sqb_runs WHERE worker_instance IS NOT NULL AND root_run_id=?", diff --git a/tests/integration/src/sqlbuild/executor/build/_test_types.py b/tests/integration/src/sqlbuild/executor/build/_test_types.py index b12e53944a..6b33f1741d 100644 --- a/tests/integration/src/sqlbuild/executor/build/_test_types.py +++ b/tests/integration/src/sqlbuild/executor/build/_test_types.py @@ -1,4 +1,6 @@ +from collections.abc import Callable from dataclasses import dataclass, field +from typing import Any from sqlbuild._native import MicrobatchLimitAction from sqlbuild.executor.build.types import BuildStatus @@ -193,3 +195,45 @@ class TableTypeRoutingTestCase: expected_conversions: tuple[tuple[str, int], ...] expected_order_rows: int expected_error_fragment: str | None = None + + +@dataclass(frozen=True) +class NodeErrorTestCase: + description: str + # The module and function that run one kind of node, and the node it raises `error` in. + module: Any + injection_point: str + node: str + error: Exception + # How the failed node's message starts: the error's type, then its message. + expected_reason: str + # The nodes skipped because `node` failed; every other node succeeds. + expected_skipped: tuple[str, ...] + + +@dataclass(frozen=True) +class NodeOutcomesTestCase: + description: str + # Builds the stand-in for the function at `injection_point` (module, name). + wrap: Callable[[], Callable[..., Any]] + injection_point: tuple[Any, str] + # Nodes' (status, how the error message starts). + expected_outcomes: dict[str, tuple[str, str | None]] + + +@dataclass(frozen=True) +class DroppedConnectionTestCase: + description: str + node: str + expected_skipped: tuple[str, ...] + # The connection warnings logged, one per replaced connection. + expected_warnings: list[str] + + +@dataclass(frozen=True) +class UnrecordedLoadTestCase: + description: str + node: str + expected_skipped: tuple[str, ...] + # Lines the build's report shows, stripped. + expected_lines: frozenset[str] diff --git a/tests/integration/src/sqlbuild/executor/build/helpers.py b/tests/integration/src/sqlbuild/executor/build/helpers.py index c9c41a89a4..241f726944 100644 --- a/tests/integration/src/sqlbuild/executor/build/helpers.py +++ b/tests/integration/src/sqlbuild/executor/build/helpers.py @@ -5,8 +5,10 @@ import json from collections.abc import Callable from dataclasses import replace +from functools import partial from pathlib import Path from textwrap import dedent +from types import FunctionType from typing import Any import duckdb @@ -32,6 +34,16 @@ BuildRuntimeParams, ) from sqlbuild.executor.scheduling.types import ExecutionStatus +from tests.integration.src.sqlbuild.cli.commands.main.loads.helpers import ( + CliRun, + files_load, + land_file, + loader_file, + managed_source, + query, + run_sqb, + write_project, +) from tests.integration.src.sqlbuild.executor.build._test_types import ( BuildExecutionTestCase, ) @@ -545,3 +557,164 @@ def duckdb_row_count(*, database: Path, table: str) -> int: with duckdb.connect(str(database)) as connection: rows: list[tuple[int]] = connection.execute(f"SELECT COUNT(*) FROM {table}").fetchall() return rows[0][0] + + +NODE_KINDS_MODELS: dict[str, str] = { + "order_count": ( + "MODEL (description 'Loaded orders.', materialized table);\n" + 'SELECT COUNT(*) AS orders FROM __source("shop__orders")\n' + ), + "event_count": ( + "MODEL (description 'Loaded events.', materialized table);\n" + 'SELECT COUNT(*) AS events FROM __source("landed_events")\n' + ), + "region_count": ( + "MODEL (description 'Seeded regions.', materialized table);\n" + 'SELECT COUNT(*) AS regions FROM __seed("regions")\n' + ), + "doubled": ( + "MODEL (description 'Calls a function.', materialized table);\n" + 'SELECT __udf("udf__doubled")(2) AS amount\n' + ), + "revenue": "MODEL (description 'Revenue.', materialized table);\nSELECT 10 AS amount\n", + "revenue_share": ( + "MODEL (description 'Depends on revenue.', materialized table);\n" + 'SELECT amount FROM __ref("revenue")\n' + ), +} +_NODE_KINDS_FILES: tuple[tuple[str, str], ...] = ( + loader_file("landed_events", [{"event_id": 1}]), + ( + "sql/sources/landed.yml", + managed_source( + "landed_events", " columns:\n - name: event_id\n type: BIGINT\n" + ), + ), + ("sql/seeds/regions.csv", "id\n1\n2\n"), + ( + "sql/seeds/regions.yml", + "seeds:\n - name: regions\n description: Regions.\n columns:\n" + " - name: id\n type: INTEGER\n", + ), + ( + "sql/functions/sql/udf__doubled.sql", + 'FUNCTION (\n description "Twice its argument",\n arguments (value INTEGER),\n' + " returns INTEGER,\n);\nvalue * 2\n", + ), + ( + "tests/unit/test_revenue.sql", + "TEST ();\nWITH __ref__revenue AS (SELECT 10 AS amount),\n" + "__expected__revenue_share AS (SELECT 10 AS amount)\nSELECT 1\n", + ), +) +# Every node of the node-kinds project. +NODE_KINDS_NODES: tuple[str, ...] = ( + *NODE_KINDS_MODELS, + "regions", + "landed_events", + "shop", + "udf__doubled", + "test_revenue", +) +# Each kind's function in the build, and how its node's name is read from its arguments. +_NODE_NAMES: dict[str, Callable[[dict[str, Any]], str]] = { + "execute_seed": lambda kwargs: kwargs["seed_entry"].name, + "run_on_engine": lambda kwargs: kwargs["source_entry"].name, + "run_load": lambda kwargs: kwargs["entry"].name, + "execute_function": lambda kwargs: kwargs["function_entry"].name, + "execute_sql_test": lambda kwargs: kwargs["test_entry"].name, + "_dispatch_model": lambda kwargs: kwargs["context"].entry.name, +} +# A check's status as the same word an asset uses. +_CHECK_STATUSES: dict[str, str] = {"pass": "success", "error": "failed"} + + +def _raise(error: BaseException) -> None: + raise error + + +def raising_in(node: str, error: Exception, original: FunctionType) -> Callable[..., Any]: + """`original`, raising `error` instead when it runs node `node`.""" + + name: Callable[[dict[str, Any]], str] = _NODE_NAMES[original.__name__] + + def run(**kwargs: Any) -> Any: + return {node: partial(_raise, error)}.get(name(kwargs), partial(original, **kwargs))() + + return run + + +def _drop_connection(context: Any) -> None: + context.connection.close() + raise ConnectionResetError("connection reset by peer") + + +def dropping_connection_in(node: str, original: Callable[..., Any]) -> Callable[..., Any]: + """`_dispatch_model`, closing model `node`'s connection and failing as a dropped one would.""" + + def run(**kwargs: Any) -> Any: + context: Any = kwargs["context"] + return {node: partial(_drop_connection, context)}.get( + context.entry.name, partial(original, **kwargs) + )() + + return run + + +def _drop_load_connection(kwargs: dict[str, Any]) -> None: + kwargs["base_connection"].close() + raise ConnectionResetError("connection reset by peer") + + +def dropping_load_connection_in(node: str, original: Callable[..., Any]) -> Callable[..., Any]: + """`run_load`, closing load `node`'s connection and failing as a dropped one would.""" + + def run(**kwargs: Any) -> Any: + return {node: partial(_drop_load_connection, kwargs)}.get( + kwargs["entry"].name, partial(original, **kwargs) + )() + + return run + + +def without_load_projects(original: Callable[..., Any]) -> Callable[..., Any]: + """`execute_build_load_node` given no load projects, so the load's own code raises.""" + + def run(**kwargs: Any) -> Any: + runtime: Any = replace(kwargs.pop("runtime"), load_projects={}) + return original(runtime=runtime, **kwargs) + + return run + + +def build_node_kinds_project( + *, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> tuple[CliRun, dict[str, tuple[str, str | None]]]: + """Build the node-kinds project: each node's status and error message, loads' from the node + results the build recorded.""" + + project_dir: Path = write_project( + root=tmp_path, + sources_yml=files_load(table_name="shop__orders", source="shop__orders"), + models=NODE_KINDS_MODELS, + files=_NODE_KINDS_FILES, + ) + land_file(root=tmp_path, name="a.csv", text="id,name\n1,a\n2,b\n") + run: CliRun = run_sqb(project_dir=project_dir, args=("build", "--json"), capsys=capsys) + report: dict[str, Any] = json.loads(run.stdout) + outcomes: dict[str, tuple[str, str | None]] = { + node["name"]: ( + _CHECK_STATUSES.get(node["status"], node["status"]), + node.get("error_message"), + ) + for node in [*report["assets"], *report["checks"]] + } + outcomes.update( + (str(name), (str(status), message)) + for name, status, message in query( + project_dir=project_dir, + sql="SELECT node_name, status, error_message FROM dev._sqlbuild_node_results " + "WHERE node_type = 'load'", + ) + ) + return run, outcomes diff --git a/tests/integration/src/sqlbuild/executor/build/test_node_errors.py b/tests/integration/src/sqlbuild/executor/build/test_node_errors.py new file mode 100644 index 0000000000..7e27c74683 --- /dev/null +++ b/tests/integration/src/sqlbuild/executor/build/test_node_errors.py @@ -0,0 +1,232 @@ +"""An error raised while one node does its own work fails that node, whatever its kind: its +dependents are skipped, every independent node still runs, and the build is not stopped.""" + +from __future__ import annotations + +import logging +from itertools import product +from pathlib import Path +from typing import Any + +import pytest + +import sqlbuild.executor.build._helpers.load_node as load_node_module +import sqlbuild.executor.build.classes.build_scheduler as build_scheduler_module +import sqlbuild.executor.load.main._execute as load_execute_module +from tests.integration.src.sqlbuild.executor.build._test_types import ( + DroppedConnectionTestCase, + NodeErrorTestCase, + NodeOutcomesTestCase, + UnrecordedLoadTestCase, +) +from tests.integration.src.sqlbuild.executor.build.helpers import ( + NODE_KINDS_NODES, + build_node_kinds_project, + dropping_connection_in, + dropping_load_connection_in, + raising_in, + without_load_projects, +) + +# Each kind: the module and function its node runs through, the node, the nodes its failure skips, +# and how its failure message starts. A `@loader` source with no upstream loads before the +# scheduler starts, and its own handler names the loader phase that failed. +_KINDS: tuple[tuple[Any, str, str, tuple[str, ...], str], ...] = ( + (build_scheduler_module, "execute_seed", "regions", ("region_count",), "{type}: {error}"), + ( + load_execute_module, + "run_on_engine", + "landed_events", + ("event_count",), + "Loader write failed: {error}", + ), + (load_node_module, "run_load", "shop", ("order_count",), "{type}: {error}"), + (build_scheduler_module, "execute_function", "udf__doubled", ("doubled",), "{type}: {error}"), + ( + build_scheduler_module, + "execute_sql_test", + "test_revenue", + ("revenue_share",), + "{type}: {error}", + ), + (build_scheduler_module, "_dispatch_model", "revenue", ("revenue_share",), "{type}: {error}"), +) +_ERRORS: tuple[Exception, ...] = ( + OSError("connection reset by peer"), + TimeoutError("read timed out"), + Exception("unexpected reply"), +) + + +@pytest.mark.parametrize( + "test_case", + [ + NodeErrorTestCase( + description=f"{type(error).__name__} in {node}: it fails, the rest of the build runs", + module=module, + injection_point=point, + node=node, + error=error, + expected_reason=reason.format(type=type(error).__name__, error=error), + expected_skipped=skipped, + ) + for (module, point, node, skipped, reason), error in product(_KINDS, _ERRORS) + ], + ids=lambda case: case.description, +) +def test_given_a_node_raising_when_building_then_only_it_fails_and_its_dependents_skip( + test_case: NodeErrorTestCase, + tmp_path: Path, + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr( + test_case.module, + test_case.injection_point, + raising_in( + test_case.node, test_case.error, getattr(test_case.module, test_case.injection_point) + ), + ) + + run, outcomes = build_node_kinds_project(tmp_path=tmp_path, capsys=capsys) + + assert run.exit_code == 1, run.output + assert str(outcomes[test_case.node][1]).startswith(test_case.expected_reason), outcomes + assert {name: outcome[0] for name, outcome in outcomes.items()} == { + **dict.fromkeys(NODE_KINDS_NODES, "success"), + **dict.fromkeys(test_case.expected_skipped, "skipped"), + test_case.node: "failed", + }, run.output + + +@pytest.mark.parametrize( + "test_case", + [ + NodeOutcomesTestCase( + description="a load raising an OSError records its failed node result", + wrap=lambda: raising_in( + "shop", OSError("connection reset by peer"), load_node_module.run_load + ), + injection_point=(load_node_module, "run_load"), + expected_outcomes={ + "shop": ("failed", "OSError: connection reset by peer"), + "order_count": ("skipped", None), + }, + ), + NodeOutcomesTestCase( + description="a bug in SQLBuild's own load code says where it was raised", + wrap=lambda: without_load_projects(build_scheduler_module.execute_build_load_node), + injection_point=(build_scheduler_module, "execute_build_load_node"), + expected_outcomes={ + "shop": ( + "failed", + "KeyError raised in SQLBuild's own code at " + "sqlbuild.executor.build._helpers.load_node:", + ), + "order_count": ("skipped", None), + "revenue_share": ("success", None), + }, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_failing_load_when_building_then_its_outcome_and_reason_are_recorded( + test_case: NodeOutcomesTestCase, + tmp_path: Path, + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + module, name = test_case.injection_point + monkeypatch.setattr(module, name, test_case.wrap()) + + run, outcomes = build_node_kinds_project(tmp_path=tmp_path, capsys=capsys) + + assert run.exit_code == 1, run.output + assert { + node: (outcomes[node][0], str(outcomes[node][1] or "")[: len(message or "")] or None) + for node, (_, message) in test_case.expected_outcomes.items() + } == test_case.expected_outcomes, outcomes + + +@pytest.mark.parametrize( + "test_case", + [ + UnrecordedLoadTestCase( + description="a load whose own connection drops reports its error, not the recording's", + node="shop", + expected_skipped=("order_count",), + expected_lines=frozenset( + { + "✗ shop ConnectionResetError: connection reset by peer", + "Its node result row was not recorded: ConnectionException: " + "Connection Error: Connection already closed!", + } + ), + ), + ], + ids=lambda case: case.description, +) +def test_given_a_load_dropping_its_connection_when_building_then_it_fails_with_its_own_error( + test_case: UnrecordedLoadTestCase, + tmp_path: Path, + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr( + load_node_module, + "run_load", + dropping_load_connection_in(test_case.node, load_node_module.run_load), + ) + + run, outcomes = build_node_kinds_project(tmp_path=tmp_path, capsys=capsys) + + assert run.exit_code == 1, run.output + assert test_case.expected_lines <= set(map(str.strip, run.output.splitlines())), run.output + assert {name: outcome[0] for name, outcome in outcomes.items()} == { + **dict.fromkeys(filter(test_case.node.__ne__, NODE_KINDS_NODES), "success"), + **dict.fromkeys(test_case.expected_skipped, "skipped"), + }, run.output + + +@pytest.mark.parametrize( + "test_case", + [ + DroppedConnectionTestCase( + description="a model dropping its connection fails; the next node gets a new one", + node="revenue", + expected_skipped=("revenue_share",), + expected_warnings=[ + "A connection left unusable by a timed-out statement or a failed node was replaced" + ], + ), + ], + ids=lambda case: case.description, +) +def test_given_a_node_dropping_its_connection_when_building_then_the_next_node_gets_a_new_one( + test_case: DroppedConnectionTestCase, + tmp_path: Path, + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + monkeypatch.setattr( + build_scheduler_module, + "_dispatch_model", + dropping_connection_in(test_case.node, build_scheduler_module._dispatch_model), + ) + + run, outcomes = build_node_kinds_project(tmp_path=tmp_path, capsys=capsys) + messages: list[str] = list(map(logging.LogRecord.getMessage, caplog.records)) + + assert {name: outcome[0] for name, outcome in outcomes.items()} == { + **dict.fromkeys(NODE_KINDS_NODES, "success"), + **dict.fromkeys(test_case.expected_skipped, "skipped"), + test_case.node: "failed", + }, run.output + assert list(filter(lambda message: "connection left unusable" in message, messages)) == ( + test_case.expected_warnings + ) + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"]) diff --git a/tests/unit/src/sqlbuild/executor/build/classes/_test_types.py b/tests/unit/src/sqlbuild/executor/build/classes/_test_types.py index 2fa8bab1bf..a35f845f0e 100644 --- a/tests/unit/src/sqlbuild/executor/build/classes/_test_types.py +++ b/tests/unit/src/sqlbuild/executor/build/classes/_test_types.py @@ -118,5 +118,15 @@ class UnreportedNodeTestCase: error: BaseException # Each node result the build recorded, as (node name, status, error message, rows affected). expected_recorded: list[tuple[str, ExecutionStatus, str | None, int | None]] + # What escapes the build; the injected error's own type when None. + expected_escaped: type[BaseException] | None = None recording_error: Exception | None = None resource_type: CompiledResourceType = CompiledResourceType.MODEL + + +@dataclass(frozen=True) +class MidFlightRecordingFailureTestCase: + description: str + expected_message: str + # Each result the build recorded, as (node name, status). + expected_recorded: list[tuple[str, ExecutionStatus]] diff --git a/tests/unit/src/sqlbuild/executor/build/classes/helpers.py b/tests/unit/src/sqlbuild/executor/build/classes/helpers.py index 31dfb10bef..280d45668f 100644 --- a/tests/unit/src/sqlbuild/executor/build/classes/helpers.py +++ b/tests/unit/src/sqlbuild/executor/build/classes/helpers.py @@ -69,6 +69,7 @@ def _bare_scheduler( scheduler: Any = object.__new__(BuildScheduler) scheduler._ready = deque() scheduler._in_flight = set() + scheduler._completed_keys = set() scheduler._verdicts = verdicts_for({}) scheduler._max_concurrency = max_concurrency scheduler._stop = False @@ -293,6 +294,48 @@ def handle_completion(*, key: CompiledObjectKey, result: Any) -> None: raise AssertionError("the build swallowed the node's error") +def run_build_whose_recording_fails_mid_flight() -> tuple[ + BaseException, list[tuple[str, ExecutionStatus]], set[CompiledObjectKey] +]: + """Run `orders` and `customers` together, with recording `orders`' result raising while + `customers` still runs: what escapes, each result recorded, and the nodes left in flight.""" + + scheduler: Any = _bare_scheduler(job_limits={}, node_jobs={}, max_concurrency=2) + recorded: list[tuple[str, ExecutionStatus]] = [] + orders_handled: threading.Event = threading.Event() + scheduler._ready.extend((model_key("orders"), model_key("customers"))) + + def worker(key: CompiledObjectKey) -> None: + _ = {"customers": orders_handled.wait}.get(key.name, orders_handled.is_set)() + scheduler._completion_queue.put( + NodeCompletion( + key=key, + result=ModelExecutionResult(model_name=key.name, status=ExecutionStatus.SUCCESS), + ) + ) + + def fail_recording() -> None: + orders_handled.set() + raise RuntimeError("heartbeat lost") + + def handle_completion(*, key: CompiledObjectKey, result: Any) -> None: + def record() -> None: + recorded.append((key.name, result.status)) + + {"orders": fail_recording}.get(key.name, record)() + + scheduler._worker = worker + scheduler._handle_completion = handle_completion + scheduler._pre_dispatch = lambda _key: True + scheduler._is_concurrent_microbatch = lambda _key: False + scheduler._report_scheduler_state = lambda: None + try: + scheduler._run_concurrent() + except BaseException as escaped: # noqa: BLE001 - the test reports what escaped + return escaped, recorded, set(scheduler._in_flight) + raise AssertionError("the build went on after its own bookkeeping failed") + + def reserve_subworkers(test_case: SubworkerReservationTestCase) -> tuple[int, tuple[bool, ...]]: """The coordinator demand with the queued coordinators, then each reservation's outcome.""" diff --git a/tests/unit/src/sqlbuild/executor/build/classes/test_build_scheduler_unreported.py b/tests/unit/src/sqlbuild/executor/build/classes/test_build_scheduler_unreported.py index 588e15ef3b..3722b1cc59 100644 --- a/tests/unit/src/sqlbuild/executor/build/classes/test_build_scheduler_unreported.py +++ b/tests/unit/src/sqlbuild/executor/build/classes/test_build_scheduler_unreported.py @@ -1,69 +1,86 @@ -"""A node whose execution raises before it reports a result fails, unless the build itself stopped.""" +"""An error that escapes a node's boundary to the scheduler stops the build: a failure of the +scheduler's own work around the node fails that node and says so, and an interrupt or the build's +time limit fails nothing.""" from __future__ import annotations import pytest from sqlbuild._native import CompiledResourceType +from sqlbuild.executor.build.exceptions import BuildSchedulerError from sqlbuild.executor.scheduling.types import ExecutionStatus from sqlbuild.runtime.execution_limits.exceptions import ExecutionDurationLimitError -from tests.unit.src.sqlbuild.executor.build.classes._test_types import UnreportedNodeTestCase -from tests.unit.src.sqlbuild.executor.build.classes.helpers import run_build_whose_node_raises +from tests.unit.src.sqlbuild.executor.build.classes._test_types import ( + MidFlightRecordingFailureTestCase, + UnreportedNodeTestCase, +) +from tests.unit.src.sqlbuild.executor.build.classes.helpers import ( + run_build_whose_node_raises, + run_build_whose_recording_fails_mid_flight, +) @pytest.mark.parametrize( "test_case", [ UnreportedNodeTestCase( - description="an error escaping the node fails it with that error and still escapes", + description="the scheduler's own work failing around a node fails it and stops the build", error=ConnectionResetError("warehouse connection reset"), expected_recorded=[ ( "orders", ExecutionStatus.FAILED, - "execution ended before the node reported a result: warehouse connection reset", + "the build scheduler failed while running model:orders: " + "warehouse connection reset", None, ) ], + expected_escaped=BuildSchedulerError, ), UnreportedNodeTestCase( - description="when recording the failure raises, the node's own error still escapes", + description="when recording the failure raises, the scheduler's error still escapes", error=ConnectionResetError("warehouse connection reset"), recording_error=RuntimeError("heartbeat lost"), expected_recorded=[ ( "orders", ExecutionStatus.FAILED, - "execution ended before the node reported a result: warehouse connection reset", + "the build scheduler failed while running model:orders: " + "warehouse connection reset", None, ) ], + expected_escaped=BuildSchedulerError, ), UnreportedNodeTestCase( - description="a load that raised before it counted its rows fails with no row count", + description="a load whose scheduler work failed before it counted rows has no count", error=ConnectionResetError("warehouse connection reset"), resource_type=CompiledResourceType.LOAD, expected_recorded=[ ( "orders", ExecutionStatus.FAILED, - "execution ended before the node reported a result: warehouse connection reset", + "the build scheduler failed while running load:orders: " + "warehouse connection reset", None, ) ], + expected_escaped=BuildSchedulerError, ), UnreportedNodeTestCase( - description="a source that raised before it counted its rows fails with no row count", + description="a source whose scheduler work failed before it counted rows has no count", error=ConnectionResetError("warehouse connection reset"), resource_type=CompiledResourceType.SOURCE, expected_recorded=[ ( "orders", ExecutionStatus.FAILED, - "execution ended before the node reported a result: warehouse connection reset", + "the build scheduler failed while running source:orders: " + "warehouse connection reset", None, ) ], + expected_escaped=BuildSchedulerError, ), UnreportedNodeTestCase( description="a run cancel stops the build without failing the running node", @@ -80,7 +97,7 @@ ], ids=lambda case: case.description, ) -def test_given_a_node_that_raises_when_the_build_runs_then_only_a_node_error_fails_it( +def test_given_an_error_escaping_a_node_when_the_build_runs_then_the_build_stops( test_case: UnreportedNodeTestCase, ) -> None: escaped, recorded = run_build_whose_node_raises( @@ -89,5 +106,30 @@ def test_given_a_node_that_raises_when_the_build_runs_then_only_a_node_error_fai resource_type=test_case.resource_type, ) - assert escaped is type(test_case.error) + assert escaped is (test_case.expected_escaped or type(test_case.error)) + assert recorded == test_case.expected_recorded + + +@pytest.mark.parametrize( + "test_case", + [ + MidFlightRecordingFailureTestCase( + description="the running node is drained and recorded before the scheduler error escapes", + expected_message=( + "the build scheduler failed while recording model:orders's result: " + "RuntimeError: heartbeat lost" + ), + expected_recorded=[("customers", ExecutionStatus.SUCCESS)], + ), + ], + ids=lambda case: case.description, +) +def test_given_recording_a_result_failing_while_a_node_runs_when_building_then_the_build_stops( + test_case: MidFlightRecordingFailureTestCase, +) -> None: + escaped, recorded, in_flight = run_build_whose_recording_fails_mid_flight() + + assert isinstance(escaped, BuildSchedulerError) + assert str(escaped) == test_case.expected_message assert recorded == test_case.expected_recorded + assert in_flight == set() From 52757db2875eac84992dbc4624277504d3361123 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Sun, 6 Dec 2026 12:58:54 +0000 Subject: [PATCH 3/8] refactor: pass a load's plan as one tuple --- .../src/bindings/_helpers/plan_binding.rs | 7 +++---- .../src/bindings/_helpers/run_binding.rs | 14 ++++++-------- src/sqlbuild/_native.pyi | 6 ++---- src/sqlbuild/executor/loads/main/_run_load.py | 7 +++---- src/sqlbuild/executor/loads/main/plan_loads.py | 4 ++-- .../adapters/postgres/test_load_session.py | 2 +- .../executor/load_sessions/main/helpers.py | 4 ++-- .../load_sessions/main/test_open_load_session.py | 2 +- 8 files changed, 20 insertions(+), 26 deletions(-) diff --git a/crates/sqlbuild-python-load/src/bindings/_helpers/plan_binding.rs b/crates/sqlbuild-python-load/src/bindings/_helpers/plan_binding.rs index 67589e88a2..c94676fe11 100644 --- a/crates/sqlbuild-python-load/src/bindings/_helpers/plan_binding.rs +++ b/crates/sqlbuild-python-load/src/bindings/_helpers/plan_binding.rs @@ -10,16 +10,15 @@ use crate::runs::models::PlannedProject; /// Plan `project` (SQLLoad TOML), its targets writing through `sessions`; `{lines, ready, tables, missing}` as JSON. #[pyfunction] -#[pyo3(signature = (*, project, sessions, tables, reload = false))] +#[pyo3(signature = (*, project, sessions, plan))] pub(crate) fn plan_sqlload_project( project: &str, sessions: &Bound<'_, PyDict>, - tables: (Vec, Vec), - reload: bool, + plan: (Vec, Vec, bool), ) -> PyResult { let planned: PlannedProject = detached_load( (project, sessions), - (tables, reload), + plan, |project, (connections, options, require)| { plan_project(&project, connections, (options, require)) }, diff --git a/crates/sqlbuild-python-load/src/bindings/_helpers/run_binding.rs b/crates/sqlbuild-python-load/src/bindings/_helpers/run_binding.rs index 87e990b163..41d18ac877 100644 --- a/crates/sqlbuild-python-load/src/bindings/_helpers/run_binding.rs +++ b/crates/sqlbuild-python-load/src/bindings/_helpers/run_binding.rs @@ -15,20 +15,19 @@ use crate::runs::main::run_project::run_project; use crate::runs::models::ProjectRun; use crate::sessions::main::session_connection::session_connection; -/// Load `project` (SQLLoad TOML) through `sessions`, calling `on_rows` with the rows committed so far after each commit; `{tables, planned, missing}` JSON, nothing loaded when `require` misses. +/// Load `project` (SQLLoad TOML) through `sessions`, calling `on_rows` with the rows committed so far after each commit; `{tables, planned, missing}` JSON, nothing loaded when `plan`'s required tables miss. #[pyfunction] -#[pyo3(signature = (*, project, sessions, tables, reload = false, on_rows = None))] +#[pyo3(signature = (*, project, sessions, plan, on_rows = None))] pub(crate) fn run_sqlload_project( project: &str, sessions: &Bound<'_, PyDict>, - tables: (Vec, Vec), - reload: bool, + plan: (Vec, Vec, bool), on_rows: Option>, ) -> PyResult { let committed: Option = on_rows.map(committed_rows); let run: ProjectRun = detached_load( (project, sessions), - (tables, reload), + plan, |project, (connections, options, require)| { run_project( (&project, Vec::new(), None), @@ -78,13 +77,12 @@ pub(crate) type LoadRequest = ( Vec, ); -/// `work` on `project` and its load request (`sessions`, `tables`, `reload`), with the GIL released. +/// `work` on `project` and its load request (`sessions` and the `(select, require, reload)` plan), with the GIL released. pub(crate) fn detached_load( (project, sessions): (&str, &Bound<'_, PyDict>), - (tables, reload): ((Vec, Vec), bool), + (select, require, reload): (Vec, Vec, bool), work: impl FnOnce(String, LoadRequest) -> Result + Send, ) -> PyResult { - let (select, require): (Vec, Vec) = tables; let options = PlanOptions { select, reload, diff --git a/src/sqlbuild/_native.pyi b/src/sqlbuild/_native.pyi index a6ede30a86..7cc06cac7e 100644 --- a/src/sqlbuild/_native.pyi +++ b/src/sqlbuild/_native.pyi @@ -4124,8 +4124,7 @@ def run_sqlload_project( *, project: str, sessions: dict[str, dict[str, object]], - tables: tuple[list[str], list[str]], - reload: bool = False, + plan: tuple[list[str], list[str], bool], on_rows: Callable[[int], None] | None = None, ) -> str: ... def loader_projects( @@ -4145,8 +4144,7 @@ def plan_sqlload_project( *, project: str, sessions: dict[str, dict[str, object]], - tables: tuple[list[str], list[str]], - reload: bool = False, + plan: tuple[list[str], list[str], bool], ) -> str: ... def resolve_adapter(*, adapter_name: str, project_dir: Path | None = None) -> BaseAdapter: ... diff --git a/src/sqlbuild/executor/loads/main/_run_load.py b/src/sqlbuild/executor/loads/main/_run_load.py index d6262caa8b..23847416a5 100644 --- a/src/sqlbuild/executor/loads/main/_run_load.py +++ b/src/sqlbuild/executor/loads/main/_run_load.py @@ -29,8 +29,7 @@ def run_load( database: str | None, on_rows: Callable[[int], None] | None = None, ) -> tuple[LoadedTable, ...]: - """Each table `entry` loads, `on_rows` hearing the rows committed so far after each commit; - nothing loads when its plan leaves out a source's table.""" + """Each table `entry` loads, `on_rows` hearing the committed total after each commit.""" report: dict[str, Any] = json.loads( run_sqlload_project( project=project.text, @@ -41,11 +40,11 @@ def run_load( base_connection=base_connection, database=database, ), - tables=( + plan=( selected_tables(entry=entry, source_map=source_map), required_tables(entry=entry, source_map=source_map), + entry.is_reload, ), - reload=entry.is_reload, on_rows=on_rows, ) ) diff --git a/src/sqlbuild/executor/loads/main/plan_loads.py b/src/sqlbuild/executor/loads/main/plan_loads.py index 55539732e0..10febe685f 100644 --- a/src/sqlbuild/executor/loads/main/plan_loads.py +++ b/src/sqlbuild/executor/loads/main/plan_loads.py @@ -68,11 +68,11 @@ def _planned_entry( plan_sqlload_project( project=project.text, sessions=sessions, - tables=( + plan=( selected_tables(entry=entry, source_map=plan.source_map), required_tables(entry=entry, source_map=plan.source_map), + entry.is_reload, ), - reload=entry.is_reload, ) ) if planned["missing"]: diff --git a/tests/integration/src/sqlbuild/adapters/postgres/test_load_session.py b/tests/integration/src/sqlbuild/adapters/postgres/test_load_session.py index 13255b1974..967b06a449 100644 --- a/tests/integration/src/sqlbuild/adapters/postgres/test_load_session.py +++ b/tests/integration/src/sqlbuild/adapters/postgres/test_load_session.py @@ -78,7 +78,7 @@ def opener() -> LoadSession: for file_name, text in test_case.files: (landing / file_name).write_text(text) report: dict[str, Any] = json.loads( - run_sqlload_project(project=project, sessions={"warehouse": session}, tables=([], [])) + run_sqlload_project(project=project, sessions={"warehouse": session}, plan=([], [], False)) ) errors.extend(table["error"] for table in report["tables"]) result: QueryResult = adapter.query( diff --git a/tests/unit/src/sqlbuild/executor/load_sessions/main/helpers.py b/tests/unit/src/sqlbuild/executor/load_sessions/main/helpers.py index 4ba73c9e55..d468efe96a 100644 --- a/tests/unit/src/sqlbuild/executor/load_sessions/main/helpers.py +++ b/tests/unit/src/sqlbuild/executor/load_sessions/main/helpers.py @@ -29,7 +29,7 @@ def opener() -> LoadSession: "description": "a DuckDB file", } }, - tables=([], []), + plan=([], [], False), ) ) return [table["error"] for table in report["tables"]] @@ -63,7 +63,7 @@ def opener() -> LoadSession: "description": "a DuckDB file", } }, - tables=([], []), + plan=([], [], False), on_rows=on_rows, ) return totals, threads diff --git a/tests/unit/src/sqlbuild/executor/load_sessions/main/test_open_load_session.py b/tests/unit/src/sqlbuild/executor/load_sessions/main/test_open_load_session.py index b74f0189e1..f5463edb39 100644 --- a/tests/unit/src/sqlbuild/executor/load_sessions/main/test_open_load_session.py +++ b/tests/unit/src/sqlbuild/executor/load_sessions/main/test_open_load_session.py @@ -156,5 +156,5 @@ def test_given_an_adapter_sqlload_cant_load_into_when_running_then_the_error_nam "description": "", } }, - tables=([], []), + plan=([], [], False), ) From a58651654f4c00581aa7dc80d673ba55fd5cdba9 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Sun, 6 Dec 2026 13:01:42 +0000 Subject: [PATCH 4/8] refactor: name the build node result union once --- .../executor/build/_helpers/node_errors.py | 9 +-- .../executor/build/classes/build_scheduler.py | 70 +++---------------- src/sqlbuild/executor/build/types.py | 13 ++++ 3 files changed, 24 insertions(+), 68 deletions(-) diff --git a/src/sqlbuild/executor/build/_helpers/node_errors.py b/src/sqlbuild/executor/build/_helpers/node_errors.py index b9522027a5..e40f5c2895 100644 --- a/src/sqlbuild/executor/build/_helpers/node_errors.py +++ b/src/sqlbuild/executor/build/_helpers/node_errors.py @@ -9,6 +9,7 @@ from sqlbuild._native import CompiledObjectKey, CompiledResourceType, PlanOutput, SourceEntry from sqlbuild.executor.build.constants import BUILD_WORKER_FAILED_CODE from sqlbuild.executor.build.models import FunctionExecutionResult, SeedExecutionResult +from sqlbuild.executor.build.types import BuildNodeResult from sqlbuild.executor.load.main._resource_kind import load_resource_kind from sqlbuild.executor.load.models import LoadExecutionResult from sqlbuild.executor.run.models import ModelExecutionResult @@ -45,13 +46,7 @@ def failed_node_result( error: BaseException | None = None, code: str = BUILD_WORKER_FAILED_CODE, phase: ExecutionPhase | None = None, -) -> ( - ModelExecutionResult - | SeedExecutionResult - | FunctionExecutionResult - | SqlTestExecutionResult - | LoadExecutionResult -): +) -> BuildNodeResult: """The failed result of the node's own kind, so its kind's failure handling applies.""" said: dict[str, Any] = {"reason": reason, "error": error, "code": code, "phase": phase} diff --git a/src/sqlbuild/executor/build/classes/build_scheduler.py b/src/sqlbuild/executor/build/classes/build_scheduler.py index 6108f9c207..9e1b97d5fc 100644 --- a/src/sqlbuild/executor/build/classes/build_scheduler.py +++ b/src/sqlbuild/executor/build/classes/build_scheduler.py @@ -111,7 +111,7 @@ SeedExecutionResult, SourceAuditRunResult, ) -from sqlbuild.executor.build.types import BeforeNodeWriteCallback +from sqlbuild.executor.build.types import BeforeNodeWriteCallback, BuildNodeResult from sqlbuild.executor.custom.models import MaterializationResult from sqlbuild.executor.functions.constants import FUNCTION_ENTRY_MISSING_CODE from sqlbuild.executor.functions.main._execute import execute_function @@ -497,13 +497,7 @@ def _run_serial(self) -> None: self._mark_complete(key) continue with self._scheduler_step(step=f"running {_node_label(key)}", key=key): - result: ( - ModelExecutionResult - | SeedExecutionResult - | FunctionExecutionResult - | SqlTestExecutionResult - | LoadExecutionResult - ) = self._execute_node(key=key, connection=connection) + result: BuildNodeResult = self._execute_node(key=key, connection=connection) connection = self._connection_recovery.usable(connection) with self._scheduler_step(step=f"recording {_node_label(key)}'s result"): self._handle_completion(key=key, result=result) @@ -1201,15 +1195,7 @@ def _run_source_audits(self, *, source_keys: tuple[CompiledObjectKey, ...]) -> b self._source_audit_results.extend(audit_run.audit_results) return audit_run.blocked - def _execute_node( - self, *, key: CompiledObjectKey, connection: Any - ) -> ( - ModelExecutionResult - | SeedExecutionResult - | FunctionExecutionResult - | SqlTestExecutionResult - | LoadExecutionResult - ): + def _execute_node(self, *, key: CompiledObjectKey, connection: Any) -> BuildNodeResult: resource_kind: str = self._canonical_resource_kind(key=key) planned: ModelPlanEntry | None = self._indexes.model_entries_by_key.get(key) with ResourceAttemptLifecycle( @@ -1232,13 +1218,7 @@ def _execute_node( on_statement_complete=self._on_statement_complete, ), ): - result: ( - ModelExecutionResult - | SeedExecutionResult - | FunctionExecutionResult - | SqlTestExecutionResult - | LoadExecutionResult - ) = self._at_node_boundary( + result: BuildNodeResult = self._at_node_boundary( key=key, connection=connection, work=lambda: self._execute_node_with_cost_context( @@ -1298,23 +1278,10 @@ def _canonical_resource_id(self, *, key: CompiledObjectKey) -> str: def _execute_node_with_cost_context( self, *, key: CompiledObjectKey, connection: Any - ) -> ( - ModelExecutionResult - | SeedExecutionResult - | FunctionExecutionResult - | SqlTestExecutionResult - | LoadExecutionResult - ): + ) -> BuildNodeResult: """Execute a single node. Runs in a worker thread (or scheduler thread for serial).""" - failure: ( - ModelExecutionResult - | SeedExecutionResult - | FunctionExecutionResult - | SqlTestExecutionResult - | LoadExecutionResult - | None - ) = self._enter_node_warehouse(key=key, connection=connection) + failure: BuildNodeResult | None = self._enter_node_warehouse(key=key, connection=connection) if failure is not None: return failure if key.resource_type == CompiledResourceType.SEED: @@ -1372,14 +1339,7 @@ def _switch_failure(self, *, key: CompiledObjectKey, connection: Any) -> str | N def _enter_node_warehouse( self, *, key: CompiledObjectKey, connection: Any - ) -> ( - ModelExecutionResult - | SeedExecutionResult - | FunctionExecutionResult - | SqlTestExecutionResult - | LoadExecutionResult - | None - ): + ) -> BuildNodeResult | None: """Put `connection` on the node's warehouse; the node's own kind of failure if not.""" failure: str | None = self._switch_failure(key=key, connection=connection) @@ -1401,13 +1361,7 @@ def _at_node_boundary[ResultT]( def _node_error_result( self, *, key: CompiledObjectKey, connection: Any, error: Exception - ) -> ( - ModelExecutionResult - | SeedExecutionResult - | FunctionExecutionResult - | SqlTestExecutionResult - | LoadExecutionResult - ): + ) -> BuildNodeResult: """Node `key`'s failure for `error`, which escapes instead when it stops the build.""" if stops_build(error): @@ -1831,13 +1785,7 @@ def _handle_completion( self, *, key: CompiledObjectKey, - result: ( - ModelExecutionResult - | SeedExecutionResult - | FunctionExecutionResult - | SqlTestExecutionResult - | LoadExecutionResult - ), + result: BuildNodeResult, ) -> None: """Process a completed node: record its result and outcome, and enqueue what is ready.""" diff --git a/src/sqlbuild/executor/build/types.py b/src/sqlbuild/executor/build/types.py index 109032ccc1..672eb1052d 100644 --- a/src/sqlbuild/executor/build/types.py +++ b/src/sqlbuild/executor/build/types.py @@ -7,10 +7,23 @@ if TYPE_CHECKING: from sqlbuild._native import ModelPlanEntry, SeedPlanEntry + from sqlbuild.executor.build.models import FunctionExecutionResult, SeedExecutionResult + from sqlbuild.executor.load.models import LoadExecutionResult + from sqlbuild.executor.run.models import ModelExecutionResult + from sqlbuild.executor.testing.models import SqlTestExecutionResult from sqlbuild.executor.scheduling.types import ExecutionStatus as ExecutionStatus from sqlbuild.runtime.contracts.types import ExecutionResourceKind as ExecutionResourceKind +type BuildNodeResult = ( + ModelExecutionResult + | SeedExecutionResult + | FunctionExecutionResult + | SqlTestExecutionResult + | LoadExecutionResult +) +"""One build node's result, of the node's own kind.""" + class BeforeNodeWriteCallback(Protocol): """Called before a model or seed changes its relation; raising fails that node.""" From 9a65826965aa0cc282f2ce5550150a2cdd87b338 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Sun, 6 Dec 2026 13:03:32 +0000 Subject: [PATCH 5/8] feat: report the rows a node wrote before it failed --- .../executor/build/_helpers/load_node.py | 4 +++ .../executor/build/_helpers/node_errors.py | 10 ++++--- .../executor/build/classes/build_scheduler.py | 5 +++- .../executor/build/classes/node_progress.py | 28 +++++++++++++++++++ .../executor/load/main/_run_on_engine.py | 18 +++--------- .../scheduling/main/_rows_reporter.py | 15 ++++++++++ .../cli/commands/main/loads/_test_types.py | 5 ++-- .../commands/main/loads/test_load_build.py | 5 ++++ 8 files changed, 69 insertions(+), 21 deletions(-) create mode 100644 src/sqlbuild/executor/build/classes/node_progress.py create mode 100644 src/sqlbuild/executor/scheduling/main/_rows_reporter.py diff --git a/src/sqlbuild/executor/build/_helpers/load_node.py b/src/sqlbuild/executor/build/_helpers/load_node.py index 6a4a88ce5b..32f69fb9e8 100644 --- a/src/sqlbuild/executor/build/_helpers/load_node.py +++ b/src/sqlbuild/executor/build/_helpers/load_node.py @@ -18,6 +18,7 @@ from sqlbuild.executor.node_results.classes.direct_store import DirectNodeResultStore from sqlbuild.executor.node_results.main._direct_store import build_direct_node_result_store from sqlbuild.executor.scheduling.main._failed_result import failed_result +from sqlbuild.executor.scheduling.main._rows_reporter import rows_reporter from sqlbuild.executor.scheduling.types import ExecutionStatus from sqlbuild.runtime.contracts.types import ExecutionResourceKind @@ -47,6 +48,9 @@ def execute_build_load_node( connection_config=connection_config, base_connection=connection, database=runtime.default_database, + on_rows=rows_reporter( + on_rows_written=callbacks.on_rows_written, label=f"load:{entry.name}" + ), ) failures: list[str] = [f"{table.table}: {table.error}" for table in tables if table.error] fields: dict[str, Any] = { diff --git a/src/sqlbuild/executor/build/_helpers/node_errors.py b/src/sqlbuild/executor/build/_helpers/node_errors.py index e40f5c2895..fb600cf8a9 100644 --- a/src/sqlbuild/executor/build/_helpers/node_errors.py +++ b/src/sqlbuild/executor/build/_helpers/node_errors.py @@ -46,8 +46,10 @@ def failed_node_result( error: BaseException | None = None, code: str = BUILD_WORKER_FAILED_CODE, phase: ExecutionPhase | None = None, + rows: int | None = None, ) -> BuildNodeResult: - """The failed result of the node's own kind, so its kind's failure handling applies.""" + """The failed result of the node's own kind, so its kind's failure handling applies; `rows` + is what the node reported writing before it failed, for kinds that count rows.""" said: dict[str, Any] = {"reason": reason, "error": error, "code": code, "phase": phase} if key.resource_type == CompiledResourceType.SEED: @@ -60,7 +62,7 @@ def failed_node_result( loader_name=source.loader or "", target=source.table or source.name, resource_kind=load_resource_kind(source), - rows_affected=None, + rows_affected=rows, **said, ) if key.resource_type == CompiledResourceType.LOAD: @@ -70,7 +72,7 @@ def failed_node_result( loader_name="", target=key.name, resource_kind=ExecutionResourceKind.LOAD, - rows_affected=None, + rows_affected=rows, **said, ) if key.resource_type in {CompiledResourceType.UDF, CompiledResourceType.TABLE_FN}: @@ -82,7 +84,7 @@ def failed_node_result( ) if key.resource_type == CompiledResourceType.SQL_TEST: return failed_result(SqlTestExecutionResult, test_name=key.name, **said) - return failed_result(ModelExecutionResult, model_name=key.name, **said) + return failed_result(ModelExecutionResult, model_name=key.name, rows_affected=rows, **said) def _own_code_place(error: BaseException) -> str | None: diff --git a/src/sqlbuild/executor/build/classes/build_scheduler.py b/src/sqlbuild/executor/build/classes/build_scheduler.py index 9e1b97d5fc..902ee52f24 100644 --- a/src/sqlbuild/executor/build/classes/build_scheduler.py +++ b/src/sqlbuild/executor/build/classes/build_scheduler.py @@ -91,6 +91,7 @@ from sqlbuild.executor.build._helpers.skipped_node import skipped_node_result from sqlbuild.executor.build._helpers.source_audits import run_pending_source_audits from sqlbuild.executor.build._helpers.source_node import execute_build_source_node +from sqlbuild.executor.build.classes.node_progress import NodeProgress from sqlbuild.executor.build.constants import ( BUILD_MODEL_ENTRY_MISSING_CODE, BUILD_UNKNOWN_RESOURCE_FAILED_CODE, @@ -235,7 +236,8 @@ def __init__( if runtime.promotion_mode is None: raise ExecutorInputError("build scheduler requires a resolved promotion mode") self._runtime: BuildRuntimeParams = runtime - self._callbacks: BuildCallbacks = callbacks + self._progress: NodeProgress = NodeProgress(callbacks) + self._callbacks: BuildCallbacks = self._progress.callbacks self._plan: PlanOutput = plan self._indexes: BuildIndexes = build_execution_indexes(plan) self._table_type_entries: dict[str, TableTypePlanEntry] = { @@ -1374,6 +1376,7 @@ def _node_error_result( error=error, code=error_code(error=error, fallback_code=BUILD_WORKER_FAILED_CODE), phase=ExecutionPhase.EXECUTE, + rows=self._progress.rows(key), ) def _scheduler_failure( diff --git a/src/sqlbuild/executor/build/classes/node_progress.py b/src/sqlbuild/executor/build/classes/node_progress.py new file mode 100644 index 0000000000..9e454e23df --- /dev/null +++ b/src/sqlbuild/executor/build/classes/node_progress.py @@ -0,0 +1,28 @@ +"""What each build node has reported doing while it runs.""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import replace + +from sqlbuild._native import CompiledObjectKey +from sqlbuild.executor.build.models import BuildCallbacks + + +class NodeProgress: + """The rows each node last reported writing, so a node that then raises still reports them.""" + + def __init__(self, callbacks: BuildCallbacks) -> None: + self._forward: Callable[[str, int], None] | None = callbacks.on_rows_written + self._rows: dict[str, int] = {} + self.callbacks: BuildCallbacks = replace(callbacks, on_rows_written=self._rows_written) + + def rows(self, key: CompiledObjectKey) -> int | None: + """The total node `key` last reported, or None when it reported none.""" + + return self._rows.get(f"{key.resource_type}:{key.name}") + + def _rows_written(self, label: str, total: int) -> None: + self._rows[label] = total + if self._forward is not None: + self._forward(label, total) diff --git a/src/sqlbuild/executor/load/main/_run_on_engine.py b/src/sqlbuild/executor/load/main/_run_on_engine.py index 95ca5ef00e..51bb3e2a51 100644 --- a/src/sqlbuild/executor/load/main/_run_on_engine.py +++ b/src/sqlbuild/executor/load/main/_run_on_engine.py @@ -4,7 +4,6 @@ import json import time -from collections.abc import Callable from typing import Any from sqlbuild._native import CostContext, DiscoveredLoaderFunction, SourceEntry, run_sqlload_loader @@ -14,6 +13,7 @@ from sqlbuild.executor.load.constants import LOADER_SESSION, NOT_CALLED from sqlbuild.executor.load.models import LoaderRunState, LoadExecutionResult, LoadRuntimeParams from sqlbuild.executor.loads.main._load_sessions import load_sessions +from sqlbuild.executor.scheduling.main._rows_reporter import rows_reporter def run_on_engine( @@ -53,7 +53,9 @@ def run_on_engine( else runtime.default_database ), ), - on_rows=_rows_reporter(source_entry=source_entry, runtime=runtime), + on_rows=rows_reporter( + on_rows_written=runtime.on_rows_written, label=f"source:{source_entry.name}" + ), ) ) result: LoadExecutionResult = engine_result( @@ -62,15 +64,3 @@ def run_on_engine( if runtime.on_rows_written is not None and result.rows_affected: runtime.on_rows_written(f"source:{source_entry.name}", result.rows_affected) return result - - -def _rows_reporter( - *, source_entry: SourceEntry, runtime: LoadRuntimeParams -) -> Callable[[int], None] | None: - """Report the loader's committed rows to the build as each commit lands.""" - - on_rows_written: Callable[[str, int], None] | None = runtime.on_rows_written - if on_rows_written is None: - return None - key: str = f"source:{source_entry.name}" - return lambda total: on_rows_written(key, total) diff --git a/src/sqlbuild/executor/scheduling/main/_rows_reporter.py b/src/sqlbuild/executor/scheduling/main/_rows_reporter.py new file mode 100644 index 0000000000..4317194ce8 --- /dev/null +++ b/src/sqlbuild/executor/scheduling/main/_rows_reporter.py @@ -0,0 +1,15 @@ +"""Report a node's committed rows as each commit lands.""" + +from __future__ import annotations + +from collections.abc import Callable + + +def rows_reporter( + *, on_rows_written: Callable[[str, int], None] | None, label: str +) -> Callable[[int], None] | None: + """`on_rows_written` hearing node `label`'s committed total, or None when nothing listens.""" + + if on_rows_written is None: + return None + return lambda total: on_rows_written(label, total) diff --git a/tests/integration/src/sqlbuild/cli/commands/main/loads/_test_types.py b/tests/integration/src/sqlbuild/cli/commands/main/loads/_test_types.py index 046bcc886e..f1aef27648 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/loads/_test_types.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/loads/_test_types.py @@ -141,8 +141,9 @@ class CaseOnlyColumnTestCase: @dataclass(frozen=True) class RaisedAfterCommitTestCase: - """A load whose run raises after its rows committed, and the rows its failure reports.""" + """A load whose run raises after its rows committed, and the rows its failure reports: None + when nothing committed.""" description: str landed: tuple[tuple[str, str], ...] - expected_rows_loaded: int + expected_rows_loaded: int | None diff --git a/tests/integration/src/sqlbuild/cli/commands/main/loads/test_load_build.py b/tests/integration/src/sqlbuild/cli/commands/main/loads/test_load_build.py index 5f47641ff3..0a814c6192 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/loads/test_load_build.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/loads/test_load_build.py @@ -593,6 +593,11 @@ def test_given_a_load_depends_on_when_an_unrelated_model_changes_then_compiling_ landed=(("a.csv", "id,name\n1,a\n"), ("b.csv", "id,name\n2,b\n")), expected_rows_loaded=2, ), + RaisedAfterCommitTestCase( + description="a load raising with nothing committed reports no row count", + landed=(), + expected_rows_loaded=None, + ), ], ids=lambda case: case.description, ) From 6b134bb778116b622729e2a7a297d0076701df88 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Sun, 6 Dec 2026 13:31:54 +0000 Subject: [PATCH 6/8] fixup! feat: report the rows a node wrote before it failed x --- src/sqlbuild/executor/build/_helpers/node_errors.py | 3 +-- src/sqlbuild/executor/build/classes/node_progress.py | 6 ++++-- src/sqlbuild/executor/build/types.py | 1 - 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/sqlbuild/executor/build/_helpers/node_errors.py b/src/sqlbuild/executor/build/_helpers/node_errors.py index fb600cf8a9..d0817463d6 100644 --- a/src/sqlbuild/executor/build/_helpers/node_errors.py +++ b/src/sqlbuild/executor/build/_helpers/node_errors.py @@ -48,8 +48,7 @@ def failed_node_result( phase: ExecutionPhase | None = None, rows: int | None = None, ) -> BuildNodeResult: - """The failed result of the node's own kind, so its kind's failure handling applies; `rows` - is what the node reported writing before it failed, for kinds that count rows.""" + """The failed result of the node's own kind, with `rows` written when its kind counts them.""" said: dict[str, Any] = {"reason": reason, "error": error, "code": code, "phase": phase} if key.resource_type == CompiledResourceType.SEED: diff --git a/src/sqlbuild/executor/build/classes/node_progress.py b/src/sqlbuild/executor/build/classes/node_progress.py index 9e454e23df..846e25c155 100644 --- a/src/sqlbuild/executor/build/classes/node_progress.py +++ b/src/sqlbuild/executor/build/classes/node_progress.py @@ -15,14 +15,16 @@ class NodeProgress: def __init__(self, callbacks: BuildCallbacks) -> None: self._forward: Callable[[str, int], None] | None = callbacks.on_rows_written self._rows: dict[str, int] = {} - self.callbacks: BuildCallbacks = replace(callbacks, on_rows_written=self._rows_written) + self.callbacks: BuildCallbacks = replace(callbacks, on_rows_written=self) def rows(self, key: CompiledObjectKey) -> int | None: """The total node `key` last reported, or None when it reported none.""" return self._rows.get(f"{key.resource_type}:{key.name}") - def _rows_written(self, label: str, total: int) -> None: + def __call__(self, label: str, total: int) -> None: + """Record node `label`'s committed total and pass it on.""" + self._rows[label] = total if self._forward is not None: self._forward(label, total) diff --git a/src/sqlbuild/executor/build/types.py b/src/sqlbuild/executor/build/types.py index 672eb1052d..805f8924ae 100644 --- a/src/sqlbuild/executor/build/types.py +++ b/src/sqlbuild/executor/build/types.py @@ -22,7 +22,6 @@ | SqlTestExecutionResult | LoadExecutionResult ) -"""One build node's result, of the node's own kind.""" class BeforeNodeWriteCallback(Protocol): From 1064fa245756d463b65d02688204329f741ed4c7 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Sun, 6 Dec 2026 15:23:54 +0000 Subject: [PATCH 7/8] build: give windows-sys 0.59 the same features in the extension and CLI builds SQLLoad 0.92.0 brings in windows-sys 0.59 on Windows, where the extension enables its debug and diagnostics features and the CLI does not. --- Cargo.lock | 1 + Cargo.toml | 1 + crates/sqlbuild-build-features/Cargo.toml | 1 + 3 files changed, 3 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index d89eeff5f5..efcf4166de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6534,6 +6534,7 @@ dependencies = [ "tower-http", "uuid", "windows-sys 0.52.0", + "windows-sys 0.59.0", "windows-sys 0.60.2", "windows-sys 0.61.2", "zerocopy", diff --git a/Cargo.toml b/Cargo.toml index d1bfe24ddc..fbd7b2b3c9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -299,6 +299,7 @@ tokio-stream = { version = "0.1", default-features = false } tokio-util = { version = "0.7", default-features = false } toml_writer = { version = "1.1", default-features = false } windows-sys-v052 = { package = "windows-sys", version = "0.52", default-features = false } +windows-sys-v059 = { package = "windows-sys", version = "0.59", default-features = false } windows-sys-v060 = { package = "windows-sys", version = "0.60", default-features = false } zerocopy = { version = "0.8", default-features = false } zeroize = { version = "1.9", default-features = false } diff --git a/crates/sqlbuild-build-features/Cargo.toml b/crates/sqlbuild-build-features/Cargo.toml index 7311436ece..aefb05af0d 100644 --- a/crates/sqlbuild-build-features/Cargo.toml +++ b/crates/sqlbuild-build-features/Cargo.toml @@ -83,6 +83,7 @@ nix = { workspace = true, features = ["default", "fs", "mman", "resource"] } tokio = { workspace = true, features = ["windows-sys"] } windows-sys = { workspace = true, features = ["Wdk", "Wdk_Foundation", "Wdk_Storage", "Wdk_Storage_FileSystem", "Wdk_System", "Wdk_System_IO", "Win32", "Win32_Foundation", "Win32_Networking", "Win32_Networking_WinSock", "Win32_Security", "Win32_Security_Authentication", "Win32_Security_Authentication_Identity", "Win32_Security_Authorization", "Win32_Security_Credentials", "Win32_Security_Cryptography", "Win32_Storage", "Win32_Storage_FileSystem", "Win32_System", "Win32_System_Com", "Win32_System_Console", "Win32_System_Diagnostics", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_Ioctl", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Pipes", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_SystemServices", "Win32_System_Threading", "Win32_System_WindowsProgramming", "Win32_UI", "Win32_UI_Shell"] } windows-sys-v052 = { workspace = true, features = ["Win32_System", "Win32_System_Diagnostics", "Win32_System_Diagnostics_Debug"] } +windows-sys-v059 = { workspace = true, features = ["Win32_System", "Win32_System_Diagnostics", "Win32_System_Diagnostics_Debug"] } windows-sys-v060 = { workspace = true, features = ["Win32_Security_Authorization", "Win32_Storage", "Win32_Storage_FileSystem"] } [target.'cfg(any(target_os = "macos", windows))'.dependencies] From 85b42d7e8331e6b56b12ec09734b127046290697 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Sun, 6 Dec 2026 15:43:22 +0000 Subject: [PATCH 8/8] style: format the load session test --- .../src/sqlbuild/adapters/postgres/test_load_session.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/integration/src/sqlbuild/adapters/postgres/test_load_session.py b/tests/integration/src/sqlbuild/adapters/postgres/test_load_session.py index 967b06a449..e7cbdf2464 100644 --- a/tests/integration/src/sqlbuild/adapters/postgres/test_load_session.py +++ b/tests/integration/src/sqlbuild/adapters/postgres/test_load_session.py @@ -78,7 +78,9 @@ def opener() -> LoadSession: for file_name, text in test_case.files: (landing / file_name).write_text(text) report: dict[str, Any] = json.loads( - run_sqlload_project(project=project, sessions={"warehouse": session}, plan=([], [], False)) + run_sqlload_project( + project=project, sessions={"warehouse": session}, plan=([], [], False) + ) ) errors.extend(table["error"] for table in report["tables"]) result: QueryResult = adapter.query(