diff --git a/Cargo.lock b/Cargo.lock index 7205ed4d7b..efcf4166de 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]] @@ -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", @@ -7126,9 +7127,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 +7201,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 +7366,7 @@ dependencies = [ "cfg-if", "libc", "psm", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -7493,7 +7494,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -7948,7 +7949,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -8344,7 +8345,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 +8960,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..fbd7b2b3c9 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"] } @@ -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] 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/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 3e4ceca119..41d18ac877 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,23 +15,25 @@ 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 `plan`'s required tables miss. #[pyfunction] -#[pyo3(signature = (*, project, sessions, tables, reload = false))] +#[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), connections, (options, require), + committed, ) }, )?; @@ -56,6 +59,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, @@ -63,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/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 b68efdf00e..bcb50b769f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,7 +20,7 @@ dependencies = [ "PyYAML>=6.0.2", "sqlbuild-cli==0.309.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..7cc06cac7e 100644 --- a/src/sqlbuild/_native.pyi +++ b/src/sqlbuild/_native.pyi @@ -4124,8 +4124,8 @@ 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( *, @@ -4134,13 +4134,17 @@ 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, 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/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 b9522027a5..d0817463d6 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,14 +46,9 @@ def failed_node_result( 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.""" + rows: int | None = None, +) -> BuildNodeResult: + """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: @@ -65,7 +61,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: @@ -75,7 +71,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}: @@ -87,7 +83,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 6108f9c207..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, @@ -111,7 +112,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 @@ -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] = { @@ -497,13 +499,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 +1197,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 +1220,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 +1280,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 +1341,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 +1363,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): @@ -1420,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( @@ -1831,13 +1788,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/classes/node_progress.py b/src/sqlbuild/executor/build/classes/node_progress.py new file mode 100644 index 0000000000..846e25c155 --- /dev/null +++ b/src/sqlbuild/executor/build/classes/node_progress.py @@ -0,0 +1,30 @@ +"""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) + + 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 __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 109032ccc1..805f8924ae 100644 --- a/src/sqlbuild/executor/build/types.py +++ b/src/sqlbuild/executor/build/types.py @@ -7,10 +7,22 @@ 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 +) + class BeforeNodeWriteCallback(Protocol): """Called before a model or seed changes its relation; raising fails that node.""" diff --git a/src/sqlbuild/executor/load/main/_run_on_engine.py b/src/sqlbuild/executor/load/main/_run_on_engine.py index 5ea7b23a23..51bb3e2a51 100644 --- a/src/sqlbuild/executor/load/main/_run_on_engine.py +++ b/src/sqlbuild/executor/load/main/_run_on_engine.py @@ -13,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( @@ -52,6 +53,9 @@ def run_on_engine( else runtime.default_database ), ), + on_rows=rows_reporter( + on_rows_written=runtime.on_rows_written, label=f"source:{source_entry.name}" + ), ) ) result: LoadExecutionResult = engine_result( diff --git a/src/sqlbuild/executor/loads/main/_run_load.py b/src/sqlbuild/executor/loads/main/_run_load.py index 11ce1941db..23847416a5 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,9 @@ 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 committed total after each commit.""" report: dict[str, Any] = json.loads( run_sqlload_project( project=project.text, @@ -39,11 +40,12 @@ 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, ) ) if report["missing"]: 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/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/adapters/postgres/test_load_session.py b/tests/integration/src/sqlbuild/adapters/postgres/test_load_session.py index 13255b1974..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}, 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/integration/src/sqlbuild/cli/commands/main/loads/_test_types.py b/tests/integration/src/sqlbuild/cli/commands/main/loads/_test_types.py index c286dc2571..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 @@ -137,3 +137,13 @@ 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: None + when nothing committed.""" + + description: str + landed: tuple[tuple[str, str], ...] + 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 57486c06f3..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 @@ -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,51 @@ 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, + ), + RaisedAfterCommitTestCase( + description="a load raising with nothing committed reports no row count", + landed=(), + expected_rows_loaded=None, + ), + ], + 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..d468efe96a 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 @@ -28,7 +29,41 @@ def opener() -> LoadSession: "description": "a DuckDB file", } }, - tables=([], []), + plan=([], [], False), ) ) 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", + } + }, + 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 79d9c7b83d..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 @@ -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", [ @@ -98,5 +156,5 @@ def test_given_an_adapter_sqlload_cant_load_into_when_running_then_the_error_nam "description": "", } }, - tables=([], []), + plan=([], [], False), ) diff --git a/uv.lock b/uv.lock index 7388d7bbaa..04e1a5a8fc 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]]