diff --git a/Cargo.lock b/Cargo.lock index 105dd80fdd..8cf080a272 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4333,18 +4333,18 @@ dependencies = [ "sqlbuild-render", "sqlbuild-scopes", "sqlbuild-sqltext", - "sqlquack-fingerprint", - "sqlquack-parse", - "sqlquack-semantics", - "sqlquack-syntax", - "sqlquack-syntax-bigquery", + "sqlquack-fingerprint 0.24.1", + "sqlquack-parse 0.24.1", + "sqlquack-semantics 0.24.1", + "sqlquack-syntax 0.24.1", + "sqlquack-syntax-bigquery 0.24.1", "sqlquack-syntax-clickhouse", - "sqlquack-syntax-databricks", + "sqlquack-syntax-databricks 0.24.1", "sqlquack-syntax-duckdb", - "sqlquack-syntax-postgres", + "sqlquack-syntax-postgres 0.24.1", "sqlquack-syntax-sqlite", - "sqlquack-syntax-sqlserver", - "sqlquack-tokenize", + "sqlquack-syntax-sqlserver 0.24.1", + "sqlquack-tokenize 0.24.1", "stacker", ] @@ -4397,6 +4397,7 @@ dependencies = [ name = "sqlbuild-cli" version = "0.261.0" dependencies = [ + "axum", "blake3", "chrono", "ctrlc", @@ -4517,7 +4518,7 @@ dependencies = [ "sqlbuild-model-config", "sqlbuild-recall", "sqlbuild-state", - "sqlquack-fingerprint", + "sqlquack-fingerprint 0.24.1", "sqlx-core", "sqlx-postgres", "subtle", @@ -4755,6 +4756,7 @@ dependencies = [ "sqlbuild-pysource", "sqlbuild-python-base", "sqlbuild-python-front", + "sqlbuild-recall", "sqlbuild-rules", "sqlbuild-sqltext", "sqlbuild-state", @@ -4830,9 +4832,9 @@ dependencies = [ "sqlbuild-scopes", "sqlbuild-sqltext", "sqlclean", - "sqlquack-parse", - "sqlquack-syntax", - "sqlquack-tokenize", + "sqlquack-parse 0.24.1", + "sqlquack-syntax 0.24.1", + "sqlquack-tokenize 0.24.1", "stacker", "stats_alloc", "tempfile", @@ -4884,12 +4886,12 @@ dependencies = [ "serde_json", "sha2 0.10.9", "sqlclean-lint", - "sqlquack-fingerprint", + "sqlquack-fingerprint 0.23.1", "sqlquack-format", - "sqlquack-parse", - "sqlquack-syntax", - "sqlquack-syntax-sqlserver", - "sqlquack-tokenize", + "sqlquack-parse 0.23.1", + "sqlquack-syntax 0.23.1", + "sqlquack-syntax-sqlserver 0.23.1", + "sqlquack-tokenize 0.23.1", ] [[package]] @@ -4901,10 +4903,10 @@ dependencies = [ "serde", "serde_json", "sqlclean-rules", - "sqlquack-parse", - "sqlquack-semantics", - "sqlquack-syntax", - "sqlquack-tokenize", + "sqlquack-parse 0.23.1", + "sqlquack-semantics 0.23.1", + "sqlquack-syntax 0.23.1", + "sqlquack-tokenize 0.23.1", ] [[package]] @@ -4912,7 +4914,7 @@ name = "sqlclean-rules" version = "0.12.1" source = "git+https://github.com/sqlstack-io/sqlclean.git?rev=462a98779a2a11ff11884ff79feefbfb190ab8d1#462a98779a2a11ff11884ff79feefbfb190ab8d1" dependencies = [ - "sqlquack-syntax", + "sqlquack-syntax 0.23.1", ] [[package]] @@ -4925,6 +4927,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "sqlquack-derive" +version = "0.24.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9#63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "sqlquack-diagnostics" version = "0.23.1" @@ -4932,7 +4944,17 @@ source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c47 dependencies = [ "serde", "serde_json", - "sqlquack-syntax", + "sqlquack-syntax 0.23.1", +] + +[[package]] +name = "sqlquack-diagnostics" +version = "0.24.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9#63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" +dependencies = [ + "serde", + "serde_json", + "sqlquack-syntax 0.24.1", ] [[package]] @@ -4941,9 +4963,20 @@ version = "0.23.1" source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "sha2 0.10.9", - "sqlquack-parse", - "sqlquack-syntax", - "sqlquack-tokenize", + "sqlquack-parse 0.23.1", + "sqlquack-syntax 0.23.1", + "sqlquack-tokenize 0.23.1", +] + +[[package]] +name = "sqlquack-fingerprint" +version = "0.24.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9#63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" +dependencies = [ + "sha2 0.10.9", + "sqlquack-parse 0.24.1", + "sqlquack-syntax 0.24.1", + "sqlquack-tokenize 0.24.1", ] [[package]] @@ -4952,9 +4985,9 @@ version = "0.23.1" source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ "serde_json", - "sqlquack-parse", - "sqlquack-syntax", - "sqlquack-tokenize", + "sqlquack-parse 0.23.1", + "sqlquack-syntax 0.23.1", + "sqlquack-tokenize 0.23.1", ] [[package]] @@ -4962,12 +4995,24 @@ name = "sqlquack-parse" version = "0.23.1" source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ - "sqlquack-syntax", - "sqlquack-syntax-bigquery", - "sqlquack-syntax-databricks", - "sqlquack-syntax-postgres", - "sqlquack-syntax-snowflake", - "sqlquack-syntax-sqlserver", + "sqlquack-syntax 0.23.1", + "sqlquack-syntax-bigquery 0.23.1", + "sqlquack-syntax-databricks 0.23.1", + "sqlquack-syntax-postgres 0.23.1", + "sqlquack-syntax-snowflake 0.23.1", + "sqlquack-syntax-sqlserver 0.23.1", +] + +[[package]] +name = "sqlquack-parse" +version = "0.24.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9#63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" +dependencies = [ + "sqlquack-syntax 0.24.1", + "sqlquack-syntax-bigquery 0.24.1", + "sqlquack-syntax-postgres 0.24.1", + "sqlquack-syntax-snowflake 0.24.1", + "sqlquack-syntax-sqlserver 0.24.1", ] [[package]] @@ -4980,9 +5025,25 @@ dependencies = [ "saphyr-parser", "serde", "serde_json", - "sqlquack-diagnostics", - "sqlquack-parse", - "sqlquack-syntax", + "sqlquack-diagnostics 0.23.1", + "sqlquack-parse 0.23.1", + "sqlquack-syntax 0.23.1", + "stacker", +] + +[[package]] +name = "sqlquack-semantics" +version = "0.24.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9#63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" +dependencies = [ + "regex", + "rustc-hash", + "saphyr-parser", + "serde", + "serde_json", + "sqlquack-diagnostics 0.24.1", + "sqlquack-parse 0.24.1", + "sqlquack-syntax 0.24.1", "stacker", ] @@ -4993,7 +5054,20 @@ source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c47 dependencies = [ "serde", "serde_json", - "sqlquack-derive", + "sqlquack-derive 0.23.1", + "stacker", + "thiserror 1.0.69", + "unicode-segmentation", +] + +[[package]] +name = "sqlquack-syntax" +version = "0.24.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9#63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" +dependencies = [ + "serde", + "serde_json", + "sqlquack-derive 0.24.1", "stacker", "thiserror 1.0.69", "unicode-segmentation", @@ -5004,16 +5078,25 @@ name = "sqlquack-syntax-bigquery" version = "0.23.1" source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ - "sqlquack-syntax", + "sqlquack-syntax 0.23.1", + "stacker", +] + +[[package]] +name = "sqlquack-syntax-bigquery" +version = "0.24.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9#63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" +dependencies = [ + "sqlquack-syntax 0.24.1", "stacker", ] [[package]] name = "sqlquack-syntax-clickhouse" -version = "0.23.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" +version = "0.24.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9#63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" dependencies = [ - "sqlquack-syntax", + "sqlquack-syntax 0.24.1", "stacker", ] @@ -5022,16 +5105,25 @@ name = "sqlquack-syntax-databricks" version = "0.23.1" source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ - "sqlquack-syntax", + "sqlquack-syntax 0.23.1", + "stacker", +] + +[[package]] +name = "sqlquack-syntax-databricks" +version = "0.24.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9#63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" +dependencies = [ + "sqlquack-syntax 0.24.1", "stacker", ] [[package]] name = "sqlquack-syntax-duckdb" -version = "0.23.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" +version = "0.24.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9#63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" dependencies = [ - "sqlquack-syntax", + "sqlquack-syntax 0.24.1", "stacker", ] @@ -5040,7 +5132,16 @@ name = "sqlquack-syntax-postgres" version = "0.23.1" source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ - "sqlquack-syntax", + "sqlquack-syntax 0.23.1", + "stacker", +] + +[[package]] +name = "sqlquack-syntax-postgres" +version = "0.24.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9#63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" +dependencies = [ + "sqlquack-syntax 0.24.1", "stacker", ] @@ -5051,8 +5152,22 @@ source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c47 dependencies = [ "serde", "serde_json", - "sqlquack-syntax", - "sqlquack-tokenize", + "sqlquack-syntax 0.23.1", + "sqlquack-tokenize 0.23.1", + "stacker", + "thiserror 1.0.69", + "unicode-segmentation", +] + +[[package]] +name = "sqlquack-syntax-snowflake" +version = "0.24.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9#63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" +dependencies = [ + "serde", + "serde_json", + "sqlquack-syntax 0.24.1", + "sqlquack-tokenize 0.24.1", "stacker", "thiserror 1.0.69", "unicode-segmentation", @@ -5060,10 +5175,10 @@ dependencies = [ [[package]] name = "sqlquack-syntax-sqlite" -version = "0.23.1" -source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" +version = "0.24.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9#63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" dependencies = [ - "sqlquack-syntax", + "sqlquack-syntax 0.24.1", "stacker", ] @@ -5072,8 +5187,18 @@ name = "sqlquack-syntax-sqlserver" version = "0.23.1" source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ - "sqlquack-syntax", - "sqlquack-tokenize", + "sqlquack-syntax 0.23.1", + "sqlquack-tokenize 0.23.1", + "stacker", +] + +[[package]] +name = "sqlquack-syntax-sqlserver" +version = "0.24.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9#63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" +dependencies = [ + "sqlquack-syntax 0.24.1", + "sqlquack-tokenize 0.24.1", "stacker", ] @@ -5082,7 +5207,16 @@ name = "sqlquack-tokenize" version = "0.23.1" source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=083ccc7121a43a3c471d646ef45845ce3ea69d6d#083ccc7121a43a3c471d646ef45845ce3ea69d6d" dependencies = [ - "sqlquack-syntax", + "sqlquack-syntax 0.23.1", + "thiserror 1.0.69", +] + +[[package]] +name = "sqlquack-tokenize" +version = "0.24.1" +source = "git+https://github.com/sqlstack-io/sqlquack.git?rev=63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9#63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" +dependencies = [ + "sqlquack-syntax 0.24.1", "thiserror 1.0.69", ] diff --git a/Cargo.toml b/Cargo.toml index 88ff8e5e70..090513cb70 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -215,22 +215,22 @@ sqlbuild-state = { path = "crates/sqlbuild-state" } # SQL lint Rules, quality Rules and the formatter. sqlclean = { git = "https://github.com/sqlstack-io/sqlclean.git", rev = "462a98779a2a11ff11884ff79feefbfb190ab8d1" } # SQL change fingerprints over SQLQuack's tokenizers. -sqlquack-fingerprint = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "083ccc7121a43a3c471d646ef45845ce3ea69d6d", features = ["bigquery", "databricks", "duckdb", "postgres", "snowflake", "sqlite", "sqlserver"] } +sqlquack-fingerprint = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9", features = ["bigquery", "databricks", "duckdb", "postgres", "snowflake", "sqlite", "sqlserver"] } # Scopes, name resolution, types and lineage for the native analysis route. -sqlquack-semantics = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "083ccc7121a43a3c471d646ef45845ce3ea69d6d", features = ["bigquery", "clickhouse", "databricks", "duckdb", "postgres", "snowflake", "sqlite", "sqlserver"] } +sqlquack-semantics = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9", features = ["bigquery", "clickhouse", "databricks", "duckdb", "postgres", "snowflake", "sqlite", "sqlserver"] } # SQLQuack's Snowflake-family parser and tokenizer, reached as SQLQuack exposes them. -sqlquack-parse = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "083ccc7121a43a3c471d646ef45845ce3ea69d6d" } +sqlquack-parse = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" } # SQLQuack's syntax tree and lossless tokens. -sqlquack-syntax = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "083ccc7121a43a3c471d646ef45845ce3ea69d6d" } +sqlquack-syntax = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" } # SQLQuack's tokenizer: lossless tokens and tokenize failures. -sqlquack-tokenize = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "083ccc7121a43a3c471d646ef45845ce3ea69d6d" } -sqlquack-syntax-bigquery = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "083ccc7121a43a3c471d646ef45845ce3ea69d6d" } -sqlquack-syntax-clickhouse = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "083ccc7121a43a3c471d646ef45845ce3ea69d6d" } -sqlquack-syntax-databricks = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "083ccc7121a43a3c471d646ef45845ce3ea69d6d" } -sqlquack-syntax-duckdb = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "083ccc7121a43a3c471d646ef45845ce3ea69d6d" } -sqlquack-syntax-postgres = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "083ccc7121a43a3c471d646ef45845ce3ea69d6d" } -sqlquack-syntax-sqlite = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "083ccc7121a43a3c471d646ef45845ce3ea69d6d" } -sqlquack-syntax-sqlserver = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "083ccc7121a43a3c471d646ef45845ce3ea69d6d" } +sqlquack-tokenize = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" } +sqlquack-syntax-bigquery = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" } +sqlquack-syntax-clickhouse = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" } +sqlquack-syntax-databricks = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" } +sqlquack-syntax-duckdb = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" } +sqlquack-syntax-postgres = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" } +sqlquack-syntax-sqlite = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" } +sqlquack-syntax-sqlserver = { git = "https://github.com/sqlstack-io/sqlquack.git", rev = "63d0ce3baf8c981fac3c7164cbeb653f3ddb83a9" } stacker = "0.1" # Counts heap allocations in growth tests, which measure work instead of time. stats_alloc = "0.1" diff --git a/Makefile b/Makefile index df6e08f39f..801c2c0953 100644 --- a/Makefile +++ b/Makefile @@ -58,7 +58,8 @@ rust-check: rust-lint uv run fensu check $(MAKE) test-native -NATIVE_TEST_ARGS ?= --workspace --all-features +# Every test binary runs, so one failing crate never hides another crate's failures. +NATIVE_TEST_ARGS ?= --workspace --all-features --no-fail-fast .PHONY: test-native test-native: @@ -219,6 +220,7 @@ E2E_DUCKDB_CLI_DATA_PATHS := \ tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_fixture_columns.py \ tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_variant.py \ tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_lambda.py \ + tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_guard.py \ tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_escaped_quotes.py \ tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_snapshot_staleness.py \ tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_unmocked_inputs.py diff --git a/benchmarks/duckshop/edge_cases/orchestration/check_transitions.json b/benchmarks/duckshop/edge_cases/orchestration/check_transitions.json index 98838e4419..e4c8ac0134 100644 --- a/benchmarks/duckshop/edge_cases/orchestration/check_transitions.json +++ b/benchmarks/duckshop/edge_cases/orchestration/check_transitions.json @@ -1,13 +1,13 @@ [ - {"nodes": ["success", "failed"], "started": [true, true], "outcome": "partial"}, + {"nodes": ["success", "failed"], "started": [true, true], "outcome": "failed"}, {"nodes": ["failed", "failed"], "started": [true, true], "outcome": "failed"}, - {"nodes": ["success", "cancelled"], "started": [true, true], "outcome": "partial"}, - {"nodes": ["success", "skipped"], "started": [true, false], "outcome": "partial"}, + {"nodes": ["success", "cancelled"], "started": [true, true], "outcome": "failed"}, + {"nodes": ["success", "skipped"], "started": [true, false], "outcome": "failed"}, {"nodes": ["success", "warn"], "started": [true, true], "outcome": "warn"}, - {"nodes": ["success", "failed"], "started": [true, true], "outcome": "partial"}, + {"nodes": ["success", "failed"], "started": [true, true], "outcome": "failed"}, {"nodes": ["success", "success"], "started": [true, false], "outcome": "success"}, - {"nodes": ["success", "failed"], "started": [true, true], "outcome": "partial"}, + {"nodes": ["success", "failed"], "started": [true, true], "outcome": "failed"}, {"nodes": ["success", "success"], "started": [true, true], "outcome": "success"}, {"nodes": ["success", "success"], "started": [true, true], "outcome": "success"}, - {"nodes": ["success", "failed"], "started": [true, true], "outcome": "partial"} + {"nodes": ["success", "failed"], "started": [true, true], "outcome": "failed"} ] diff --git a/benchmarks/duckshop/project/orchestration/sensors/edge_cases/edge_job_outcomes_sensor.py b/benchmarks/duckshop/project/orchestration/sensors/edge_cases/edge_job_outcomes_sensor.py index bd601e2aac..b93609e9d7 100644 --- a/benchmarks/duckshop/project/orchestration/sensors/edge_cases/edge_job_outcomes_sensor.py +++ b/benchmarks/duckshop/project/orchestration/sensors/edge_cases/edge_job_outcomes_sensor.py @@ -1,11 +1,11 @@ -"""Keep warning and partial job outcomes distinct from success.""" +"""Keep warning and failed job outcomes distinct from success.""" from sqlbuild.orchestration import RunEventKind, RunRequest, run_event, sensor @sensor( - description="Keep warning and partial outcomes distinct from success.", - when=run_event(job="edge_snapshot_orders_job", kinds=[RunEventKind.WARN, RunEventKind.PARTIAL]), + description="Keep warning and failed outcomes distinct from success.", + when=run_event(job="edge_snapshot_orders_job", kinds=[RunEventKind.WARN, RunEventKind.FAILED]), default_status="paused", ) def edge_job_outcomes_sensor(ctx): diff --git a/clients/typescript/src/schema.d.ts b/clients/typescript/src/schema.d.ts index 9ddea767e3..424117f2f5 100644 --- a/clients/typescript/src/schema.d.ts +++ b/clients/typescript/src/schema.d.ts @@ -1161,6 +1161,22 @@ export interface paths { patch?: never; trace?: never; }; + "/api/control/locations/{location_id}/targets/{target}/selection/runs": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: operations["readPastRuns"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/control/locations/{location_id}/targets/{target}/selection/vocabulary": { parameters: { query?: never; @@ -1433,6 +1449,38 @@ export interface paths { patch?: never; trace?: never; }; + "/api/health": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: operations["readHealth"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/health/details": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get: operations["readHealthDetails"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/locations/{location_id}/health": { parameters: { query?: never; @@ -1833,6 +1881,23 @@ export interface paths { patch?: never; trace?: never; }; + "/livez": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The process answers; nothing else is checked. */ + get: operations["livez"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; } export type webhooks = Record; export interface components { @@ -1907,12 +1972,18 @@ export interface components { */ AdministratorChange: "grant" | "revoke" | "disable" | "enable"; ApiErrorBody: { + cause?: null | components["schemas"]["ErrorCause"]; /** * Format: uuid * @description Existing durable denial audit ID; absent when no decision was recorded. */ decision_id?: string | null; error: string; + /** + * Format: uuid + * @description This request's ID, as the server log and the `x-request-id` header name it. + */ + request_id?: string | null; }; /** @description A condition whose latest acknowledgement event marks it handled. */ AttentionAcknowledgement: { @@ -1964,6 +2035,21 @@ export interface components { /** Format: uuid */ request_id: string; }; + BTreeMap: { + [key: string]: { + /** @description Its failed, cancelled and never-reached nodes, and its failed audits. */ + failed: string[]; + /** + * Format: uuid + * @description The run the typed ID names. + */ + run_id: string; + /** @description Every node the run selected. */ + selected: string[]; + /** @description The nodes it skipped because something they depend on failed. */ + skipped: string[]; + }; + }; /** * @description How one recorded stretch of a microbatch model's cursor stands. * @enum {string} @@ -2112,6 +2198,8 @@ export interface components { columns: string[]; /** Format: uuid */ event_id: string; + /** @description The warehouse's error, SQLSTATE included, when the audit's query could not run; redacted like a node's. */ + execution_error?: string | null; /** @description Scalar cells aligned to `columns`; a row without a key holds null there. */ rows: Record[][]; truncated?: string | null; @@ -2195,6 +2283,42 @@ export interface components { /** Format: uuid */ snapshot_id?: string | null; }; + /** @description One component's details for administrators: where it is, each cause's message, and the failed requests. */ + ComponentDetails: { + component: components["schemas"]["HealthComponent"]; + error_chain: string[]; + /** @description The control database's host and port. */ + host?: string | null; + /** Format: uuid */ + location_id?: string | null; + request_ids: string[]; + }; + /** @description One component as anyone may see it: its state, since when, and a short reason. */ + ComponentHealth: { + case?: null | components["schemas"]["ControlCauseCase"]; + component: components["schemas"]["HealthComponent"]; + /** Format: date-time */ + last_failure?: string | null; + /** + * Format: date-time + * @description When it last worked; for a location, its last report. + */ + last_success?: string | null; + /** + * Format: uuid + * @description The location this row is about. + */ + location_id?: string | null; + /** @description What people call it: "Control database", "Scheduler", or a location's name. */ + name: string; + reason?: string | null; + /** + * Format: date-time + * @description When it stopped being healthy. + */ + since?: string | null; + status: components["schemas"]["HealthStatus"]; + }; /** @description A row whose key was already stored with different content; the first row is kept. */ ConflictEvidence: { existing_sha256: string; @@ -2233,6 +2357,11 @@ export interface components { /** @description Where signing out goes when a trusted proxy owns the sign-in; absent means no sign-out link. */ logout_url?: string | null; }; + /** + * @description Which kind of control database failure an error is; the sentence people read follows from it. + * @enum {string} + */ + ControlCauseCase: "name_lookup" | "unreachable" | "login_rejected" | "no_free_connections" | "restarting" | "pool_exhausted" | "locked" | "other"; /** @description One job's estimated query cost on one node: in the period, and in the period before it. */ CostFactRecord: { /** Format: int64 */ @@ -2482,6 +2611,12 @@ export interface components { /** Format: uuid */ trigger_id: string; }; + /** @description A control database failure as an error response names it: its case and since when it has been failing. */ + ErrorCause: { + case: components["schemas"]["ControlCauseCase"]; + /** Format: date-time */ + since: string; + }; ExternalIdentityResponse: { csrf_token: string; /** Format: date-time */ @@ -2491,6 +2626,16 @@ export interface components { /** Format: uuid */ session_id: string; }; + /** @description An event webhook this server can't deliver to: since when, and why; its events stay queued. */ + FailingForwarding: { + /** Format: date-time */ + last_success_at?: string | null; + /** @description Such as `Platform event forwarding`. */ + name: string; + reason: string; + /** Format: date-time */ + since: string; + }; /** @description A checking-in location whose latest load, plan of what changed, discovery or connection check failed, and what it serves instead. */ FailingLocation: { /** @description What failed, redacted; absent when an older location reported no text. */ @@ -2508,6 +2653,62 @@ export interface components { state: components["schemas"]["LocationState"]; target: string; }; + /** @description A lifecycle event sink whose runs lose events: since its first lossy run in a row, and why. */ + FailingSink: { + /** + * Format: date-time + * @description The newest run before that whose events it all delivered. + */ + last_success_at?: string | null; + /** Format: uuid */ + location_id: string; + location_name: string; + /** @description What it lost, such as `8 of 8 events not delivered (8 failed)`. */ + reason: string; + /** + * Format: uuid + * @description The newest run whose events it lost; `None` when the location's own interpreter lost them. + */ + run_id?: string | null; + /** + * Format: date-time + * @description The first run in a row whose events it lost. + */ + since: string; + /** @description The sink's name in the project. */ + sink: string; + target: string; + }; + /** @description A checking-in location whose run-history sync is failing: since when, why, and when it tries again. */ + FailingSync: { + /** @description Failed reads stopped the sync; it resumes on request, after the next run or a publish. */ + halted: boolean; + /** + * Format: date-time + * @description The newest report of a sync that worked. + */ + last_success_at?: string | null; + /** Format: uuid */ + location_id: string; + location_name: string; + /** @description What failed, redacted. */ + reason: string; + /** + * Format: date-time + * @description When the location tries again, and how many seconds it waits between tries. + */ + retry_at?: string | null; + /** Format: int64 */ + retry_seconds?: number | null; + /** + * Format: date-time + * @description The first failure in a row. + */ + since: string; + target: string; + /** @description The location couldn't reach the warehouse, so no compute ran. */ + unreachable: boolean; + }; /** @description Build evidence only: no SQL, arbitrary metadata, or inference about live relation existence. */ FingerprintObservation: { definition_hash: string; @@ -2528,6 +2729,34 @@ export interface components { role_key: string; target?: string | null; }; + /** + * @description A part of the server whose health is reported. + * @enum {string} + */ + HealthComponent: "server" | "control_database" | "scheduler" | "location" | "event_forwarding"; + /** @description `GET /api/health/details`: what administrators see beside the public report. */ + HealthDetails: { + components: components["schemas"]["ComponentDetails"][]; + }; + /** @description `GET /api/health`: every component's state, readable without signing in and without the control database. */ + HealthReport: { + /** Format: date-time */ + checked_at: string; + components: components["schemas"]["ComponentHealth"][]; + /** + * Format: int64 + * @description How often a client should ask again while the server isn't healthy, in seconds. + */ + retry_seconds: number; + server: components["schemas"]["ServerSummary"]; + /** @description The worst component's: unavailable when the control database is, degraded when anything else isn't healthy. */ + status: components["schemas"]["HealthStatus"]; + }; + /** + * @description How a component, or the server as a whole, stands. + * @enum {string} + */ + HealthStatus: "healthy" | "degraded" | "unavailable"; HeartbeatResponse: { cancel_requested: boolean; }; @@ -2723,6 +2952,10 @@ export interface components { /** @enum {string} */ kind: "change_plan_failed"; reason: string; + } | { + /** @enum {string} */ + kind: "sink_deliveries"; + sinks: components["schemas"]["SinkDelivery"][]; } | { /** Format: int64 */ generation: number; @@ -2734,6 +2967,11 @@ export interface components { elapsed_millis: number; /** @description A failed read's warehouse error, redacted and bounded; absent otherwise. */ error?: string | null; + /** + * Format: date-time + * @description While the sync fails, when its first failure in a row was; absent once it works and from older locations. + */ + failing_since?: string | null; failure?: null | components["schemas"]["WarehouseSyncFailure"]; /** Format: int64 */ generation: number; @@ -2759,6 +2997,13 @@ export interface components { read_failure?: null | components["schemas"]["WarehouseReadFailure"]; /** Format: int64 */ records_sent: number; + /** + * Format: date-time + * @description On a failure the sync retries, when it tries again and how many seconds it waits. + */ + retry_at?: string | null; + /** Format: int64 */ + retry_seconds?: number | null; table: components["schemas"]["WarehouseHistoryKind"]; }; /** @description Receipt time belongs to the server; consumers derive freshness rather than storing availability. */ @@ -3175,7 +3420,7 @@ export interface components { */ sequences: number; }; - /** @description A failed or partial run reruns from failure up to `retries` times, each `retry_delay_seconds` after the last ended. */ + /** @description A failed run reruns from failure up to `retries` times, each `retry_delay_seconds` after the last ended. */ OnFailure: { /** Format: int32 */ retries: number; @@ -3374,6 +3619,12 @@ export interface components { csrf_token: string; identity: components["schemas"]["SessionIdentity"]; }; + /** @description The past runs read, or why one can't be: too short, unknown or ambiguous. */ + PastRunsRead: { + error?: string | null; + /** @description Each run by the ID as given; empty when `error` is set. */ + runs: components["schemas"]["BTreeMap"]; + }; /** @description The person's name, the actions allowed server-wide, and the location targets they can view. */ PersonAccess: { actions: components["schemas"]["Action"][]; @@ -3674,22 +3925,10 @@ export interface components { kind: "launch_failed"; /** Format: uuid */ run_id: string; - } | { - /** Format: int64 */ - failed_node_count: number; - /** @description The first failed nodes by key, with redacted and bounded error text. */ - failed_nodes: components["schemas"]["RunNodeFailure"][]; - job_key?: string | null; + } | (components["schemas"]["RunFailureEvent"] & { /** @enum {string} */ kind: "run_failed"; - /** Format: uuid */ - location_id: string; - outcome: components["schemas"]["RunOutcome"]; - /** Format: uuid */ - run_id: string; - run_kind: components["schemas"]["RunKind"]; - target: string; - } | { + }) | { /** @enum {string} */ kind: "trigger_skipped"; reason: string; @@ -3722,8 +3961,14 @@ export interface components { broken_locations: components["schemas"]["BrokenLocation"][]; /** @description Calendars whose pending times a republish dropped, until their next successful tick. */ dropped_calendar_times?: components["schemas"]["DroppedCalendarTimes"][]; + /** @description This server's event webhooks that can't deliver, until one delivers again. */ + failing_forwarding?: components["schemas"]["FailingForwarding"][]; /** @description Checking-in locations whose latest load, plan of what changed, discovery or connection check failed. */ failing_locations?: components["schemas"]["FailingLocation"][]; + /** @description Lifecycle event sinks whose newest run lost events, until a run delivers all of its events. */ + failing_sinks?: components["schemas"]["FailingSink"][]; + /** @description Checking-in locations whose run-history sync is failing, until a sync report succeeds. */ + failing_syncs?: components["schemas"]["FailingSync"][]; /** @description Running calendar schedules whose dates run out within a day. */ low_calendars?: components["schemas"]["LowCalendar"][]; overdue_ticks: components["schemas"]["OverdueTick"][]; @@ -4087,6 +4332,21 @@ export interface components { /** Format: uuid */ run_id: string; }; + /** @description An error-severity audit failure in one run: its name, the warehouse's SQLSTATE and redacted error text, or its failing rows. */ + RunAuditFailure: { + /** + * Format: int64 + * @description The rows that failed it, when its query ran. + */ + failing_rows?: number | null; + /** @description The warehouse's error when the query could not run, redacted and bounded like a node's. */ + message?: string | null; + name: string; + /** @description The node it checks; null for an end-of-build singular audit. */ + node_key?: string | null; + /** @description The warehouse's SQLSTATE when the audit's query could not run, such as `42S02`. */ + sqlstate?: string | null; + }; /** @description This is a server-owned instruction, not an arbitrary status supplied by a worker. */ RunChange: { container_id?: string | null; @@ -4125,6 +4385,8 @@ export interface components { no_change_reason?: string | null; node_key: string; outcome: components["schemas"]["NodeOutcome"]; + /** @description Where a failed model failed, such as `staging` or `post_hook`; a short lowercase token or absent. */ + phase?: string | null; /** Format: int64 */ rows_affected?: number | null; skipped_because_of?: string | null; @@ -4171,6 +4433,12 @@ export interface components { count: number; /** @enum {string} */ kind: "audit_failures_ignored"; + } | { + /** @enum {string} */ + kind: "sink_deliveries"; + sinks: components["schemas"]["SinkDelivery"][]; + /** @description Each sink provider whose teardown raised, such as `'kafka' (KafkaProducer) raised KafkaException`. */ + teardown_failures?: string[]; }; RunChangeRequest: { change: components["schemas"]["RunChange"]; @@ -4199,7 +4467,7 @@ export interface components { occurred_at?: string | null; }; /** @enum {string} */ - RunEventKind: "completed" | "success" | "warn" | "partial" | "failed" | "cancelled" | "skipped"; + RunEventKind: "completed" | "success" | "warn" | "failed" | "cancelled" | "skipped"; /** @description Recall event metadata of a run. Payloads are left out: they can carry SQL, request settings and error text. */ RunEventRecord: { /** Format: int64 */ @@ -4217,7 +4485,7 @@ export interface components { event_id: string; event_type: string; invocation_id: string; - /** @description A summary of what an event names, such as a member retry or the command a worker started; never error or SQL text. */ + /** @description A summary of what an event names, such as a member retry, the command a worker started or why an audit was not run; never error or SQL text. */ message?: string | null; occurred_at: string; outcome?: string | null; @@ -4254,6 +4522,52 @@ export interface components { }; sqb_version: string; }; + /** @description Why a run failed outside any node: where, the error's type or code, and its redacted, bounded text. */ + RunFailureCause: { + code?: string | null; + message?: string | null; + phase: components["schemas"]["RunFailurePhase"]; + }; + /** @description What a `run_failed` event says: the run, what started it, when, what failed and why, with UI links. */ + RunFailureEvent: { + /** Format: int64 */ + duration_ms?: number | null; + /** Format: date-time */ + ended_at?: string | null; + error?: null | components["schemas"]["RunFailureCause"]; + /** Format: int64 */ + failed_audit_count: number; + /** @description The first error-severity audit failures by name. */ + failed_audits: components["schemas"]["RunAuditFailure"][]; + /** Format: int64 */ + failed_node_count: number; + /** @description The first failed nodes by key, with redacted and bounded error text. */ + failed_nodes: components["schemas"]["RunNodeFailure"][]; + job_key?: string | null; + /** Format: uuid */ + location_id: string; + outcome: components["schemas"]["RunOutcome"]; + /** Format: uuid */ + run_id: string; + run_kind: components["schemas"]["RunKind"]; + /** Format: int64 */ + skipped_node_count: number; + /** @description The first skipped nodes by key. */ + skipped_nodes: string[]; + /** Format: date-time */ + started_at?: string | null; + /** Format: int64 */ + succeeded_node_count: number; + target: string; + trigger: components["schemas"]["RunTrigger"]; + /** @description The run's UI page; null when the server has no origin. */ + url?: string | null; + }; + /** + * @description Where a run failed outside any node. + * @enum {string} + */ + RunFailurePhase: "launch" | "worker_start" | "load" | "planning" | "build"; /** @description One error-severity audit failure a run or one of its current members let through; never its SQL or evidence. */ RunIgnoredAuditFailure: { attached_column_name?: string | null; @@ -4283,11 +4597,17 @@ export interface components { /** @description A node's outcome error in one run: redacted, bounded text and the project file of the node, never its SQL. */ RunNodeFailure: { error_code?: string | null; + /** @description The node's output in the UI; null when the server has no origin. */ + logs_url?: string | null; /** @description Null when the worker reported none or the run's history has been pruned. */ message?: string | null; node_key: string; /** @description Relative to the project root, with `/` separators; null when the run's snapshot is gone. */ path?: string | null; + /** @description Where a model failed, such as `staging`, `audit` or `post_hook`; null for other nodes or when not reported. */ + phase?: string | null; + /** @description The node in the run's UI page; null when the server has no origin. */ + url?: string | null; }; RunNodeRecord: { /** Format: date-time */ @@ -4326,7 +4646,7 @@ export interface components { * @description Terminal outcomes cannot be confused with a request to change an active status. * @enum {string} */ - RunOutcome: "success" | "warn" | "partial" | "failed" | "cancelled" | "skipped"; + RunOutcome: "success" | "warn" | "failed" | "cancelled" | "skipped"; /** @description Captured output and error text of a run's invocations; both can quote warehouse data. */ RunOutput: { /** @description Invocation failures and error diagnostics, oldest first. */ @@ -4380,6 +4700,8 @@ export interface components { RunRecord: { /** Format: date-time */ cancel_requested_at?: string | null; + /** @description An ad-hoc run's command as the person typed it, as argument tokens after `sqb`; absent for every other run. */ + command?: string[] | null; /** Format: date-time */ ended_at?: string | null; git_dirty?: boolean | null; @@ -4545,7 +4867,17 @@ export interface components { statement_id: string; }; /** @enum {string} */ - RunStatus: "queued" | "launched" | "running" | "unresponsive" | "success" | "warn" | "partial" | "failed" | "cancelled" | "skipped"; + RunStatus: "queued" | "launched" | "running" | "unresponsive" | "success" | "warn" | "failed" | "cancelled" | "skipped"; + /** @description What started a run: a schedule or sensor by name, or a person or service account (`api`). */ + RunTrigger: { + kind: components["schemas"]["RunTriggerKind"]; + /** @description The schedule's or sensor's name; null for manual and API runs. */ + name?: string | null; + /** @description Who asked for a manual or API run, by display name. */ + person?: string | null; + }; + /** @enum {string} */ + RunTriggerKind: "schedule" | "sensor" | "manual" | "api"; /** @description Inclusive typed CLI cursor bounds; the native planner derives exclusive execution ends. */ RunWindow: { /** Format: date-time */ @@ -4599,7 +4931,12 @@ export interface components { SelectionEvaluation: { /** * Format: int64 - * @description Every selected node, across all pages. + * @description How many of them are audits, keyed `audit:[:…]`. + */ + audits?: number; + /** + * Format: int64 + * @description Every selected node and audit, across all pages. */ count: number; error?: null | components["schemas"]["SelectionProblem"]; @@ -4658,6 +4995,8 @@ export interface components { }; /** @description The values each selector type takes in the current publication, with how many nodes each one selects. */ SelectionVocabulary: { + /** @description `audit:` names: the audits each name selects, one per target it is attached to. */ + audits?: components["schemas"]["VocabularyEntry"][]; /** @description `job:` names: the nodes each job or job group selects. */ jobs: components["schemas"]["VocabularyEntry"][]; /** @description `kind:` values: the nodes of each kind. */ @@ -4888,6 +5227,14 @@ export interface components { scheduler: boolean; version: string; }; + /** @description The server row of the health report. */ + ServerSummary: { + /** Format: date-time */ + started_at: string; + /** Format: int64 */ + uptime_seconds: number; + version: string; + }; ServiceAccountRole: { role: components["schemas"]["BuiltinRole"]; }; @@ -4957,6 +5304,24 @@ export interface components { /** Format: uuid */ session_id: string; }; + /** @description One lifecycle event sink's deliveries in a run. */ + SinkDelivery: { + /** Format: int64 */ + accepted: number; + /** Format: int64 */ + delivered: number; + /** + * Format: int64 + * @description Events the sink never got: its queue was full or it was too slow. + */ + dropped: number; + /** + * Format: int64 + * @description Events the sink raised on. + */ + failed: number; + name: string; + }; /** @description A trigger the scheduler skips because its stored job or pinned snapshot can't be read, or a sensor whose check failed; it clears once its location publishes again or, for a sensor, a later check completes. */ SkippedTrigger: { /** Format: uuid */ @@ -5290,6 +5655,9 @@ export interface components { WarehouseReadFailure: { /** @enum {string} */ kind: "read_error"; + } | { + /** @enum {string} */ + kind: "unreachable"; } | { /** @enum {string} */ kind: "timed_out"; @@ -8729,6 +9097,47 @@ export interface operations { }; }; }; + readPastRuns: { + parameters: { + query?: { + /** @description Comma-separated run IDs, each full or a unique prefix of at least 8 characters */ + ids?: string; + }; + header?: never; + path: { + location_id: string; + target: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description What each run selected, didn't finish and skipped, or why one can't be read */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PastRunsRead"]; + }; + }; + /** @description Session rejected */ + 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + }; + }; readSelectionVocabulary: { parameters: { query?: never; @@ -9470,6 +9879,69 @@ export interface operations { }; }; }; + readHealth: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Every component is healthy */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HealthReport"]; + }; + }; + /** @description A component is degraded or the control database is unavailable */ + 503: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HealthReport"]; + }; + }; + }; + }; + readHealthDetails: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HealthDetails"]; + }; + }; + /** @description Session rejected */ + 401: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ApiErrorBody"]; + }; + }; + }; + }; read_location_health: { parameters: { query?: { @@ -10800,4 +11272,24 @@ export interface operations { }; }; }; + livez: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The server process is running */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "text/plain": string; + }; + }; + }; + }; } diff --git a/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/rendering.rs b/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/rendering.rs index eff8501aea..b8d1ed7ec8 100644 --- a/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/rendering.rs +++ b/crates/sqlbuild-analysis/src/compiler/_helpers/sql_tests/rendering.rs @@ -15,6 +15,7 @@ use crate::compiler::_helpers::sql_tests::cte_sql::{cte_definition_sql, leading_ use crate::compiler::_helpers::sql_tests::helper_names::HELPER_PREFIX; use crate::compiler::_helpers::sql_tests::planning::REF_PREFIX; use crate::compiler::models::{SqlTestAssertionStep, SqlTestChainStep}; +use crate::compiler::types::PlacedComparisonSql; use rayon::iter::{IntoParallelIterator, ParallelIterator}; use serde::{Deserialize, Serialize}; @@ -477,13 +478,87 @@ impl RenderCteState { } fn definitions(&mut self) -> Vec { + self.placed_definitions() + .into_iter() + .map(|(definition, _, _)| definition) + .collect() + } + + /// Each lifted CTE's definition, with its body text and what it stands for. + fn placed_definitions(&mut self) -> Vec<(String, String, String)> { std::mem::take(&mut self.lifted) - .iter() - .map(|cte| cte_definition_sql(&cte.header, &cte.body)) + .into_iter() + .map(|cte| { + ( + cte_definition_sql(&cte.header, &cte.body), + cte.body, + cte.origin, + ) + }) .collect() } } +/// One CTE body's character range in a rendered comparison, and what it stands for. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ComparisonSegment { + pub(crate) start: usize, + pub(crate) end: usize, + pub(crate) origin: String, +} + +/// The comparison SQL of one planned test and where each CTE body sits in it. +#[derive(Debug)] +pub(crate) struct PlacedComparison { + pub(crate) sql: String, + pub(crate) segments: Vec, +} + +/// `WITH` and the definitions joined, then `rest`, with each body's character range. +fn placed_statement(definitions: &[(String, String, String)], rest: &str) -> PlacedComparison { + let mut sql: String = "WITH ".to_owned(); + let mut segments: Vec = Vec::new(); + for (index, (definition, body, origin)) in definitions.iter().enumerate() { + if index > 0 { + sql.push_str(",\n"); + } + let body: &str = body.trim_end(); + if let Some(at) = definition.find(body).filter(|_| !body.is_empty()) { + let start: usize = sql[..].chars().count() + definition[..at].chars().count(); + segments.push(ComparisonSegment { + start, + end: start + body.chars().count(), + origin: origin.clone(), + }); + } + sql.push_str(definition); + } + sql.push('\n'); + sql.push_str(rest); + PlacedComparison { sql, segments } +} + +/// Render one planned test's comparison query with the place of each CTE body in it. +pub(crate) fn render_placed_comparison( + request: &RenderRequest, +) -> Result { + let plain: RenderRequest = RenderRequest { + chain: request.chain.clone(), + assertions: request.assertions.clone(), + sql_analysis_enabled: request.sql_analysis_enabled, + set_difference_operator: request.set_difference_operator.clone(), + sql_analysis_dialect: request.sql_analysis_dialect.clone(), + probe_step_index: None, + actual_relations: HashMap::new(), + output_step_index: None, + }; + let (sql, placed): (String, Option) = render_comparison(&plain)?; + Ok(placed.unwrap_or(PlacedComparison { + sql, + segments: Vec::new(), + })) +} + fn collision_message(origin: &str, collisions: &[(&str, &LiftedCte)]) -> String { collisions .iter() @@ -578,6 +653,19 @@ pub(crate) fn rendered_chain_steps( .collect() } +/// One planned test's comparison SQL and each CTE body's start, end and origin in it. +pub(crate) fn render_placed_request(request_json: &str) -> Result { + let request: RenderRequest = + serde_json::from_str(request_json).map_err(|error| error.to_string())?; + let placed: PlacedComparison = render_placed_comparison(&request)?; + let segments: Vec<(usize, usize, String)> = placed + .segments + .into_iter() + .map(|segment| (segment.start, segment.end, segment.origin)) + .collect(); + Ok((placed.sql, segments)) +} + pub(crate) fn render_json(request_json: &str) -> Result { let request: RenderBatchRequest = serde_json::from_str(request_json).map_err(|error| error.to_string())?; @@ -723,8 +811,15 @@ pub(crate) fn comparison_counts_sql( /// Render one planned test's comparison query, lifting authored CTE text verbatim. pub(crate) fn render_comparison_sql(request: &RenderRequest) -> Result { + render_comparison(request).map(|(sql, _placed)| sql) +} + +/// The comparison SQL, and the placed comparison with each CTE body's range when it has one. +fn render_comparison( + request: &RenderRequest, +) -> Result<(String, Option), String> { if request.chain.is_empty() && request.assertions.is_empty() { - return Ok(String::new()); + return Ok((String::new(), None)); } let enabled = request.sql_analysis_enabled; let model_test = !request.assertions.is_empty() @@ -737,6 +832,7 @@ pub(crate) fn render_comparison_sql(request: &RenderRequest) -> Result = Vec::new(); + let mut comparison_origins: Vec = Vec::new(); let mut select_parts: Vec = Vec::new(); let rendered_steps = rendered_chain_steps(&request.chain, &request.assertions); let mut probe_actual_cte: Option = None; @@ -761,6 +857,7 @@ pub(crate) fn render_comparison_sql(request: &RenderRequest) -> Result cte_state.actual_step_sql(step, &suffix, enabled)?, }; comparison_ctes.push((actual_cte.clone(), actual_sql)); + comparison_origins.push(format!("model '{}'", step.model_name)); if request.probe_step_index == Some(step_index) { probe_actual_cte = Some(actual_cte.clone()); } @@ -773,6 +870,7 @@ pub(crate) fn render_comparison_sql(request: &RenderRequest) -> Result Result Result Result Result = cte_state.placed_definitions(); + placed_parts.extend( comparison_ctes .iter() - .map(|(name, sql)| cte_definition_sql(name, sql)), + .zip(&comparison_origins) + .map(|((name, sql), origin)| { + (cte_definition_sql(name, sql), sql.clone(), origin.clone()) + }), ); + let cte_parts: Vec = placed_parts + .iter() + .map(|(definition, _, _)| definition.clone()) + .collect(); let single_read = !request.actual_relations.is_empty(); if request.probe_step_index.is_some() { - return Ok(probe_actual_cte.map_or_else(String::new, |actual_cte| { - let statement = format!( - "WITH {}\nSELECT * FROM {actual_cte} WHERE 1 = 0", - cte_parts.join(",\n") - ); - if single_read { - pruned_statement(&statement, dialect) - } else { - statement - } - })); + return Ok(( + probe_actual_cte.map_or_else(String::new, |actual_cte| { + let statement = format!( + "WITH {}\nSELECT * FROM {actual_cte} WHERE 1 = 0", + cte_parts.join(",\n") + ); + if single_read { + pruned_statement(&statement, dialect) + } else { + statement + } + }), + None, + )); } let statement = format!( "WITH {}\n{}", @@ -852,9 +961,11 @@ pub(crate) fn render_comparison_sql(request: &RenderRequest) -> Result String { diff --git a/crates/sqlbuild-analysis/src/compiler/main/mod.rs b/crates/sqlbuild-analysis/src/compiler/main/mod.rs index fc2ae2ccfb..b75668bfb7 100644 --- a/crates/sqlbuild-analysis/src/compiler/main/mod.rs +++ b/crates/sqlbuild-analysis/src/compiler/main/mod.rs @@ -14,5 +14,6 @@ pub mod sql_test_difference_sampling; pub mod sql_test_extraction; pub mod sql_test_fixture_facts; pub mod sql_test_glue; +pub mod sql_test_placed_rendering; pub mod sql_test_plan_errors; pub mod sql_test_rendering; diff --git a/crates/sqlbuild-analysis/src/compiler/main/sql_test_placed_rendering.rs b/crates/sqlbuild-analysis/src/compiler/main/sql_test_placed_rendering.rs new file mode 100644 index 0000000000..6835fe15f8 --- /dev/null +++ b/crates/sqlbuild-analysis/src/compiler/main/sql_test_placed_rendering.rs @@ -0,0 +1,7 @@ +use crate::compiler::_helpers; +use crate::compiler::types::PlacedComparisonSql; + +/// One planned test's comparison SQL and each CTE body's start, end and origin in it. +pub fn render_placed_comparison(request_json: &str) -> Result { + _helpers::sql_tests::rendering::render_placed_request(request_json) +} diff --git a/crates/sqlbuild-analysis/src/compiler/mod.rs b/crates/sqlbuild-analysis/src/compiler/mod.rs index b9965bee44..ed528337ce 100644 --- a/crates/sqlbuild-analysis/src/compiler/mod.rs +++ b/crates/sqlbuild-analysis/src/compiler/mod.rs @@ -2,6 +2,7 @@ pub mod _helpers; pub(crate) mod constants; pub mod main; pub mod models; +pub mod types; #[cfg(test)] mod tests; diff --git a/crates/sqlbuild-analysis/src/compiler/types.rs b/crates/sqlbuild-analysis/src/compiler/types.rs new file mode 100644 index 0000000000..b01c3978ff --- /dev/null +++ b/crates/sqlbuild-analysis/src/compiler/types.rs @@ -0,0 +1,4 @@ +//! Type aliases of the compiler's public results. + +/// A rendered comparison's SQL and each CTE body's start, end and origin in it. +pub type PlacedComparisonSql = (String, Vec<(usize, usize, String)>); diff --git a/crates/sqlbuild-analysis/src/graph/_helpers/mod.rs b/crates/sqlbuild-analysis/src/graph/_helpers/mod.rs index 32fb6b3e21..bd76fc0bbc 100644 --- a/crates/sqlbuild-analysis/src/graph/_helpers/mod.rs +++ b/crates/sqlbuild-analysis/src/graph/_helpers/mod.rs @@ -2,5 +2,6 @@ pub(crate) mod closure; pub(crate) mod indexes; pub(crate) mod jobs; pub(crate) mod layers; +pub(crate) mod run_selectors; pub(crate) mod selectors; pub(crate) mod unique_ids; diff --git a/crates/sqlbuild-analysis/src/graph/_helpers/run_selectors.rs b/crates/sqlbuild-analysis/src/graph/_helpers/run_selectors.rs new file mode 100644 index 0000000000..1581682cf3 --- /dev/null +++ b/crates/sqlbuild-analysis/src/graph/_helpers/run_selectors.rs @@ -0,0 +1,98 @@ +//! `audit:` and the past-run selectors `run:`, `failed:` and `skipped:` over what a command attached to the graph. + +use std::collections::{BTreeMap, BTreeSet}; + +use crate::assembly::project::types::ObjectKey; +use crate::graph::_helpers::selectors::{Keys, error, matching_names, parse}; +use crate::graph::constants::{ + AUDIT_KIND, FAILED_KIND, INTERSECTION_SEPARATOR, KIND_SEPARATOR, RUN_SELECTOR_KINDS, + SKIPPED_KIND, UNMAPPED_KIND_CODE, UNMAPPED_KINDS, +}; +use crate::graph::errors::SelectorError; +use crate::graph::models::{ParsedSelector, ProjectGraph, RunResults}; + +type Resolved = Result; + +/// The audits `value` names or matches, as `("audit", name)` keys. +pub(crate) fn audit(graph: &ProjectGraph, value: &str) -> Resolved { + let Some(audits) = &graph.audits else { + return Err(error( + UNMAPPED_KIND_CODE, + format!( + "selector '{AUDIT_KIND}{KIND_SEPARATOR}{value}' selects an audit; \ + only plan, build, test, audit and check select audits" + ), + )); + }; + Ok(matching_names(value, audits.iter(), "audit")? + .into_iter() + .map(|name| (AUDIT_KIND.to_owned(), name.clone())) + .collect()) +} + +/// What the run `value` names selected, didn't finish or skipped, by `kind`. +pub(crate) fn run_results(graph: &ProjectGraph, (kind, value): (&str, &str)) -> Resolved { + let Some(results) = graph.runs.as_ref().and_then(|runs| runs.get(value)) else { + return Err(error( + UNMAPPED_KIND_CODE, + format!( + "selector '{kind}{KIND_SEPARATOR}{value}' selects from a past run; \ + only plan, build, test, audit and check read past runs" + ), + )); + }; + Ok(match kind { + FAILED_KIND => results.failed.clone(), + SKIPPED_KIND => results.skipped.clone(), + _ => results.selected.clone(), + }) +} + +/// The run IDs, as typed, that `run:`, `failed:` and `skipped:` parts of `selectors` name. +pub(crate) fn run_ids(selectors: &[String]) -> BTreeSet { + selectors + .iter() + .flat_map(|selector| selector.split(char::is_whitespace)) + .flat_map(|token| token.split(INTERSECTION_SEPARATOR)) + .filter(|part| !part.is_empty()) + .filter_map(|part| match parse(part) { + Ok(ParsedSelector::Kind { kind, value, .. }) + if RUN_SELECTOR_KINDS.contains(&kind.as_str()) => + { + Some(value) + } + _ => None, + }) + .collect() +} + +/// `graph` with each run's results kept to the SQL keys and audits it still has; Python nodes pass, as a job's do, for the caller to keep or leave out. +pub(crate) fn attach(graph: ProjectGraph, runs: BTreeMap) -> ProjectGraph { + let known = |key: &ObjectKey| { + if key.0 == AUDIT_KIND { + return graph + .audits + .as_ref() + .is_some_and(|audits| audits.contains(&key.1)); + } + UNMAPPED_KINDS.contains(&key.0.as_str()) || graph.key_named(&key.1) == Some(key) + }; + let kept = |keys: &BTreeSet| keys.iter().filter(|key| known(key)).cloned().collect(); + let runs: BTreeMap = runs + .iter() + .map(|(id, results)| { + ( + id.clone(), + RunResults { + selected: kept(&results.selected), + failed: kept(&results.failed), + skipped: kept(&results.skipped), + }, + ) + }) + .collect(); + ProjectGraph { + runs: Some(runs), + ..graph + } +} diff --git a/crates/sqlbuild-analysis/src/graph/_helpers/selectors.rs b/crates/sqlbuild-analysis/src/graph/_helpers/selectors.rs index 15580b2211..35da14bf94 100644 --- a/crates/sqlbuild-analysis/src/graph/_helpers/selectors.rs +++ b/crates/sqlbuild-analysis/src/graph/_helpers/selectors.rs @@ -4,15 +4,17 @@ use std::collections::{BTreeSet, HashSet}; use std::convert::Infallible; use crate::assembly::project::types::ObjectKey; +use crate::graph::_helpers::run_selectors::{audit, run_results}; use crate::graph::constants::{ - EMPTY_SELECTOR_CODE, EMPTY_VALUE_CODE, EXPANSION_MARKER, FOLDER_SEPARATOR, FUNCTION_KIND_ALIAS, - INTERSECTION_SEPARATOR, JOB_KIND, KIND_SEPARATOR, MISPLACED_MARKER_CODE, MISSING_NAME_CODE, - MODEL_RESOURCE, MODEL_ROOT, MODEL_ROOT_PREFIX, NAME_KIND, NODE_KIND_KIND, PATH_KIND, - PATH_ROOT_CODE, PATH_ROOT_ERROR, PATH_SELECTOR_CODE, PATH_SEPARATOR, PATTERN_CHARACTERS, - PLANNER_DEFAULT_CODE, SEED_RESOURCE, SELECTABLE_NODE_KINDS, SOURCE_RESOURCE, SQL_FILE_SUFFIX, - SUGGESTION_CUTOFF, SUGGESTION_LIMIT, TABLE_FUNCTION_RESOURCE, TAG_KIND, TEST_KIND, - UDF_RESOURCE, UNIT_TEST_CODE, UNIT_TEST_ONLY_TEST_AND_BUILD, UNKNOWN_KIND_CODE, - UNKNOWN_NAME_CODE, UNKNOWN_PATH_CODE, UNKNOWN_TAG_CODE, UNMAPPED_KIND_CODE, UNMAPPED_KINDS, + AUDIT_KIND, EMPTY_SELECTOR_CODE, EMPTY_VALUE_CODE, EXPANSION_MARKER, FOLDER_SEPARATOR, + FUNCTION_KIND_ALIAS, INTERSECTION_SEPARATOR, JOB_KIND, KIND_SEPARATOR, MISPLACED_MARKER_CODE, + MISSING_NAME_CODE, MODEL_RESOURCE, MODEL_ROOT, MODEL_ROOT_PREFIX, NAME_KIND, NODE_KIND_KIND, + PATH_KIND, PATH_ROOT_CODE, PATH_ROOT_ERROR, PATH_SELECTOR_CODE, PATH_SEPARATOR, + PATTERN_CHARACTERS, PLANNER_DEFAULT_CODE, RUN_SELECTOR_KINDS, SEED_RESOURCE, + SELECTABLE_NODE_KINDS, SOURCE_RESOURCE, SQL_FILE_SUFFIX, SUGGESTION_CUTOFF, SUGGESTION_LIMIT, + TABLE_FUNCTION_RESOURCE, TAG_KIND, TEST_KIND, UDF_RESOURCE, UNIT_TEST_CODE, + UNIT_TEST_ONLY_TEST_AND_BUILD, UNKNOWN_KIND_CODE, UNKNOWN_NAME_CODE, UNKNOWN_PATH_CODE, + UNKNOWN_TAG_CODE, UNMAPPED_KIND_CODE, UNMAPPED_KINDS, }; use crate::graph::errors::SelectorError; use crate::graph::models::{ @@ -25,7 +27,7 @@ use sqlbuild_core::text::main::glob_match::glob_match; pub(crate) type Keys = BTreeSet; type Resolved = Result; -fn error(code: &'static str, message: String) -> SelectorError { +pub(crate) fn error(code: &'static str, message: String) -> SelectorError { SelectorError { code, message, @@ -282,8 +284,10 @@ fn is_selector_kind(prefix: &str) -> bool { TEST_KIND, JOB_KIND, NODE_KIND_KIND, + AUDIT_KIND, ] .contains(&prefix) + || RUN_SELECTOR_KINDS.contains(&prefix) || UNMAPPED_KINDS.contains(&prefix) } @@ -302,6 +306,8 @@ pub(crate) fn matched(graph: &ProjectGraph, kind: &str, value: &str) -> Resolved } PATH_KIND => folder(graph, value), JOB_KIND => job(graph, value), + AUDIT_KIND => audit(graph, value), + kind if RUN_SELECTOR_KINDS.contains(&kind) => run_results(graph, (kind, value)), NODE_KIND_KIND => of_kind(graph, value), TEST_KIND => Err(error( UNIT_TEST_CODE, @@ -436,26 +442,35 @@ fn job(graph: &ProjectGraph, value: &str) -> Resolved { ), )); }; - let pattern: bool = is_pattern(value); let mut keys: Keys = Keys::new(); - let mut found: bool = false; - for (name, selected) in jobs { - if name == value || (pattern && glob_matches(value, name)) { - found = true; - keys.extend(selected.clone()?); - } + for name in matching_names(value, jobs.keys(), "job")? { + keys.extend(jobs[name].clone()?); } - if found { - return Ok(keys); + Ok(keys) +} + +/// The `names` that `value` names or, as a glob, matches; none is an unknown-`noun` error suggesting the closest name. +pub(crate) fn matching_names<'n>( + value: &str, + names: impl Iterator + Clone, + noun: &str, +) -> Result, SelectorError> { + let pattern: bool = is_pattern(value); + let matched: Vec<&String> = names + .clone() + .filter(|name| *name == value || (pattern && glob_matches(value, name))) + .collect(); + if !matched.is_empty() { + return Ok(matched); } Err(SelectorError { code: UNKNOWN_NAME_CODE, message: format!( - "unknown job {} '{value}'", + "unknown {noun} {} '{value}'", if pattern { "pattern" } else { "name" } ), help: (!pattern) - .then(|| suggestion(value, jobs.keys().map(String::as_str).collect())) + .then(|| suggestion(value, names.map(String::as_str).collect())) .flatten(), }) } @@ -514,6 +529,6 @@ impl ProjectGraph { } /// Python's `fnmatch.fnmatchcase`: `*`, `?`, `[seq]` and `[!seq]` over characters. -fn glob_matches(pattern: &str, name: &str) -> bool { +pub(crate) fn glob_matches(pattern: &str, name: &str) -> bool { glob_match(name, pattern) } diff --git a/crates/sqlbuild-analysis/src/graph/constants.rs b/crates/sqlbuild-analysis/src/graph/constants.rs index 9bfdc3311b..fda2bb5002 100644 --- a/crates/sqlbuild-analysis/src/graph/constants.rs +++ b/crates/sqlbuild-analysis/src/graph/constants.rs @@ -19,6 +19,16 @@ pub(crate) const TAG_KIND: &str = "tag"; pub(crate) const PATH_KIND: &str = "path"; pub(crate) const TEST_KIND: &str = "test"; pub(crate) const JOB_KIND: &str = "job"; +/// `audit:` selects an audit by name, as its key `("audit", name)`. +pub const AUDIT_KIND: &str = "audit"; +/// `run:` selects what a past run selected. +pub const RUN_KIND: &str = "run"; +/// `failed:` selects what didn't succeed in a past run: nodes and audits. +pub const FAILED_KIND: &str = "failed"; +/// `skipped:` selects what a past run skipped. +pub const SKIPPED_KIND: &str = "skipped"; +/// The selector kinds that name a past run. +pub const RUN_SELECTOR_KINDS: [&str; 3] = [RUN_KIND, FAILED_KIND, SKIPPED_KIND]; pub(crate) const NODE_KIND_KIND: &str = "kind"; /// The node kinds `kind:` selects, as the catalog names them: SQL resources, then Python nodes. pub(crate) const SELECTABLE_NODE_KINDS: [&str; 9] = [ diff --git a/crates/sqlbuild-analysis/src/graph/main/attach_audits_and_runs.rs b/crates/sqlbuild-analysis/src/graph/main/attach_audits_and_runs.rs new file mode 100644 index 0000000000..8beb453a37 --- /dev/null +++ b/crates/sqlbuild-analysis/src/graph/main/attach_audits_and_runs.rs @@ -0,0 +1,19 @@ +//! Let `audit:` select these audit names, and `run:`, `failed:` and `skipped:` each past run's results, keeping keys the project still has. + +use std::collections::{BTreeMap, BTreeSet}; + +use crate::graph::models::{ProjectGraph, RunResults}; + +/// Let `audit:` select `audits`, and run selectors the `runs` they name by ID as typed. +pub fn attach_audits_and_runs( + graph: ProjectGraph, + (audits, runs): (BTreeSet, BTreeMap), +) -> ProjectGraph { + crate::graph::_helpers::run_selectors::attach( + ProjectGraph { + audits: Some(audits), + ..graph + }, + runs, + ) +} diff --git a/crates/sqlbuild-analysis/src/graph/main/mod.rs b/crates/sqlbuild-analysis/src/graph/main/mod.rs index c772010b62..531c81543a 100644 --- a/crates/sqlbuild-analysis/src/graph/main/mod.rs +++ b/crates/sqlbuild-analysis/src/graph/main/mod.rs @@ -1,3 +1,4 @@ +pub mod attach_audits_and_runs; pub mod attach_jobs; pub mod attach_jobs_with; pub mod build_project_graph; @@ -13,6 +14,7 @@ pub mod reachable_graph_keys; pub mod reachable_keys; pub mod resolve_selector_tokens; pub mod resolve_selectors; +pub mod run_selector_ids; pub mod selector_name_help; pub mod selectors_need_jobs; pub mod unique_id_edges; diff --git a/crates/sqlbuild-analysis/src/graph/main/run_selector_ids.rs b/crates/sqlbuild-analysis/src/graph/main/run_selector_ids.rs new file mode 100644 index 0000000000..5d6a1b951a --- /dev/null +++ b/crates/sqlbuild-analysis/src/graph/main/run_selector_ids.rs @@ -0,0 +1,9 @@ +//! The run IDs, as typed, that the `run:`, `failed:` and `skipped:` selectors name. + +use std::collections::BTreeSet; + +/// The run IDs, as typed, that the `run:`, `failed:` and `skipped:` selectors name. +#[must_use] +pub fn run_selector_ids(selectors: &[String]) -> BTreeSet { + crate::graph::_helpers::run_selectors::run_ids(selectors) +} diff --git a/crates/sqlbuild-analysis/src/graph/models.rs b/crates/sqlbuild-analysis/src/graph/models.rs index a4247f5b7c..8f5096bf27 100644 --- a/crates/sqlbuild-analysis/src/graph/models.rs +++ b/crates/sqlbuild-analysis/src/graph/models.rs @@ -40,6 +40,21 @@ pub struct ProjectGraph { pub(crate) name_index: HashMap, /// Each job and job group's resolved selection, or why it fails; `None` until a command attaches jobs. pub jobs: Option, SelectorError>>>, + /// The audit names `audit:` selects; `None` where a command cannot select audits. + pub audits: Option>, + /// What each run named by `run:`, `failed:` or `skipped:` selected, by the ID as typed; `None` until a command attaches them. + pub runs: Option>, +} + +/// A past run's results as selector keys; audits are `("audit", name)` keys. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RunResults { + /// Everything the run selected. + pub selected: BTreeSet, + /// What didn't succeed: failed, cancelled and never-reached nodes, and failed audits. + pub failed: BTreeSet, + /// What the run skipped because something it depends on failed. + pub skipped: BTreeSet, } /// What one job or job group selects: its own selector tokens, its member jobs, or resolved keys. diff --git a/crates/sqlbuild-analysis/src/graph/tests.rs b/crates/sqlbuild-analysis/src/graph/tests.rs index 27c0469a1c..1cf620da67 100644 --- a/crates/sqlbuild-analysis/src/graph/tests.rs +++ b/crates/sqlbuild-analysis/src/graph/tests.rs @@ -6,6 +6,8 @@ mod helpers; mod job_selectors; #[path = "tests/test_named_selector_atoms.rs"] mod named_selector_atoms; +#[path = "tests/test_run_selectors.rs"] +mod run_selectors; #[path = "tests/test_selector_scenarios.rs"] mod selector_scenarios; #[path = "tests/test_types.rs"] diff --git a/crates/sqlbuild-analysis/src/graph/tests/helpers.rs b/crates/sqlbuild-analysis/src/graph/tests/helpers.rs index e38a899592..8a3d9b245c 100644 --- a/crates/sqlbuild-analysis/src/graph/tests/helpers.rs +++ b/crates/sqlbuild-analysis/src/graph/tests/helpers.rs @@ -2,11 +2,12 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::assembly::project::types::ObjectKey; use crate::graph::errors::SelectorError; +use crate::graph::main::attach_audits_and_runs::attach_audits_and_runs; use crate::graph::main::attach_jobs::attach_jobs; use crate::graph::main::build_project_graph::build_project_graph; use crate::graph::main::resolve_selectors::resolve_selectors; use crate::graph::main::selectors_need_jobs::selectors_need_jobs; -use crate::graph::models::{GraphResource, JobSelection, ParsedSelector, ProjectGraph}; +use crate::graph::models::{GraphResource, JobSelection, ParsedSelector, ProjectGraph, RunResults}; use crate::graph::tests::test_types::SelectorFailure; type OwnedFailure = (String, String, Option); @@ -285,3 +286,48 @@ pub(super) fn needs_jobs(selectors: &[&str], also_known: &[&str]) -> bool { let selectors: Vec = selectors.iter().map(|value| (*value).to_owned()).collect(); selectors_need_jobs(&orders_graph(), &selectors, also_known) } + +/// The audits the run-selector tests may select. +const ORDERS_AUDITS: [&str; 2] = ["not_null_orders_id", "orders_match_payments"]; + +/// The orders project with its audits and one past run attached: `orders` and an end-of-build audit failed, `order_items` was skipped. +pub(super) fn run_selection( + attached: bool, + select: &[&str], + exclude: &[&str], +) -> Result, OwnedFailure> { + let keys = |pairs: &[(&str, &str)]| pairs.iter().map(key).collect::>(); + let mut graph: ProjectGraph = attach_audits_and_runs( + orders_graph(), + ( + ORDERS_AUDITS + .iter() + .map(|name| (*name).to_owned()) + .collect(), + BTreeMap::from([( + "01a1d3b9".to_owned(), + RunResults { + selected: keys(&[ + ("model", "orders"), + ("model", "order_items"), + ("model", "customers"), + ("model", "retired"), + ]), + failed: keys(&[ + ("model", "orders"), + ("audit", "orders_match_payments"), + ("audit", "retired_audit"), + ]), + skipped: keys(&[("model", "order_items")]), + }, + )]), + ), + ); + graph.audits = graph.audits.filter(|_| attached); + graph.runs = graph.runs.filter(|_| attached); + resolved_in(&graph, select, exclude).map(|keys| { + keys.into_iter() + .map(|(kind, name)| format!("{kind}:{name}")) + .collect() + }) +} diff --git a/crates/sqlbuild-analysis/src/graph/tests/test_run_selectors.rs b/crates/sqlbuild-analysis/src/graph/tests/test_run_selectors.rs new file mode 100644 index 0000000000..b500f56c71 --- /dev/null +++ b/crates/sqlbuild-analysis/src/graph/tests/test_run_selectors.rs @@ -0,0 +1,159 @@ +use crate::graph::main::run_selector_ids::run_selector_ids; +use crate::graph::tests::helpers::{failure, names, run_selection}; +use crate::graph::tests::test_types::{ + RunSelectorErrorTestCase, RunSelectorIdsTestCase, RunSelectorTestCase, +}; + +#[test] +fn given_a_past_run_and_audits_when_resolving_then_run_and_audit_selectors_compose() { + let test_cases = [ + RunSelectorTestCase { + description: "failed: selects the run's failed nodes and failed audits, and the functions they need", + select: &["failed:01a1d3b9"], + exclude: &[], + expected_keys: &["audit:orders_match_payments", "model:orders", "udf:tax"], + }, + RunSelectorTestCase { + description: "failed:+ adds what reads the failed nodes; an audit has nothing downstream", + select: &["failed:01a1d3b9+"], + exclude: &[], + expected_keys: &[ + "audit:orders_match_payments", + "model:customer_orders", + "model:order_items", + "model:orders", + "udf:tax", + ], + }, + RunSelectorTestCase { + description: "run: selects what the run selected that the project still has", + select: &["run:01a1d3b9"], + exclude: &[], + expected_keys: &[ + "model:customers", + "model:order_items", + "model:orders", + "udf:tax", + ], + }, + RunSelectorTestCase { + description: "skipped: selects what the run skipped, and the functions it needs", + select: &["skipped:01a1d3b9"], + exclude: &[], + expected_keys: &["model:order_items", "udf:tax"], + }, + RunSelectorTestCase { + description: "an intersection keeps the failed nodes with the tag; audits have no tags", + select: &["failed:01a1d3b9+,tag:finance"], + exclude: &[], + expected_keys: &["model:order_items", "udf:tax"], + }, + RunSelectorTestCase { + description: "an exclusion drops the run's audits", + select: &["failed:01a1d3b9"], + exclude: &["audit:*"], + expected_keys: &["model:orders", "udf:tax"], + }, + RunSelectorTestCase { + description: "a run selector joins other selectors", + select: &["customers failed:01a1d3b9"], + exclude: &[], + expected_keys: &[ + "audit:orders_match_payments", + "model:customers", + "model:orders", + "udf:tax", + ], + }, + RunSelectorTestCase { + description: "audit: selects an audit by name or pattern", + select: &["audit:not_null_*"], + exclude: &[], + expected_keys: &["audit:not_null_orders_id"], + }, + ]; + for test_case in test_cases { + assert_eq!( + run_selection(true, test_case.select, test_case.exclude), + Ok(names(test_case.expected_keys)), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_run_and_audit_selectors_when_unresolvable_then_fails_with_message() { + let test_cases = [ + RunSelectorErrorTestCase { + description: "an unknown audit suggests the closest", + attached: true, + select: &["audit:orders_match_payment"], + expected_error: ( + "S007", + "unknown audit name 'orders_match_payment'", + Some("did you mean 'orders_match_payments'?"), + ), + }, + RunSelectorErrorTestCase { + description: "a command that selects no audits refuses audit:", + attached: false, + select: &["audit:orders_match_payments"], + expected_error: ( + "S010", + "selector 'audit:orders_match_payments' selects an audit; only plan, build, test, audit and check select audits", + None, + ), + }, + RunSelectorErrorTestCase { + description: "a command that reads no past runs refuses failed:", + attached: false, + select: &["failed:01a1d3b9+"], + expected_error: ( + "S010", + "selector 'failed:01a1d3b9' selects from a past run; only plan, build, test, audit and check read past runs", + None, + ), + }, + ]; + for test_case in test_cases { + assert_eq!( + run_selection(test_case.attached, test_case.select, &[]), + Err(failure(test_case.expected_error)), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_selectors_when_scanning_then_run_ids_are_listed_as_typed() { + let test_cases = [ + RunSelectorIdsTestCase { + description: "each run kind names its run, inside intersections and with expansion", + selectors: &[ + "failed:01a1d3b9+ customers,run:01a1d3c0", + "skipped:01a1d3b9", + ], + expected_ids: &["01a1d3b9", "01a1d3c0"], + }, + RunSelectorIdsTestCase { + description: "other selectors name no run", + selectors: &["job:nightly audit:not_null_orders_id tag:daily"], + expected_ids: &[], + }, + ]; + for test_case in test_cases { + let selectors: Vec = test_case + .selectors + .iter() + .map(|selector| (*selector).to_owned()) + .collect(); + assert_eq!( + run_selector_ids(&selectors), + names(test_case.expected_ids), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-analysis/src/graph/tests/test_types.rs b/crates/sqlbuild-analysis/src/graph/tests/test_types.rs index 096f86e041..029aa587b9 100644 --- a/crates/sqlbuild-analysis/src/graph/tests/test_types.rs +++ b/crates/sqlbuild-analysis/src/graph/tests/test_types.rs @@ -79,3 +79,24 @@ pub(super) struct NamedAtomsTestCase { pub(super) selection: &'static str, pub(super) expected_atoms: &'static [&'static str], } + +pub(super) struct RunSelectorTestCase { + pub(super) description: &'static str, + pub(super) select: &'static [&'static str], + pub(super) exclude: &'static [&'static str], + pub(super) expected_keys: &'static [&'static str], +} + +pub(super) struct RunSelectorErrorTestCase { + pub(super) description: &'static str, + /// Whether the command attached audits and past runs. + pub(super) attached: bool, + pub(super) select: &'static [&'static str], + pub(super) expected_error: SelectorFailure, +} + +pub(super) struct RunSelectorIdsTestCase { + pub(super) description: &'static str, + pub(super) selectors: &'static [&'static str], + pub(super) expected_ids: &'static [&'static str], +} diff --git a/crates/sqlbuild-analysis/src/job_settings/constants.rs b/crates/sqlbuild-analysis/src/job_settings/constants.rs index b2e5852418..8acbc362f9 100644 --- a/crates/sqlbuild-analysis/src/job_settings/constants.rs +++ b/crates/sqlbuild-analysis/src/job_settings/constants.rs @@ -14,7 +14,7 @@ pub const JOB_SETTING_CONFLICT_CODE: &str = "S027"; /// How a conflict names a job's `[retry]` table. pub const RETRY_SETTING: &str = "[retry]"; /// Every option of `sqb build`, in the parser's order, as a job setting. -pub const JOB_SETTINGS: [JobSettingSpec; 54] = [ +pub const JOB_SETTINGS: [JobSettingSpec; 57] = [ JobSettingSpec { name: "help", options: &["-h", "--help"], @@ -455,6 +455,36 @@ pub const JOB_SETTINGS: [JobSettingSpec; 54] = [ consumer: None, group: OneBuild, }, + JobSettingSpec { + name: "login_server", + options: &["--server"], + scope: RunRequest, + python_nodes: false, + whole_run: false, + command_line: CommandLineValues::Any, + consumer: None, + group: OneBuild, + }, + JobSettingSpec { + name: "login_ca", + options: &["--ca-cert"], + scope: RunRequest, + python_nodes: false, + whole_run: false, + command_line: CommandLineValues::Any, + consumer: None, + group: OneBuild, + }, + JobSettingSpec { + name: "person_location", + options: &["--location-id"], + scope: RunRequest, + python_nodes: false, + whole_run: false, + command_line: CommandLineValues::Any, + consumer: None, + group: OneBuild, + }, JobSettingSpec { name: "positional_select", options: &[], diff --git a/crates/sqlbuild-analysis/src/planner_fixtures/_helpers/resolved_reads.rs b/crates/sqlbuild-analysis/src/planner_fixtures/_helpers/resolved_reads.rs index 8ab1fbca56..d4570bc6c0 100644 --- a/crates/sqlbuild-analysis/src/planner_fixtures/_helpers/resolved_reads.rs +++ b/crates/sqlbuild-analysis/src/planner_fixtures/_helpers/resolved_reads.rs @@ -22,6 +22,18 @@ pub(crate) fn resolved_reads( let reads = reads.clone(); return (cache, Ok(reads)); } + cache.misses += 1; + let reads = match uncached_reads(key) { + Ok(reads) => reads, + Err(error) => return (cache, Err(error)), + }; + (stored(cache, key, reads.clone()), Ok(reads)) +} + +/// Resolve one key's reads without the cache. +pub(crate) fn uncached_reads( + key: &FixtureReadKey, +) -> Result, RequiredColumnsError> { let references: Vec = key .references .iter() @@ -30,11 +42,15 @@ pub(crate) fn resolved_reads( name: reference.name.clone(), }) .collect(); - cache.misses += 1; - let reads = match resolve_required_columns(&key.sql, &references, key.dialect.as_deref()) { - Ok(reads) => reads, - Err(error) => return (cache, Err(error)), - }; + resolve_required_columns(&key.sql, &references, key.dialect.as_deref()) +} + +/// Keep one key's successful reads, evicting the least recently used entry at capacity. +pub(crate) fn stored( + mut cache: FixtureReadCache, + key: &FixtureReadKey, + reads: Vec, +) -> FixtureReadCache { if cache.entries.len() >= crate::planner_fixtures::constants::READ_CACHE_CAPACITY && let Some((_, oldest)) = cache.recency.pop_first() { @@ -43,6 +59,6 @@ pub(crate) fn resolved_reads( cache.clock += 1; let clock = cache.clock; cache.recency.insert(clock, key.clone()); - cache.entries.insert(key.clone(), (clock, reads.clone())); - (cache, Ok(reads)) + cache.entries.insert(key.clone(), (clock, reads)); + cache } diff --git a/crates/sqlbuild-analysis/src/planner_fixtures/main/mod.rs b/crates/sqlbuild-analysis/src/planner_fixtures/main/mod.rs index 61b86c8338..321e72faf8 100644 --- a/crates/sqlbuild-analysis/src/planner_fixtures/main/mod.rs +++ b/crates/sqlbuild-analysis/src/planner_fixtures/main/mod.rs @@ -5,6 +5,7 @@ pub mod empty_fixture_marker; pub mod fixture_line; pub mod fixture_schema; pub mod merge_metadata; +pub mod prewarm_reads; pub mod propagate_types; pub mod render_completed; pub mod render_empty; diff --git a/crates/sqlbuild-analysis/src/planner_fixtures/main/prewarm_reads.rs b/crates/sqlbuild-analysis/src/planner_fixtures/main/prewarm_reads.rs new file mode 100644 index 0000000000..d0031c7004 --- /dev/null +++ b/crates/sqlbuild-analysis/src/planner_fixtures/main/prewarm_reads.rs @@ -0,0 +1,33 @@ +//! Parallel resolution of the reads a batch of tests will look up. + +use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; +use std::collections::HashSet; + +use crate::planner_fixtures::_helpers::resolved_reads::{stored, uncached_reads}; +use crate::planner_fixtures::models::{FixtureReadCache, FixtureReadKey}; +use crate::required_columns::errors::RequiredColumnsError; +use crate::required_columns::models::ColumnRead; + +/// Resolve the uncached keys in parallel and keep the successful reads; failures stay uncached. +pub fn prewarm_reads(mut cache: FixtureReadCache, keys: &[FixtureReadKey]) -> FixtureReadCache { + let mut seen: HashSet<&FixtureReadKey> = HashSet::new(); + let missing: Vec<&FixtureReadKey> = keys + .iter() + .filter(|key| !cache.entries.contains_key(*key) && seen.insert(*key)) + .collect(); + let resolved: Vec<( + &FixtureReadKey, + Result, RequiredColumnsError>, + )> = missing + .par_iter() + .map(|key| (*key, uncached_reads(key))) + .collect(); + for (key, reads) in resolved { + cache.misses += 1; + let Ok(reads) = reads else { + continue; + }; + cache = stored(cache, key, reads); + } + cache +} diff --git a/crates/sqlbuild-analysis/src/planner_fixtures/tests/helpers.rs b/crates/sqlbuild-analysis/src/planner_fixtures/tests/helpers.rs index 4afe32de53..5469dc4784 100644 --- a/crates/sqlbuild-analysis/src/planner_fixtures/tests/helpers.rs +++ b/crates/sqlbuild-analysis/src/planner_fixtures/tests/helpers.rs @@ -1,4 +1,5 @@ use crate::planner_fixtures::models::FixtureColumn; +use crate::planner_fixtures::models::{FixtureReadKey, FixtureReadReference}; use crate::planner_fixtures::models::{FixtureTypeModel, FixtureTypeProjection, FixtureTypeRead}; pub(super) fn type_model() -> FixtureTypeModel { @@ -28,3 +29,17 @@ pub(super) fn column(name: &str, sql_type: &str, nullable: bool) -> FixtureColum nullable: Some(nullable), } } + +/// A read cache key over one `orders` source reference. +pub(super) fn source_read_key(sql: &str) -> FixtureReadKey { + FixtureReadKey { + sql: sql.to_owned(), + references: vec![FixtureReadReference { + kind: "source".into(), + name: "orders".into(), + package: None, + argument_count: None, + }], + dialect: Some("duckdb".into()), + } +} diff --git a/crates/sqlbuild-analysis/src/planner_fixtures/tests/test_reads.rs b/crates/sqlbuild-analysis/src/planner_fixtures/tests/test_reads.rs index b7832b9526..a9188e5126 100644 --- a/crates/sqlbuild-analysis/src/planner_fixtures/tests/test_reads.rs +++ b/crates/sqlbuild-analysis/src/planner_fixtures/tests/test_reads.rs @@ -1,7 +1,11 @@ use crate::planner_fixtures::_helpers::resolved_reads::resolved_reads; use crate::planner_fixtures::_helpers::stub_markers::stub_markers; +use crate::planner_fixtures::main::prewarm_reads::prewarm_reads; use crate::planner_fixtures::models::{FixtureReadCache, FixtureReadKey, FixtureReadReference}; -use crate::planner_fixtures::tests::test_types::{FixtureMarkerTestCase, FixtureReadCacheTestCase}; +use crate::planner_fixtures::tests::helpers::source_read_key; +use crate::planner_fixtures::tests::test_types::{ + FixtureMarkerTestCase, FixtureReadCacheTestCase, FixtureReadPrewarmTestCase, +}; #[test] fn given_repeated_reads_when_resolving_then_full_reference_identity_controls_reuse() { @@ -115,3 +119,48 @@ fn given_marker_text_when_stubbing_for_star_analysis_then_preserves_legacy_lexic ); } } + +#[test] +fn given_prewarmed_reads_when_resolving_each_key_then_no_key_is_analysed_twice() { + let test_cases = [ + FixtureReadPrewarmTestCase { + description: "distinct keys", + sqls: &[ + "SELECT order_id FROM __source(\"orders\")", + "SELECT status FROM __source(\"orders\")", + ], + expected_misses: 2, + }, + FixtureReadPrewarmTestCase { + description: "repeated key", + sqls: &[ + "SELECT order_id FROM __source(\"orders\")", + "SELECT order_id FROM __source(\"orders\")", + ], + expected_misses: 1, + }, + ]; + for test_case in test_cases { + let keys: Vec = test_case + .sqls + .iter() + .map(|sql| source_read_key(sql)) + .collect(); + let mut cache = prewarm_reads(FixtureReadCache::default(), &keys); + assert_eq!( + cache.misses, test_case.expected_misses, + "{}", + test_case.description + ); + for key in &keys { + let (updated, reads) = resolved_reads(cache, key); + assert!(reads.is_ok(), "{}", test_case.description); + cache = updated; + } + assert_eq!( + cache.misses, test_case.expected_misses, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-analysis/src/planner_fixtures/tests/test_types.rs b/crates/sqlbuild-analysis/src/planner_fixtures/tests/test_types.rs index 6dc5c8b85d..948a28281f 100644 --- a/crates/sqlbuild-analysis/src/planner_fixtures/tests/test_types.rs +++ b/crates/sqlbuild-analysis/src/planner_fixtures/tests/test_types.rs @@ -74,3 +74,10 @@ pub(crate) struct RequiredColumnsTestCase { pub(crate) expected_required: &'static [&'static str], pub(crate) expected_completed: &'static [usize], } + +#[derive(Debug)] +pub(super) struct FixtureReadPrewarmTestCase { + pub description: &'static str, + pub sqls: &'static [&'static str], + pub expected_misses: u64, +} diff --git a/crates/sqlbuild-analysis/src/python_selection/_helpers/unified.rs b/crates/sqlbuild-analysis/src/python_selection/_helpers/unified.rs index 276b0c240d..1c62ad4862 100644 --- a/crates/sqlbuild-analysis/src/python_selection/_helpers/unified.rs +++ b/crates/sqlbuild-analysis/src/python_selection/_helpers/unified.rs @@ -8,6 +8,7 @@ use sqlbuild_core::text::main::glob_match::glob_match; use crate::assembly::project::types::ObjectKey; use crate::definition_changes::constants::PYTHON_NODE_KINDS; +use crate::graph::constants::{AUDIT_KIND, RUN_SELECTOR_KINDS}; use crate::graph::errors::SelectorError; use crate::graph::main::build_resources::build_resources; use crate::graph::main::edge_keys::edge_keys; @@ -344,6 +345,8 @@ fn single_side(context: &SelectionContext<'_>, raw: &str) -> Resolved { PATH_KIND => resolve_path(context, raw, &value)?, SEED_KIND | SOURCE_KIND => resolve_sql(context, raw)?, JOB_KIND => resolve_job(context, raw)?, + kind if RUN_SELECTOR_KINDS.contains(&kind) => resolve_job(context, raw)?, + AUDIT_KIND => resolve_sql(context, raw)?, ASSET_KIND | LOADER_KIND | CHECK_KIND => { return resolve_typed(context, raw, (&kind, &value)); } @@ -379,7 +382,7 @@ fn resolve_sql(context: &SelectionContext<'_>, raw: &str) -> Resolved { )?)) } -/// A job's SQL keys and Python nodes, with `+` also expanding them over the Python node graph. +/// A job's or past run's SQL keys and Python nodes, with `+` also expanding them over the Python node graph. fn resolve_job(context: &SelectionContext<'_>, raw: &str) -> Resolved { let ParsedSelector::Kind { upstream, diff --git a/crates/sqlbuild-cli/Cargo.toml b/crates/sqlbuild-cli/Cargo.toml index 7fc467cd0c..b0d0249977 100644 --- a/crates/sqlbuild-cli/Cargo.toml +++ b/crates/sqlbuild-cli/Cargo.toml @@ -51,6 +51,7 @@ ctrlc.workspace = true same-file.workspace = true [dev-dependencies] +axum.workspace = true rusqlite.workspace = true tempfile.workspace = true diff --git a/crates/sqlbuild-cli/src/adhoc/_helpers/evaluation.rs b/crates/sqlbuild-cli/src/adhoc/_helpers/evaluation.rs index 68d042c9a2..805a3633ca 100644 --- a/crates/sqlbuild-cli/src/adhoc/_helpers/evaluation.rs +++ b/crates/sqlbuild-cli/src/adhoc/_helpers/evaluation.rs @@ -79,6 +79,13 @@ pub(crate) fn vocabulary(publication: &IndexedPublication) -> SelectionVocabular sources: entries(sources), seeds: entries(seeds), kinds: entries(kinds), + audits: entries( + publication + .audits + .iter() + .map(|(name, keys)| (name.clone(), keys.len() as u64)) + .collect(), + ), } } diff --git a/crates/sqlbuild-cli/src/adhoc/_helpers/mod.rs b/crates/sqlbuild-cli/src/adhoc/_helpers/mod.rs index e8ad7efbef..de8fc83408 100644 --- a/crates/sqlbuild-cli/src/adhoc/_helpers/mod.rs +++ b/crates/sqlbuild-cli/src/adhoc/_helpers/mod.rs @@ -1,4 +1,5 @@ pub(crate) mod evaluation; pub(crate) mod job_pins; +pub(crate) mod past_runs; pub(crate) mod planner; pub(crate) mod publication; diff --git a/crates/sqlbuild-cli/src/adhoc/_helpers/past_runs.rs b/crates/sqlbuild-cli/src/adhoc/_helpers/past_runs.rs new file mode 100644 index 0000000000..bde6e8b26f --- /dev/null +++ b/crates/sqlbuild-cli/src/adhoc/_helpers/past_runs.rs @@ -0,0 +1,78 @@ +//! The past runs and audits a command's selectors name, attached to the publication's graph for one plan or evaluation. + +use std::borrow::Cow; +use std::cell::RefCell; +use std::collections::BTreeSet; + +use sqlbuild_analysis::assembly::project::types::ObjectKey; +use sqlbuild_analysis::graph::constants::AUDIT_KIND; +use sqlbuild_analysis::graph::main::attach_audits_and_runs::attach_audits_and_runs; +use sqlbuild_analysis::graph::models::{ProjectGraph, RunResults}; +use sqlbuild_orchestration::runs::models::PastRunResults; +use sqlbuild_orchestration::runs::types::PastRuns; + +use crate::adhoc::_helpers::publication::{IndexedPublication, python_kind}; +use crate::run_selectors::main::names_audits_or_runs::names_audits_or_runs; + +thread_local! { + /// The past runs of the plan or evaluation running on this thread. + static PAST_RUNS: RefCell = const { RefCell::new(PastRuns::new()) }; +} + +/// Run `run` with `past` as the runs its selectors read, restoring the enclosing ones after. +pub(crate) fn with_past_runs(past: &PastRuns, run: impl FnOnce() -> T) -> T { + let previous: PastRuns = PAST_RUNS.with(|current| current.replace(past.clone())); + let result: T = run(); + PAST_RUNS.with(|current| *current.borrow_mut() = previous); + result +} + +/// `graph` with the publication's audits and the past runs attached when `selectors` name an audit or a run. +pub(crate) fn with_audits_and_runs<'g>( + publication: &IndexedPublication, + graph: &'g ProjectGraph, + (selectors, include_python): (&[String], bool), +) -> Cow<'g, ProjectGraph> { + if !names_audits_or_runs(selectors) { + return Cow::Borrowed(graph); + } + let runs = PAST_RUNS.with(|past| { + past.borrow() + .iter() + .map(|(id, results)| (id.clone(), graph_results(results, include_python))) + .collect() + }); + Cow::Owned(attach_audits_and_runs( + graph.clone(), + (publication.audits.keys().cloned().collect(), runs), + )) +} + +/// A past run's results as selector graph keys. +fn graph_results(results: &PastRunResults, include_python: bool) -> RunResults { + RunResults { + selected: graph_keys(&results.selected, include_python), + failed: graph_keys(&results.failed, include_python), + skipped: graph_keys(&results.skipped, include_python), + } +} + +fn graph_keys(nodes: &BTreeSet, include_python: bool) -> BTreeSet { + nodes + .iter() + .filter_map(|node| run_key(node, include_python)) + .collect() +} + +/// A run node key as a selector graph key: an audit by its name, a Python node only when the command runs Python. +fn run_key(node: &str, include_python: bool) -> Option { + let (kind, name) = node.split_once(':')?; + if kind == AUDIT_KIND { + let name = name.split_once(':').map_or(name, |(name, _)| name); + return Some((AUDIT_KIND.to_owned(), name.to_owned())); + } + if python_kind(node).is_some() && !include_python { + return None; + } + Some((kind.to_owned(), name.to_owned())) +} diff --git a/crates/sqlbuild-cli/src/adhoc/_helpers/planner.rs b/crates/sqlbuild-cli/src/adhoc/_helpers/planner.rs index a59d8137f2..4b981c147b 100644 --- a/crates/sqlbuild-cli/src/adhoc/_helpers/planner.rs +++ b/crates/sqlbuild-cli/src/adhoc/_helpers/planner.rs @@ -5,7 +5,9 @@ use std::sync::Arc; use serde_json::{Value as Json, json}; use sqlbuild_analysis::assembly::project::types::ObjectKey; +use sqlbuild_analysis::graph::constants::AUDIT_KIND; use sqlbuild_analysis::graph::errors::SelectorError; +use sqlbuild_analysis::graph::main::run_selector_ids::run_selector_ids; use sqlbuild_analysis::graph::main::selectors_need_jobs::selectors_need_jobs; use sqlbuild_analysis::planner_selection::main::split_unit_test_selectors::split_unit_test_selectors; use sqlbuild_analysis::planner_selection::models::SelectorGroups; @@ -17,10 +19,12 @@ use sqlbuild_orchestration::runs::models::{ CommandPlan, PinnedJob, PlannerResource, PublicationCache, PublishedJobs, SelectionProblem, SelectionVocabulary, }; +use sqlbuild_orchestration::runs::types::PastRuns; use sqlbuild_orchestration::runs::types::{CommandPlanner, PreparedPublication}; use crate::adhoc::_helpers::evaluation::{evaluate, vocabulary}; use crate::adhoc::_helpers::job_pins::{named_job_settings, pinned_jobs}; +use crate::adhoc::_helpers::past_runs::{with_audits_and_runs, with_past_runs}; use crate::adhoc::_helpers::publication::{IndexedPublication, python_kind}; use crate::adhoc::models::Refusal; @@ -64,7 +68,30 @@ impl CommandPlanner for CliPlanner { } impl PreparedPublication for IndexedPublication { - fn plan(&self, command: &[String]) -> Result { + fn run_selector_ids(&self, texts: &[String]) -> BTreeSet { + run_selector_ids(texts) + } + + fn plan(&self, command: &[String], past: &PastRuns) -> Result { + with_past_runs(past, || self.planned(command)) + } + + fn evaluate( + &self, + (select, exclude): (&str, &str), + past: &PastRuns, + ) -> Result, Box> { + with_past_runs(past, || evaluate(self, (select, exclude))) + } + + fn vocabulary(&self) -> SelectionVocabulary { + self.vocabulary.get_or_init(|| vocabulary(self)).clone() + } +} + +impl IndexedPublication { + /// [`PreparedPublication::plan`] with the past runs in place. + fn planned(&self, command: &[String]) -> Result { let (verb, mut selectors, settings) = command_parts(command)?; let mut select: Vec = selectors.remove("select").unwrap_or_default(); select.extend(selectors.remove("positional_select").unwrap_or_default()); @@ -108,14 +135,6 @@ impl PreparedPublication for IndexedPublication { job_settings, }) } - - fn evaluate(&self, select: &str, exclude: &str) -> Result, Box> { - evaluate(self, (select, exclude)) - } - - fn vocabulary(&self) -> SelectionVocabulary { - self.vocabulary.get_or_init(|| vocabulary(self)).clone() - } } /// Whether a command runs Python nodes: a build does unless its flags or named jobs turn them off. @@ -345,10 +364,18 @@ fn resolved( ) -> Result, Refusal> { Ok(selected_keys(publication, select, exclude, include_python)? .iter() - .map(|key| key_text(publication, key)) + .flat_map(|key| node_keys(publication, key)) .collect()) } +/// The node keys a selected graph key freezes as: an audit's under each of its targets, else one. +fn node_keys(publication: &IndexedPublication, key: &ObjectKey) -> Vec { + if key.0 == AUDIT_KIND { + return publication.audits.get(&key.1).cloned().unwrap_or_default(); + } + vec![key_text(publication, key)] +} + /// A selected graph key as a frozen node key; a loader's Python key names the source it loads. pub(crate) fn key_text(publication: &IndexedPublication, (kind, name): &ObjectKey) -> String { if python_kind(&format!("{kind}:{name}")).is_some() { @@ -372,6 +399,8 @@ pub(crate) fn selected_keys( } else { &publication.graph }; + let graph = with_audits_and_runs(publication, graph, (&selectors, include_python)); + let graph = graph.as_ref(); let sources = &publication.sources; let selection = resolve_python_sql_run_selection( SqlSelectionGraph { diff --git a/crates/sqlbuild-cli/src/adhoc/_helpers/publication.rs b/crates/sqlbuild-cli/src/adhoc/_helpers/publication.rs index dfd70afd90..0ba9cca3c0 100644 --- a/crates/sqlbuild-cli/src/adhoc/_helpers/publication.rs +++ b/crates/sqlbuild-cli/src/adhoc/_helpers/publication.rs @@ -4,6 +4,7 @@ use std::collections::BTreeMap; use std::sync::OnceLock; use sqlbuild_analysis::definition_changes::constants::PYTHON_NODE_KINDS; +use sqlbuild_analysis::graph::constants::AUDIT_KIND; use sqlbuild_analysis::graph::main::attach_jobs::attach_jobs; use sqlbuild_analysis::graph::main::build_project_graph::build_project_graph; use sqlbuild_analysis::graph::models::{GraphResource, JobSelection, ProjectGraph}; @@ -22,6 +23,8 @@ pub(crate) struct IndexedPublication { pub(crate) jobs: PublishedJobs, /// SQL unit test names, and every other resource and job name, for splitting `test:` selectors. pub(crate) names: UnitTestSelectorNames, + /// Each audit's name and the node keys it is published under: one for a singular audit, one per target for an attached one. + pub(crate) audits: BTreeMap>, /// `(source name, loader)` for every published source. pub(crate) sources: Vec<(String, Option)>, /// The SQL resources' graph without jobs; most commands never name one. @@ -88,7 +91,17 @@ impl IndexedPublication { .map(|node| (node.name.clone(), node.kind.clone())) .collect(), }; + let mut audits: BTreeMap> = BTreeMap::new(); + for resource in resources.iter().filter(|resource| is_audit(resource)) { + let name = name_of(&resource.key); + let name = name.split_once(':').map_or(name, |(name, _)| name); + audits + .entry(name.to_owned()) + .or_default() + .push(resource.key.clone()); + } Self { + audits, graph: build_project_graph(&graph_resources), with_jobs: [OnceLock::new(), OnceLock::new()], vocabulary: OnceLock::new(), @@ -125,6 +138,11 @@ impl IndexedPublication { } } +/// An audit node, singular (`audit:`) or attached (`audit:::`). +fn is_audit(resource: &PlannerResource) -> bool { + resource.key.split_once(':').map(|(kind, _)| kind) == Some(AUDIT_KIND) +} + pub(crate) fn is_sql_test(resource: &PlannerResource) -> bool { resource.key.split_once(':').map(|(kind, _)| kind) == Some(SQL_TEST_KIND) } diff --git a/crates/sqlbuild-cli/src/adhoc/tests.rs b/crates/sqlbuild-cli/src/adhoc/tests.rs index 5b3529382c..72a77ed0fd 100644 --- a/crates/sqlbuild-cli/src/adhoc/tests.rs +++ b/crates/sqlbuild-cli/src/adhoc/tests.rs @@ -4,6 +4,8 @@ mod adhoc_planner; mod helpers; #[path = "tests/test_job_pins.rs"] mod job_pins; +#[path = "tests/test_run_selectors.rs"] +mod run_selectors; #[path = "tests/test_selection_evaluation.rs"] mod selection_evaluation; #[path = "tests/test_types.rs"] diff --git a/crates/sqlbuild-cli/src/adhoc/tests/helpers.rs b/crates/sqlbuild-cli/src/adhoc/tests/helpers.rs index 327cb225e6..241d1b857f 100644 --- a/crates/sqlbuild-cli/src/adhoc/tests/helpers.rs +++ b/crates/sqlbuild-cli/src/adhoc/tests/helpers.rs @@ -1,5 +1,9 @@ +use std::collections::BTreeSet; + use serde_json::Value; +use sqlbuild_orchestration::runs::models::PastRunResults; use sqlbuild_orchestration::runs::models::PlannerResource; +use sqlbuild_orchestration::runs::types::PastRuns; /// A published node as the planner receives it from the control plane. pub(super) fn resource( @@ -30,7 +34,27 @@ pub(super) fn owned_plan( /// SQL models, a source with its loaders, Python nodes and a job, all published, indexed by the server's planner. pub(super) fn orders_publication() -> std::sync::Arc { - let resources = vec![ + publication_of(orders_resources()) +} + +/// [`orders_publication`] with a singular audit and an audit attached to a column of `orders`. +pub(super) fn audited_orders_publication() +-> std::sync::Arc { + let mut resources = orders_resources(); + resources.extend([ + resource("audit:orders_match_payments", &["model:orders"], &[], None), + resource( + "audit:not_null_orders_id:model:orders:order_id", + &["model:orders"], + &[], + None, + ), + ]); + publication_of(resources) +} + +fn orders_resources() -> Vec { + vec![ resource( "model:stg_orders", &[], @@ -78,7 +102,13 @@ pub(super) fn orders_publication() &[], Some("python/nodes/loaders"), ), - ]; + ] +} + +/// `resources` and the `carrier_sync` job, indexed by the server's planner. +fn publication_of( + resources: Vec, +) -> std::sync::Arc { let jobs = sqlbuild_orchestration::runs::models::PublishedJobs { selections: std::collections::BTreeMap::from([( "carrier_sync".to_owned(), @@ -137,3 +167,21 @@ pub(super) fn expected_pins( }) .map_err(str::to_owned) } + +/// A past run where `stg_orders` and the end-of-build audit failed and `orders` was skipped. +pub(super) fn past_runs() -> PastRuns { + let keys = |keys: &[&str]| { + keys.iter() + .map(|key| (*key).to_owned()) + .collect::>() + }; + PastRuns::from([( + "01a1d3b9".to_owned(), + PastRunResults { + run_id: uuid::Uuid::nil(), + selected: keys(&["model:stg_orders", "model:orders", "model:customers"]), + failed: keys(&["model:stg_orders", "audit:orders_match_payments"]), + skipped: keys(&["model:orders"]), + }, + )]) +} diff --git a/crates/sqlbuild-cli/src/adhoc/tests/test_adhoc_planner.rs b/crates/sqlbuild-cli/src/adhoc/tests/test_adhoc_planner.rs index 228272cb29..442d099abc 100644 --- a/crates/sqlbuild-cli/src/adhoc/tests/test_adhoc_planner.rs +++ b/crates/sqlbuild-cli/src/adhoc/tests/test_adhoc_planner.rs @@ -5,6 +5,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde_json::json; use sqlbuild_orchestration::runs::models::PlannerResource; use sqlbuild_orchestration::runs::models::PublishedJobs; +use sqlbuild_orchestration::runs::types::PastRuns; use crate::adhoc::main::adhoc_planner::adhoc_planner; use crate::adhoc::tests::helpers::{owned_plan, resource}; @@ -334,7 +335,7 @@ fn given_ad_hoc_commands_when_planned_then_flags_follow_the_allowlist_and_select .map(|token| (*token).to_owned()) .collect(); let actual = publication - .plan(&command) + .plan(&command, &PastRuns::new()) .map(|plan| { ( plan.selection.into_iter().collect::>(), @@ -572,7 +573,7 @@ fn given_published_python_nodes_when_planned_then_selectors_resolve_as_on_the_co .map(|token| (*token).to_owned()) .collect(); let actual = publication - .plan(&command) + .plan(&command, &PastRuns::new()) .map(|plan| { ( plan.selection.into_iter().collect::>(), diff --git a/crates/sqlbuild-cli/src/adhoc/tests/test_job_pins.rs b/crates/sqlbuild-cli/src/adhoc/tests/test_job_pins.rs index 4cee584b57..ad1baed120 100644 --- a/crates/sqlbuild-cli/src/adhoc/tests/test_job_pins.rs +++ b/crates/sqlbuild-cli/src/adhoc/tests/test_job_pins.rs @@ -4,6 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; use sqlbuild_orchestration::runs::models::PublishedJobs; +use sqlbuild_orchestration::runs::types::PastRuns; use crate::adhoc::main::adhoc_planner::adhoc_planner; use crate::adhoc::tests::helpers::{expected_pins, nightly_pin, resource, weekly_pin}; @@ -176,7 +177,7 @@ fn given_a_build_naming_jobs_when_planned_then_each_is_pinned_to_the_nodes_it_gi .map(|token| (*token).to_owned()) .collect(); let planned = publication - .plan(&command) + .plan(&command, &PastRuns::new()) .map(|plan| { ( plan.selection.into_iter().collect::>(), diff --git a/crates/sqlbuild-cli/src/adhoc/tests/test_run_selectors.rs b/crates/sqlbuild-cli/src/adhoc/tests/test_run_selectors.rs new file mode 100644 index 0000000000..42c5b007ad --- /dev/null +++ b/crates/sqlbuild-cli/src/adhoc/tests/test_run_selectors.rs @@ -0,0 +1,118 @@ +use std::collections::BTreeSet; + +use crate::adhoc::tests::helpers::{audited_orders_publication, past_runs}; +use crate::adhoc::tests::test_types::{RunSelectorIdsTestCase, RunSelectorPlanTestCase}; + +#[test] +fn given_past_runs_and_audits_when_planned_then_run_and_audit_selectors_freeze_exact_keys() { + let test_cases = [ + RunSelectorPlanTestCase { + description: "failed: freezes the failed model and the failed end-of-build audit", + command: &["build", "failed:01a1d3b9"], + expected_selection: Ok(&["audit:orders_match_payments", "model:stg_orders"]), + }, + RunSelectorPlanTestCase { + description: "failed:+ adds what reads the failed model", + command: &[ + "build", + "--select", + "failed:01a1d3b9+", + "--exclude", + "kind:asset", + ], + expected_selection: Ok(&[ + "audit:orders_match_payments", + "model:orders", + "model:stg_orders", + ]), + }, + RunSelectorPlanTestCase { + description: "an attached audit freezes under its target", + command: &["build", "audit:not_null_*"], + expected_selection: Ok(&["audit:not_null_orders_id:model:orders:order_id"]), + }, + RunSelectorPlanTestCase { + description: "run: less what it skipped", + command: &[ + "build", + "--select", + "run:01a1d3b9", + "--exclude", + "skipped:01a1d3b9", + ], + expected_selection: Ok(&["model:customers", "model:stg_orders"]), + }, + RunSelectorPlanTestCase { + description: "an unknown audit is refused", + command: &["build", "audit:orders_match_payment"], + expected_selection: Err("unknown audit name 'orders_match_payment'"), + }, + ]; + let publication = audited_orders_publication(); + for test_case in test_cases { + let command: Vec = test_case + .command + .iter() + .map(|token| (*token).to_owned()) + .collect(); + let actual = publication + .plan(&command, &past_runs()) + .map(|plan| plan.selection.into_iter().collect::>()) + .map_err(|error| { + test_case + .expected_selection + .err() + .filter(|fragment| error.contains(fragment)) + .unwrap_or(error.as_str()) + .to_owned() + }); + assert_eq!( + actual, + test_case + .expected_selection + .map(|keys| keys.iter().map(|key| (*key).to_owned()).collect()) + .map_err(str::to_owned), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_command_texts_when_scanned_then_the_run_ids_they_name_are_listed() { + let test_cases = [ + RunSelectorIdsTestCase { + description: "every run a command names, in expansions and intersections, flags ignored", + texts: &[ + "build", + "failed:01a1d3b9+", + "--exclude", + "skipped:01a1d3c0,tag:x", + ], + expected_ids: &["01a1d3b9", "01a1d3c0"], + }, + RunSelectorIdsTestCase { + description: "audits and jobs name no run", + texts: &["build", "audit:orders_match_payments", "job:carrier_sync"], + expected_ids: &[], + }, + ]; + let publication = audited_orders_publication(); + for test_case in test_cases { + let texts: Vec = test_case + .texts + .iter() + .map(|text| (*text).to_owned()) + .collect(); + assert_eq!( + publication.run_selector_ids(&texts), + test_case + .expected_ids + .iter() + .map(|id| (*id).to_owned()) + .collect::>(), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/src/adhoc/tests/test_selection_evaluation.rs b/crates/sqlbuild-cli/src/adhoc/tests/test_selection_evaluation.rs index 2d0661bbcd..4fa80061f3 100644 --- a/crates/sqlbuild-cli/src/adhoc/tests/test_selection_evaluation.rs +++ b/crates/sqlbuild-cli/src/adhoc/tests/test_selection_evaluation.rs @@ -1,8 +1,11 @@ //! A selection evaluates as `sqb build` resolves it, refusals point at their token, and the vocabulary counts nodes. use sqlbuild_orchestration::runs::models::{SelectionField, SelectionProblem, SelectionRefusal}; +use sqlbuild_orchestration::runs::types::PastRuns; -use crate::adhoc::tests::helpers::{orders_publication, owned_evaluation}; +use crate::adhoc::tests::helpers::{ + audited_orders_publication, orders_publication, owned_evaluation, +}; use crate::adhoc::tests::test_types::{ RefusedPartTestCase, SelectionEvaluationTestCase, VocabularyTestCase, }; @@ -86,7 +89,7 @@ fn given_typed_selections_when_evaluated_then_keys_or_located_refusals_match_sqb let publication = orders_publication(); for test_case in test_cases { let actual = publication - .evaluate(test_case.select, test_case.exclude) + .evaluate((test_case.select, test_case.exclude), &PastRuns::new()) .map_err(|problem| { Box::new(SelectionProblem { help: None, @@ -156,6 +159,27 @@ fn given_a_publication_when_its_vocabulary_is_read_then_each_value_counts_the_no } } +#[test] +fn given_audits_when_the_vocabulary_is_read_then_each_audit_name_counts_its_targets() { + let test_cases = [VocabularyTestCase { + description: "a singular audit and an attached audit are each listed once, by name", + entries_of: |vocabulary| &vocabulary.audits, + expected_entries: &[("not_null_orders_id", 1), ("orders_match_payments", 1)], + }]; + let vocabulary = audited_orders_publication().vocabulary(); + for test_case in test_cases { + let actual: Vec<(&str, u64)> = (test_case.entries_of)(&vocabulary) + .iter() + .map(|entry| (entry.value.as_str(), entry.count)) + .collect(); + assert_eq!( + actual, test_case.expected_entries, + "{}", + test_case.description + ); + } +} + #[test] fn given_refused_selectors_when_evaluated_then_the_refused_part_its_type_and_value_are_reported() { let test_cases = [ @@ -232,7 +256,9 @@ fn given_refused_selectors_when_evaluated_then_the_refused_part_its_type_and_val .select .split_once(" --exclude ") .unwrap_or((test_case.select, "")); - let problem = publication.evaluate(select, exclude).err(); + let problem = publication + .evaluate((select, exclude), &PastRuns::new()) + .err(); assert_eq!( ( problem.as_ref().and_then(|problem| problem.code.clone()), diff --git a/crates/sqlbuild-cli/src/adhoc/tests/test_types.rs b/crates/sqlbuild-cli/src/adhoc/tests/test_types.rs index 5ebc38f04b..66a4dbfc97 100644 --- a/crates/sqlbuild-cli/src/adhoc/tests/test_types.rs +++ b/crates/sqlbuild-cli/src/adhoc/tests/test_types.rs @@ -60,3 +60,17 @@ pub(super) struct RefusedPartTestCase { pub(super) expected_code: Option<&'static str>, pub(super) expected_refused: Option<(&'static str, u32, &'static str, &'static str)>, } + +/// A command and the past runs its selectors name, and the keys it freezes or how it is refused. +pub(super) struct RunSelectorPlanTestCase { + pub(super) description: &'static str, + pub(super) command: &'static [&'static str], + pub(super) expected_selection: Result<&'static [&'static str], &'static str>, +} + +/// Command tokens and the run IDs their selectors name. +pub(super) struct RunSelectorIdsTestCase { + pub(super) description: &'static str, + pub(super) texts: &'static [&'static str], + pub(super) expected_ids: &'static [&'static str], +} diff --git a/crates/sqlbuild-cli/src/argv/command_table.json b/crates/sqlbuild-cli/src/argv/command_table.json index 4ec154ae0a..39a6278ea8 100644 --- a/crates/sqlbuild-cli/src/argv/command_table.json +++ b/crates/sqlbuild-cli/src/argv/command_table.json @@ -2519,6 +2519,33 @@ "default": [], "group": 1 }, + { + "kind": "store", + "options": [ + "--server" + ], + "dest": "login_server", + "help": "HTTPS SQLBuild server to read the runs that run:, failed: and skipped: name from, signed in with sqb login; without it, local Recall history", + "group": 1 + }, + { + "kind": "store", + "options": [ + "--ca-cert" + ], + "dest": "login_ca", + "help": "additional trusted PEM CA certificate for --server", + "group": 1 + }, + { + "kind": "store", + "options": [ + "--location-id" + ], + "dest": "person_location", + "help": "published location UUID; required with --server", + "group": 1 + }, { "kind": "store", "dest": "positional_select", @@ -3140,6 +3167,33 @@ "default": [], "group": 1 }, + { + "kind": "store", + "options": [ + "--server" + ], + "dest": "login_server", + "help": "HTTPS SQLBuild server to read the runs that run:, failed: and skipped: name from, signed in with sqb login; without it, local Recall history", + "group": 1 + }, + { + "kind": "store", + "options": [ + "--ca-cert" + ], + "dest": "login_ca", + "help": "additional trusted PEM CA certificate for --server", + "group": 1 + }, + { + "kind": "store", + "options": [ + "--location-id" + ], + "dest": "person_location", + "help": "published location UUID; required with --server", + "group": 1 + }, { "kind": "store", "dest": "positional_select", @@ -3564,6 +3618,32 @@ "help": "Per-test timeout for this run, such as '30s' or '2m', or 'disabled'; overrides TEST() and project settings", "group": 1 }, + { + "kind": "store", + "options": [ + "--run-on" + ], + "dest": "run_on", + "choices": [ + "auto", + "local", + "warehouse" + ], + "help": "Where unit tests run: auto (locally when SQLQuack converts them, otherwise on the warehouse), local or warehouse; overrides the target and [settings] test_run_on", + "group": 1 + }, + { + "kind": "store_true", + "options": [ + "--verbose" + ], + "dest": "verbose", + "nargs": 0, + "const": true, + "default": false, + "help": "Print every refusal that keeps a test off DuckDB in full", + "group": 1 + }, { "kind": "store", "options": [ @@ -3672,6 +3752,33 @@ "default": [], "group": 1 }, + { + "kind": "store", + "options": [ + "--server" + ], + "dest": "login_server", + "help": "HTTPS SQLBuild server to read the runs that run:, failed: and skipped: name from, signed in with sqb login; without it, local Recall history", + "group": 1 + }, + { + "kind": "store", + "options": [ + "--ca-cert" + ], + "dest": "login_ca", + "help": "additional trusted PEM CA certificate for --server", + "group": 1 + }, + { + "kind": "store", + "options": [ + "--location-id" + ], + "dest": "person_location", + "help": "published location UUID; required with --server", + "group": 1 + }, { "kind": "store", "dest": "positional_select", @@ -3876,6 +3983,33 @@ "default": [], "group": 1 }, + { + "kind": "store", + "options": [ + "--server" + ], + "dest": "login_server", + "help": "HTTPS SQLBuild server to read the runs that run:, failed: and skipped: name from, signed in with sqb login; without it, local Recall history", + "group": 1 + }, + { + "kind": "store", + "options": [ + "--ca-cert" + ], + "dest": "login_ca", + "help": "additional trusted PEM CA certificate for --server", + "group": 1 + }, + { + "kind": "store", + "options": [ + "--location-id" + ], + "dest": "person_location", + "help": "published location UUID; required with --server", + "group": 1 + }, { "kind": "store", "dest": "positional_select", @@ -4097,6 +4231,33 @@ "default": [], "group": 1 }, + { + "kind": "store", + "options": [ + "--server" + ], + "dest": "login_server", + "help": "HTTPS SQLBuild server to read the runs that run:, failed: and skipped: name from, signed in with sqb login; without it, local Recall history", + "group": 1 + }, + { + "kind": "store", + "options": [ + "--ca-cert" + ], + "dest": "login_ca", + "help": "additional trusted PEM CA certificate for --server", + "group": 1 + }, + { + "kind": "store", + "options": [ + "--location-id" + ], + "dest": "person_location", + "help": "published location UUID; required with --server", + "group": 1 + }, { "kind": "store", "dest": "positional_select", @@ -7806,25 +7967,29 @@ "group": 1 }, { - "kind": "store_true", + "kind": "store", "options": [ - "--local" + "--run-on" ], - "dest": "scenario_local", - "nargs": 0, - "const": true, - "default": false, + "dest": "run_on", + "choices": [ + "auto", + "local", + "warehouse" + ], + "help": "Where scenarios run: auto (locally when they can, otherwise on the warehouse), local or warehouse; overrides the target and [settings] scenario_run_on", "group": 1 }, { "kind": "store_true", "options": [ - "--strict" + "--verbose" ], - "dest": "scenario_strict", + "dest": "verbose", "nargs": 0, "const": true, "default": false, + "help": "Print every reason that keeps a scenario off DuckDB in full", "group": 1 }, { diff --git a/crates/sqlbuild-cli/src/argv/constants.rs b/crates/sqlbuild-cli/src/argv/constants.rs index fab4aaa541..a1e9b05366 100644 --- a/crates/sqlbuild-cli/src/argv/constants.rs +++ b/crates/sqlbuild-cli/src/argv/constants.rs @@ -77,7 +77,7 @@ pub(crate) const INT_CONVERTER: &str = "int"; pub(crate) const PATH_CONVERTER: &str = "Path"; /// Every `CliNamespace` attribute with a default, in declaration order. -pub(crate) const CLI_NAMESPACE_DEFAULTS: [(&str, NamespaceDefault); 195] = [ +pub(crate) const CLI_NAMESPACE_DEFAULTS: [(&str, NamespaceDefault); 194] = [ ("command", NamespaceDefault::None), ("project_dir", NamespaceDefault::None), ("dbt_project_dir", NamespaceDefault::None), @@ -222,8 +222,7 @@ pub(crate) const CLI_NAMESPACE_DEFAULTS: [(&str, NamespaceDefault); 195] = [ ("scenario_selector", NamespaceDefault::EmptyList), ("scenario_retain", NamespaceDefault::Bool(false)), ("scenario_namespace", NamespaceDefault::None), - ("scenario_local", NamespaceDefault::Bool(false)), - ("scenario_strict", NamespaceDefault::Bool(false)), + ("run_on", NamespaceDefault::None), ("scenario_sync_snapshots", NamespaceDefault::Bool(false)), ("scenario_refresh", NamespaceDefault::Bool(false)), ("scenario_force", NamespaceDefault::Bool(false)), diff --git a/crates/sqlbuild-cli/src/dev_session/_helpers/runs.rs b/crates/sqlbuild-cli/src/dev_session/_helpers/runs.rs index 3a0c13ef0c..de4aaf5dcb 100644 --- a/crates/sqlbuild-cli/src/dev_session/_helpers/runs.rs +++ b/crates/sqlbuild-cli/src/dev_session/_helpers/runs.rs @@ -53,7 +53,6 @@ fn outcome(status: RunStatus) -> &'static str { match status { RunStatus::Success => "succeeded", RunStatus::Warn => "succeeded with warnings", - RunStatus::Partial => "partly succeeded", RunStatus::Failed => "failed", RunStatus::Cancelled => "cancelled", RunStatus::Skipped => "skipped", diff --git a/crates/sqlbuild-cli/src/dispatch/_helpers/subcommands.rs b/crates/sqlbuild-cli/src/dispatch/_helpers/subcommands.rs index afa9349fa9..0ea7631816 100644 --- a/crates/sqlbuild-cli/src/dispatch/_helpers/subcommands.rs +++ b/crates/sqlbuild-cli/src/dispatch/_helpers/subcommands.rs @@ -36,21 +36,8 @@ pub(crate) fn dbt_dispatch(subcommand: &str) -> Dispatch { Dispatch::Run(route, None) } -pub(crate) fn scenario_dispatch(facts: &CommandFacts, subcommand: &str) -> Dispatch { +pub(crate) fn scenario_dispatch(subcommand: &str) -> Dispatch { match subcommand { - "test" if facts.scenario_local && facts.scenario_retain => Dispatch::Fail(failure( - "scenario test --local does not support --retain", - "C452", - Some("Local scenario DuckDB files are always kept under target/run/scenarios/."), - )), - "test" if !facts.scenario_local && facts.scenario_snapshot_sync => Dispatch::Fail(failure( - "scenario snapshot sync flags require --local", - "C454", - Some( - "Use sqb scenario test --local --sync-snapshots or sqb scenario test --local \ - --refresh.", - ), - )), "test" => Dispatch::Run(&SCENARIO_TEST_ROUTE, None), "capture" => Dispatch::Run(&SCENARIO_CAPTURE_ROUTE, None), _ => Dispatch::Fail(failure( diff --git a/crates/sqlbuild-cli/src/dispatch/constants.rs b/crates/sqlbuild-cli/src/dispatch/constants.rs index 445dfe454c..94ea7a5e12 100644 --- a/crates/sqlbuild-cli/src/dispatch/constants.rs +++ b/crates/sqlbuild-cli/src/dispatch/constants.rs @@ -221,7 +221,7 @@ pub(crate) const FRESHNESS_ROUTE: Route = routed( REQUEST_KEYWORD_SHAPE, ); -const TEST_FIELDS: [Field; 17] = [ +const TEST_FIELDS: [Field; 19] = [ PROJECT_DIR, NO_SQL_VALIDATION, NO_COLOR, @@ -235,6 +235,8 @@ const TEST_FIELDS: [Field; 17] = [ attr("case_name", "case"), same("inspect"), same("test_timeout"), + same("run_on"), + same("verbose"), same("since"), same("explain"), same("sql_only"), @@ -795,8 +797,8 @@ const SCENARIO_TEST_FIELDS: [Field; 18] = [ SCENARIO_COMMON[4], SCENARIO_COMMON[5], SCENARIO_COMMON[6], - attr("local", "scenario_local"), - attr("strict", "scenario_strict"), + same("run_on"), + same("verbose"), same("concurrency"), attr("sync_snapshots", "scenario_sync_snapshots"), attr("refresh", "scenario_refresh"), diff --git a/crates/sqlbuild-cli/src/dispatch/main/command_dispatch.rs b/crates/sqlbuild-cli/src/dispatch/main/command_dispatch.rs index dbce0bf3d3..eb11640bb5 100644 --- a/crates/sqlbuild-cli/src/dispatch/main/command_dispatch.rs +++ b/crates/sqlbuild-cli/src/dispatch/main/command_dispatch.rs @@ -69,7 +69,7 @@ pub fn command_dispatch(facts: &CommandFacts) -> Dispatch { "init" => run(&INIT_ROUTE), "playground" => run(&PLAYGROUND_ROUTE), "skills" => run(&SKILLS_ROUTE), - "scenario" => scenario_dispatch(facts, subcommand), + "scenario" => scenario_dispatch(subcommand), "format" => checked(&FORMAT_ROUTE, format_failure(facts)), "rules" => run(&RULES_ROUTE), _ => Dispatch::Nothing, diff --git a/crates/sqlbuild-cli/src/dispatch/models.rs b/crates/sqlbuild-cli/src/dispatch/models.rs index 4b61dca4ae..d4d118d6d5 100644 --- a/crates/sqlbuild-cli/src/dispatch/models.rs +++ b/crates/sqlbuild-cli/src/dispatch/models.rs @@ -102,9 +102,6 @@ pub struct CommandFacts { pub format_diff: bool, pub format_fix: bool, pub format_fixtures_only: bool, - pub scenario_local: bool, - pub scenario_retain: bool, - pub scenario_snapshot_sync: bool, /// Whether `diff` compares raw queries rather than project models. pub raw_query_diff: bool, /// Whether `--ignore-audit-failures` is combined with `--no-audits`, which leaves nothing to ignore. diff --git a/crates/sqlbuild-cli/src/dispatch/tests/test_command_dispatch.rs b/crates/sqlbuild-cli/src/dispatch/tests/test_command_dispatch.rs index 32498f2b62..34726c94a0 100644 --- a/crates/sqlbuild-cli/src/dispatch/tests/test_command_dispatch.rs +++ b/crates/sqlbuild-cli/src/dispatch/tests/test_command_dispatch.rs @@ -3,7 +3,7 @@ use crate::dispatch::constants::{ SCENARIO_CAPTURE_ROUTE, }; use crate::dispatch::main::command_dispatch::command_dispatch; -use crate::dispatch::models::{CommandFacts, Dispatch, DispatchFailure}; +use crate::dispatch::models::{CommandFacts, Dispatch}; use crate::dispatch::tests::helpers::{facts, failure, runs}; use crate::dispatch::tests::test_types::CommandDispatchTestCase; @@ -68,35 +68,6 @@ fn given_parsed_command_when_dispatching_then_selects_python_dispatcher_route() )), ), }, - CommandDispatchTestCase { - description: "scenario test --local --retain fails", - facts: CommandFacts { - scenario_local: true, - scenario_retain: true, - ..facts("scenario", Some("test")) - }, - expected_dispatch: Dispatch::Fail(DispatchFailure { - message: "scenario test --local does not support --retain".to_owned(), - code: "C452", - help: Some( - "Local scenario DuckDB files are always kept under target/run/scenarios/.", - ), - }), - }, - CommandDispatchTestCase { - description: "scenario sync flags need --local", - facts: CommandFacts { - scenario_snapshot_sync: true, - ..facts("scenario", Some("test")) - }, - expected_dispatch: Dispatch::Fail(DispatchFailure { - message: "scenario snapshot sync flags require --local".to_owned(), - code: "C454", - help: Some( - "Use sqb scenario test --local --sync-snapshots or sqb scenario test --local --refresh.", - ), - }), - }, CommandDispatchTestCase { description: "scenario capture runs the capture slot", facts: facts("scenario", Some("capture")), diff --git a/crates/sqlbuild-cli/src/lib.rs b/crates/sqlbuild-cli/src/lib.rs index b275b14686..7135763c9e 100644 --- a/crates/sqlbuild-cli/src/lib.rs +++ b/crates/sqlbuild-cli/src/lib.rs @@ -15,5 +15,6 @@ pub mod launcher; pub mod native_commands; pub mod person_login; pub mod replay; +pub mod run_selectors; pub(crate) mod server_config; pub(crate) mod workers; diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/command/decision.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/command/decision.rs index b192b3b710..2f68256887 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/command/decision.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/command/decision.rs @@ -43,6 +43,7 @@ use crate::native_commands::models::{ }; use crate::server_config::models::{ServerConfig, ServerSection}; use sqlbuild_core::cost_command::constants::DESCENDING_ORDER; +use sqlbuild_orchestration::health::models::ServerHealth; /// Whether `sqb review --json` failed to parse, which Python reports as a JSON document. pub(crate) fn review_json_failure(arguments: &[String], outcome: &ArgvOutcome) -> bool { @@ -353,6 +354,10 @@ pub(crate) fn control_api_settings( origin, version: env!("CARGO_PKG_VERSION").into(), scheduler: scheduler_enabled(namespace, standalone, &config.server), + health: ServerHealth::new( + env!("CARGO_PKG_VERSION"), + scheduler_enabled(namespace, standalone, &config.server), + ), output: None, audit, statistics, diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/api_standby.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/api_standby.rs new file mode 100644 index 0000000000..64625a09e3 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/api_standby.rs @@ -0,0 +1,100 @@ +//! Bind first and answer health and the UI while the control store opens, waiting out a database it can't reach yet. + +use std::net::SocketAddr; + +use chrono::Utc; +use sqlbuild_orchestration::api::main::serve_standby::serve_standby; +use sqlbuild_orchestration::health::main::control_cause::control_cause; +use sqlbuild_orchestration::health::main::control_target::control_target; +use sqlbuild_orchestration::health::models::ServerHealth; +use sqlbuild_orchestration::store::errors::ControlError; +use sqlbuild_orchestration::store::models::ControlStore; + +use crate::argv::models::{Namespace, Stream}; +use crate::native_commands::_helpers::command::decision::{ + control_database, control_database_variable, +}; +use crate::native_commands::_helpers::command::terminal::write_output; +use crate::native_commands::_helpers::location::execution::open_migrated_store; +use crate::native_commands::constants::{ + OPENING_STORE, STORE_READY, STORE_RETRY_FIRST, STORE_RETRY_MAX, +}; +use crate::native_commands::models::ApiStandby; +use crate::server_config::models::ServerSection; + +/// Bind `address` and serve the standby on it until the returned standby is ended. +pub(crate) async fn start_standby( + address: SocketAddr, + health: &ServerHealth, +) -> Result { + drop(write_output(&[( + Stream::Stderr, + "Starting control API...\n", + )])); + let bound = std::net::TcpListener::bind(address)?; + bound.set_nonblocking(true)?; + let standby = tokio::net::TcpListener::from_std(bound.try_clone()?)?; + let listener = tokio::net::TcpListener::from_std(bound)?; + drop(write_output(&[( + Stream::Stderr, + &format!("Control API listening: {}\n", listener.local_addr()?), + )])); + let (end, ended) = tokio::sync::oneshot::channel::<()>(); + let health = health.clone(); + drop(tokio::spawn(async move { + let done = async move { + drop(ended.await); + }; + if let Err(error) = serve_standby(standby, health, done).await { + drop(write_output(&[( + Stream::Stderr, + &format!("Control API standby stopped: {error}\n"), + )])); + } + })); + Ok(ApiStandby { listener, end }) +} + +/// Open and migrate the server's store, retrying while the database can't be reached and recording why in `health`. +pub(crate) async fn open_store_waiting( + namespace: &Namespace, + server: &ServerSection, + health: &ServerHealth, +) -> Result { + let url = control_database(namespace, &control_database_variable(namespace, server))?; + let target = control_target(&url); + health.set_target(target.clone()); + drop(write_output(&[(Stream::Stderr, OPENING_STORE)])); + let mut wait = STORE_RETRY_FIRST; + loop { + let error = match open_migrated_store(&url).await { + Ok(store) => { + drop(write_output(&[(Stream::Stderr, STORE_READY)])); + return Ok(store); + } + Err(error) => error, + }; + let Some(cause) = control_cause(&error, (&target, false)) else { + return Err(error); + }; + let detail = cause.chain.join(": "); + if !error.transient() { + drop(write_output(&[( + Stream::Stderr, + &format!("{}: {detail}\n", cause.message), + )])); + return Err(error); + } + health.control_failed(&cause, (Utc::now(), None)); + drop(write_output(&[( + Stream::Stderr, + &format!( + "{} ({detail}); retrying in {} s\n", + cause.message, + wait.as_secs() + ), + )])); + tokio::time::sleep(wait).await; + wait = (wait * 2).min(STORE_RETRY_MAX); + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/api_start.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/api_start.rs index bb2968feae..f0d5b38a3d 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/api_start.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/api_start.rs @@ -1,20 +1,26 @@ //! Start the control API and the platform roles that run beside it. -use std::net::SocketAddr; - use sqlbuild_orchestration::api::main::serve_api::serve_api; use sqlbuild_orchestration::api::models::{ApiAuthentication, ServerFacts}; +use sqlbuild_orchestration::health::models::ServerHealth; +use sqlbuild_orchestration::platform::constants::PLATFORM_WEBHOOK_VARIABLE; +use sqlbuild_orchestration::platform::main::installation::run_maintenance::run_maintenance; use sqlbuild_orchestration::platform::models::RetentionPolicies; use sqlbuild_orchestration::run_output::models::OutputStore; use sqlbuild_orchestration::runs::types::RunHandoff; use sqlbuild_orchestration::store::errors::ControlError; use sqlbuild_orchestration::store::models::ControlStore; +use sqlbuild_orchestration::webhooks::constants::SECURITY_AUDIT_WEBHOOK_VARIABLE; +use sqlbuild_orchestration::webhooks::main::connect_webhook::connect_webhook; +use sqlbuild_orchestration::webhooks::main::run_webhook::run_webhook; +use sqlbuild_orchestration::webhooks::models::{Webhook, WebhookSource}; use tokio::sync::watch; use tokio::task::JoinSet; +use uuid::Uuid; use crate::argv::models::Stream; use crate::native_commands::_helpers::command::terminal::write_output; -use crate::native_commands::_helpers::location::execution::start_platform_roles; +use crate::native_commands::models::ApiStandby; /// Resolve once `shutdown` turns true or its sender is gone. async fn stopped(mut shutdown: watch::Receiver) { @@ -28,15 +34,11 @@ async fn stopped(mut shutdown: watch::Receiver) { /// Start the control API and the platform roles beside it, with the retention `facts` and `run_output` set. pub(crate) async fn start_api( mut tasks: JoinSet>, - (address, store, shutdown): (SocketAddr, &ControlStore, &watch::Receiver), + (standby, store, shutdown): (ApiStandby, &ControlStore, &watch::Receiver), (authentication, handoff, facts): (ApiAuthentication, RunHandoff, &ServerFacts), run_output: Option<(OutputStore, u16)>, ) -> Result>, ControlError> { - drop(write_output(&[( - Stream::Stderr, - "Starting control API...\n", - )])); - let listener = tokio::net::TcpListener::bind(address).await?; + let ApiStandby { listener, end } = standby; let address = listener.local_addr()?; tasks.spawn(serve_api( store.clone(), @@ -52,9 +54,10 @@ pub(crate) async fn start_api( stopped(shutdown.clone()), ), )); + end.send(()).unwrap_or_default(); start_platform_roles( &mut tasks, - (store, shutdown), + (store, shutdown, Some(&facts.health)), RetentionPolicies { audit: facts.audit, statistics: facts.statistics, @@ -66,3 +69,75 @@ pub(crate) async fn start_api( )?; Ok(tasks) } + +/// Health production and delivery remain native and independent of scheduler leadership. +pub(crate) fn start_platform_roles( + tasks: &mut JoinSet>, + (store, shutdown, health): (&ControlStore, &watch::Receiver, Option<&ServerHealth>), + retention: RetentionPolicies, +) -> Result<(), ControlError> { + let mut sinks: Vec<(Webhook, &str)> = Vec::new(); + for (variable, source, label) in [ + ( + PLATFORM_WEBHOOK_VARIABLE, + WebhookSource::Platform, + "Platform", + ), + ( + SECURITY_AUDIT_WEBHOOK_VARIABLE, + WebhookSource::SecurityAudit, + "Security audit", + ), + ] { + match std::env::var(variable) { + Ok(endpoint) => sinks.push((connect_webhook(&endpoint, source)?, label)), + Err(std::env::VarError::NotPresent) => {} + Err(_) => { + return Err(ControlError::Invalid(format!( + "{label} webhook configuration must be UTF-8" + ))); + } + } + } + drop(write_output(&[( + Stream::Stderr, + "Starting platform maintenance...\n", + )])); + let maintenance_store = store.clone(); + let maintenance_shutdown = shutdown.clone(); + let audit_sinks: Vec = sinks.iter().map(|(sink, _)| sink.clone()).collect(); + tasks.spawn(async move { + let report = |retained: i64| { + drop(write_output(&[( + Stream::Stderr, + &format!("Security audit retention: retained past horizon: {retained}\n"), + )])); + }; + run_maintenance( + (&maintenance_store, Uuid::now_v7()), + (retention, &audit_sinks), + (report, maintenance_shutdown), + ) + .await + }); + drop(write_output(&[( + Stream::Stderr, + "Platform maintenance started\n", + )])); + for (sink, label) in sinks { + drop(write_output(&[( + Stream::Stderr, + &format!("Starting {label} webhook...\n"), + )])); + tasks.spawn(run_webhook( + (store.clone(), health.cloned()), + sink, + shutdown.clone(), + )); + drop(write_output(&[( + Stream::Stderr, + &format!("{label} webhook started\n"), + )])); + } + Ok(()) +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs index 402e372107..299f2bd9d2 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/execution.rs @@ -34,6 +34,7 @@ use crate::native_commands::_helpers::command::terminal::{ finish_lost_stdout, terminal_columns, write_output, }; use crate::native_commands::_helpers::command::terminal::{live_screen, screen_colour}; +use crate::native_commands::_helpers::location::api_start::start_platform_roles; use crate::native_commands::_helpers::location::dev_cancel::DevRuns; use crate::native_commands::_helpers::location::dev_exposure::{ allowed_hosts, connect_address, exposure, listens_beyond_loopback, @@ -68,7 +69,8 @@ use crate::native_commands::models::AdminDone; use crate::native_commands::models::{ CommandOutput, DevControlState, InstalledPackage, LocationCompileRequest, LocationCompiler, LocationMetadataPage, LocationMetadataSync, LocationServe, LocationWatch, LostStdout, - MetadataReply, NativeCommand, NativeInvocation, ProjectLocation, ScanToken, + MetadataReply, NativeCommand, NativeInvocation, ProjectLocation, ScanToken, SinkTally, + SyncStreak, }; use crate::native_commands::models::{LoadedGeneration, PendingRepublish}; use crate::native_commands::models::{ @@ -111,14 +113,13 @@ use sqlbuild_orchestration::dev_events::main::emit_dev_event::emit_dev_event; use sqlbuild_orchestration::dev_events::main::parse_dev_control::parse_dev_control; use sqlbuild_orchestration::dev_events::main::parse_dev_event::parse_dev_event; use sqlbuild_orchestration::dev_events::models::{DevControl, DevEvent}; -use sqlbuild_orchestration::platform::constants::PLATFORM_WEBHOOK_VARIABLE; +use sqlbuild_orchestration::health::models::ServerHealth; use sqlbuild_orchestration::platform::main::health::report_remote_location_health::report_remote_location_health; -use sqlbuild_orchestration::platform::main::installation::run_maintenance::run_maintenance; use sqlbuild_orchestration::platform::models::ConnectionCheckTrigger; use sqlbuild_orchestration::platform::models::LocationRuleFailure; use sqlbuild_orchestration::platform::models::PublishedGeneration; use sqlbuild_orchestration::platform::models::{ - LocationHealth, LocationHealthReport, LocationWorkClient, LocationWorkPoll, RetentionPolicies, + LocationHealth, LocationHealthReport, LocationWorkClient, LocationWorkPoll, WarehouseSyncFailure, }; use sqlbuild_orchestration::run_output::main::open_output_store::open_output_store; @@ -140,10 +141,6 @@ use sqlbuild_orchestration::warehouse_metadata::models::{ WarehouseWatermarkRead, }; use sqlbuild_orchestration::webhooks::constants::SECURITY_AUDIT_WEBHOOK_VARIABLE; -use sqlbuild_orchestration::webhooks::main::{ - connect_webhook::connect_webhook, run_webhook::run_webhook, -}; -use sqlbuild_orchestration::webhooks::models::{Webhook, WebhookSource}; use std::collections::{BTreeMap, HashMap}; use std::future::Future; use std::io; @@ -154,7 +151,6 @@ use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; use tokio::process::{Child, Command}; use tokio::sync::mpsc::UnboundedSender; use tokio::sync::{mpsc, oneshot, watch}; -use tokio::task::JoinSet; use tokio::time::{Instant, Interval, MissedTickBehavior}; use uuid::Uuid; @@ -180,6 +176,7 @@ pub(crate) async fn run_development_roles( (url.clone(), written.clone()), )?; let (stop, shutdown) = watch::channel(false); + let health = ServerHealth::new(env!("CARGO_PKG_VERSION"), scheduler); let mut roles: DevRoles = DevRoles::default(); drop(messages.send(ScreenMessage::Started { step: DevStep::Api, @@ -200,6 +197,7 @@ pub(crate) async fn run_development_roles( ServerFacts { version: env!("CARGO_PKG_VERSION").into(), scheduler, + health: health.clone(), output: Some(output.clone()), ..ServerFacts::default() }, @@ -218,7 +216,11 @@ pub(crate) async fn run_development_roles( ), ), ); - start_platform_roles(&mut roles.tasks, (&store, &shutdown), Default::default())?; + start_platform_roles( + &mut roles.tasks, + (&store, &shutdown, Some(&health)), + Default::default(), + )?; let (location, pipes) = development_location_role( (&project, &executable), (location_id, &target), @@ -257,7 +259,9 @@ pub(crate) async fn run_development_roles( roles.spawn(Some("scheduler"), async move { run_scheduler( &scheduler_store, - SchedulerState::new(Uuid::now_v7()).with_origin(origin), + SchedulerState::new(Uuid::now_v7()) + .with_origin(origin) + .with_health(health), shutdown, workers, ) @@ -579,6 +583,7 @@ pub(crate) fn metadata_sync( safety_seconds, safety_at: Instant::now() + Duration::from_secs(safety_seconds), failed_reads: 0, + streak: SyncStreak::default(), halted: false, change_tokens: HashMap::new(), scan_token: None, @@ -1126,76 +1131,6 @@ pub(crate) fn location_child(options: &LocationServe, script: &Path) -> Command command } -/// Health production and delivery remain native and independent of scheduler leadership. -pub(crate) fn start_platform_roles( - tasks: &mut JoinSet>, - (store, shutdown): (&ControlStore, &watch::Receiver), - retention: RetentionPolicies, -) -> Result<(), ControlError> { - let mut sinks: Vec<(Webhook, &str)> = Vec::new(); - for (variable, source, label) in [ - ( - PLATFORM_WEBHOOK_VARIABLE, - WebhookSource::Platform, - "Platform", - ), - ( - SECURITY_AUDIT_WEBHOOK_VARIABLE, - WebhookSource::SecurityAudit, - "Security audit", - ), - ] { - match std::env::var(variable) { - Ok(endpoint) => sinks.push((connect_webhook(&endpoint, source)?, label)), - Err(std::env::VarError::NotPresent) => {} - Err(_) => { - return Err(ControlError::Invalid(format!( - "{label} webhook configuration must be UTF-8" - ))); - } - } - } - drop(write_output(&[( - Stream::Stderr, - "Starting platform maintenance...\n", - )])); - let maintenance_store = store.clone(); - let maintenance_shutdown = shutdown.clone(); - let audit_sinks: Vec = sinks.iter().map(|(sink, _)| sink.clone()).collect(); - tasks.spawn(async move { - let report = |retained: i64| { - drop(write_output(&[( - Stream::Stderr, - &format!("Security audit retention: retained past horizon: {retained}\n"), - )])); - }; - run_maintenance( - (&maintenance_store, Uuid::now_v7()), - (retention, &audit_sinks), - (report, maintenance_shutdown), - ) - .await - }); - drop(write_output(&[( - Stream::Stderr, - "Platform maintenance started\n", - )])); - for (sink, label) in sinks { - drop(write_output(&[( - Stream::Stderr, - &format!("Starting {label} webhook...\n"), - )])); - let sink_store = store.clone(); - let sink_shutdown = shutdown.clone(); - tasks.spawn(async move { run_webhook(&sink_store, sink, sink_shutdown).await }); - drop(write_output(&[( - Stream::Stderr, - &format!("{label} webhook started\n"), - )])); - } - Ok(()) -} - /// Dispatch maintenance actions without implicitly initializing or upgrading their store. pub(crate) async fn run_control_action( namespace: &Namespace, @@ -1379,6 +1314,7 @@ pub(crate) fn open_location_runtime( stdin, stdout: BufReader::new(stdout), python_sources, + sinks: SinkTally::default(), }) } @@ -1514,6 +1450,7 @@ async fn exchange_metadata_read( let failed = |reason: &str, page_size| WarehouseHistoryFailure { reason: reason.into(), page_size, + connection: false, }; let result = async { let written: std::io::Result<()> = async { diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/health.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/health.rs index 9876d7b010..6a656cf437 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/health.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/health.rs @@ -1,6 +1,22 @@ -//! What `sqb location health` exits with for each state. +//! What `sqb location health` exits with for each state, and what the location's interpreters' sinks delivered. -use sqlbuild_orchestration::platform::models::LocationState; +use std::time::Duration; + +use sqlbuild_orchestration::platform::constants::SINK_DELIVERIES_REQUEST; +use sqlbuild_orchestration::platform::models::{LocationHealth, LocationState, SinkDeliveryTotals}; +use sqlbuild_orchestration::runs::models::SinkDelivery; +use sqlbuild_orchestration::store::errors::ControlError; +use tokio::time::Instant; + +use uuid::Uuid; + +use crate::argv::models::Stream; +use crate::native_commands::_helpers::command::terminal::write_output; +use crate::native_commands::_helpers::location::execution::{ + exchange_reply, report_location_health, stop_location_runtime, +}; +use crate::native_commands::constants::{SINK_CHECK_SECONDS, SINK_CHECK_TIMEOUT_SECONDS}; +use crate::native_commands::models::{LocationCompiler, LocationServe, SinkTally}; use crate::native_commands::constants::STARTING_EXIT_CODE; @@ -18,3 +34,101 @@ pub(crate) fn health_exit_code(state: LocationState, allow_starting: bool) -> i3 | LocationState::Degraded => 1, } } + +/// Each sink's change between two totals, keeping only sinks that took events or lost some. +pub(crate) fn sink_interval( + previous: &[SinkDelivery], + current: &[SinkDelivery], +) -> Vec { + let mut changed: Vec = Vec::new(); + for sink in current { + let before: Option<&SinkDelivery> = + previous.iter().find(|earlier| earlier.name == sink.name); + let since = + |count: fn(&SinkDelivery) -> u64| count(sink).saturating_sub(before.map_or(0, count)); + let interval = SinkDelivery { + name: sink.name.clone(), + accepted: since(|sink| sink.accepted), + delivered: since(|sink| sink.delivered), + dropped: since(|sink| sink.dropped), + failed: since(|sink| sink.failed), + }; + if interval.accepted > 0 || interval.dropped > 0 || interval.failed > 0 { + changed.push(interval); + } + } + changed +} + +/// When `compiler` is next due a sink check. +pub(crate) fn sink_due(compiler: &LocationCompiler) -> Instant { + compiler + .sinks + .checked_at + .map_or_else(Instant::now, |checked| { + checked + Duration::from_secs(SINK_CHECK_SECONDS) + }) +} + +/// Once due, ask `compiler` what its sinks delivered: it back, with the interval's report if they took or lost events. +pub(crate) async fn sink_check( + mut compiler: LocationCompiler, +) -> ( + LocationCompiler, + Result, ControlError>, +) { + if sink_due(&compiler) > Instant::now() { + return (compiler, Ok(None)); + } + let request = serde_json::json!({ SINK_DELIVERIES_REQUEST: {} }); + let answered = tokio::time::timeout( + Duration::from_secs(SINK_CHECK_TIMEOUT_SECONDS), + exchange_reply::(&mut compiler, &request, "sink delivery totals"), + ) + .await; + let totals: SinkDeliveryTotals = match answered { + Ok(Ok(totals)) => totals, + Ok(Err(error)) => return (compiler, Err(error)), + Err(_) => { + let silent = "the interpreter didn't say what its sinks delivered"; + return (compiler, Err(ControlError::Invalid(silent.into()))); + } + }; + let sinks: Vec = sink_interval(&compiler.sinks.totals, &totals.sinks); + compiler.sinks = SinkTally { + totals: totals.sinks, + checked_at: Some(Instant::now()), + }; + ( + compiler, + Ok((!sinks.is_empty()).then_some(LocationHealth::SinkDeliveries { sinks })), + ) +} + +/// Report what an idle `compiler`'s sinks delivered once due; an interpreter that can't say is stopped. +pub(crate) async fn report_compiler_sinks( + compiler: Option, + (options, (bearer, session_id)): (&LocationServe, (&str, Uuid)), +) -> Result, ControlError> { + let Some(active) = compiler else { + return Ok(None); + }; + let (active, checked) = sink_check(active).await; + match checked { + Ok(None) => Ok(Some(active)), + Ok(Some(health)) => { + report_location_health(options, bearer, session_id, health).await; + Ok(Some(active)) + } + Err(error) => { + drop(write_output(&[( + Stream::Stderr, + &format!( + "Checking event sink deliveries failed: {error}; the location restarts its interpreter\n" + ), + )])); + stop_location_runtime(Some(active)).await?; + Ok(None) + } + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs index a7dd6bb746..2aa45b5062 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/mod.rs @@ -1,3 +1,4 @@ +pub(crate) mod api_standby; pub(crate) mod api_start; pub(crate) mod changed_build; pub(crate) mod compile_turn; diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/sync_outcomes.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/sync_outcomes.rs index 72fb8c532a..6506e23c15 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/sync_outcomes.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/sync_outcomes.rs @@ -28,6 +28,7 @@ pub(crate) fn retry_metadata( error: ClientError, ) -> Result, ControlError> { refuse_rejected_sign_in(&error)?; + state.note_failure(chrono::Utc::now()); state.next_at = Instant::now() + Duration::from_secs(METADATA_POLL_SECONDS); state.reader = None; location_warning( @@ -56,7 +57,8 @@ pub(crate) async fn failed_read( } else { WarehouseSyncFailure::Read }; - let halts: bool = !busy && state.halts(failure.page_size()); + let unreached: bool = failure.unreached(); + let halts: bool = !busy && state.halts((failure.page_size(), unreached)); tokio::select! { result = stopped => { result?; return Ok(None); }, () = report_metadata_health(&state, (client, poll), (started, Some(stage), Some((&failure, halts)))) => {}, @@ -66,8 +68,18 @@ pub(crate) async fn failed_read( return Ok(Some(state)); } let line: String = read_failure_line(&state, &failure); - let shrinks: bool = state.shrinks(failure.page_size()); - let outcome: String = match state.fail_read(failure.page_size()) { + let shrinks: bool = !unreached && state.shrinks(failure.page_size()); + let outcome: String = match state.fail_read((failure.page_size(), unreached)) { + Some(wait) if unreached => { + location_warning( + "warehouse unreachable", + format!("retrying in {}s: {}", wait.as_secs(), failure.reason()), + ); + format!( + " Run history can't reach the warehouse; no compute ran. Retrying in {} s; this never stops the sync.\n", + wait.as_secs() + ) + } Some(wait) if shrinks => { format!( " Sync incomplete; retaining mirror and retrying a smaller page in {} s.\n", @@ -141,5 +153,8 @@ pub(crate) async fn deliver_metadata_page( result = &mut stopped => { result?; return Ok(None); }, () = metadata_health(&state, (client, poll), (started, None)) => {}, } + if state.pending.is_some() { + state.note_delivered(); + } finish_metadata_page(acknowledge_metadata_page(state), stopped).await } diff --git a/crates/sqlbuild-cli/src/native_commands/_helpers/location/sync_report.rs b/crates/sqlbuild-cli/src/native_commands/_helpers/location/sync_report.rs index 45cc7ab425..b8f55a145b 100644 --- a/crates/sqlbuild-cli/src/native_commands/_helpers/location/sync_report.rs +++ b/crates/sqlbuild-cli/src/native_commands/_helpers/location/sync_report.rs @@ -12,11 +12,15 @@ use uuid::Uuid; use crate::argv::models::Stream; use crate::native_commands::_helpers::command::terminal::write_output; -use crate::native_commands::_helpers::location::execution::location_warning; +use crate::native_commands::_helpers::location::execution::{ + location_warning, stop_location_runtime, +}; +use crate::native_commands::_helpers::location::health::sink_check; use crate::native_commands::constants::{ METADATA_ERROR_CHARS, METADATA_POLL_SECONDS, STATISTICS_RELATION_SECONDS, }; use crate::native_commands::models::{LocationMetadataSync, ReadFailure}; +use sqlbuild_orchestration::store::errors::ControlError; /// One table's line as its scan completes, e.g. `Warehouse history 3/14: audit results, 1,204 rows in 0.8 s`. pub(crate) fn scan_line(state: &LocationMetadataSync, scans: usize) -> String { @@ -111,6 +115,13 @@ pub(crate) fn metadata_health_of( completed_sync_next_at(state, failure, now) }; let read_failure = read.and_then(|(read, _)| read.cause()); + let waits: u64 = state + .next_at + .saturating_duration_since(Instant::now()) + .as_secs(); + let retry_at = (failure.is_some_and(|failure| failure != WarehouseSyncFailure::Busy) + && !halted) + .then(|| (now + chrono::TimeDelta::seconds(waits as i64), waits)); LocationHealth::WarehouseSync { generation: state.generation, location: state.location().clone(), @@ -132,6 +143,9 @@ pub(crate) fn metadata_health_of( }), next_sync_at, mirrored_records: state.progress.scan_mirrored, + failing_since: state.streak.failing_since.filter(|_| failure.is_some()), + retry_at: retry_at.map(|(at, _)| at), + retry_seconds: retry_at.map(|(_, seconds)| seconds), } } @@ -212,3 +226,55 @@ pub(crate) fn read_failure_line(state: &LocationMetadataSync, failure: &ReadFail failure.reason(), ) } + +/// Log that the sync recovered, once it `completed` after a failing streak. +pub(crate) fn report_recovery(state: &mut LocationMetadataSync, completed: bool) { + let Some(line) = completed + .then(|| state.take_recovery_line(Utc::now())) + .flatten() + else { + return; + }; + drop(write_output(&[(Stream::Stderr, &line)])); +} + +/// Report what the reader's sinks delivered once due; a reader that can't say is stopped. +pub(crate) async fn report_reader_sinks( + mut state: LocationMetadataSync, + (client, poll): (&LocationWorkClient, &LocationWorkPoll), +) -> Result { + let Some(reader) = state.reader.take() else { + return Ok(state); + }; + let (reader, checked) = sink_check(reader).await; + let health = match checked { + Ok(health) => health, + Err(error) => { + drop(write_output(&[( + Stream::Stderr, + &format!( + "Checking event sink deliveries failed: {error}; the location restarts its reader\n" + ), + )])); + stop_location_runtime(Some(reader)).await?; + return Ok(state); + } + }; + state.reader = Some(reader); + let Some(health) = health else { + return Ok(state); + }; + let report = LocationHealthReport { + event_id: Uuid::now_v7(), + session_id: poll.session_id, + target: poll.target.clone(), + health, + }; + if let Err(error) = client.report_health(&report).await { + drop(write_output(&[( + Stream::Stderr, + &format!("Event sink delivery report failed: {error}\n"), + )])); + } + Ok(state) +} diff --git a/crates/sqlbuild-cli/src/native_commands/constants.rs b/crates/sqlbuild-cli/src/native_commands/constants.rs index ae61acdb36..edb1ddab10 100644 --- a/crates/sqlbuild-cli/src/native_commands/constants.rs +++ b/crates/sqlbuild-cli/src/native_commands/constants.rs @@ -93,6 +93,9 @@ pub(crate) const ADMIN_OPEN_NOTICE: std::time::Duration = std::time::Duration::f pub(crate) const OPENING_STORE: &str = "Opening control store...\n"; /// Printed when the control store is open. pub(crate) const STORE_READY: &str = "Control store ready\n"; +/// The first wait before opening an unreachable control store again; each retry doubles it up to `STORE_RETRY_MAX`. +pub(crate) const STORE_RETRY_FIRST: std::time::Duration = std::time::Duration::from_secs(1); +pub(crate) const STORE_RETRY_MAX: std::time::Duration = std::time::Duration::from_secs(30); /// An admin command committed, and its result didn't reach stdout. pub(crate) const ADMIN_DELIVERY_FAILED: &str = "Control administration result delivery failed; changes may already be committed\n"; @@ -175,6 +178,20 @@ pub(crate) const SENSOR_RESULT_BYTES: u64 = 1_048_576; /// Read timeout, and the delay before retrying a failed page of an unfinished synchronization. pub(crate) const METADATA_POLL_SECONDS: u64 = 30; +/// The longest wait between attempts of a failing run-history sync, whatever failed. +pub(crate) const METADATA_RETRY_MAX_SECONDS: u64 = 60; +/// Fragments of connector and resolver messages for a warehouse the reader never reached, lowercase. +pub(crate) const UNREACHED_WAREHOUSE_MESSAGES: [&str; 9] = [ + "250001", + "could not connect", + "failed to lookup address", + "name or service not known", + "temporary failure in name resolution", + "nodename nor servname", + "connection refused", + "network is unreachable", + "no route to host", +]; /// Failed reads in a row, waiting twice as long after each, that stop a sync until one is requested. pub(crate) const METADATA_FAILURE_LIMIT: u32 = 5; @@ -283,3 +300,9 @@ pub(crate) const LOOKUP_FAILURES_REPORTED: u32 = 3; /// The most characters of a failed load's error a location reports; the server refuses more. pub(crate) const MAX_LOAD_ERROR_CHARS: usize = 4000; + +/// How often a location asks each idle interpreter what its event sinks delivered. +pub(crate) const SINK_CHECK_SECONDS: u64 = 60; + +/// How long an interpreter may take to say what its event sinks delivered. +pub(crate) const SINK_CHECK_TIMEOUT_SECONDS: u64 = 10; diff --git a/crates/sqlbuild-cli/src/native_commands/main/_location_compiler.rs b/crates/sqlbuild-cli/src/native_commands/main/_location_compiler.rs index 4a00e7f3c8..9581589acc 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_location_compiler.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_location_compiler.rs @@ -16,6 +16,7 @@ use crate::native_commands::_helpers::location::execution::exchange_reply; use crate::native_commands::_helpers::location::execution::{ open_location_runtime, stop_location_runtime, }; +use crate::native_commands::_helpers::location::health::{report_compiler_sinks, sink_due}; use crate::native_commands::models::{ LocationCompileRequest, LocationCompiler, LocationLoad, LocationPlanRequest, LocationRuntimeRequest, LocationServe, @@ -34,14 +35,19 @@ pub(crate) async fn run_location_compiler( let result = async { loop { let due: Option = discovery.next_due().filter(|_| compiler.is_some()); + let sinks_due: Option = compiler.as_ref().map(sink_due); let request: Option = tokio::select! { request = requests.recv() => match request { Some(request) => Some(request), None => break, }, - () = sleep_until(due) => None, + () = sleep_until(due.into_iter().chain(sinks_due).min()) => None, }; let Some(request) = request else { + compiler = report_compiler_sinks(compiler.take(), (options, controls.1)).await?; + if due.is_none_or(|due| due > Instant::now()) { + continue; + } compiler = check_discovered(compiler.take(), &mut discovery, (controls, &requests)) .await?; if requests.is_closed() { diff --git a/crates/sqlbuild-cli/src/native_commands/main/_location_metadata.rs b/crates/sqlbuild-cli/src/native_commands/main/_location_metadata.rs index 4075792e6b..f074fd045f 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_location_metadata.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_location_metadata.rs @@ -16,6 +16,7 @@ use crate::native_commands::_helpers::location::execution::{ use crate::native_commands::_helpers::location::sync_outcomes::{ deliver_metadata_page, failed_read, retry_metadata, }; +use crate::native_commands::_helpers::location::sync_report::report_reader_sinks; use crate::native_commands::_helpers::location::sync_report::{metadata_health, resumed_line}; use crate::native_commands::constants::METADATA_PAGE_SECONDS; use crate::native_commands::models::{LocationMetadataSync, LocationServe, LocationWatch}; @@ -91,6 +92,7 @@ pub(crate) async fn sync_location_metadata( .await; } }; + state = report_reader_sinks(state, (client, poll)).await?; if location_files( &options.project_dir, &watch.rules, diff --git a/crates/sqlbuild-cli/src/native_commands/main/_run_control.rs b/crates/sqlbuild-cli/src/native_commands/main/_run_control.rs index 666c7657e1..4bba9194a5 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_run_control.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_run_control.rs @@ -1,5 +1,6 @@ //! Supervise native API/scheduler roles together; a failed role stops its siblings. +use sqlbuild_orchestration::health::models::ServerHealth; use sqlbuild_orchestration::scheduler::main::run_scheduler::run_scheduler; use sqlbuild_orchestration::scheduler::models::SchedulerState; use sqlbuild_orchestration::store::errors::ControlError; @@ -13,6 +14,7 @@ use crate::native_commands::_helpers::command::decision::{ control_address, control_api_settings, control_output, }; use crate::native_commands::_helpers::command::terminal::write_output; +use crate::native_commands::_helpers::location::api_standby::{open_store_waiting, start_standby}; use crate::native_commands::_helpers::location::api_start::start_api; use crate::native_commands::_helpers::location::execution::{ open_control_store, open_control_workers, @@ -28,7 +30,14 @@ pub(crate) async fn run_control( let config = read_server_config(namespace)?; let address = control_address(namespace, standalone, &config.server)?; let (authentication, mut facts) = control_api_settings(namespace, standalone, &config)?; - let store = open_control_store(namespace, Some(&config.server)).await?; + let standby = match address { + Some(address) => Some(start_standby(address, &facts.health).await?), + None => None, + }; + let store = match standby { + Some(_) => open_store_waiting(namespace, &config.server, &facts.health).await?, + None => open_control_store(namespace, Some(&config.server)).await?, + }; let run_output = control_output(namespace, &config, (&store, &mut facts))?; let (workers, handoff) = open_control_workers( (&store, namespace), @@ -39,17 +48,22 @@ pub(crate) async fn run_control( facts.pool_caps = workers.pool_caps(); let (stop, shutdown) = watch::channel(false); let mut tasks = JoinSet::new(); - if let Some(address) = address { + if let Some(standby) = standby { tasks = start_api( tasks, - (address, &store, &shutdown), + (standby, &store, &shutdown), (authentication, handoff, &facts), run_output, ) .await?; } if facts.scheduler { - start_scheduler(&mut tasks, (store, facts.origin.clone()), shutdown, workers); + start_scheduler( + &mut tasks, + (store, facts.origin.clone(), facts.health.clone()), + shutdown, + workers, + ); } supervise_control_roles(tasks, stop).await } @@ -57,7 +71,7 @@ pub(crate) async fn run_control( /// Start the scheduler, whose sensor events link runs under `origin`. fn start_scheduler( tasks: &mut JoinSet>, - (store, origin): (ControlStore, Option), + (store, origin, health): (ControlStore, Option, ServerHealth), shutdown: watch::Receiver, workers: Workers, ) { @@ -65,7 +79,9 @@ fn start_scheduler( tasks.spawn(async move { run_scheduler( &store, - SchedulerState::new(Uuid::now_v7()).with_origin(origin), + SchedulerState::new(Uuid::now_v7()) + .with_origin(origin) + .with_health(health), shutdown, workers, ) diff --git a/crates/sqlbuild-cli/src/native_commands/main/_run_location.rs b/crates/sqlbuild-cli/src/native_commands/main/_run_location.rs index dc256e329c..ce58d70867 100644 --- a/crates/sqlbuild-cli/src/native_commands/main/_run_location.rs +++ b/crates/sqlbuild-cli/src/native_commands/main/_run_location.rs @@ -25,6 +25,7 @@ use crate::native_commands::_helpers::location::execution::{ }; use crate::native_commands::_helpers::location::republish::start_republish; use crate::native_commands::_helpers::location::shutdown::shutdown_signal; +use crate::native_commands::_helpers::location::sync_report::report_recovery; use crate::native_commands::_helpers::location::work::next_work_check; use crate::native_commands::constants::LOCATION_WORK_IDLE_POLL; use crate::native_commands::main::_location_changed_build::report_changed_build; @@ -207,6 +208,7 @@ async fn poll_location( }; let unsynced: bool = state.locations.is_empty(); let completed: bool = syncing && state.idle && !state.halted; + report_recovery(state, completed); if (completed || unsynced) && state.take_replan() { let Some(reported) = report_changed_build( (options, runtime, &watch), diff --git a/crates/sqlbuild-cli/src/native_commands/models.rs b/crates/sqlbuild-cli/src/native_commands/models.rs index bc2648c325..5629423399 100644 --- a/crates/sqlbuild-cli/src/native_commands/models.rs +++ b/crates/sqlbuild-cli/src/native_commands/models.rs @@ -23,7 +23,9 @@ use sqlbuild_orchestration::warehouse_metadata::models::{ use uuid::{NoContext, Timestamp, Uuid}; use crate::argv::models::Namespace; -use crate::native_commands::constants::{METADATA_FAILURE_LIMIT, METADATA_POLL_SECONDS}; +use crate::native_commands::constants::{ + METADATA_FAILURE_LIMIT, METADATA_POLL_SECONDS, METADATA_RETRY_MAX_SECONDS, +}; /// Privileged local operations require direct ownership of the control database. pub(crate) enum ControlAdmin { @@ -371,6 +373,15 @@ pub(crate) struct LocationCompiler { pub(crate) stdin: tokio::process::ChildStdin, pub(crate) stdout: tokio::io::BufReader, pub(crate) python_sources: Vec, + /// What this interpreter's sinks had delivered at its last check. + pub(crate) sinks: SinkTally, +} + +/// An interpreter's sink totals at its last check, and when that was; `None` before the first. +#[derive(Debug, Default)] +pub(crate) struct SinkTally { + pub(crate) totals: Vec, + pub(crate) checked_at: Option, } /// A delivered source page remains frozen until the API acknowledges it. @@ -411,6 +422,8 @@ pub(crate) struct LocationMetadataSync { pub(crate) safety_at: tokio::time::Instant, /// Failed reads in a row that did not shrink the page; a delivered page resets it. pub(crate) failed_reads: u32, + /// The failing streak, and the recovery after one. + pub(crate) streak: SyncStreak, /// Failed reads in a row stopped the sync; it rests idle until a run, a request, a publish or a safety sync. pub(crate) halted: bool, /// Per scan index: the table's change token after its last complete read. @@ -497,10 +510,23 @@ impl ReadFailure { } } + /// Whether the reader never reached the warehouse, so no billed compute ran. + pub(crate) fn unreached(&self) -> bool { + let Self::Read(failure) = self else { + return false; + }; + let reason: String = failure.reason.to_ascii_lowercase(); + failure.connection + || crate::native_commands::constants::UNREACHED_WAREHOUSE_MESSAGES + .iter() + .any(|fragment| reason.contains(fragment)) + } + /// The closed cause a health report carries; a busy warehouse file is no failure. pub(crate) fn cause(&self) -> Option { match self { Self::Busy => None, + Self::Read(_) if self.unreached() => Some(WarehouseReadFailure::Unreachable {}), Self::ReaderStart(_) | Self::Read(_) => Some(WarehouseReadFailure::ReadError {}), Self::TimedOut(seconds) => Some(WarehouseReadFailure::TimedOut { seconds: *seconds }), } @@ -613,14 +639,47 @@ impl LocationMetadataSync { page_size && limit > 1 } - /// Whether a failed read stops the sync: it does not shrink the page and is the last failure allowed. - pub(crate) fn halts(&self, page_size: bool) -> bool { - !self.shrinks(page_size) && self.failed_reads + 1 >= METADATA_FAILURE_LIMIT + /// Whether a failed read stops the sync: it reached the warehouse, can't shrink the page and is the last allowed. + pub(crate) fn halts(&self, (page_size, unreached): (bool, bool)) -> bool { + !unreached && !self.shrinks(page_size) && self.failed_reads + 1 >= METADATA_FAILURE_LIMIT } - /// Record a failed read and return the wait before the next one; `None` once failures stop the sync. - pub(crate) fn fail_read(&mut self, page_size: bool) -> Option { - let shrinks: bool = self.shrinks(page_size); + /// Start the failing streak at server time `now`, unless one is already running. + pub(crate) fn note_failure(&mut self, now: DateTime) { + self.streak + .failing_since + .get_or_insert(now + self.server_offset); + self.streak.recovering = None; + } + + /// A page was delivered: the streak ends, and the pages caught up since are counted for the recovery line. + pub(crate) fn note_delivered(&mut self) { + if let Some(since) = self.streak.failing_since.take() { + self.streak.recovering = Some((since, 0)); + } + if let Some((_, pages)) = self.streak.recovering.as_mut() { + *pages += 1; + } + self.streak.unreached_reads = 0; + } + + /// Once a sync completes after a failing streak, the line saying how long it failed and what it caught up. + pub(crate) fn take_recovery_line(&mut self, now: DateTime) -> Option { + let (since, pages) = self.streak.recovering.take()?; + let minutes: i64 = ((now + self.server_offset) - since).num_minutes().max(0); + let noun: &str = if pages == 1 { "page" } else { "pages" }; + Some(format!( + "Run history sync recovered after {minutes} min; {pages} {noun} caught up.\n" + )) + } + + /// Record a failed read and return the wait, at most a minute; `None` once reads that reached the warehouse stop it. + pub(crate) fn fail_read( + &mut self, + (page_size, unreached): (bool, bool), + ) -> Option { + self.note_failure(Utc::now()); + let shrinks: bool = !unreached && self.shrinks(page_size); self.statistics = None; let statistics = self.kind() == WarehouseHistoryKind::Statistics; if statistics { @@ -635,7 +694,10 @@ impl LocationMetadataSync { } else { &mut self.limit }; - let seconds = if shrinks { + let seconds = if unreached { + self.streak.unreached_reads += 1; + METADATA_POLL_SECONDS << (self.streak.unreached_reads - 1).min(1) + } else if shrinks { *limit /= 2; METADATA_POLL_SECONDS } else { @@ -648,9 +710,9 @@ impl LocationMetadataSync { + std::time::Duration::from_secs(self.safety_seconds); return None; } - METADATA_POLL_SECONDS << (self.failed_reads - 1) + METADATA_POLL_SECONDS << (self.failed_reads - 1).min(1) }; - let wait = std::time::Duration::from_secs(seconds); + let wait = std::time::Duration::from_secs(seconds.min(METADATA_RETRY_MAX_SECONDS)); self.next_at = tokio::time::Instant::now() + wait; Some(wait) } @@ -875,3 +937,23 @@ impl GenerationLookups { self.last.map_or(1, |generation| generation + 1) } } + +/// The server's bound address while its standby answers there, until the control API takes it over. +#[derive(Debug)] +pub(crate) struct ApiStandby { + /// The API's own handle on the bound socket. + pub(crate) listener: tokio::net::TcpListener, + /// Ends the standby, which finishes its open requests first. + pub(crate) end: tokio::sync::oneshot::Sender<()>, +} + +/// A run-history sync's failing streak: since when, unreached reads, and the pages caught up after it. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct SyncStreak { + /// Reads in a row that never reached the warehouse; they back off but never stop the sync. + pub(crate) unreached_reads: u32, + /// The first failure of the streak, by server time; `None` while the sync works. + pub(crate) failing_since: Option>, + /// After a streak: when it began and the pages delivered since it ended, for the recovery line. + pub(crate) recovering: Option<(DateTime, u64)>, +} diff --git a/crates/sqlbuild-cli/src/native_commands/tests.rs b/crates/sqlbuild-cli/src/native_commands/tests.rs index d64cf8e840..67753462a5 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests.rs @@ -26,6 +26,10 @@ mod project_facts; mod provider_secrets; #[path = "tests/test_rules.rs"] mod rules; +#[path = "tests/test_sink_checks.rs"] +mod sink_checks; +#[path = "tests/test_sync_recovery.rs"] +mod sync_recovery; #[path = "tests/test_sync_schedule.rs"] mod sync_schedule; #[path = "tests/test_terminal.rs"] diff --git a/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs b/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs index 4ee37e10da..125b870911 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests/helpers.rs @@ -326,6 +326,7 @@ pub(super) fn scripted_compiler(script: &str) -> crate::native_commands::models: stdout: tokio::io::BufReader::new(child.stdout.take().expect("interpreter output")), child, python_sources: Vec::new(), + sinks: crate::native_commands::models::SinkTally::default(), } } @@ -339,3 +340,44 @@ pub(crate) fn answered(lookups: &mut crate::native_commands::models::GenerationL lookups.answered(4); false } + +/// A server on a local port that answers `statuses` in turn, then `200`, each with `{"applied": true}`, and how many it answered. +pub(super) async fn answering_server( + statuses: &'static [u16], +) -> (String, std::sync::Arc) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("local port"); + let url = format!("http://{}", listener.local_addr().expect("address")); + let answered = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let counter = answered.clone(); + let application = axum::Router::new().fallback(move || { + let seen = counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let status = statuses.get(seen).copied().unwrap_or(200); + async move { + ( + axum::http::StatusCode::from_u16(status).expect("status"), + axum::Json(json!({ "applied": true })), + ) + } + }); + drop(tokio::spawn(async move { + axum::serve(listener, application).await + })); + (url, answered) +} + +/// `kafka`'s interval with `accepted`, `delivered` and `failed` events. +pub(super) fn kafka( + (accepted, delivered, failed): (u64, u64, u64), +) -> sqlbuild_orchestration::platform::models::LocationHealth { + sqlbuild_orchestration::platform::models::LocationHealth::SinkDeliveries { + sinks: vec![sqlbuild_orchestration::runs::models::SinkDelivery { + name: "kafka".into(), + accepted, + delivered, + dropped: 0, + failed, + }], + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_location_metadata.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_location_metadata.rs index b77835d974..b85c193735 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests/test_location_metadata.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_location_metadata.rs @@ -87,7 +87,7 @@ fn given_failed_metadata_read_when_back_at_statistics_then_page_shrinks_until_sc .iter() .position(|kind| *kind == test_case.failed_kind) .expect("kind is listed"); - let wait = state.fail_read(test_case.page_size); + let wait = state.fail_read((test_case.page_size, false)); assert!(wait.is_some(), "{}", test_case.description); let state = acknowledge_complete_pages(state, test_case.acknowledged_pages); assert_eq!( @@ -111,7 +111,7 @@ fn given_repeated_failed_reads_when_retrying_then_only_page_size_errors_shrink_a description: "a permission or missing-table error never shrinks the page, and a request ends its wait", failures: vec![false, false, false], failures_after_request: vec![], - expected_waits: vec![Some(30), Some(60), Some(120)], + expected_waits: vec![Some(30), Some(60), Some(60)], expected_limit: MAX_HISTORY_PAGE_RECORDS, expected_halted: false, expected_paging: (true, true), @@ -120,7 +120,7 @@ fn given_repeated_failed_reads_when_retrying_then_only_page_size_errors_shrink_a description: "the fifth failure in a row stops the sync, which then never pages", failures: vec![], failures_after_request: vec![false, false, false, false, false], - expected_waits: vec![Some(30), Some(60), Some(120), Some(240), None], + expected_waits: vec![Some(30), Some(60), Some(60), Some(60), None], expected_limit: MAX_HISTORY_PAGE_RECORDS, expected_halted: true, expected_paging: (true, false), @@ -138,7 +138,7 @@ fn given_repeated_failed_reads_when_retrying_then_only_page_size_errors_shrink_a description: "a sync request resumes a stopped sync with a fresh count", failures: vec![false, false, false, false, false], failures_after_request: vec![false], - expected_waits: vec![Some(30), Some(60), Some(120), Some(240), None, Some(30)], + expected_waits: vec![Some(30), Some(60), Some(60), Some(60), None, Some(30)], expected_limit: MAX_HISTORY_PAGE_RECORDS, expected_halted: false, expected_paging: (true, false), @@ -154,7 +154,11 @@ fn given_repeated_failed_reads_when_retrying_then_only_page_size_errors_shrink_a let mut waits: Vec> = test_case .failures .into_iter() - .map(|page_size| state.fail_read(page_size).map(|wait| wait.as_secs())) + .map(|page_size| { + state + .fail_read((page_size, false)) + .map(|wait| wait.as_secs()) + }) .collect(); state.request_sync(); (state.idle && state.sync_due(None)).then(|| state.begin_sync(Utc::now())); @@ -163,7 +167,11 @@ fn given_repeated_failed_reads_when_retrying_then_only_page_size_errors_shrink_a test_case .failures_after_request .into_iter() - .map(|page_size| state.fail_read(page_size).map(|wait| wait.as_secs())), + .map(|page_size| { + state + .fail_read((page_size, false)) + .map(|wait| wait.as_secs()) + }), ); assert_eq!( ( @@ -233,7 +241,8 @@ fn given_a_stopped_sync_when_a_run_or_its_safety_sync_resumes_it_then_failed_rea let mut state = metadata_sync((one_location(), 1), (3600, test_case.safety_seconds)); state.reads_wake_compute = test_case.billed; state.begin_sync(Utc::now()); - let stopped: Vec> = (0..5).map(|_| state.fail_read(false)).collect(); + let stopped: Vec> = + (0..5).map(|_| state.fail_read((false, false))).collect(); let stopped_for: Duration = state.safety_at.saturating_duration_since(Instant::now()); state.safety_at = Instant::now() + test_case.due_in; let runs_ended_at = test_case @@ -242,7 +251,7 @@ fn given_a_stopped_sync_when_a_run_or_its_safety_sync_resumes_it_then_failed_rea let resumed: bool = state.idle && state.sync_due(runs_ended_at); resumed.then(|| state.begin_sync(Utc::now())); let paging: bool = state.paging(); - let wait: Option = state.fail_read(false); + let wait: Option = state.fail_read((false, false)); assert_eq!( ( stopped[4], @@ -285,7 +294,7 @@ fn given_a_sync_stopped_mid_pass_when_a_later_run_resumes_it_then_the_pass_resta state.applied = true; state = acknowledge_complete_pages(state, statistics); (0..METADATA_FAILURE_LIMIT).for_each(|_| { - let _ = state.fail_read(false); + let _ = state.fail_read((false, false)); }); let stopped_at = state.cycle_started_at.expect("stop time"); let resumed: bool = state.sync_due(Some( @@ -753,6 +762,7 @@ fn given_a_failing_metadata_read_when_the_page_fails_then_the_cause_kind_and_pag == ReadFailure::Read(WarehouseHistoryFailure { reason: "permission denied for table _sqlbuild_audit_results".into(), page_size: false, + connection: false, }) }, expected_line: "Warehouse history read failed for audit results (2000-row page): permission denied for table _sqlbuild_audit_results.", @@ -999,6 +1009,7 @@ fn given_a_failed_read_when_reporting_health_then_it_carries_cause_error_and_whe ReadFailure::Read(WarehouseHistoryFailure { reason: "permission denied for table _sqlbuild_fingerprints".into(), page_size: false, + connection: false, }) }; let test_cases = [ @@ -1077,10 +1088,10 @@ fn given_a_failed_read_when_reporting_health_then_it_carries_cause_error_and_whe state.reads_wake_compute = test_case.billed; state.begin_sync(Utc::now()); (0..test_case.failures_before).for_each(|_| { - let _ = state.fail_read(false); + let _ = state.fail_read((false, false)); }); let page_size: bool = test_case.failure.page_size(); - let halts: bool = state.halts(page_size); + let halts: bool = state.halts((page_size, false)); let now = Utc::now(); let health = metadata_health_of( &state, diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_sink_checks.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_sink_checks.rs new file mode 100644 index 0000000000..fc69a89b9b --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_sink_checks.rs @@ -0,0 +1,93 @@ +//! A location asks each idle interpreter what its sinks delivered once a minute and reports each interval's change. + +use std::time::Duration; + +use sqlbuild_orchestration::platform::models::LocationHealth; +use uuid::Uuid; + +use crate::native_commands::_helpers::location::health::{report_compiler_sinks, sink_check}; +use crate::native_commands::tests::helpers::{ + answering_server, kafka, location_options, scripted_compiler, +}; +use crate::native_commands::tests::test_types::{SinkCheckTestCase, SinkReportTestCase}; + +const TOTALS: &str = "read line; echo '{\"sinks\":[{\"name\":\"kafka\",\"accepted\":4,\"delivered\":4,\"dropped\":0,\"failed\":0}]}'; \ + read line; echo '{\"sinks\":[{\"name\":\"kafka\",\"accepted\":120,\"delivered\":4,\"dropped\":0,\"failed\":116}]}'; exec sleep 600"; + +#[test] +fn given_an_interpreters_sink_totals_when_checked_then_each_due_check_reports_the_change_since_the_last() + { + let test_cases = [SinkCheckTestCase { + description: "a clean minute, a minute that failed every event, then a check that isn't due", + script: TOTALS, + minutes_passed: vec![1, 1, 0], + expected_reports: vec![Some(kafka((4, 4, 0))), Some(kafka((116, 0, 116))), None], + }]; + for test_case in test_cases { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime"); + let mut compiler = runtime.block_on(async { scripted_compiler(test_case.script) }); + let mut reports: Vec> = Vec::new(); + for minutes in &test_case.minutes_passed { + compiler.sinks.checked_at = compiler + .sinks + .checked_at + .map(|checked| checked - Duration::from_secs(61 * minutes)); + let (checked, report) = runtime.block_on(sink_check(compiler)); + compiler = checked; + reports.push(report.expect("sink check")); + } + assert_eq!( + reports, test_case.expected_reports, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_an_idle_interpreter_when_its_sinks_are_due_then_the_location_reports_them_or_restarts_a_silent_one() + { + let test_cases = [ + SinkReportTestCase { + description: "an interpreter that answers is kept and its interval reported", + script: TOTALS, + expected_outcome: (true, 1), + }, + SinkReportTestCase { + description: "an interpreter that answers nonsense is stopped and nothing reported", + script: "read line; echo 'not json'; exec sleep 600", + expected_outcome: (false, 0), + }, + ]; + for test_case in test_cases { + let directory = tempfile::tempdir().expect("temporary directory"); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime"); + let (url, answered) = runtime.block_on(answering_server(&[])); + let options = crate::native_commands::models::LocationServe { + server_url: url, + ..location_options(directory.path()) + }; + let compiler = runtime.block_on(async { scripted_compiler(test_case.script) }); + let kept = runtime + .block_on(report_compiler_sinks( + Some(compiler), + (&options, ("token", Uuid::nil())), + )) + .expect("no control error"); + assert_eq!( + ( + kept.is_some(), + answered.load(std::sync::atomic::Ordering::SeqCst), + ), + test_case.expected_outcome, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_sync_recovery.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_sync_recovery.rs new file mode 100644 index 0000000000..0df5c8ea99 --- /dev/null +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_sync_recovery.rs @@ -0,0 +1,122 @@ +//! A failing sync waits at most a minute, never stops for an unreached warehouse, and resumes once the server answers. + +use chrono::Utc; +use sqlbuild_orchestration::platform::main::work::connect_location_work::connect_location_work; +use sqlbuild_orchestration::warehouse_metadata::models::{MetadataBatch, WarehouseHistoryKind}; +use tokio::time::Instant; + +use crate::native_commands::_helpers::location::execution::metadata_sync; +use crate::native_commands::_helpers::location::sync_outcomes::deliver_metadata_page; +use crate::native_commands::models::LocationMetadataPage; +use crate::native_commands::tests::helpers::{answering_server, one_location, published_location}; +use crate::native_commands::tests::test_types::{ServerRecoveryTestCase, UnreachedReadsTestCase}; + +#[test] +fn given_reads_that_never_reach_the_warehouse_when_retrying_then_they_wait_at_most_a_minute_and_never_stop() + { + let test_cases = [UnreachedReadsTestCase { + description: "eight unreached reads, then five that reached the warehouse", + unreached: 8, + reached: 5, + expected_waits: ( + vec![ + Some(30), + Some(60), + Some(60), + Some(60), + Some(60), + Some(60), + Some(60), + Some(60), + ], + vec![Some(30), Some(60), Some(60), Some(60), None], + ), + expected_halted: true, + }]; + for test_case in test_cases { + let mut state = metadata_sync((one_location(), 1), (3600, 0)); + state.begin_sync(Utc::now()); + let unreached: Vec> = (0..test_case.unreached) + .map(|_| state.fail_read((false, true)).map(|wait| wait.as_secs())) + .collect(); + let reached: Vec> = (0..test_case.reached) + .map(|_| state.fail_read((false, false)).map(|wait| wait.as_secs())) + .collect(); + assert_eq!( + ((unreached, reached), state.halted), + (test_case.expected_waits, test_case.expected_halted), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_server_that_fails_then_answers_when_delivering_then_the_sync_resumes_by_itself() { + let test_cases = [ServerRecoveryTestCase { + description: "the page and its health report fail twice, then the server answers", + statuses: &[503, 503, 503, 503], + attempts: 3, + expected_failing: vec![true, true, false], + expected_line: "Run history sync recovered after 0 min; 1 page caught up.\n", + }]; + for test_case in test_cases { + let directory = tempfile::tempdir().expect("temporary directory"); + let ((options, _), (_, poll), mut state) = published_location(directory.path(), false); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime"); + let (url, _) = runtime.block_on(answering_server(test_case.statuses)); + let client = + connect_location_work((&url, "token"), options.location_id).expect("work client"); + state.pending = Some(LocationMetadataPage { + batch: MetadataBatch { + kind: WarehouseHistoryKind::ALL[state.index], + session_id: poll.session_id, + generation: state.generation, + records: vec![serde_json::json!({})], + scan: None, + last_page: false, + }, + next_source_after: None, + }); + let mut waits: Vec = Vec::new(); + let mut failing: Vec = Vec::new(); + for _ in 0..test_case.attempts { + state = runtime + .block_on(deliver_metadata_page( + state, + &options.target, + (&client, &poll), + (Instant::now(), std::future::pending()), + )) + .expect("no control error") + .expect("not stopped"); + waits.push( + state + .next_at + .saturating_duration_since(Instant::now()) + .as_secs(), + ); + failing.push(state.streak.failing_since.is_some()); + state.next_at = Instant::now(); + } + assert_eq!( + ( + waits.iter().all(|wait| *wait <= 60), + failing, + state.pending.is_none(), + state.take_recovery_line(Utc::now()), + ), + ( + true, + test_case.expected_failing, + true, + Some(test_case.expected_line.to_owned()), + ), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-cli/src/native_commands/tests/test_types.rs b/crates/sqlbuild-cli/src/native_commands/tests/test_types.rs index 393c51a8b7..bfca6a34d1 100644 --- a/crates/sqlbuild-cli/src/native_commands/tests/test_types.rs +++ b/crates/sqlbuild-cli/src/native_commands/tests/test_types.rs @@ -513,3 +513,39 @@ pub(super) struct LookupFailureHealthTestCase { pub(super) answered: Option, pub(super) expected_generation: i64, } + +pub(super) struct UnreachedReadsTestCase { + pub(super) description: &'static str, + pub(super) unreached: usize, + pub(super) reached: usize, + /// The waits of the unreached reads, then of the reads that reached the warehouse. + pub(super) expected_waits: (Vec>, Vec>), + pub(super) expected_halted: bool, +} + +pub(super) struct ServerRecoveryTestCase { + pub(super) description: &'static str, + /// What the server answers in turn before it answers 200. + pub(super) statuses: &'static [u16], + pub(super) attempts: usize, + /// Whether the sync was failing after each attempt. + pub(super) expected_failing: Vec, + pub(super) expected_line: &'static str, +} + +pub(super) struct SinkCheckTestCase { + pub(super) description: &'static str, + /// A shell script answering the sink requests in turn. + pub(super) script: &'static str, + /// Minutes that pass before each check. + pub(super) minutes_passed: Vec, + pub(super) expected_reports: + Vec>, +} + +pub(super) struct SinkReportTestCase { + pub(super) description: &'static str, + pub(super) script: &'static str, + /// Whether the interpreter is kept, and how many reports the server got. + pub(super) expected_outcome: (bool, usize), +} diff --git a/crates/sqlbuild-cli/src/person_login/_helpers/transport.rs b/crates/sqlbuild-cli/src/person_login/_helpers/transport.rs index 6500164f19..994c68fde4 100644 --- a/crates/sqlbuild-cli/src/person_login/_helpers/transport.rs +++ b/crates/sqlbuild-cli/src/person_login/_helpers/transport.rs @@ -8,6 +8,7 @@ use sqlbuild_orchestration::api::main::parse_origin::parse_origin; use sqlbuild_orchestration::api::models::{ApiErrorBody, MutationResponse}; use sqlbuild_orchestration::credentials::models::SessionIdentity; use sqlbuild_orchestration::platform::models::{PersonWorkRequest, RepublishCall, RepublishStatus}; +use sqlbuild_orchestration::runs::models::PastRunsRead; use sqlbuild_orchestration::sensors::models::{SensorEventChoice, SensorTrialEvents}; use sqlbuild_orchestration::snapshots::models::NodeSql; use uuid::Uuid; @@ -252,6 +253,28 @@ async fn send_json( .map_err(|_| std::io::Error::other(format!("server returned an invalid {result}"))) } +/// What each run `ids` names selected, didn't finish and skipped in the location and target, or why one can't be read. +pub(crate) async fn past_runs( + client: &PersonClient, + credential: &PersonCredential, + (location, target): (Uuid, &str), + ids: &[String], +) -> Result { + let path = target_path(client, (location, target), &["selection", "runs"])?; + let response = authorized(client, reqwest::Method::GET, &path, credential)? + .query(&[("ids", ids.join(","))]) + .send() + .await + .map_err(|_| std::io::Error::other("could not read past runs from the server"))?; + if !response.status().is_success() { + return Err(rejection(response, "Reading past runs").await); + } + response + .json() + .await + .map_err(|_| std::io::Error::other("server returned invalid past runs")) +} + /// Each segment is percent-encoded, so a target or node key cannot change the route. fn target_path( client: &PersonClient, diff --git a/crates/sqlbuild-cli/src/person_login/main/mod.rs b/crates/sqlbuild-cli/src/person_login/main/mod.rs index bbdf074733..36caabfcc6 100644 --- a/crates/sqlbuild-cli/src/person_login/main/mod.rs +++ b/crates/sqlbuild-cli/src/person_login/main/mod.rs @@ -1,6 +1,7 @@ pub(crate) mod call_republish; pub(crate) mod open_browser; pub(crate) mod read_node_sql; +pub(crate) mod read_past_runs; pub(crate) mod read_sensor_events; pub(crate) mod request_warehouse_sync; pub(crate) mod run_login; diff --git a/crates/sqlbuild-cli/src/person_login/main/read_past_runs.rs b/crates/sqlbuild-cli/src/person_login/main/read_past_runs.rs new file mode 100644 index 0000000000..edbef50849 --- /dev/null +++ b/crates/sqlbuild-cli/src/person_login/main/read_past_runs.rs @@ -0,0 +1,19 @@ +//! A saved person session reads past runs' results for a command's run selectors; reading changes nothing. + +use std::path::Path; + +use sqlbuild_orchestration::runs::models::PastRunsRead; +use uuid::Uuid; + +use crate::person_login::_helpers::transport; + +/// What each run `ids` names did in the location and target, read with the saved session for `server`. +pub(crate) fn read_past_runs( + server: (&str, Option<&Path>), + (location, target): (Uuid, &str), + ids: &[String], +) -> Result { + transport::with_person_session(server, async |client, credential| { + transport::past_runs(client, credential, (location, target), ids).await + }) +} diff --git a/crates/sqlbuild-cli/src/run_selectors/main/mod.rs b/crates/sqlbuild-cli/src/run_selectors/main/mod.rs new file mode 100644 index 0000000000..c87fbfbaa0 --- /dev/null +++ b/crates/sqlbuild-cli/src/run_selectors/main/mod.rs @@ -0,0 +1,3 @@ +pub mod names_audits_or_runs; +pub mod past_run_source; +pub mod read_past_run_keys; diff --git a/crates/sqlbuild-cli/src/run_selectors/main/names_audits_or_runs.rs b/crates/sqlbuild-cli/src/run_selectors/main/names_audits_or_runs.rs new file mode 100644 index 0000000000..8a1d833430 --- /dev/null +++ b/crates/sqlbuild-cli/src/run_selectors/main/names_audits_or_runs.rs @@ -0,0 +1,18 @@ +//! Whether a command's selectors name an audit or a past run, so its graph needs them attached. + +use sqlbuild_analysis::graph::constants::{AUDIT_KIND, RUN_SELECTOR_KINDS}; +use sqlbuild_analysis::graph::main::parse_selector::parse_selector; +use sqlbuild_analysis::graph::models::ParsedSelector; + +/// Whether a part of `selectors` is an `audit:` or a past-run selector. +#[must_use] +pub fn names_audits_or_runs(selectors: &[String]) -> bool { + selectors + .iter() + .flat_map(|selector| selector.split(char::is_whitespace)) + .flat_map(|token| token.split(',')) + .any(|part| { + matches!(parse_selector(part), Ok(ParsedSelector::Kind { kind, .. }) + if kind == AUDIT_KIND || RUN_SELECTOR_KINDS.contains(&kind.as_str())) + }) +} diff --git a/crates/sqlbuild-cli/src/run_selectors/main/past_run_source.rs b/crates/sqlbuild-cli/src/run_selectors/main/past_run_source.rs new file mode 100644 index 0000000000..ea2aa5c2b0 --- /dev/null +++ b/crates/sqlbuild-cli/src/run_selectors/main/past_run_source.rs @@ -0,0 +1,44 @@ +//! Where a command's run selectors read past runs: the server it names, else the local SQLite Recall history. + +use std::path::{Path, PathBuf}; + +use uuid::Uuid; + +use crate::native_commands::main::effective_target::effective_target; +use crate::run_selectors::models::PastRunSource; + +/// The `--server` with its `--ca-cert` and `--location-id` on the project's target, else the local `recall_store`; why neither works when that's so. +#[must_use] +pub fn past_run_source( + (server, ca, location): (Option, Option, Option), + (project_dir, selected_target): (&Path, Option), + recall_store: Option, +) -> PastRunSource { + let unavailable = |reason: &str| PastRunSource::Unavailable(reason.to_owned()); + let Some(origin) = server else { + return recall_store.map_or_else( + || { + unavailable( + "run selectors read the local Recall history only from a SQLite store; pass --server to read the server's runs", + ) + }, + |store| PastRunSource::Recall { store }, + ); + }; + let Some(location_id) = location.as_deref().map(Uuid::parse_str) else { + return unavailable("--location-id is required with --server"); + }; + let Ok(location_id) = location_id else { + return unavailable("--location-id must be a UUID"); + }; + match effective_target(project_dir, selected_target) { + Ok(Some(target)) => PastRunSource::Server { + origin, + ca, + location_id, + target, + }, + Ok(None) => unavailable("--server needs a target; pass --target"), + Err(error) => PastRunSource::Unavailable(error), + } +} diff --git a/crates/sqlbuild-cli/src/run_selectors/main/read_past_run_keys.rs b/crates/sqlbuild-cli/src/run_selectors/main/read_past_run_keys.rs new file mode 100644 index 0000000000..8da5c950a8 --- /dev/null +++ b/crates/sqlbuild-cli/src/run_selectors/main/read_past_run_keys.rs @@ -0,0 +1,71 @@ +//! Read the past runs a command's selectors name, from the server it names or the local Recall history. + +use std::collections::BTreeSet; + +use sqlbuild_recall::store::main::open_sqlite_store::open_sqlite_store; +use sqlbuild_recall::store::main::read_run_results::read_run_results; +use sqlbuild_recall::store::main::resolve_run::resolve_run; +use sqlbuild_recall::store::models::OpenMode; + +use crate::person_login::main::read_past_runs::read_past_runs; +use crate::run_selectors::models::{PastRunKeys, PastRunSource}; +use crate::run_selectors::types::PastRunKeysById; + +/// What each run `ids` names selected, didn't finish and skipped, or why one can't be read. +pub fn read_past_run_keys( + source: &PastRunSource, + ids: &BTreeSet, +) -> Result { + match source { + PastRunSource::Server { + origin, + ca, + location_id, + target, + } => { + let ids: Vec = ids.iter().cloned().collect(); + let read = read_past_runs((origin, ca.as_deref()), (*location_id, target), &ids) + .map_err(|error| error.to_string())?; + if let Some(error) = read.error { + return Err(error); + } + Ok(read + .runs + .into_iter() + .map(|(id, run)| { + ( + id, + PastRunKeys { + selected: run.selected, + failed: run.failed, + skipped: run.skipped, + }, + ) + }) + .collect()) + } + PastRunSource::Recall { store } => { + let store = open_sqlite_store(store, OpenMode::ReadOnly).map_err(|error| { + format!( + "can't read the local Recall history for run selectors: {}", + error.message + ) + })?; + let mut runs = PastRunKeysById::new(); + for id in ids { + let run_id = resolve_run(&store, id).map_err(|error| error.message)?; + let results = read_run_results(&store, &run_id).map_err(|error| error.message)?; + runs.insert( + id.clone(), + PastRunKeys { + selected: results.selected, + failed: results.failed, + skipped: results.skipped, + }, + ); + } + Ok(runs) + } + PastRunSource::Unavailable(reason) => Err(reason.clone()), + } +} diff --git a/crates/sqlbuild-cli/src/run_selectors/mod.rs b/crates/sqlbuild-cli/src/run_selectors/mod.rs new file mode 100644 index 0000000000..2c8f0ecf65 --- /dev/null +++ b/crates/sqlbuild-cli/src/run_selectors/mod.rs @@ -0,0 +1,5 @@ +//! The past runs a command's `run:`, `failed:` and `skipped:` selectors name, from a server or the local Recall history. + +pub mod main; +pub mod models; +pub mod types; diff --git a/crates/sqlbuild-cli/src/run_selectors/models.rs b/crates/sqlbuild-cli/src/run_selectors/models.rs new file mode 100644 index 0000000000..2f789f910a --- /dev/null +++ b/crates/sqlbuild-cli/src/run_selectors/models.rs @@ -0,0 +1,30 @@ +//! Where a command reads past runs from, and what it reads. + +use std::collections::BTreeSet; +use std::path::PathBuf; + +use uuid::Uuid; + +/// Where a command's run selectors read past runs from. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum PastRunSource { + /// A server, with the `sqb login` session for it. + Server { + origin: String, + ca: Option, + location_id: Uuid, + target: String, + }, + /// The local SQLite Recall store. + Recall { store: PathBuf }, + /// Neither can be read, and why. + Unavailable(String), +} + +/// One past run's results as node keys; failed audits are `audit:`. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PastRunKeys { + pub selected: BTreeSet, + pub failed: BTreeSet, + pub skipped: BTreeSet, +} diff --git a/crates/sqlbuild-cli/src/run_selectors/types.rs b/crates/sqlbuild-cli/src/run_selectors/types.rs new file mode 100644 index 0000000000..369fe694fc --- /dev/null +++ b/crates/sqlbuild-cli/src/run_selectors/types.rs @@ -0,0 +1,8 @@ +//! The past runs a command reads, by the run ID as typed. + +use std::collections::BTreeMap; + +use crate::run_selectors::models::PastRunKeys; + +/// Each past run by the ID as typed. +pub type PastRunKeysById = BTreeMap; diff --git a/crates/sqlbuild-cli/tests/native_commands/test_control.rs b/crates/sqlbuild-cli/tests/native_commands/test_control.rs index f09a128696..ef85d95471 100644 --- a/crates/sqlbuild-cli/tests/native_commands/test_control.rs +++ b/crates/sqlbuild-cli/tests/native_commands/test_control.rs @@ -379,13 +379,13 @@ fn given_a_control_store_when_running_server_migrate_then_dry_run_lists_and_migr StoreMigrationCommandTestCase { description: "migrate an empty store", arguments: &["server", "migrate"], - expected_stdout: "The control store is empty: created schema version 11.\n", + expected_stdout: "The control store is empty: created schema version 12.\n", expected_store: true, }, StoreMigrationCommandTestCase { description: "dry run on a current store", arguments: &["server", "migrate", "--dry-run"], - expected_stdout: "The control store is at schema version 11: nothing to migrate.\n", + expected_stdout: "The control store is at schema version 12: nothing to migrate.\n", expected_store: true, }, ]; diff --git a/crates/sqlbuild-config/src/effective/constants.rs b/crates/sqlbuild-config/src/effective/constants.rs index 14dad5e45e..d75f0e39c4 100644 --- a/crates/sqlbuild-config/src/effective/constants.rs +++ b/crates/sqlbuild-config/src/effective/constants.rs @@ -217,6 +217,20 @@ pub(crate) const TARGET_FIELDS: &[TargetField] = &[ decided_by: &["concurrency"], }, }, + TargetField { + group: None, + name: "test_run_on", + rule: MergeRule::Overlay { + decided_by: &["test_run_on"], + }, + }, + TargetField { + group: None, + name: "scenario_run_on", + rule: MergeRule::Overlay { + decided_by: &["scenario_run_on"], + }, + }, TargetField { group: None, name: "catalog_connection", diff --git a/crates/sqlbuild-config/src/project/_helpers/sections.rs b/crates/sqlbuild-config/src/project/_helpers/sections.rs index c8c1f739b2..1415b19ed9 100644 --- a/crates/sqlbuild-config/src/project/_helpers/sections.rs +++ b/crates/sqlbuild-config/src/project/_helpers/sections.rs @@ -13,10 +13,10 @@ use crate::project::_helpers::keys::{Place, reject_removed_virtual_keys, validat use crate::project::_helpers::targets::seconds_value; use crate::project::_helpers::values::{int_below, python_equal}; use crate::project::constants::{ - ALLOW_MISSING_SECRETS_KEY, ALLOW_WAREHOUSE_ROUND_TRIPS_KEY, DEFAULT_TEST_TIMEOUT, - DEFAULT_UNIT_TEST_MAX_REAL_MODELS, DELTA_COMPILE_KEY, DISABLED_VALUE, - IGNORE_AUDIT_FAILURES_KEY, RECORD_RUN_HOST_KEY, SCENARIO_TIMEOUT_KEY, TEST_TIMEOUT_KEY, - UNIT_TEST_MAX_REAL_MODELS_KEY, + ALLOW_MISSING_SECRETS_KEY, ALLOW_WAREHOUSE_ROUND_TRIPS_KEY, DEFAULT_RUN_ON, + DEFAULT_TEST_TIMEOUT, DEFAULT_UNIT_TEST_MAX_REAL_MODELS, DELTA_COMPILE_KEY, DISABLED_VALUE, + IGNORE_AUDIT_FAILURES_KEY, RECORD_RUN_HOST_KEY, RUN_ON_CHOICES, SCENARIO_RUN_ON_KEY, + SCENARIO_TIMEOUT_KEY, TEST_RUN_ON_KEY, TEST_TIMEOUT_KEY, UNIT_TEST_MAX_REAL_MODELS_KEY, }; use crate::project::constants::{ AUDIT_SEVERITIES, CHECK_DECLARED_COLUMNS_KEY, COLLECTION_RENDERINGS, COLUMN_CONTRACT_MODES, @@ -166,6 +166,20 @@ fn check_declared_columns(mapping: &Entries) -> Loaded { }) } +/// Where tests or scenarios run, `auto`, `local` or `warehouse`; `None` when `key` is unset. +pub(crate) fn run_on(mapping: &Entries, key: &str, label: &str) -> Loaded> { + let Some(value) = optional_str(mapping, key)? else { + return Ok(None); + }; + if !RUN_ON_CHOICES.contains(&value.as_str()) { + return Err(ConfigFailure::plain(format!( + "{label}.{key} must be one of: {}", + RUN_ON_CHOICES.join(", ") + ))); + } + Ok(Some(value)) +} + fn unaccounted_partition_policy(mapping: &Entries) -> Loaded { let policy = optional_str(mapping, "microbatch_unaccounted_partition_policy")? .unwrap_or_else(|| "synthesize".to_owned()); @@ -317,6 +331,11 @@ pub(crate) fn load_settings(payload: Option<&ConfigValue>, file: ConfigFile) -> ), ]; let mut fields = fields; + for key in [TEST_RUN_ON_KEY, SCENARIO_RUN_ON_KEY] { + let value: String = + run_on(mapping, key, "settings")?.unwrap_or_else(|| DEFAULT_RUN_ON.to_owned()); + fields.push((key, Built::Value(ConfigValue::String(value)))); + } for (key, seconds_key, default) in [ ( TEST_TIMEOUT_KEY, diff --git a/crates/sqlbuild-config/src/project/_helpers/targets.rs b/crates/sqlbuild-config/src/project/_helpers/targets.rs index da849df615..e7a6f8d901 100644 --- a/crates/sqlbuild-config/src/project/_helpers/targets.rs +++ b/crates/sqlbuild-config/src/project/_helpers/targets.rs @@ -12,13 +12,13 @@ use crate::project::_helpers::fields::{ use crate::project::_helpers::keys::{ Place, reject_removed_virtual_keys, reject_unknown_mapping_keys, validate_allowed_keys, }; -use crate::project::_helpers::sections::{fixed_duration_seconds, item_timeout}; +use crate::project::_helpers::sections::{fixed_duration_seconds, item_timeout, run_on}; use crate::project::_helpers::values::{int_below, is_int}; use crate::project::constants::{ ALLOW_MISSING_SECRETS_KEY, CLONE_KEYS, CONCURRENCY_KEY, CONFIRMATION_POLICIES, ENV_FILE_KEY, EXECUTION_LIMIT_KEYS, IGNORE_AUDIT_FAILURES_KEY, MAX_FULL_ROWS_KEY, PAUSE_DYNAMIC_KEY, - PLAN_FROM_KEY, PLAN_FROM_SOURCES, POOLS_KEY, RETENTION_MATERIALIZATIONS, TARGET_KEYS, - UNLIMITED_DIFF_FULL_ROWS, WAREHOUSE_GROUPS, + PLAN_FROM_KEY, PLAN_FROM_SOURCES, POOLS_KEY, RETENTION_MATERIALIZATIONS, SCENARIO_RUN_ON_KEY, + TARGET_KEYS, TEST_RUN_ON_KEY, UNLIMITED_DIFF_FULL_ROWS, WAREHOUSE_GROUPS, }; use crate::project::errors::ConfigFailure; use crate::project::models::{Built, ConfigFile}; @@ -435,6 +435,10 @@ fn local_target(payload: &ConfigValue, target: TargetPlace<'_>) -> Loaded>()?; fields.push(("clone", object("LocalClonePolicy", clone_fields))); fields.push(("concurrency", target_concurrency(mapping, target)?)); + for key in [TEST_RUN_ON_KEY, SCENARIO_RUN_ON_KEY] { + let label: String = format!("targets.{}", target.name); + fields.push((key, text_or_none(run_on(mapping, key, &label)?))); + } fields.push(( IGNORE_AUDIT_FAILURES_KEY, bool_or_none(optional_nullable_bool(mapping, IGNORE_AUDIT_FAILURES_KEY)?), diff --git a/crates/sqlbuild-config/src/project/constants.rs b/crates/sqlbuild-config/src/project/constants.rs index 0976e837ff..1fa6a86708 100644 --- a/crates/sqlbuild-config/src/project/constants.rs +++ b/crates/sqlbuild-config/src/project/constants.rs @@ -65,7 +65,14 @@ pub(crate) const PARENT_SEGMENT: &str = ".."; /// Whether each run records the machine it ran on in the runs state table. pub(crate) const RECORD_RUN_HOST_KEY: &str = "record_run_host"; pub(crate) const DEFAULT_TEST_TIMEOUT: &str = "30s"; -pub(crate) const SETTINGS_KEYS: [&str; 19] = [ +/// Where unit tests run: `auto`, `local` or `warehouse`; `[settings]` and each target may set it. +pub(crate) const TEST_RUN_ON_KEY: &str = "test_run_on"; +/// Where scenarios run, as `test_run_on` does for unit tests. +pub(crate) const SCENARIO_RUN_ON_KEY: &str = "scenario_run_on"; +/// The places a test or scenario may run; `auto` picks per test. +pub(crate) const RUN_ON_CHOICES: [&str; 3] = ["auto", "local", "warehouse"]; +pub(crate) const DEFAULT_RUN_ON: &str = "auto"; +pub(crate) const SETTINGS_KEYS: [&str; 21] = [ "sql_analysis", "require_sql_analysis", "query_change_tracking", @@ -85,6 +92,8 @@ pub(crate) const SETTINGS_KEYS: [&str; 19] = [ "allow_warehouse_round_trips", IGNORE_AUDIT_FAILURES_KEY, RECORD_RUN_HOST_KEY, + TEST_RUN_ON_KEY, + SCENARIO_RUN_ON_KEY, ]; pub(crate) const DEFAULTS_KEYS: [&str; 34] = [ "append_cursor_inclusive", @@ -207,7 +216,7 @@ pub(crate) const MAX_POOL_LIMIT: i64 = 10_000; pub(crate) const PLAN_FROM_KEY: &str = "plan_from"; /// What `plan_from` may name; `live` is the default. pub(crate) const PLAN_FROM_SOURCES: [&str; 2] = ["live", "synced_state"]; -pub(crate) const TARGET_KEYS: [&str; 27] = [ +pub(crate) const TARGET_KEYS: [&str; 29] = [ "connection", "catalog_connection", "vars", @@ -235,6 +244,8 @@ pub(crate) const TARGET_KEYS: [&str; 27] = [ PAUSE_DYNAMIC_KEY, ENV_FILE_KEY, ALLOW_MISSING_SECRETS_KEY, + TEST_RUN_ON_KEY, + SCENARIO_RUN_ON_KEY, ]; pub(crate) const CONTROL_KEYS: [&str; 3] = ["location", "server", "sync_at_least_every"]; pub(crate) const CHANGES_KEYS: [&str; 2] = ["counts", "reach"]; diff --git a/crates/sqlbuild-core/src/audit_command/main/render_audit_summary.rs b/crates/sqlbuild-core/src/audit_command/main/render_audit_summary.rs index 3cf437a738..0e902a1052 100644 --- a/crates/sqlbuild-core/src/audit_command/main/render_audit_summary.rs +++ b/crates/sqlbuild-core/src/audit_command/main/render_audit_summary.rs @@ -4,13 +4,6 @@ use crate::audit_command::models::AuditCounts; use crate::cli_text::main::format_summary_footer::format_summary_footer; use crate::cli_text::models::{CliStyle, SummaryCount}; -fn count(label: &str, value: usize) -> SummaryCount { - SummaryCount { - label: label.to_owned(), - value: i64::try_from(value).unwrap_or(i64::MAX), - } -} - /// A blank line and the PASS, WARN, FAIL, INSUFFICIENT and TOTAL counts. #[must_use] pub fn render_audit_summary(counts: AuditCounts, style: CliStyle) -> String { @@ -19,11 +12,11 @@ pub fn render_audit_summary(counts: AuditCounts, style: CliStyle) -> String { format_summary_footer( style, &[ - count("PASS", counts.passed), - count("WARN", counts.warned), - count("FAIL", counts.failed), - count("INSUFFICIENT", counts.insufficient), - count("TOTAL", counts.total), + SummaryCount::of("PASS", counts.passed), + SummaryCount::of("WARN", counts.warned), + SummaryCount::of("FAIL", counts.failed), + SummaryCount::of("INSUFFICIENT", counts.insufficient), + SummaryCount::of("TOTAL", counts.total), ], None, ) diff --git a/crates/sqlbuild-core/src/build_aggregate/constants.rs b/crates/sqlbuild-core/src/build_aggregate/constants.rs index 73f1b40b37..a44c25555f 100644 --- a/crates/sqlbuild-core/src/build_aggregate/constants.rs +++ b/crates/sqlbuild-core/src/build_aggregate/constants.rs @@ -8,6 +8,7 @@ pub(crate) const AUDIT_WARN: &str = "warn"; pub(crate) const AUDIT_ERROR: &str = "error"; pub(crate) const AUDIT_INSUFFICIENT: &str = "insufficient"; pub(crate) const AUDIT_SKIPPED: &str = "skipped"; +pub(crate) const AUDIT_NOT_RUN: &str = "not_run"; /// The outcome a fact names an error-severity audit failure by when the build ignored it. pub const IGNORED_AUDIT_FAILURE: &str = "ignored"; pub(crate) const SOURCE_FRESHNESS_BLOCKED_CODE: &str = "B005"; diff --git a/crates/sqlbuild-core/src/build_aggregate/main/aggregate_build_counts.rs b/crates/sqlbuild-core/src/build_aggregate/main/aggregate_build_counts.rs index f5cd39b599..165888c175 100644 --- a/crates/sqlbuild-core/src/build_aggregate/main/aggregate_build_counts.rs +++ b/crates/sqlbuild-core/src/build_aggregate/main/aggregate_build_counts.rs @@ -1,8 +1,9 @@ //! Aggregate counts and overall status of one build. use crate::build_aggregate::constants::{ - AUDIT_ERROR, AUDIT_INSUFFICIENT, AUDIT_SKIPPED, AUDIT_WARN, FAILED, IGNORED_AUDIT_FAILURE, - ITEM_TIMEOUT_CODE, SKIPPED, SOURCE_FRESHNESS_BLOCKED_CODE, SUCCESS, TEST_PASS, TEST_TIMEOUT, + AUDIT_ERROR, AUDIT_INSUFFICIENT, AUDIT_NOT_RUN, AUDIT_SKIPPED, AUDIT_WARN, FAILED, + IGNORED_AUDIT_FAILURE, ITEM_TIMEOUT_CODE, SKIPPED, SOURCE_FRESHNESS_BLOCKED_CODE, SUCCESS, + TEST_PASS, TEST_TIMEOUT, }; use crate::build_aggregate::models::{BuildCounts, BuildResultFacts}; @@ -65,6 +66,9 @@ pub fn aggregate_build_counts(facts: &BuildResultFacts) -> BuildCounts { counts.ignored_audit_failures = audit_outcomes() .filter(|outcome| *outcome == IGNORED_AUDIT_FAILURE) .count(); + counts.not_run = audit_outcomes() + .filter(|outcome| *outcome == AUDIT_NOT_RUN) + .count(); counts.skipped += matching(&facts.source_audit_outcomes, AUDIT_SKIPPED) + matching(&facts.end_audit_outcomes, AUDIT_SKIPPED); counts.failure += matching(&facts.source_audit_outcomes, AUDIT_ERROR); diff --git a/crates/sqlbuild-core/src/build_aggregate/models.rs b/crates/sqlbuild-core/src/build_aggregate/models.rs index a8d1ea3b59..ce7061db69 100644 --- a/crates/sqlbuild-core/src/build_aggregate/models.rs +++ b/crates/sqlbuild-core/src/build_aggregate/models.rs @@ -35,5 +35,7 @@ pub struct BuildCounts { pub insufficient: usize, /// Error-severity audit failures that held nothing back, counted in no other field. pub ignored_audit_failures: usize, + /// End-of-build audits whose reads the target doesn't have, counted in no other field. + pub not_run: usize, pub failed: bool, } diff --git a/crates/sqlbuild-core/src/build_progress/_helpers/footer.rs b/crates/sqlbuild-core/src/build_progress/_helpers/footer.rs index f6f0501c2c..cc09d62100 100644 --- a/crates/sqlbuild-core/src/build_progress/_helpers/footer.rs +++ b/crates/sqlbuild-core/src/build_progress/_helpers/footer.rs @@ -3,8 +3,8 @@ use crate::build_progress::_helpers::error_rows::failure_error_block; use crate::build_progress::_helpers::text::pad; use crate::build_progress::constants::{ - DELTA_SUFFIX, ERROR, FAILED, PASS, PYTHON_NODE_NAME_WIDTH, SKIPPED, SKIPPED_ROLLUP_CAP, - SUCCESS, TIMEOUT_CODE, TIMEOUT_OUTCOME, WARN, + DELTA_SUFFIX, ERROR, FAILED, NOT_RUN, PASS, PYTHON_NODE_NAME_WIDTH, SKIPPED, + SKIPPED_ROLLUP_CAP, SUCCESS, TIMEOUT_CODE, TIMEOUT_OUTCOME, WARN, }; use crate::build_progress::models::{AuditResultText, BuildResultText, ErrorText, PythonNodeText}; use crate::cli_text::models::CliStyle; @@ -19,6 +19,8 @@ pub(crate) struct FooterCounts { pub(crate) skip: i64, /// Error-severity audit failures the build let through; not counted as failures. pub(crate) ignored: i64, + /// End-of-build audits whose reads the target doesn't have; neither passes nor failures. + pub(crate) not_run: i64, } impl FooterCounts { @@ -58,6 +60,7 @@ pub(crate) fn count_results(result: &BuildResultText, python: &[PythonNodeText]) ERROR if audit.ignored => counts.ignored += 1, ERROR => counts.fail += 1, SKIPPED => counts.skip += 1, + NOT_RUN => counts.not_run += 1, _ => {} } } @@ -336,6 +339,28 @@ pub(crate) fn python_failure_details(python: &[PythonNodeText], style: CliStyle) lines } +/// `Not run (N):` with each end-of-build audit whose reads the target doesn't have, and what it reads. +pub(crate) fn not_run_details(result: &BuildResultText, style: CliStyle) -> Vec { + let not_run: Vec<&AuditResultText> = build_audits(result) + .filter(|audit| audit.outcome == NOT_RUN) + .collect(); + if not_run.is_empty() { + return Vec::new(); + } + let mut lines: Vec = vec![ + String::new(), + style.warning_strong(&format!("Not run ({}):", not_run.len())), + ]; + for audit in not_run { + lines.push(format!( + " {} (audit) {}", + audit.audit_name, + audit.skip_reason.as_deref().unwrap_or_default() + )); + } + lines +} + /// A skipped audit's rollup entry: its name and why it did not run. fn skipped_audit_label(audit: &AuditResultText) -> String { match &audit.skip_reason { diff --git a/crates/sqlbuild-core/src/build_progress/_helpers/text.rs b/crates/sqlbuild-core/src/build_progress/_helpers/text.rs index 67933791b1..1caa715a13 100644 --- a/crates/sqlbuild-core/src/build_progress/_helpers/text.rs +++ b/crates/sqlbuild-core/src/build_progress/_helpers/text.rs @@ -1,9 +1,9 @@ //! Python formatting idioms and small labels shared by build progress rows. use crate::build_progress::constants::{ - ERROR, FAILED, INSUFFICIENT, PASS, ROW_COUNT_ABBREVIATION_THRESHOLD, ROW_COUNT_BILLION, - ROW_COUNT_MILLION, ROW_COUNT_THOUSAND, SECONDS_PER_MINUTE, SKIPPED, SUCCESS, TIMEOUT_CODE, - TIMEOUT_OUTCOME, WARN, + ERROR, FAILED, INSUFFICIENT, NOT_RUN, PASS, ROW_COUNT_ABBREVIATION_THRESHOLD, + ROW_COUNT_BILLION, ROW_COUNT_MILLION, ROW_COUNT_THOUSAND, SECONDS_PER_MINUTE, SKIPPED, SUCCESS, + TIMEOUT_CODE, TIMEOUT_OUTCOME, WARN, }; use crate::build_progress::models::SkipText; use crate::number_text::main::format_thousands::format_thousands; @@ -75,6 +75,7 @@ pub(crate) fn audit_outcome_display(outcome: &str) -> String { ERROR => "FAIL".to_owned(), INSUFFICIENT => "INSUFFICIENT".to_owned(), SKIPPED => "SKIP".to_owned(), + NOT_RUN => "NOT RUN".to_owned(), other => other.to_owned(), } } diff --git a/crates/sqlbuild-core/src/build_progress/constants.rs b/crates/sqlbuild-core/src/build_progress/constants.rs index c0a30dbb22..c4d524f55f 100644 --- a/crates/sqlbuild-core/src/build_progress/constants.rs +++ b/crates/sqlbuild-core/src/build_progress/constants.rs @@ -34,6 +34,8 @@ pub(crate) const PASS: &str = "pass"; pub(crate) const WARN: &str = "warn"; pub(crate) const ERROR: &str = "error"; pub(crate) const INSUFFICIENT: &str = "insufficient"; +/// An end-of-build audit that reads something the target doesn't have: neither a pass nor a failure. +pub(crate) const NOT_RUN: &str = "not_run"; pub(crate) const DELTA_AND_FINAL: &str = "delta_and_final"; pub(crate) const TIMEOUT_OUTCOME: &str = "timeout"; pub(crate) const TIMEOUT_CODE: &str = "C417"; diff --git a/crates/sqlbuild-core/src/build_progress/main/format_build_footer.rs b/crates/sqlbuild-core/src/build_progress/main/format_build_footer.rs index c6a62e8ea0..545b2a3264 100644 --- a/crates/sqlbuild-core/src/build_progress/main/format_build_footer.rs +++ b/crates/sqlbuild-core/src/build_progress/main/format_build_footer.rs @@ -1,8 +1,8 @@ //! The completion line, warnings, failures and skipped rollup printed after a build. use crate::build_progress::_helpers::footer::{ - FooterCounts, count_results, failure_details, ignored_failure_details, python_failure_details, - skipped_rollup, warning_details, + FooterCounts, count_results, failure_details, ignored_failure_details, not_run_details, + python_failure_details, skipped_rollup, warning_details, }; use crate::build_progress::constants::FAILED; use crate::build_progress::models::{BuildResultText, PythonNodeText}; @@ -33,8 +33,13 @@ pub fn format_build_footer( ) -> String { let counts: FooterCounts = count_results(result, python); let insufficient: i64 = result.insufficient_count; - let total: i64 = - counts.pass + counts.warn + counts.fail + counts.timeout + counts.skip + counts.ignored; + let total: i64 = counts.pass + + counts.warn + + counts.fail + + counts.timeout + + counts.skip + + counts.ignored + + counts.not_run; let mut summary_counts: Vec = vec![ count("PASS", counts.pass), count("WARN", counts.warn), @@ -49,8 +54,11 @@ pub fn format_build_footer( summary_counts.extend([ count("INSUFFICIENT", insufficient), count("SKIP", counts.skip), - count("TOTAL", total + insufficient), ]); + if counts.not_run > 0 { + summary_counts.push(count("NOT_RUN", counts.not_run)); + } + summary_counts.extend([count("TOTAL", total + insufficient)]); let summary: String = format_summary_footer(style, &summary_counts, Some(&format!("{elapsed:.2}s"))); let python_failed: bool = python.iter().any(|node| node.status == FAILED); @@ -69,5 +77,6 @@ pub fn format_build_footer( lines.extend(failure_details(result, style)); lines.extend(python_failure_details(python, style)); lines.extend(skipped_rollup(result, python, style)); + lines.extend(not_run_details(result, style)); lines.join("\n") } diff --git a/crates/sqlbuild-core/src/cli_text/_helpers/plan_document.rs b/crates/sqlbuild-core/src/cli_text/_helpers/plan_document.rs index 9a4edd216c..95b1d6b98d 100644 --- a/crates/sqlbuild-core/src/cli_text/_helpers/plan_document.rs +++ b/crates/sqlbuild-core/src/cli_text/_helpers/plan_document.rs @@ -2,9 +2,10 @@ use crate::cli_text::_helpers::layout::surface_header; use crate::cli_text::_helpers::plan_sections::{ - full_refresh_count_lines, functions_lines, plan_name_width, provider_usage_lines, pruned_lines, - python_entry_lines, ready_summary, reason_group_lines, remaining_stale_lines, - routine_model_lines, seed_lines, source_freshness_lines, source_load_lines, warning_lines, + audit_lines, full_refresh_count_lines, functions_lines, not_run_audit_lines, plan_name_width, + provider_usage_lines, pruned_lines, python_entry_lines, ready_summary, reason_group_lines, + remaining_stale_lines, routine_model_lines, seed_lines, source_freshness_lines, + source_load_lines, warning_lines, }; use crate::cli_text::_helpers::tree_rows::treeify; use crate::cli_text::constants::{ @@ -63,6 +64,8 @@ pub(crate) fn full_refresh_lines( } lines.extend(full_refresh_count_lines(active)); lines.extend(seed_lines(report)); + lines.extend(audit_lines(report)); + lines.extend(not_run_audit_lines(report)); lines.extend(python_entry_lines( (report, READ_SIDE_PHASE, PYTHON_READ_SIDE_TITLE), width, @@ -93,6 +96,8 @@ pub(crate) fn incremental_lines(report: &PlanTextReport, active: &[&ModelPlanTex lines.extend(routine_model_lines(report, active, width)); lines.extend(functions_lines(report, false, width)); lines.extend(seed_lines(report)); + lines.extend(audit_lines(report)); + lines.extend(not_run_audit_lines(report)); lines.extend(python_entry_lines( (report, READ_SIDE_PHASE, PYTHON_READ_SIDE_TITLE), width, diff --git a/crates/sqlbuild-core/src/cli_text/_helpers/plan_sections.rs b/crates/sqlbuild-core/src/cli_text/_helpers/plan_sections.rs index 10f92cd260..0396a0a765 100644 --- a/crates/sqlbuild-core/src/cli_text/_helpers/plan_sections.rs +++ b/crates/sqlbuild-core/src/cli_text/_helpers/plan_sections.rs @@ -19,6 +19,8 @@ use crate::cli_text::models::{ PlanWarningText, ProviderUsageText, PythonPlanText, SchemaFindingText, SourceFreshnessText, SourceLoadPlanText, }; +use crate::plan_display::main::plan_summary_parts::plan_summary_parts; +use crate::plan_display::models::PlanSummaryCounts; const STYLE: CliStyle = CliStyle { use_color: true }; @@ -60,30 +62,18 @@ pub(crate) fn full_refresh_layout(report: &PlanTextReport) -> bool { || (report.full_refresh && active.is_empty()) } -/// `N selected`, with the full-refresh, source-load and Python-node parts. +/// `N selected`, with the full-refresh, source-load and Python-node parts, leaving out zero counts. pub(crate) fn ready_summary(report: &PlanTextReport, full_refresh: bool) -> String { - let mut parts: Vec = Vec::new(); - if full_refresh { - parts.push("full refresh".to_owned()); - } - let selected: usize = report.models.len() + report.seeds.len() + report.functions.len(); - parts.push(format!("{selected} selected")); - let sources: usize = report.source_loads.len(); - if sources > 0 { - let noun: &str = if sources == 1 { "source" } else { "sources" }; - let action: &str = if report.source_loads.iter().any(|load| load.is_reload) { - "reload" - } else { - "load" - }; - parts.push(format!("{sources} {noun} to {action}")); - } - let python: usize = report.python_entries.len(); - if python > 0 { - let noun: &str = if python == 1 { "node" } else { "nodes" }; - parts.push(format!("{python} Python {noun}")); - } - parts.join(", ") + plan_summary_parts(&PlanSummaryCounts { + full_refresh, + selected: report.models.len() + report.seeds.len() + report.functions.len(), + sources: report.source_loads.len(), + reloads_sources: report.source_loads.iter().any(|load| load.is_reload), + python: report.python_entries.len(), + audits: report.audits.len(), + audits_not_run: report.audits_not_run.len(), + }) + .join(", ") } /// The name column every plan section aligns to. @@ -701,6 +691,39 @@ pub(crate) fn seed_lines(report: &PlanTextReport) -> Vec { }) } +/// `Audits (N)`: the audits selected by name, which run whether or not their targets build. +pub(crate) fn audit_lines(report: &PlanTextReport) -> Vec { + if report.audits.is_empty() { + return Vec::new(); + } + section_lines("Audits", &report.audits, &report.display, |audit| { + vec![format!(" {audit}")] + }) +} + +/// `Audits not run (N)`: end-of-build audits that read something the target doesn't have, each naming what. +pub(crate) fn not_run_audit_lines(report: &PlanTextReport) -> Vec { + if report.audits_not_run.is_empty() { + return Vec::new(); + } + section_lines( + "Audits not run", + &report.audits_not_run, + &report.display, + |(audit, missing)| { + let verb: &str = if missing.len() == 1 { + "which doesn't" + } else { + "which don't" + }; + vec![format!( + " {audit} reads {}, {verb} exist in the target", + missing.join(", ") + )] + }, + ) +} + /// `Full refresh (N)` with one count row per materialization label, most common first. pub(crate) fn full_refresh_count_lines(active: &[&ModelPlanText]) -> Vec { let mut counts: Vec<(&str, usize)> = Vec::new(); diff --git a/crates/sqlbuild-core/src/cli_text/models.rs b/crates/sqlbuild-core/src/cli_text/models.rs index 91ec3eba16..42ff752198 100644 --- a/crates/sqlbuild-core/src/cli_text/models.rs +++ b/crates/sqlbuild-core/src/cli_text/models.rs @@ -436,6 +436,10 @@ pub struct PlanTextReport { pub ignore_audit_failure_jobs: Vec, /// Each named job whose nodes run on its own warehouse, and that warehouse. pub job_warehouses: Vec<(String, String)>, + /// Audits selected by name, with `audit:` or as a past run's failed audits, sorted. + pub audits: Vec, + /// End-of-build audits that won't run, each with the reads that don't exist in the target, sorted. + pub audits_not_run: Vec<(String, Vec)>, } /// The structural kind of a rendered plan line. @@ -462,6 +466,17 @@ pub struct SummaryCount { pub value: i64, } +impl SummaryCount { + /// The count `value` under `label`, saturating at `i64::MAX`. + #[must_use] + pub fn of(label: &str, value: usize) -> Self { + Self { + label: label.to_owned(), + value: i64::try_from(value).unwrap_or(i64::MAX), + } + } +} + /// One aligned name/value row: the plain name sets the width, the styled name is shown. #[derive(Clone, Debug, PartialEq, Eq)] pub struct AlignedRow { diff --git a/crates/sqlbuild-core/src/cli_text/tests/helpers.rs b/crates/sqlbuild-core/src/cli_text/tests/helpers.rs index 84281b7848..bac37f3240 100644 --- a/crates/sqlbuild-core/src/cli_text/tests/helpers.rs +++ b/crates/sqlbuild-core/src/cli_text/tests/helpers.rs @@ -58,6 +58,8 @@ pub(super) fn plan_report(models: Vec) -> PlanTextReport { ignore_audit_failures: false, ignore_audit_failure_jobs: Vec::new(), job_warehouses: Vec::new(), + audits: Vec::new(), + audits_not_run: Vec::new(), } } diff --git a/crates/sqlbuild-core/src/format_command/_helpers/diagnostics.rs b/crates/sqlbuild-core/src/format_command/_helpers/diagnostics.rs index aed12e2d2f..9642c42b08 100644 --- a/crates/sqlbuild-core/src/format_command/_helpers/diagnostics.rs +++ b/crates/sqlbuild-core/src/format_command/_helpers/diagnostics.rs @@ -62,7 +62,7 @@ fn source_excerpt(finding: &LintFinding, source_line: &str, style: CliStyle) -> ] } -fn help_lines(remediation: &str, style: CliStyle) -> Vec { +pub(crate) fn help_lines(remediation: &str, style: CliStyle) -> Vec { let wrapped: Vec = text_wrap( remediation, REPORT_LINE_WIDTH, diff --git a/crates/sqlbuild-core/src/format_command/main/mod.rs b/crates/sqlbuild-core/src/format_command/main/mod.rs index 93bbaa9828..23d41618eb 100644 --- a/crates/sqlbuild-core/src/format_command/main/mod.rs +++ b/crates/sqlbuild-core/src/format_command/main/mod.rs @@ -4,6 +4,8 @@ pub mod format_path_selectors; pub mod lint_sql_paths; pub mod partition_lint_selectors; pub mod render_format_status; +pub mod render_help_lines; pub mod render_lint_json; pub mod render_lint_text; +pub mod render_violation_block; pub mod resolve_lint_paths; diff --git a/crates/sqlbuild-core/src/format_command/main/render_help_lines.rs b/crates/sqlbuild-core/src/format_command/main/render_help_lines.rs new file mode 100644 index 0000000000..c64c49af6c --- /dev/null +++ b/crates/sqlbuild-core/src/format_command/main/render_help_lines.rs @@ -0,0 +1,10 @@ +//! A diagnostic's help text as `= help:` lines. + +use crate::cli_text::models::CliStyle; +use crate::format_command::_helpers::diagnostics::help_lines; + +/// The help text wrapped under a `= help:` label, continuation lines aligned under the text. +#[must_use] +pub fn render_help_lines(help: &str, style: CliStyle) -> Vec { + help_lines(help, style) +} diff --git a/crates/sqlbuild-core/src/format_command/main/render_violation_block.rs b/crates/sqlbuild-core/src/format_command/main/render_violation_block.rs new file mode 100644 index 0000000000..dcb991d7d2 --- /dev/null +++ b/crates/sqlbuild-core/src/format_command/main/render_violation_block.rs @@ -0,0 +1,11 @@ +//! One lint finding as a located diagnostic block. + +use crate::cli_text::models::CliStyle; +use crate::format_command::_helpers::diagnostics::violation_block; +use crate::format_command::models::LintFinding; + +/// The finding's header, `-->` place, source line and caret, in the lint report's layout. +#[must_use] +pub fn render_violation_block(finding: &LintFinding, style: CliStyle) -> String { + violation_block(finding, style) +} diff --git a/crates/sqlbuild-core/src/lib.rs b/crates/sqlbuild-core/src/lib.rs index 0f4d1c3ae3..05e677ca89 100644 --- a/crates/sqlbuild-core/src/lib.rs +++ b/crates/sqlbuild-core/src/lib.rs @@ -50,6 +50,7 @@ pub mod process_environment; pub mod progress; pub mod query_command; pub mod redaction; +pub mod run_on; pub mod scenario_command; pub mod screen_text; pub mod seed_command; diff --git a/crates/sqlbuild-core/src/lifecycle_events/constants.rs b/crates/sqlbuild-core/src/lifecycle_events/constants.rs index 1bef321972..b459a0334c 100644 --- a/crates/sqlbuild-core/src/lifecycle_events/constants.rs +++ b/crates/sqlbuild-core/src/lifecycle_events/constants.rs @@ -108,7 +108,7 @@ pub(crate) const FORBIDDEN_STATEMENT_PAYLOAD_FIELDS: [&str; 8] = [ "statement_sql", ]; -pub(crate) const STRING_PAYLOAD_FIELDS: [&str; 56] = [ +pub(crate) const STRING_PAYLOAD_FIELDS: [&str; 58] = [ "adapter", "attached_column_name", "attached_target_kind", @@ -142,6 +142,7 @@ pub(crate) const STRING_PAYLOAD_FIELDS: [&str; 56] = [ "measurement_sql", "microbatch_run_type", "microbatch_strategy", + "not_run_reason", "operation_kind", "operation_name", "outcome", @@ -155,6 +156,7 @@ pub(crate) const STRING_PAYLOAD_FIELDS: [&str; 56] = [ "resource_name", "result_id", "run_kind", + "run_on", "run_scope_phase", "sample_unit", "scope", @@ -574,6 +576,7 @@ pub(crate) const LIFECYCLE_EVENT_CATALOG_V1: [EventDefinition; 20] = [ "measured_value", "measurement_sql", "minimum_samples", + "not_run_reason", "outcome", "result_id", "reused", @@ -959,6 +962,7 @@ pub(crate) const LIFECYCLE_EVENT_CATALOG_V2: [EventDefinition; 24] = [ "measured_value", "measurement_sql", "minimum_samples", + "not_run_reason", "outcome", "result_id", "reused", @@ -989,6 +993,7 @@ pub(crate) const LIFECYCLE_EVENT_CATALOG_V2: [EventDefinition; 24] = [ "purpose", "query_id", "row_count", + "run_on", "sql_digest", "statement_kind", ], @@ -1007,6 +1012,7 @@ pub(crate) const LIFECYCLE_EVENT_CATALOG_V2: [EventDefinition; 24] = [ "metadata", "purpose", "query_id", + "run_on", "sql_digest", "statement_kind", ], @@ -1027,6 +1033,7 @@ pub(crate) const LIFECYCLE_EVENT_CATALOG_V2: [EventDefinition; 24] = [ "purpose", "query_id", "row_count", + "run_on", "sql_digest", "statement_kind", ], @@ -1047,6 +1054,7 @@ pub(crate) const LIFECYCLE_EVENT_CATALOG_V2: [EventDefinition; 24] = [ "purpose", "query_id", "row_count", + "run_on", "sql_digest", "statement_kind", ], @@ -1070,6 +1078,7 @@ pub(crate) const LIFECYCLE_EVENT_CATALOG_V2: [EventDefinition; 24] = [ "purpose", "query_id", "row_count", + "run_on", "sql_digest", "statement_kind", ], diff --git a/crates/sqlbuild-core/src/plan_display/main/mod.rs b/crates/sqlbuild-core/src/plan_display/main/mod.rs index 7e862d98a7..ead907c355 100644 --- a/crates/sqlbuild-core/src/plan_display/main/mod.rs +++ b/crates/sqlbuild-core/src/plan_display/main/mod.rs @@ -13,3 +13,4 @@ pub mod model_resource_type; pub mod old_name_rows; pub mod plan_section_page; pub mod plan_summary; +pub mod plan_summary_parts; diff --git a/crates/sqlbuild-core/src/plan_display/main/plan_summary_parts.rs b/crates/sqlbuild-core/src/plan_display/main/plan_summary_parts.rs new file mode 100644 index 0000000000..433a5ed157 --- /dev/null +++ b/crates/sqlbuild-core/src/plan_display/main/plan_summary_parts.rs @@ -0,0 +1,40 @@ +//! What a plan will run, in the parts its `Plan ready` line and its `planned` event share. + +use crate::plan_display::models::PlanSummaryCounts; + +/// Each non-zero count with its noun, such as `3 selected` and `1 Python node`; `0 selected` when all are zero. +#[must_use] +pub fn plan_summary_parts(counts: &PlanSummaryCounts) -> Vec { + let noun = |count: usize, one: &str, many: &str| { + format!("{count} {}", if count == 1 { one } else { many }) + }; + let action: &str = if counts.reloads_sources { + "reload" + } else { + "load" + }; + let parts: Vec = [ + (counts.full_refresh, "full refresh".to_owned()), + (counts.selected > 0, format!("{} selected", counts.selected)), + ( + counts.sources > 0, + format!("{} to {action}", noun(counts.sources, "source", "sources")), + ), + ( + counts.python > 0, + noun(counts.python, "Python node", "Python nodes"), + ), + (counts.audits > 0, noun(counts.audits, "audit", "audits")), + ( + counts.audits_not_run > 0, + format!("{} not run", noun(counts.audits_not_run, "audit", "audits")), + ), + ] + .into_iter() + .filter_map(|(shown, part)| shown.then_some(part)) + .collect(); + if parts.is_empty() { + return vec!["0 selected".to_owned()]; + } + parts +} diff --git a/crates/sqlbuild-core/src/plan_display/models.rs b/crates/sqlbuild-core/src/plan_display/models.rs index 012b1462c8..fb303c6957 100644 --- a/crates/sqlbuild-core/src/plan_display/models.rs +++ b/crates/sqlbuild-core/src/plan_display/models.rs @@ -98,3 +98,16 @@ pub struct DiffStats { /// The removed and added lines read the same with every whitespace character taken out. pub whitespace_only: bool, } + +/// What a plan will run, by kind, for its one-line summary. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PlanSummaryCounts { + pub full_refresh: bool, + /// Models, seeds and functions. + pub selected: usize, + pub sources: usize, + pub reloads_sources: bool, + pub python: usize, + pub audits: usize, + pub audits_not_run: usize, +} diff --git a/crates/sqlbuild-core/src/plan_display/tests.rs b/crates/sqlbuild-core/src/plan_display/tests.rs index 69caca92a6..5585d3b36c 100644 --- a/crates/sqlbuild-core/src/plan_display/tests.rs +++ b/crates/sqlbuild-core/src/plan_display/tests.rs @@ -4,5 +4,7 @@ mod helpers; mod plan_display; #[path = "tests/test_plan_pages.rs"] mod plan_pages; +#[path = "tests/test_plan_summary.rs"] +mod plan_summary; #[path = "tests/test_types.rs"] mod test_types; diff --git a/crates/sqlbuild-core/src/plan_display/tests/test_plan_summary.rs b/crates/sqlbuild-core/src/plan_display/tests/test_plan_summary.rs new file mode 100644 index 0000000000..d8c2b39095 --- /dev/null +++ b/crates/sqlbuild-core/src/plan_display/tests/test_plan_summary.rs @@ -0,0 +1,43 @@ +//! A plan's summary counts what it runs and leaves out zero counts; with nothing at all it is `0 selected`. + +use crate::plan_display::main::plan_summary_parts::plan_summary_parts; +use crate::plan_display::models::PlanSummaryCounts; +use crate::plan_display::tests::test_types::PlanSummaryTestCase; + +#[test] +fn given_plan_counts_when_summarised_then_only_what_runs_is_named() { + let test_cases = [ + PlanSummaryTestCase { + description: "a job of one Python asset", + counts: PlanSummaryCounts { + python: 1, + ..PlanSummaryCounts::default() + }, + expected_parts: &["1 Python node"], + }, + PlanSummaryTestCase { + description: "models, a reloaded source and Python nodes", + counts: PlanSummaryCounts { + selected: 3, + sources: 1, + reloads_sources: true, + python: 2, + ..PlanSummaryCounts::default() + }, + expected_parts: &["3 selected", "1 source to reload", "2 Python nodes"], + }, + PlanSummaryTestCase { + description: "a plan with nothing at all", + counts: PlanSummaryCounts::default(), + expected_parts: &["0 selected"], + }, + ]; + for test_case in test_cases { + assert_eq!( + plan_summary_parts(&test_case.counts), + test_case.expected_parts, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-core/src/plan_display/tests/test_types.rs b/crates/sqlbuild-core/src/plan_display/tests/test_types.rs index f99fa8d4b7..d4a16a261c 100644 --- a/crates/sqlbuild-core/src/plan_display/tests/test_types.rs +++ b/crates/sqlbuild-core/src/plan_display/tests/test_types.rs @@ -122,3 +122,9 @@ pub(super) struct ConfigChangeTestCase { pub(super) model: &'static str, pub(super) expected_change: Option<&'static str>, } + +pub(super) struct PlanSummaryTestCase { + pub(super) description: &'static str, + pub(super) counts: crate::plan_display::models::PlanSummaryCounts, + pub(super) expected_parts: &'static [&'static str], +} diff --git a/crates/sqlbuild-core/src/progress/_helpers/resources.rs b/crates/sqlbuild-core/src/progress/_helpers/resources.rs index 32c55fa84a..16111eba27 100644 --- a/crates/sqlbuild-core/src/progress/_helpers/resources.rs +++ b/crates/sqlbuild-core/src/progress/_helpers/resources.rs @@ -90,6 +90,9 @@ pub(crate) fn consume_resource_start( .insert(resource_id.clone(), resource_name.clone()); let (projection, mut lines) = render_prior_attempts(projection, (resource_id, resource_name)); let projection: ProgressProjection = store_attempt(projection, attempt_id, event); + if projection.unstarted_resource_names.contains(resource_name) { + return (projection, lines); + } if projection.settings.is_tty && (projection.enriched_resource_names.contains(resource_name) || !projection.settings.debug) diff --git a/crates/sqlbuild-core/src/progress/constants.rs b/crates/sqlbuild-core/src/progress/constants.rs index f96409d8bb..70f2375e70 100644 --- a/crates/sqlbuild-core/src/progress/constants.rs +++ b/crates/sqlbuild-core/src/progress/constants.rs @@ -114,12 +114,13 @@ pub(crate) const STATUS_ELLIPSIS: &str = "..."; pub(crate) const AUDIT_RESOURCE_KIND: &str = "audit"; pub(crate) const AUDIT_RESOURCE_PREFIX: &str = "audit:"; /// Audit outcomes and the status words their rows show. -pub(crate) const AUDIT_OUTCOME_STATUSES: [(&str, &str); 5] = [ +pub(crate) const AUDIT_OUTCOME_STATUSES: [(&str, &str); 6] = [ ("pass", "PASS"), ("warn", "WARN"), ("error", "FAIL"), ("insufficient", "INSUFFICIENT"), ("skipped", "SKIP"), + ("not_run", "NOT RUN"), ]; /// Where reported statement compile and execution time comes from. diff --git a/crates/sqlbuild-core/src/progress/main/format_statement_summary.rs b/crates/sqlbuild-core/src/progress/main/format_statement_summary.rs index c189b1de47..4f737d171d 100644 --- a/crates/sqlbuild-core/src/progress/main/format_statement_summary.rs +++ b/crates/sqlbuild-core/src/progress/main/format_statement_summary.rs @@ -2,7 +2,7 @@ use crate::progress::models::{StatementSummary, StatementTiming}; -/// `Statements: 12 (SELECT 8, CREATE 2, DROP 2); compile 1.5s, execution 0.8s`; nothing without statements. +/// `Statements: 12 on the warehouse (SELECT 8, CREATE 2, DROP 2); compile 1.5s, execution 0.8s`; nothing without statements. #[must_use] pub fn format_statement_summary( summary: &StatementSummary, @@ -41,5 +41,7 @@ pub fn format_statement_summary( StatementTiming::NotReported(adapter) => format!("compile time not reported by {adapter}"), StatementTiming::Failed(reason) => format!("compile time unavailable ({reason})"), }; - Some(format!("Statements: {total} ({kinds}); {time}")) + Some(format!( + "Statements: {total} on the warehouse ({kinds}); {time}" + )) } diff --git a/crates/sqlbuild-core/src/progress/main/mod.rs b/crates/sqlbuild-core/src/progress/main/mod.rs index c912a2b982..65499092f1 100644 --- a/crates/sqlbuild-core/src/progress/main/mod.rs +++ b/crates/sqlbuild-core/src/progress/main/mod.rs @@ -14,4 +14,5 @@ pub mod is_planning_completion_message; pub mod is_planning_failure_message; pub mod machine_output_mode; pub mod progress_terminal_duration; +pub mod statement_summary_delta; pub mod statement_summary_json; diff --git a/crates/sqlbuild-core/src/progress/main/statement_summary_delta.rs b/crates/sqlbuild-core/src/progress/main/statement_summary_delta.rs new file mode 100644 index 0000000000..840b3ec4a3 --- /dev/null +++ b/crates/sqlbuild-core/src/progress/main/statement_summary_delta.rs @@ -0,0 +1,25 @@ +//! The statements one part of an invocation finished, from summaries taken before and after it. + +use crate::progress::models::StatementSummary; + +/// The statements counted in `after` and not yet in `before`. +#[must_use] +pub fn statement_summary_delta( + before: &StatementSummary, + after: &StatementSummary, +) -> StatementSummary { + let mut delta: StatementSummary = StatementSummary::default(); + for (kind, count) in &after.by_kind { + let earlier: u64 = before.by_kind.get(kind).copied().unwrap_or(0); + if *count > earlier { + delta.by_kind.insert(kind.clone(), count - earlier); + } + } + delta.query_ids = after + .query_ids + .iter() + .filter(|query_id| !before.query_ids.contains(query_id)) + .cloned() + .collect(); + delta +} diff --git a/crates/sqlbuild-core/src/progress/models.rs b/crates/sqlbuild-core/src/progress/models.rs index f9d0f1612a..2db9164e50 100644 --- a/crates/sqlbuild-core/src/progress/models.rs +++ b/crates/sqlbuild-core/src/progress/models.rs @@ -78,6 +78,8 @@ pub struct ProgressProjection { pub(crate) operation_starts: HashMap, pub(crate) quiet_operation_ids: HashSet, pub(crate) enriched_resource_names: HashSet, + /// Resources that never start, such as an audit not run, so they show only their terminal row. + pub(crate) unstarted_resource_names: HashSet, /// Audit outcomes by attempt, which the audit's own terminal row shows. pub(crate) audit_outcomes: HashMap, pub(crate) resource_names: HashMap, @@ -137,6 +139,33 @@ impl ProgressProjection { .insert(resource_name.to_owned()); } + /// Declare that this resource never starts, so its terminal row is its only row. + pub fn expect_no_start(&mut self, resource_name: &str) { + self.unstarted_resource_names + .insert(resource_name.to_owned()); + } + + /// Treat every pending terminal of this resource as shown, so no later attempt renders it. + pub fn forget_resource_attempts(&mut self, resource_id: &str) { + let pending: VecDeque = self + .pending_terminal_ids_by_resource + .remove(resource_id) + .unwrap_or_default(); + self.rendered_terminal_ids.extend(pending); + } + + /// `forget_resource_attempts` for every resource reported under `resource_name`. + pub fn forget_resource_named(&mut self, resource_name: &str) { + let resource_ids: Vec = self + .resource_ids_by_name + .get(resource_name) + .map(|ids| ids.iter().cloned().collect()) + .unwrap_or_default(); + for resource_id in resource_ids { + self.forget_resource_attempts(&resource_id); + } + } + /// Record how one audit attempt ended, before its terminal row renders. pub fn record_audit_outcome(&mut self, resource_attempt_id: &str, outcome: &str) { self.audit_outcomes diff --git a/crates/sqlbuild-core/src/progress/tests/helpers.rs b/crates/sqlbuild-core/src/progress/tests/helpers.rs index a3367b93a7..b1b7daff39 100644 --- a/crates/sqlbuild-core/src/progress/tests/helpers.rs +++ b/crates/sqlbuild-core/src/progress/tests/helpers.rs @@ -91,6 +91,9 @@ pub(super) fn audit_rows(test_case: &AuditRowTestCase) -> Vec { for (attempt_id, outcome) in &test_case.recorded_outcomes { projection.record_audit_outcome(attempt_id, outcome); } + for name in test_case.unstarted { + projection.expect_no_start(name); + } let mut lines: Vec = Vec::new(); for (event_id, event_type) in [ ("e1", "resource_attempt_started"), diff --git a/crates/sqlbuild-core/src/progress/tests/test_progress.rs b/crates/sqlbuild-core/src/progress/tests/test_progress.rs index 0ea684b0e0..f046640fd7 100644 --- a/crates/sqlbuild-core/src/progress/tests/test_progress.rs +++ b/crates/sqlbuild-core/src/progress/tests/test_progress.rs @@ -230,6 +230,7 @@ fn given_standalone_audit_when_projecting_then_row_names_target_and_outcome() { resource_id: "audit:not_null:seed:customers:customer_id", terminal_event: "resource_attempt_completed", recorded_outcomes: vec![("a1", "pass")], + unstarted: &[], expected_lines: vec![ " audit not_null (customers.customer_id) START", " audit not_null (customers.customer_id) PASS 0.01s", @@ -240,6 +241,7 @@ fn given_standalone_audit_when_projecting_then_row_names_target_and_outcome() { resource_id: "audit:not_null:source:raw_orders:order_id", terminal_event: "resource_attempt_completed", recorded_outcomes: vec![("a1", "warn")], + unstarted: &[], expected_lines: vec![ " audit not_null (raw_orders.order_id) START", " audit not_null (raw_orders.order_id) WARN 0.01s", @@ -250,6 +252,7 @@ fn given_standalone_audit_when_projecting_then_row_names_target_and_outcome() { resource_id: "audit:not_null:singular", terminal_event: "resource_attempt_failed", recorded_outcomes: vec![("a1", "error")], + unstarted: &[], expected_lines: vec![ " audit not_null START", " audit not_null FAIL 0.01s", @@ -260,11 +263,20 @@ fn given_standalone_audit_when_projecting_then_row_names_target_and_outcome() { resource_id: "audit:not_null:model:orders", terminal_event: "resource_attempt_completed", recorded_outcomes: vec![("a2", "warn")], + unstarted: &[], expected_lines: vec![ " audit not_null (orders) START", " audit not_null (orders) PASS 0.01s", ], }, + AuditRowTestCase { + description: "an audit that isn't run shows only its NOT RUN row, never a start", + resource_id: "audit:not_null:end", + terminal_event: "resource_attempt_completed", + recorded_outcomes: vec![("a1", "not_run")], + unstarted: &["not_null"], + expected_lines: vec![" audit not_null NOT RUN 0.01s"], + }, ]; for test_case in test_cases { assert_eq!( @@ -407,7 +419,7 @@ fn given_statement_summary_when_formatting_then_line_and_json_report_kinds_and_t summary: summary.clone(), timing: reported(1540.0, 260.0, 12), expected_line: Some( - "Statements: 12 (SELECT 7, CREATE 2, DROP 2, ALTER 1); compile 1.5s, execution 0.3s", + "Statements: 12 on the warehouse (SELECT 7, CREATE 2, DROP 2, ALTER 1); compile 1.5s, execution 0.3s", ), expected_json: serde_json::json!({ "total": 12, @@ -426,7 +438,7 @@ fn given_statement_summary_when_formatting_then_line_and_json_report_kinds_and_t summary: summary.clone(), timing: reported(1000.0, 0.0, 10), expected_line: Some( - "Statements: 12 (SELECT 7, CREATE 2, DROP 2, ALTER 1); compile 1.0s, execution 0.0s (10 of 12 statements in query history)", + "Statements: 12 on the warehouse (SELECT 7, CREATE 2, DROP 2, ALTER 1); compile 1.0s, execution 0.0s (10 of 12 statements in query history)", ), expected_json: serde_json::json!({ "total": 12, @@ -445,7 +457,7 @@ fn given_statement_summary_when_formatting_then_line_and_json_report_kinds_and_t summary: summary.clone(), timing: StatementTiming::NotReported("duckdb".to_owned()), expected_line: Some( - "Statements: 12 (SELECT 7, CREATE 2, DROP 2, ALTER 1); compile time not reported by duckdb", + "Statements: 12 on the warehouse (SELECT 7, CREATE 2, DROP 2, ALTER 1); compile time not reported by duckdb", ), expected_json: serde_json::json!({ "total": 12, @@ -458,7 +470,7 @@ fn given_statement_summary_when_formatting_then_line_and_json_report_kinds_and_t summary: summary.clone(), timing: StatementTiming::Failed("query history read failed".to_owned()), expected_line: Some( - "Statements: 12 (SELECT 7, CREATE 2, DROP 2, ALTER 1); compile time unavailable (query history read failed)", + "Statements: 12 on the warehouse (SELECT 7, CREATE 2, DROP 2, ALTER 1); compile time unavailable (query history read failed)", ), expected_json: serde_json::json!({ "total": 12, diff --git a/crates/sqlbuild-core/src/progress/tests/test_types.rs b/crates/sqlbuild-core/src/progress/tests/test_types.rs index ac0b995f26..0ee37b2a2d 100644 --- a/crates/sqlbuild-core/src/progress/tests/test_types.rs +++ b/crates/sqlbuild-core/src/progress/tests/test_types.rs @@ -55,6 +55,8 @@ pub(super) struct AuditRowTestCase { pub(super) resource_id: &'static str, pub(super) terminal_event: &'static str, pub(super) recorded_outcomes: Vec<(&'static str, &'static str)>, + /// Resources declared never to start, as an audit that isn't run is. + pub(super) unstarted: &'static [&'static str], pub(super) expected_lines: Vec<&'static str>, } diff --git a/crates/sqlbuild-core/src/run_on/_helpers/mod.rs b/crates/sqlbuild-core/src/run_on/_helpers/mod.rs new file mode 100644 index 0000000000..a8135032dd --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/_helpers/mod.rs @@ -0,0 +1,2 @@ +pub(crate) mod refusal_blocks; +pub(crate) mod runner_json; diff --git a/crates/sqlbuild-core/src/run_on/_helpers/refusal_blocks.rs b/crates/sqlbuild-core/src/run_on/_helpers/refusal_blocks.rs new file mode 100644 index 0000000000..068f03942a --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/_helpers/refusal_blocks.rs @@ -0,0 +1,122 @@ +//! Refusals grouped by construct and place, laid out as SQLQuack lays out its diagnostics. + +use crate::cli_text::models::CliStyle; +use crate::format_command::main::render_help_lines::render_help_lines; +use crate::format_command::main::render_violation_block::render_violation_block; +use crate::format_command::models::LintFinding; +use crate::run_on::constants::{CARET_LINE, EXPANDED_LABEL, NOTE_LABEL, TESTS_NOTE}; +use crate::run_on::models::{GroupedRefusal, LocalRefusal, RefusalPlace, RunOnDecision}; + +/// Each refused construct and place once, in first-seen order, with every item it blocks. +pub(crate) fn grouped_refusals(decisions: &[&RunOnDecision]) -> Vec { + let mut places: Vec = Vec::new(); + let mut groups: Vec = Vec::new(); + for decision in decisions { + for refusal in &decision.refusals { + let place: RefusalPlace = refusal_place(refusal); + match places.iter().position(|seen| *seen == place) { + Some(index) => { + let names: &mut Vec = &mut groups[index].names; + if !names.contains(&decision.name) { + names.push(decision.name.clone()); + } + } + None => { + places.push(place); + groups.push(GroupedRefusal { + refusal: refusal.clone(), + names: vec![decision.name.clone()], + }); + } + } + } + } + groups +} + +fn refusal_place(refusal: &LocalRefusal) -> RefusalPlace { + RefusalPlace { + path: refusal.path.clone().unwrap_or_default(), + construct: refusal.construct.clone(), + line: refusal.line.unwrap_or(0), + column: refusal.column.unwrap_or(0), + code: refusal.code.clone().unwrap_or_default(), + } +} + +/// One refusal in SQLQuack's layout: an `error` where it stops its items running, a `note` where they fall back. +pub(crate) fn refusal_block( + refusal: &LocalRefusal, + names: &[String], + (errors, style): (bool, CliStyle), +) -> String { + let message: String = refusal.message.clone().unwrap_or_else(|| refusal.title()); + let code: String = refusal.code.clone().unwrap_or_default(); + let severity: &str = if errors { "error" } else { "note" }; + let labelled: String = if code.is_empty() { + severity.to_owned() + } else { + format!("{severity}[{code}]") + }; + let header: String = if errors { + style.error_strong(&labelled) + } else { + style.accent_strong(&labelled) + }; + let mut lines: Vec = match (&refusal.path, refusal.line, refusal.column) { + (Some(path), Some(line), Some(column)) => { + let caret: i64 = refusal.snippet_column.unwrap_or(column); + let finding: LintFinding = LintFinding { + file: path.clone(), + display_path: path.clone(), + line, + column: caret, + end_line: Some(line), + end_column: Some(caret + refusal.width.max(1)), + code: code.clone(), + message, + fault: true, + engine: String::new(), + remediation: None, + source_line: refusal.snippet.clone(), + }; + let mut located: Vec = render_violation_block(&finding, style) + .lines() + .map(str::to_owned) + .collect(); + located[0] = + located[0].replacen(&style.error_strong(&format!("error[{code}]")), &header, 1); + if caret != column && located.len() > 1 { + located[1] = style.muted(&format!(" --> {path}:{line}:{column}")); + } + let label: &str = refusal.label.as_deref().unwrap_or(&refusal.reason); + if refusal.snippet.is_some() && !label.is_empty() && located.len() > CARET_LINE { + located[CARET_LINE] = format!("{} {label}", located[CARET_LINE]); + } + located + } + _ => { + let mut header_lines: Vec = vec![format!("{header}: {message}")]; + let label: &str = refusal.label.as_deref().unwrap_or(&refusal.reason); + if !label.is_empty() && label != message { + header_lines.push(format!(" {} {label}", style.muted(NOTE_LABEL))); + } + header_lines + } + }; + for note in &refusal.notes { + lines.push(format!(" {} {note}", style.muted(NOTE_LABEL))); + } + if let Some(help) = &refusal.help { + lines.extend(render_help_lines(help, style)); + } + if let Some(expanded) = &refusal.expanded_from { + lines.push(format!(" {} {expanded}", style.muted(EXPANDED_LABEL))); + } + lines.push(format!( + " {} {}", + style.muted(TESTS_NOTE), + names.join(", ") + )); + lines.join("\n") +} diff --git a/crates/sqlbuild-core/src/run_on/_helpers/runner_json.rs b/crates/sqlbuild-core/src/run_on/_helpers/runner_json.rs new file mode 100644 index 0000000000..9338e7c073 --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/_helpers/runner_json.rs @@ -0,0 +1,58 @@ +//! Decisions and refusals read from the local runner's JSON objects. + +use serde_json::Value; + +use crate::run_on::models::{LocalRefusal, RunOnDecision}; + +/// One decision object; missing fields are empty. +pub(crate) fn decision(value: &Value) -> RunOnDecision { + let refusals: &[Value] = value + .get("refusals") + .and_then(Value::as_array) + .map_or(&[], Vec::as_slice); + RunOnDecision { + name: text(value, "name").unwrap_or_default(), + run_on: text(value, "run_on").unwrap_or_default(), + refusals: refusals.iter().map(refusal).collect(), + } +} + +fn refusal(value: &Value) -> LocalRefusal { + LocalRefusal { + category: text(value, "category").unwrap_or_default(), + construct: text(value, "construct").unwrap_or_default(), + reason: text(value, "reason").unwrap_or_default(), + code: text(value, "code"), + message: text(value, "message"), + label: text(value, "label"), + notes: strings(value, "notes"), + help: text(value, "help"), + path: text(value, "path"), + line: number(value, "line"), + column: number(value, "column"), + width: number(value, "width").unwrap_or(1), + snippet: text(value, "snippet"), + snippet_column: number(value, "snippet_column"), + expanded_from: text(value, "expanded_from"), + } +} + +fn text(value: &Value, key: &str) -> Option { + value.get(key).and_then(Value::as_str).map(str::to_owned) +} + +fn number(value: &Value, key: &str) -> Option { + value.get(key).and_then(Value::as_i64) +} + +fn strings(value: &Value, key: &str) -> Vec { + let items: &[Value] = value + .get(key) + .and_then(Value::as_array) + .map_or(&[], Vec::as_slice); + items + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() +} diff --git a/crates/sqlbuild-core/src/run_on/constants.rs b/crates/sqlbuild-core/src/run_on/constants.rs new file mode 100644 index 0000000000..7c4e03d847 --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/constants.rs @@ -0,0 +1,15 @@ +//! The run-on vocabulary and the text of its report sections. + +pub(crate) const AUTO: &str = "auto"; +pub(crate) const LOCAL: &str = "local"; +pub(crate) const WAREHOUSE: &str = "warehouse"; +/// The width of the run-on column: the longer of `local` and `warehouse`. +pub(crate) const COLUMN_WIDTH: usize = 9; +pub(crate) const CANNOT_RUN_LOCALLY_TITLE: &str = "Can't run locally"; +pub(crate) const ON_THE_WAREHOUSE_TITLE: &str = "On the warehouse"; +pub(crate) const RUNS_ON_LABEL: &str = "runs on"; +pub(crate) const TESTS_NOTE: &str = "= tests:"; +pub(crate) const NOTE_LABEL: &str = "= note:"; +pub(crate) const EXPANDED_LABEL: &str = "= expanded from"; +/// The caret line's index in a located block: header, `-->`, gutter, source, caret. +pub(crate) const CARET_LINE: usize = 4; diff --git a/crates/sqlbuild-core/src/run_on/main/apply_local_refusals.rs b/crates/sqlbuild-core/src/run_on/main/apply_local_refusals.rs new file mode 100644 index 0000000000..7c2656fde7 --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/main/apply_local_refusals.rs @@ -0,0 +1,20 @@ +//! Local tests that failed where the warehouse would not: why, and in `auto` where they then ran. + +use crate::run_on::constants::WAREHOUSE; +use crate::run_on::models::{LocalRefusal, RunOn, RunOnDecision}; + +/// Each named test's refusal from its local run; in `auto` the test ran again on the warehouse. +pub fn apply_local_refusals( + decisions: &mut [RunOnDecision], + refused: Vec<(String, LocalRefusal)>, + mode: RunOn, +) { + for (name, refusal) in refused { + if let Some(decision) = decisions.iter_mut().find(|decision| decision.name == name) { + if mode == RunOn::Auto { + WAREHOUSE.clone_into(&mut decision.run_on); + } + decision.refusals = vec![refusal]; + } + } +} diff --git a/crates/sqlbuild-core/src/run_on/main/mod.rs b/crates/sqlbuild-core/src/run_on/main/mod.rs new file mode 100644 index 0000000000..1025d334d4 --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/main/mod.rs @@ -0,0 +1,10 @@ +pub mod apply_local_refusals; +pub mod read_local_refusal; +pub mod read_run_on_decisions; +pub mod render_local_refusals; +pub mod render_warehouse_census; +pub mod resolve_run_on; +pub mod run_on_column; +pub mod run_on_inspection_line; +pub mod run_on_split; +pub mod with_run_on_json; diff --git a/crates/sqlbuild-core/src/run_on/main/read_local_refusal.rs b/crates/sqlbuild-core/src/run_on/main/read_local_refusal.rs new file mode 100644 index 0000000000..9a3771dbe0 --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/main/read_local_refusal.rs @@ -0,0 +1,21 @@ +//! A local test's failure where the warehouse would not fail, as the test runner reports it. + +use std::collections::HashMap; + +use crate::run_on::models::LocalRefusal; + +/// The test named by `fields["test"]` and its refusal, from `category`, `construct` and `reason`. +#[must_use] +pub fn read_local_refusal(mut fields: HashMap) -> (String, LocalRefusal) { + let mut take = |key: &str| fields.remove(key).unwrap_or_default(); + ( + take("test"), + LocalRefusal { + category: take("category"), + construct: take("construct"), + reason: take("reason"), + width: 1, + ..LocalRefusal::default() + }, + ) +} diff --git a/crates/sqlbuild-core/src/run_on/main/read_run_on_decisions.rs b/crates/sqlbuild-core/src/run_on/main/read_run_on_decisions.rs new file mode 100644 index 0000000000..d1d4122672 --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/main/read_run_on_decisions.rs @@ -0,0 +1,16 @@ +//! The decisions the local runner's JSON reports, one per test or scenario. + +use serde_json::Value; + +use crate::run_on::_helpers::runner_json::decision; +use crate::run_on::models::RunOnDecision; + +/// `{"decisions": [{name, run_on, refusals: [...]}, ...]}` as decisions; malformed JSON is an error. +pub fn read_run_on_decisions(json: &str) -> Result, String> { + let document: Value = serde_json::from_str(json).map_err(|error| error.to_string())?; + let decisions: &Vec = document + .get("decisions") + .and_then(Value::as_array) + .ok_or_else(|| "run-on decisions have no `decisions` list".to_owned())?; + Ok(decisions.iter().map(decision).collect()) +} diff --git a/crates/sqlbuild-core/src/run_on/main/render_local_refusals.rs b/crates/sqlbuild-core/src/run_on/main/render_local_refusals.rs new file mode 100644 index 0000000000..850792fd27 --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/main/render_local_refusals.rs @@ -0,0 +1,37 @@ +//! SQLQuack's refusals as its own diagnostics, placed in the files that hold them. + +use crate::cli_text::models::CliStyle; +use crate::run_on::_helpers::refusal_blocks::{grouped_refusals, refusal_block}; +use crate::run_on::constants::{CANNOT_RUN_LOCALLY_TITLE, ON_THE_WAREHOUSE_TITLE}; +use crate::run_on::models::{GroupedRefusal, RunOnDecision}; + +/// A titled section with one diagnostic per refused construct and place, and the items it blocks. +#[must_use] +pub fn render_local_refusals( + decisions: &[RunOnDecision], + errors: bool, + (singular, plural): (&str, &str), + style: CliStyle, +) -> String { + let refused: Vec<&RunOnDecision> = decisions + .iter() + .filter(|decision| !decision.refusals.is_empty()) + .collect(); + if refused.is_empty() { + return String::new(); + } + let noun: &str = if refused.len() == 1 { singular } else { plural }; + let title: &str = if errors { + CANNOT_RUN_LOCALLY_TITLE + } else { + ON_THE_WAREHOUSE_TITLE + }; + let mut text: String = format!("\n{} ({} {noun})\n", style.section(title), refused.len()); + for group in grouped_refusals(&refused) { + let GroupedRefusal { refusal, names } = group; + text.push('\n'); + text.push_str(&refusal_block(&refusal, &names, (errors, style))); + text.push('\n'); + } + text +} diff --git a/crates/sqlbuild-core/src/run_on/main/render_warehouse_census.rs b/crates/sqlbuild-core/src/run_on/main/render_warehouse_census.rs new file mode 100644 index 0000000000..cffa27c3a6 --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/main/render_warehouse_census.rs @@ -0,0 +1,56 @@ +//! `On the warehouse (N tests)`: the refusals that sent items to the warehouse, most items first. + +use std::collections::BTreeMap; + +use crate::cli_text::models::CliStyle; +use crate::run_on::constants::ON_THE_WAREHOUSE_TITLE; +use crate::run_on::models::RunOnDecision; + +/// One line per refusal title with how many items it keeps off DuckDB; empty with none. +#[must_use] +pub fn render_warehouse_census( + decisions: &[RunOnDecision], + (singular, plural): (&str, &str), + style: CliStyle, +) -> String { + let refused: Vec<&RunOnDecision> = decisions + .iter() + .filter(|decision| !decision.refusals.is_empty()) + .collect(); + if refused.is_empty() { + return String::new(); + } + let mut counts: BTreeMap = BTreeMap::new(); + for decision in &refused { + let mut titles: Vec = decision + .refusals + .iter() + .map(|refusal| refusal.title()) + .collect(); + titles.sort(); + titles.dedup(); + for title in titles { + *counts.entry(title).or_default() += 1; + } + } + let mut rows: Vec<(String, usize)> = counts.into_iter().collect(); + rows.sort_by(|(left_title, left), (right_title, right)| { + right.cmp(left).then_with(|| left_title.cmp(right_title)) + }); + let width: usize = rows + .iter() + .map(|(title, _)| title.chars().count()) + .max() + .unwrap_or(0); + let noun = |count: usize| if count == 1 { singular } else { plural }; + let mut text: String = format!( + "\n{} ({} {})\n", + style.section(ON_THE_WAREHOUSE_TITLE), + refused.len(), + noun(refused.len()) + ); + for (title, count) in rows { + text.push_str(&format!(" {title: RunOn { + [&layers.flag, &layers.target, &layers.settings] + .into_iter() + .flatten() + .find_map(|value| RunOn::parse(value)) + .unwrap_or_default() +} diff --git a/crates/sqlbuild-core/src/run_on/main/run_on_column.rs b/crates/sqlbuild-core/src/run_on/main/run_on_column.rs new file mode 100644 index 0000000000..1e73126e74 --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/main/run_on_column.rs @@ -0,0 +1,9 @@ +//! The run-on column of a result row, after its status. + +use crate::run_on::constants::COLUMN_WIDTH; + +/// `local` or `warehouse`, padded so the details after it line up. +#[must_use] +pub fn run_on_column(run_on: &str) -> String { + format!("{run_on:)`, with a newline. +#[must_use] +pub fn run_on_inspection_line(decision: &RunOnDecision) -> String { + match decision.reason() { + Some(reason) if !decision.local() => { + format!(" {RUNS_ON_LABEL}: {} ({reason})\n", decision.run_on) + } + _ => format!(" {RUNS_ON_LABEL}: {}\n", decision.run_on), + } +} diff --git a/crates/sqlbuild-core/src/run_on/main/run_on_split.rs b/crates/sqlbuild-core/src/run_on/main/run_on_split.rs new file mode 100644 index 0000000000..fca65b03af --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/main/run_on_split.rs @@ -0,0 +1,7 @@ +//! The summary suffix that splits a run's items between DuckDB and the warehouse. + +/// `36 local, 4 warehouse`. +#[must_use] +pub fn run_on_split(local: usize, warehouse: usize) -> String { + format!("{local} local, {warehouse} warehouse") +} diff --git a/crates/sqlbuild-core/src/run_on/main/with_run_on_json.rs b/crates/sqlbuild-core/src/run_on/main/with_run_on_json.rs new file mode 100644 index 0000000000..267153ad38 --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/main/with_run_on_json.rs @@ -0,0 +1,84 @@ +//! A `--json` document with where each item ran, why, and every refusal with the items it blocks. + +use serde_json::{Map, Value, json}; + +use crate::run_on::models::{LocalRefusal, RunOnDecision}; + +/// `payload` with `run_on` and `run_on_reason` on each item, the split in `summary`, and `refusals`. +pub fn with_run_on_json( + payload: &str, + (items_key, name_keys): (&str, &[&str]), + decisions: &[RunOnDecision], + (local_count, warehouse_count): (usize, usize), +) -> Result { + let mut document: Value = serde_json::from_str(payload).map_err(|error| error.to_string())?; + if let Some(items) = document.get_mut(items_key).and_then(Value::as_array_mut) { + for item in items { + let name: Option = name_keys + .iter() + .find_map(|key| item.get(*key).and_then(Value::as_str)) + .map(str::to_owned); + let Some(decision) = name + .as_deref() + .and_then(|name| decisions.iter().find(|decision| decision.name == name)) + else { + continue; + }; + if let Some(fields) = item.as_object_mut() { + fields.insert("run_on".to_owned(), json!(decision.run_on)); + fields.insert("run_on_reason".to_owned(), json!(decision.reason())); + } + } + } + if let Some(summary) = document.get_mut("summary").and_then(Value::as_object_mut) { + summary.insert("local_count".to_owned(), json!(local_count)); + summary.insert("warehouse_count".to_owned(), json!(warehouse_count)); + } + if let Some(fields) = document.as_object_mut() { + fields.insert("refusals".to_owned(), Value::Array(refusals(decisions))); + } + serde_json::to_string(&document).map_err(|error| error.to_string()) +} + +/// Each refusal once per construct and place, as SQLQuack's `--json` reports it, with its items. +fn refusals(decisions: &[RunOnDecision]) -> Vec { + let mut found: Vec<(LocalRefusal, Vec)> = Vec::new(); + for decision in decisions { + for refusal in &decision.refusals { + let same = |known: &LocalRefusal| { + known.code == refusal.code + && known.construct == refusal.construct + && known.path == refusal.path + && known.line == refusal.line + && known.column == refusal.column + }; + match found.iter_mut().find(|(known, _)| same(known)) { + Some((_, names)) if !names.contains(&decision.name) => { + names.push(decision.name.clone()); + } + Some(_) => {} + None => found.push((refusal.clone(), vec![decision.name.clone()])), + } + } + } + found + .into_iter() + .map(|(refusal, names)| { + let mut fields: Map = Map::new(); + fields.insert("code".to_owned(), json!(refusal.code)); + fields.insert("category".to_owned(), json!(refusal.category)); + fields.insert("construct".to_owned(), json!(refusal.construct)); + fields.insert("title".to_owned(), json!(refusal.title())); + fields.insert("reason".to_owned(), json!(refusal.reason)); + fields.insert("message".to_owned(), json!(refusal.message)); + fields.insert("label".to_owned(), json!(refusal.label)); + fields.insert("notes".to_owned(), json!(refusal.notes)); + fields.insert("help".to_owned(), json!(refusal.help)); + fields.insert("path".to_owned(), json!(refusal.path)); + fields.insert("line".to_owned(), json!(refusal.line)); + fields.insert("column".to_owned(), json!(refusal.column)); + fields.insert("tests".to_owned(), json!(names)); + Value::Object(fields) + }) + .collect() +} diff --git a/crates/sqlbuild-core/src/run_on/mod.rs b/crates/sqlbuild-core/src/run_on/mod.rs new file mode 100644 index 0000000000..55c2dc4e14 --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/mod.rs @@ -0,0 +1,9 @@ +//! Where unit tests and scenarios run: locally in DuckDB, or on the warehouse, and why. + +pub(crate) mod _helpers; +pub(crate) mod constants; +pub mod main; +pub mod models; + +#[cfg(test)] +mod tests; diff --git a/crates/sqlbuild-core/src/run_on/models.rs b/crates/sqlbuild-core/src/run_on/models.rs new file mode 100644 index 0000000000..dc548c5f64 --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/models.rs @@ -0,0 +1,112 @@ +//! Where one test or scenario runs, and the refusals that keep it off DuckDB. + +use crate::run_on::constants::{AUTO, LOCAL, WAREHOUSE}; + +/// Where a run sends its tests or scenarios: `auto` picks per item. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum RunOn { + #[default] + Auto, + Local, + Warehouse, +} + +impl RunOn { + /// The setting's value, `auto`, `local` or `warehouse`; `None` for any other text. + #[must_use] + pub fn parse(value: &str) -> Option { + match value { + AUTO => Some(Self::Auto), + LOCAL => Some(Self::Local), + WAREHOUSE => Some(Self::Warehouse), + _ => None, + } + } + + /// The setting's value as configuration spells it. + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Self::Auto => AUTO, + Self::Local => LOCAL, + Self::Warehouse => WAREHOUSE, + } + } +} + +/// Every place a run's `RunOn` can be set, from highest precedence to lowest. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RunOnLayers { + pub flag: Option, + pub target: Option, + /// `[settings]`, the local file over the project file. + pub settings: Option, +} + +/// One SQLQuack refusal, or one of SQLBuild's own reasons, placed in the file holding it. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct LocalRefusal { + pub category: String, + pub construct: String, + pub reason: String, + pub code: Option, + pub message: Option, + pub label: Option, + pub notes: Vec, + pub help: Option, + pub path: Option, + pub line: Option, + pub column: Option, + pub width: i64, + pub snippet: Option, + /// Where the caret goes in `snippet` when it is generated SQL rather than the file's line. + pub snippet_column: Option, + pub expanded_from: Option, +} + +impl LocalRefusal { + /// `: `, as SQLQuack's census labels a refusal. + #[must_use] + pub fn title(&self) -> String { + format!("{}: {}", self.category, self.construct) + } +} + +/// Where one test or scenario runs, `local` or `warehouse`, with the refusals behind `warehouse`. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RunOnDecision { + pub name: String, + pub run_on: String, + pub refusals: Vec, +} + +impl RunOnDecision { + /// The first refusal's title; `None` when nothing keeps the item off DuckDB. + #[must_use] + pub fn reason(&self) -> Option { + self.refusals.first().map(LocalRefusal::title) + } + + /// Whether the item can run locally. + #[must_use] + pub fn local(&self) -> bool { + self.run_on == LOCAL + } +} + +/// Where one refusal sits, to show each refused construct and place once. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) struct RefusalPlace { + pub(crate) path: String, + pub(crate) construct: String, + pub(crate) line: i64, + pub(crate) column: i64, + pub(crate) code: String, +} + +/// One refusal and every item it blocks. +#[derive(Clone, Debug)] +pub(crate) struct GroupedRefusal { + pub(crate) refusal: LocalRefusal, + pub(crate) names: Vec, +} diff --git a/crates/sqlbuild-core/src/run_on/tests.rs b/crates/sqlbuild-core/src/run_on/tests.rs new file mode 100644 index 0000000000..74f953ec10 --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/tests.rs @@ -0,0 +1,6 @@ +#[path = "tests/helpers.rs"] +mod helpers; +#[path = "tests/test_run_on.rs"] +mod run_on; +#[path = "tests/test_types.rs"] +mod test_types; diff --git a/crates/sqlbuild-core/src/run_on/tests/helpers.rs b/crates/sqlbuild-core/src/run_on/tests/helpers.rs new file mode 100644 index 0000000000..87cae2eca5 --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/tests/helpers.rs @@ -0,0 +1,134 @@ +use serde_json::{Value, json}; + +use crate::run_on::main::read_run_on_decisions::read_run_on_decisions; +use crate::run_on::main::with_run_on_json::with_run_on_json; +use crate::run_on::models::{LocalRefusal, RunOnDecision, RunOnLayers}; + +/// A test that runs locally. +pub(super) fn local(name: &str) -> RunOnDecision { + RunOnDecision { + name: name.to_owned(), + run_on: "local".to_owned(), + refusals: Vec::new(), + } +} + +/// A test SQLQuack refuses at `line` of `stg_orders.sql` for `construct`. +pub(super) fn refused(name: &str, construct: &str, line: i64) -> RunOnDecision { + RunOnDecision { + name: name.to_owned(), + run_on: "warehouse".to_owned(), + refusals: vec![hash_refusal(construct, line)], + } +} + +/// SQLQuack's HASH refusal at `line` of `stg_orders.sql`. +fn hash_refusal(construct: &str, line: i64) -> LocalRefusal { + LocalRefusal { + category: "a known difference that isn't allowed".to_owned(), + construct: construct.to_owned(), + reason: "fn:HASH needs known divergence `hash`".to_owned(), + code: Some("SQ0008".to_owned()), + message: Some("HASH gives a different value in DuckDB".to_owned()), + label: Some("DuckDB computes its own hash, never Snowflake's".to_owned()), + notes: vec!["Equal inputs still get equal hashes within one run.".to_owned()], + help: Some("allow it with hash = true under [allow] in a sqlquack.toml".to_owned()), + path: Some("sql/models/staging/stg_orders.sql".to_owned()), + line: Some(line), + column: Some(3), + width: 12, + snippet: Some(" HASH(status) AS status_hash".to_owned()), + snippet_column: None, + expanded_from: None, + } +} + +/// A test SQLQuack refuses without a place in any file. +pub(super) fn unplaced(name: &str) -> RunOnDecision { + RunOnDecision { + name: name.to_owned(), + run_on: "warehouse".to_owned(), + refusals: vec![LocalRefusal { + category: "missing rule".to_owned(), + construct: "node:method_call".to_owned(), + reason: "no rule converts METHOD CALL".to_owned(), + width: 1, + ..LocalRefusal::default() + }], + } +} + +/// Run-on layers from the flag, the target and settings. +pub(super) fn layers( + flag: Option<&str>, + target: Option<&str>, + settings: Option<&str>, +) -> RunOnLayers { + RunOnLayers { + flag: flag.map(str::to_owned), + target: target.map(str::to_owned), + settings: settings.map(str::to_owned), + } +} + +/// A test refused in the output of `@py.status_hash`, placed at the call in the model file. +pub(super) fn refused_in_macro_output(name: &str) -> RunOnDecision { + RunOnDecision { + name: name.to_owned(), + run_on: "warehouse".to_owned(), + refusals: vec![LocalRefusal { + column: Some(5), + snippet: Some(" status, HASH(status) AS status_hash".to_owned()), + snippet_column: Some(11), + expanded_from: Some( + "@py.status_hash at sql/models/staging/stg_orders.sql:12:5".to_owned(), + ), + ..hash_refusal("fn:HASH", 12) + }], + } +} + +/// The JSON payload with run-on fields added, or the error as a JSON string. +pub(super) fn run_on_document(decisions: &[RunOnDecision]) -> Value { + let payload: String = json!({ + "summary": {"total_count": 2}, + "checks": [{"name": "a"}, {"name": "b"}, {"name": "c"}], + }) + .to_string(); + let local_count: usize = decisions + .iter() + .filter(|decision| decision.run_on == "local") + .count(); + with_run_on_json( + &payload, + ("checks", &["name"]), + decisions, + (local_count, decisions.len() - local_count), + ) + .and_then(|text| serde_json::from_str(&text).map_err(|error| error.to_string())) + .unwrap_or_else(Value::String) +} + +/// Each refusal's tests, code and line. +pub(super) fn refusal_digest(document: &Value) -> Value { + Value::Array( + document["refusals"] + .as_array() + .map(Vec::as_slice) + .unwrap_or_default() + .iter() + .map(|refusal| json!({"tests": refusal["tests"], "code": refusal["code"], "line": refusal["line"]})) + .collect(), + ) +} + +/// Each decision's reason and first refusal width, or `None` when the JSON is rejected. +pub(super) fn read_digest(runner_json: &str) -> Option, i64)>> { + let decisions: Vec = read_run_on_decisions(runner_json).ok()?; + let mut digest: Vec<(Option, i64)> = Vec::new(); + for decision in &decisions { + let width: i64 = decision.refusals.first().map_or(0, |refusal| refusal.width); + digest.push((decision.reason(), width)); + } + Some(digest) +} diff --git a/crates/sqlbuild-core/src/run_on/tests/test_run_on.rs b/crates/sqlbuild-core/src/run_on/tests/test_run_on.rs new file mode 100644 index 0000000000..2dcb7d05b0 --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/tests/test_run_on.rs @@ -0,0 +1,317 @@ +use serde_json::json; + +use crate::cli_text::models::CliStyle; +use crate::run_on::main::apply_local_refusals::apply_local_refusals; +use crate::run_on::main::read_local_refusal::read_local_refusal; +use crate::run_on::main::render_local_refusals::render_local_refusals; +use crate::run_on::main::render_warehouse_census::render_warehouse_census; +use crate::run_on::main::resolve_run_on::resolve_run_on; +use crate::run_on::main::run_on_column::run_on_column; +use crate::run_on::main::run_on_inspection_line::run_on_inspection_line; +use crate::run_on::models::{LocalRefusal, RunOn, RunOnDecision}; +use crate::run_on::tests::helpers::{ + layers, local, read_digest, refusal_digest, refused, refused_in_macro_output, run_on_document, + unplaced, +}; +use crate::run_on::tests::test_types::{ + ColumnTestCase, FragmentTestCase, InspectionTestCase, JsonTestCase, LocalRefusalTestCase, + ReadTestCase, RenderTestCase, ResolveTestCase, +}; + +const PLAIN: CliStyle = CliStyle { use_color: false }; +const NOUNS: (&str, &str) = ("test", "tests"); + +#[test] +fn given_run_on_layers_when_resolving_then_flag_beats_target_beats_settings_beats_auto() { + let test_cases = [ + ResolveTestCase { + description: "nothing set is auto", + layers: layers(None, None, None), + expected_run_on: RunOn::Auto, + }, + ResolveTestCase { + description: "settings apply without a target or flag", + layers: layers(None, None, Some("warehouse")), + expected_run_on: RunOn::Warehouse, + }, + ResolveTestCase { + description: "the target replaces settings", + layers: layers(None, Some("local"), Some("warehouse")), + expected_run_on: RunOn::Local, + }, + ResolveTestCase { + description: "the flag replaces the target", + layers: layers(Some("auto"), Some("local"), Some("warehouse")), + expected_run_on: RunOn::Auto, + }, + ]; + for test_case in test_cases { + assert_eq!( + resolve_run_on(&test_case.layers), + test_case.expected_run_on, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_decisions_when_rendering_census_then_counts_tests_per_refusal_most_first() { + let test_cases = [ + RenderTestCase { + description: "every test local prints nothing", + decisions: vec![local("a")], + errors: false, + expected_text: "", + }, + RenderTestCase { + description: "refusals are counted per test, most tests first", + decisions: vec![ + local("a"), + refused("b", "fn:HASH", 26), + refused("c", "fn:HASH", 26), + unplaced("d"), + ], + errors: false, + expected_text: "\nOn the warehouse (3 tests)\n a known difference that isn't allowed: fn:HASH 2 tests\n missing rule: node:method_call 1 test\n", + }, + ]; + for test_case in test_cases { + assert_eq!( + render_warehouse_census(&test_case.decisions, NOUNS, PLAIN), + test_case.expected_text, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_refusals_when_rendering_diagnostics_then_dedupes_by_place_and_lists_blocked_tests() { + let test_cases = [ + RenderTestCase { + description: "one diagnostic per construct and place, with every blocked test", + decisions: vec![ + refused("test_stg_orders", "fn:HASH", 26), + refused("test_daily_revenue_chain", "fn:HASH", 26), + unplaced("test_fact_orders"), + local("calculates_line_total_cents"), + ], + expected_text: "\nCan't run locally (3 tests)\n\nerror[SQ0008]: HASH gives a different value in DuckDB\n --> sql/models/staging/stg_orders.sql:26:3\n |\n26 | HASH(status) AS status_hash\n | ^^^^^^^^^^^^ DuckDB computes its own hash, never Snowflake's\n |\n = note: Equal inputs still get equal hashes within one run.\n = help: allow it with hash = true under [allow] in a sqlquack.toml\n = tests: test_stg_orders, test_daily_revenue_chain\n\nerror: missing rule: node:method_call\n = note: no rule converts METHOD CALL\n = tests: test_fact_orders\n", + errors: true, + }, + RenderTestCase { + description: "auto: the tests run on the warehouse, so each refusal is a note", + decisions: vec![ + refused("test_stg_orders", "fn:HASH", 26), + refused("test_daily_revenue_chain", "fn:HASH", 26), + unplaced("test_fact_orders"), + local("calculates_line_total_cents"), + ], + expected_text: "\nOn the warehouse (3 tests)\n\nnote[SQ0008]: HASH gives a different value in DuckDB\n --> sql/models/staging/stg_orders.sql:26:3\n |\n26 | HASH(status) AS status_hash\n | ^^^^^^^^^^^^ DuckDB computes its own hash, never Snowflake's\n |\n = note: Equal inputs still get equal hashes within one run.\n = help: allow it with hash = true under [allow] in a sqlquack.toml\n = tests: test_stg_orders, test_daily_revenue_chain\n\nnote: missing rule: node:method_call\n = note: no rule converts METHOD CALL\n = tests: test_fact_orders\n", + errors: false, + }, + ]; + for test_case in test_cases { + assert_eq!( + render_local_refusals(&test_case.decisions, test_case.errors, NOUNS, PLAIN), + test_case.expected_text, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_decision_when_inspecting_then_names_where_it_runs_and_why() { + let test_cases = [ + InspectionTestCase { + description: "a local test", + decision: local("a"), + expected_line: " runs on: local\n", + }, + InspectionTestCase { + description: "a refused test names the refusal", + decision: refused("b", "fn:HASH", 26), + expected_line: " runs on: warehouse (a known difference that isn't allowed: fn:HASH)\n", + }, + ]; + for test_case in test_cases { + assert_eq!( + run_on_inspection_line(&test_case.decision), + test_case.expected_line, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_run_on_when_rendering_row_column_then_pads_to_one_width() { + let test_cases = [ + ColumnTestCase { + description: "local is padded to warehouse's width", + run_on: "local", + expected_column: "local ", + }, + ColumnTestCase { + description: "warehouse fills the column", + run_on: "warehouse", + expected_column: "warehouse", + }, + ]; + for test_case in test_cases { + assert_eq!( + run_on_column(test_case.run_on), + test_case.expected_column, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_decisions_when_adding_json_then_marks_checks_and_lists_refusals_with_tests() { + let test_cases = [JsonTestCase { + description: "checks name where they ran; refusals are deduplicated with their tests", + decisions: vec![ + local("a"), + refused("b", "fn:HASH", 26), + refused("c", "fn:HASH", 26), + ], + expected_checks: json!([ + {"name": "a", "run_on": "local", "run_on_reason": null}, + {"name": "b", "run_on": "warehouse", "run_on_reason": "a known difference that isn't allowed: fn:HASH"}, + {"name": "c", "run_on": "warehouse", "run_on_reason": "a known difference that isn't allowed: fn:HASH"}, + ]), + expected_summary: json!({"total_count": 2, "local_count": 1, "warehouse_count": 2}), + expected_refusals: json!([{"tests": ["b", "c"], "code": "SQ0008", "line": 26}]), + }]; + for test_case in test_cases { + let document = run_on_document(&test_case.decisions); + assert_eq!( + document["checks"], test_case.expected_checks, + "{}", + test_case.description + ); + assert_eq!( + document["summary"], test_case.expected_summary, + "{}", + test_case.description + ); + assert_eq!( + refusal_digest(&document), + test_case.expected_refusals, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_runner_json_when_reading_decisions_then_keeps_refusal_fields() { + let test_cases = [ + ReadTestCase { + description: "a refusal keeps its label and width", + runner_json: r#"{"decisions": [{"name": "a", "run_on": "warehouse", "refusals": [ + {"category": "missing rule", "construct": "fn:FLATTEN", "reason": "r", + "code": "SQ0002", "line": 3, "column": 5, "width": 7, "notes": ["n"]}]}]}"#, + expected_decisions: Some(vec![(Some("missing rule: fn:FLATTEN".to_owned()), 7)]), + }, + ReadTestCase { + description: "JSON without decisions is rejected", + runner_json: "{}", + expected_decisions: None, + }, + ]; + for test_case in test_cases { + assert_eq!( + read_digest(test_case.runner_json), + test_case.expected_decisions, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_refusal_in_macro_output_when_rendering_then_points_at_call_and_shows_generated_sql() { + let test_cases = [FragmentTestCase { + description: "the call site, the generated SQL and the macro that produced it", + decisions: vec![refused_in_macro_output("test_orders")], + expected_fragments: &[ + " --> sql/models/staging/stg_orders.sql:12:5\n", + "12 | status, HASH(status) AS status_hash\n | ^^^^^^^^^^^^ ", + " = expanded from @py.status_hash at sql/models/staging/stg_orders.sql:12:5\n", + ], + }]; + for test_case in test_cases { + let text: String = render_local_refusals(&test_case.decisions, true, NOUNS, PLAIN); + assert!( + test_case + .expected_fragments + .iter() + .all(|fragment| text.contains(fragment)), + "{}: {text}", + test_case.description + ); + } +} + +#[test] +fn given_a_local_test_refused_while_running_when_applied_then_auto_moves_it_and_local_keeps_it() { + let guard = LocalRefusal { + category: "SQLQuack guard".to_owned(), + construct: "array_agg_order".to_owned(), + reason: "ARRAY_AGG of several values in no defined order".to_owned(), + width: 1, + ..LocalRefusal::default() + }; + let test_cases = [ + LocalRefusalTestCase { + description: "auto runs the test on the warehouse, giving the guard as the reason", + mode: RunOn::Auto, + expected_decision: RunOnDecision { + name: "test_orders".to_owned(), + run_on: "warehouse".to_owned(), + refusals: vec![guard.clone()], + }, + }, + LocalRefusalTestCase { + description: "local keeps the test local and lists the guard it can't run past", + mode: RunOn::Local, + expected_decision: RunOnDecision { + name: "test_orders".to_owned(), + run_on: "local".to_owned(), + refusals: vec![guard.clone()], + }, + }, + ]; + for test_case in test_cases { + let mut decisions = vec![local("test_orders"), local("test_customers")]; + let fields = [ + ("test", "test_orders"), + ("category", "SQLQuack guard"), + ("construct", "array_agg_order"), + ("reason", "ARRAY_AGG of several values in no defined order"), + ]; + + apply_local_refusals( + &mut decisions, + vec![read_local_refusal( + fields + .into_iter() + .map(|(key, value)| (key.to_owned(), value.to_owned())) + .collect(), + )], + test_case.mode, + ); + + assert_eq!( + decisions, + vec![test_case.expected_decision, local("test_customers")], + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-core/src/run_on/tests/test_types.rs b/crates/sqlbuild-core/src/run_on/tests/test_types.rs new file mode 100644 index 0000000000..619c469c3c --- /dev/null +++ b/crates/sqlbuild-core/src/run_on/tests/test_types.rs @@ -0,0 +1,53 @@ +use crate::run_on::models::{RunOn, RunOnDecision, RunOnLayers}; + +pub(super) struct ResolveTestCase { + pub(super) description: &'static str, + pub(super) layers: RunOnLayers, + pub(super) expected_run_on: RunOn, +} + +pub(super) struct RenderTestCase { + pub(super) description: &'static str, + pub(super) decisions: Vec, + /// Whether the refusals stop the tests running, as under `--run-on local`. + pub(super) errors: bool, + pub(super) expected_text: &'static str, +} + +pub(super) struct InspectionTestCase { + pub(super) description: &'static str, + pub(super) decision: RunOnDecision, + pub(super) expected_line: &'static str, +} + +pub(super) struct ColumnTestCase { + pub(super) description: &'static str, + pub(super) run_on: &'static str, + pub(super) expected_column: &'static str, +} + +pub(super) struct JsonTestCase { + pub(super) description: &'static str, + pub(super) decisions: Vec, + pub(super) expected_checks: serde_json::Value, + pub(super) expected_summary: serde_json::Value, + pub(super) expected_refusals: serde_json::Value, +} + +pub(super) struct ReadTestCase { + pub(super) description: &'static str, + pub(super) runner_json: &'static str, + pub(super) expected_decisions: Option, i64)>>, +} + +pub(super) struct FragmentTestCase { + pub(super) description: &'static str, + pub(super) decisions: Vec, + pub(super) expected_fragments: &'static [&'static str], +} + +pub(super) struct LocalRefusalTestCase { + pub(super) description: &'static str, + pub(super) mode: RunOn, + pub(super) expected_decision: RunOnDecision, +} diff --git a/crates/sqlbuild-core/src/scenario_command/main/render_scenario_result.rs b/crates/sqlbuild-core/src/scenario_command/main/render_scenario_result.rs index 608f70ade9..1cb8c398b4 100644 --- a/crates/sqlbuild-core/src/scenario_command/main/render_scenario_result.rs +++ b/crates/sqlbuild-core/src/scenario_command/main/render_scenario_result.rs @@ -1,6 +1,7 @@ //! The result row of one finished scenario run. use crate::cli_text::models::CliStyle; +use crate::run_on::main::run_on_column::run_on_column; use crate::scenario_command::_helpers::expectations::{expectation_failures, expectation_rows}; use crate::scenario_command::_helpers::rows::{heading, indented_error_lines}; use crate::scenario_command::constants::RETAINED_KIND_WIDTH; @@ -13,7 +14,13 @@ pub fn render_scenario_result(row: &ScenarioResultRow, style: CliStyle) -> Strin .duration_ms .map(|milliseconds| format!(" {:.2}s", milliseconds / 1000.0)) .unwrap_or_default(); - let mut text: String = heading(&row.name, &style.status(&row.status), &duration); + let run_on: &str = if row.local { "local" } else { "warehouse" }; + let status: String = format!( + "{} {}", + style.status(&row.status), + run_on_column(run_on).trim_end() + ); + let mut text: String = heading(&row.name, &status, &duration); if let Some(error) = row.error.as_ref().filter(|error| !error.message.is_empty()) { text.push_str(&indented_error_lines(error, style)); if !row.retained && !row.local { diff --git a/crates/sqlbuild-core/src/scenario_command/main/sql_analysis_required_error.rs b/crates/sqlbuild-core/src/scenario_command/main/sql_analysis_required_error.rs index 89175dca2e..5b4528f6d8 100644 --- a/crates/sqlbuild-core/src/scenario_command/main/sql_analysis_required_error.rs +++ b/crates/sqlbuild-core/src/scenario_command/main/sql_analysis_required_error.rs @@ -12,7 +12,7 @@ pub fn sql_analysis_required_error( guidance: Option<(String, String)>, ) -> Option { let subject: &str = match command { - SqlAnalysisCommand::LocalTest => "scenario test --local", + SqlAnalysisCommand::LocalTest => "scenario test --run-on local", SqlAnalysisCommand::Capture => "scenario capture", }; if disabled_by_flag { diff --git a/crates/sqlbuild-core/src/scenario_command/main/validate_scenario_test_flags.rs b/crates/sqlbuild-core/src/scenario_command/main/validate_scenario_test_flags.rs index 0534bb3432..d73d88a7fa 100644 --- a/crates/sqlbuild-core/src/scenario_command/main/validate_scenario_test_flags.rs +++ b/crates/sqlbuild-core/src/scenario_command/main/validate_scenario_test_flags.rs @@ -1,4 +1,4 @@ -//! `sqb scenario test` flag combinations rejected before the project is read. +//! `sqb scenario test` flag combinations rejected before any scenario runs. use crate::scenario_command::constants::{ LOCAL_RETAIN_UNSUPPORTED_CODE, LOCAL_SNAPSHOT_FLAG_REQUIRED_CODE, @@ -6,25 +6,24 @@ use crate::scenario_command::constants::{ use crate::scenario_command::errors::ScenarioCommandError; use crate::scenario_command::models::ScenarioTestFlags; -/// `--local` cannot retain, and snapshot sync flags need `--local`. +/// `--run-on local` cannot retain, and snapshot sync flags need scenarios that can run locally. pub fn validate_scenario_test_flags(flags: ScenarioTestFlags) -> Result<(), ScenarioCommandError> { if flags.local && flags.retain { return Err(ScenarioCommandError { code: LOCAL_RETAIN_UNSUPPORTED_CODE, - message: "scenario test --local does not support --retain".to_owned(), + message: "scenario test --run-on local does not support --retain".to_owned(), help: Some( "Local scenario DuckDB files are always kept under target/run/scenarios/." .to_owned(), ), }); } - if !flags.local && (flags.sync_snapshots || flags.refresh) { + if flags.warehouse && (flags.sync_snapshots || flags.refresh) { return Err(ScenarioCommandError { code: LOCAL_SNAPSHOT_FLAG_REQUIRED_CODE, - message: "scenario snapshot sync flags require --local".to_owned(), + message: "scenario snapshot sync flags need scenarios that run locally".to_owned(), help: Some( - "Use sqb scenario test --local --sync-snapshots or sqb scenario test --local \ - --refresh." + "Use --run-on auto or --run-on local with --sync-snapshots or --refresh." .to_owned(), ), }); diff --git a/crates/sqlbuild-core/src/scenario_command/models.rs b/crates/sqlbuild-core/src/scenario_command/models.rs index c2a870d8b7..5c9a23dbed 100644 --- a/crates/sqlbuild-core/src/scenario_command/models.rs +++ b/crates/sqlbuild-core/src/scenario_command/models.rs @@ -21,7 +21,10 @@ pub struct NamespaceCandidates { /// The `sqb scenario test` flags validated before the project is read. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct ScenarioTestFlags { + /// The run replays every scenario locally (`--run-on local`). pub local: bool, + /// The run sends every scenario to the warehouse (`--run-on warehouse`). + pub warehouse: bool, pub retain: bool, pub sync_snapshots: bool, pub refresh: bool, diff --git a/crates/sqlbuild-core/src/scenario_command/tests/test_scenario_command.rs b/crates/sqlbuild-core/src/scenario_command/tests/test_scenario_command.rs index 5bdb8de153..c266292569 100644 --- a/crates/sqlbuild-core/src/scenario_command/tests/test_scenario_command.rs +++ b/crates/sqlbuild-core/src/scenario_command/tests/test_scenario_command.rs @@ -310,16 +310,18 @@ fn given_scenario_test_flags_when_validating_then_rejects_unsupported_combinatio expected_code: Some("C452"), }, FlagsTestCase { - description: "sync without local", + description: "sync on the warehouse", flags: ScenarioTestFlags { + warehouse: true, sync_snapshots: true, ..ScenarioTestFlags::default() }, expected_code: Some("C454"), }, FlagsTestCase { - description: "refresh without local", + description: "refresh on the warehouse", flags: ScenarioTestFlags { + warehouse: true, refresh: true, ..ScenarioTestFlags::default() }, @@ -334,6 +336,15 @@ fn given_scenario_test_flags_when_validating_then_rejects_unsupported_combinatio }, expected_code: None, }, + FlagsTestCase { + description: "auto sync and retain", + flags: ScenarioTestFlags { + retain: true, + sync_snapshots: true, + ..ScenarioTestFlags::default() + }, + expected_code: None, + }, ]; for test_case in test_cases { @@ -357,7 +368,7 @@ fn given_sql_analysis_off_when_checking_scenario_command_then_explains_how_to_tu disabled_by_flag: true, guidance: None, expected_error: Some(( - "scenario test --local requires SQL analysis, but `--no-sql-analysis` turns it off", + "scenario test --run-on local requires SQL analysis, but `--no-sql-analysis` turns it off", "run the command without `--no-sql-analysis`", )), }, diff --git a/crates/sqlbuild-core/src/scenario_command/tests/test_scenario_rows.rs b/crates/sqlbuild-core/src/scenario_command/tests/test_scenario_rows.rs index 5dfef4b357..1523c9a830 100644 --- a/crates/sqlbuild-core/src/scenario_command/tests/test_scenario_rows.rs +++ b/crates/sqlbuild-core/src/scenario_command/tests/test_scenario_rows.rs @@ -21,12 +21,12 @@ use crate::scenario_command::tests::test_types::{ WarehouseArtifactsTestCase, }; -const RA0: &str = "orders_paid FAIL 1.23s\n error[X506]: expected comparison failed\n second line\n = help: Compare the CTE.\n expect expected fact_orders FAIL 2 mismatched, 1 missing\n error[X506]: mismatch\n = help: look\n expect expected dim_customers PASS\n expect assertion no_negative FAIL 1 row\n expect assertion few FAIL 3 rows\n plain error\n expect assertion ok PASS\n Retained relations:\n source raw_orders -> main.__sqb_abc__source__raw_orders\n model fact_orders -> main.__sqb_abc__model__fact_orders\n expected fact_orders: actual=3 expected=2 mismatched=2 missing=1\n assertion no_negative: failing_rows=1\n sample: (1, 'a', None)\n assertion few: failing_rows=3\n"; -const RA1: &str = "orders_paid \u{1b}[38;5;167mFAIL\u{1b}[0m 1.23s\n \u{1b}[38;5;167m\u{1b}[1merror[X506]:\u{1b}[0m expected comparison failed\n \u{1b}[2msecond line\u{1b}[0m\n \u{1b}[2m= help:\u{1b}[0m Compare the CTE.\n expect expected fact_orders \u{1b}[38;5;167mFAIL\u{1b}[0m 2 mismatched, 1 missing\n \u{1b}[38;5;167m\u{1b}[1merror[X506]:\u{1b}[0m mismatch\n \u{1b}[2m= help:\u{1b}[0m look\n expect expected dim_customers \u{1b}[32mPASS\u{1b}[0m\n expect assertion no_negative \u{1b}[38;5;167mFAIL\u{1b}[0m 1 row\n expect assertion few \u{1b}[38;5;167mFAIL\u{1b}[0m 3 rows\n plain error\n expect assertion ok \u{1b}[32mPASS\u{1b}[0m\n Retained relations:\n source raw_orders -> main.__sqb_abc__source__raw_orders\n model fact_orders -> main.__sqb_abc__model__fact_orders\n expected fact_orders: actual=3 expected=2 mismatched=2 missing=1\n assertion no_negative: failing_rows=1\n sample: (1, 'a', None)\n assertion few: failing_rows=3\n"; -const RB0: &str = "orders_local ERROR\n snapshot missing\n Retained local DuckDB: /work/target/run/scenarios/orders_local/local.duckdb\n"; -const RC0: &str = "orders_warehouse FAIL\n boom\n Rerun with --retain to inspect scenario-owned artifacts.\n"; -const RD1: &str = "orders_ok \u{1b}[32mPASS\u{1b}[0m 0.01s\n expect expected m \u{1b}[32mPASS\u{1b}[0m\n"; -const RE0: &str = "orders_errored FAIL\n expect expected fact_orders ERROR\n error[X504]: comparison failed to run\n expect assertion no_negative ERROR\n error[X507]: assertion failed to run\n"; +const RA0: &str = "orders_paid FAIL warehouse 1.23s\n error[X506]: expected comparison failed\n second line\n = help: Compare the CTE.\n expect expected fact_orders FAIL 2 mismatched, 1 missing\n error[X506]: mismatch\n = help: look\n expect expected dim_customers PASS\n expect assertion no_negative FAIL 1 row\n expect assertion few FAIL 3 rows\n plain error\n expect assertion ok PASS\n Retained relations:\n source raw_orders -> main.__sqb_abc__source__raw_orders\n model fact_orders -> main.__sqb_abc__model__fact_orders\n expected fact_orders: actual=3 expected=2 mismatched=2 missing=1\n assertion no_negative: failing_rows=1\n sample: (1, 'a', None)\n assertion few: failing_rows=3\n"; +const RA1: &str = "orders_paid \u{1b}[38;5;167mFAIL\u{1b}[0m warehouse 1.23s\n \u{1b}[38;5;167m\u{1b}[1merror[X506]:\u{1b}[0m expected comparison failed\n \u{1b}[2msecond line\u{1b}[0m\n \u{1b}[2m= help:\u{1b}[0m Compare the CTE.\n expect expected fact_orders \u{1b}[38;5;167mFAIL\u{1b}[0m 2 mismatched, 1 missing\n \u{1b}[38;5;167m\u{1b}[1merror[X506]:\u{1b}[0m mismatch\n \u{1b}[2m= help:\u{1b}[0m look\n expect expected dim_customers \u{1b}[32mPASS\u{1b}[0m\n expect assertion no_negative \u{1b}[38;5;167mFAIL\u{1b}[0m 1 row\n expect assertion few \u{1b}[38;5;167mFAIL\u{1b}[0m 3 rows\n plain error\n expect assertion ok \u{1b}[32mPASS\u{1b}[0m\n Retained relations:\n source raw_orders -> main.__sqb_abc__source__raw_orders\n model fact_orders -> main.__sqb_abc__model__fact_orders\n expected fact_orders: actual=3 expected=2 mismatched=2 missing=1\n assertion no_negative: failing_rows=1\n sample: (1, 'a', None)\n assertion few: failing_rows=3\n"; +const RB0: &str = "orders_local ERROR local\n snapshot missing\n Retained local DuckDB: /work/target/run/scenarios/orders_local/local.duckdb\n"; +const RC0: &str = "orders_warehouse FAIL warehouse\n boom\n Rerun with --retain to inspect scenario-owned artifacts.\n"; +const RD1: &str = "orders_ok \u{1b}[32mPASS\u{1b}[0m warehouse 0.01s\n expect expected m \u{1b}[32mPASS\u{1b}[0m\n"; +const RE0: &str = "orders_errored FAIL warehouse\n expect expected fact_orders ERROR\n error[X504]: comparison failed to run\n expect assertion no_negative ERROR\n error[X507]: assertion failed to run\n"; const CE0: &str = "orders_paid PASS 2 relations, 3 rows\n source raw_orders PASS 2 rows, 41 B\n seed countries PASS 1 row, 1.5 KB\n snapshot tests/_scenario_snapshots/orders_paid/scenario.json\n"; const SE0R: &str = "orders_paid REFRESHED 2 relations, 3 rows\n source raw_orders PASS 2 rows, 41 B\n seed countries PASS 1 row, 1.5 KB\n snapshot tests/_scenario_snapshots/orders_paid/scenario.json\n"; const CF1: &str = "orders_big \u{1b}[38;5;167mFAIL\u{1b}[0m 0 relations, 0 rows\n \u{1b}[38;5;167m\u{1b}[1merror[X512]:\u{1b}[0m too many rows\n \u{1b}[2m= help:\u{1b}[0m narrow it\n Rerun with --retain to inspect scenario-owned artifacts.\n source raw_orders \u{1b}[38;5;167mFAIL\u{1b}[0m 0 rows, 0 B\n snapshot /elsewhere/scenario.json\n"; diff --git a/crates/sqlbuild-core/src/seed_command/main/render_seed_completion.rs b/crates/sqlbuild-core/src/seed_command/main/render_seed_completion.rs index 501c94a016..edc0c8c94b 100644 --- a/crates/sqlbuild-core/src/seed_command/main/render_seed_completion.rs +++ b/crates/sqlbuild-core/src/seed_command/main/render_seed_completion.rs @@ -4,13 +4,6 @@ use crate::cli_text::main::format_completion_line::format_completion_line; use crate::cli_text::main::format_summary_footer::format_summary_footer; use crate::cli_text::models::{CliStyle, CompletionState, SummaryCount}; -fn count(label: &str, value: usize) -> SummaryCount { - SummaryCount { - label: label.to_owned(), - value: i64::try_from(value).unwrap_or(i64::MAX), - } -} - /// A blank line and the completion state with PASS, WARN, FAIL, SKIP and TOTAL counts. #[must_use] pub fn render_seed_completion( @@ -21,11 +14,11 @@ pub fn render_seed_completion( let summary: String = format_summary_footer( style, &[ - count("PASS", passed), - count("WARN", 0), - count("FAIL", failed), - count("SKIP", 0), - count("TOTAL", total), + SummaryCount::of("PASS", passed), + SummaryCount::of("WARN", 0), + SummaryCount::of("FAIL", failed), + SummaryCount::of("SKIP", 0), + SummaryCount::of("TOTAL", total), ], Some(&format!("{elapsed_seconds:.2}s")), ); diff --git a/crates/sqlbuild-core/src/test_command/main/render_test_completion.rs b/crates/sqlbuild-core/src/test_command/main/render_test_completion.rs index aa33b13fec..47b6e914a0 100644 --- a/crates/sqlbuild-core/src/test_command/main/render_test_completion.rs +++ b/crates/sqlbuild-core/src/test_command/main/render_test_completion.rs @@ -3,17 +3,11 @@ use crate::cli_text::main::format_coded_error::format_coded_error; use crate::cli_text::main::format_summary_footer::format_summary_footer; use crate::cli_text::models::{CliStyle, SummaryCount}; +use crate::run_on::main::run_on_split::run_on_split; use crate::test_command::constants::{DEFAULT_ERROR, ERROR_LABEL, ERROR_LABEL_WIDTH, TIMEOUT_CODE}; use crate::test_command::models::TestFailure; use crate::text::main::python_splitlines::python_splitlines; -fn count(label: &str, value: usize) -> SummaryCount { - SummaryCount { - label: label.to_owned(), - value: i64::try_from(value).unwrap_or(i64::MAX), - } -} - fn failure_lines(failure: &TestFailure, style: CliStyle) -> Vec { let message: &str = failure .error_message @@ -44,11 +38,12 @@ fn failure_lines(failure: &TestFailure, style: CliStyle) -> Vec { lines } -/// A blank line, PASS, FAIL and TOTAL counts, then the failures when any, and a newline. +/// PASS, FAIL and TOTAL counts with any local and warehouse split, then any failures. #[must_use] pub fn render_test_completion( (passed, total): (usize, usize), failures: &[TestFailure], + split: Option<(usize, usize)>, style: CliStyle, ) -> String { let timed_out: usize = failures @@ -56,14 +51,15 @@ pub fn render_test_completion( .filter(|failure| failure.error_code.as_deref() == Some(TIMEOUT_CODE)) .count(); let mut counts: Vec = vec![ - count("PASS", passed), - count("FAIL", total - passed - timed_out.min(total - passed)), + SummaryCount::of("PASS", passed), + SummaryCount::of("FAIL", total - passed - timed_out.min(total - passed)), ]; if timed_out > 0 { - counts.push(count("TIMEOUT", timed_out)); + counts.push(SummaryCount::of("TIMEOUT", timed_out)); } - counts.push(count("TOTAL", total)); - let summary: String = format_summary_footer(style, &counts, None); + counts.push(SummaryCount::of("TOTAL", total)); + let split: Option = split.map(|(local, warehouse)| run_on_split(local, warehouse)); + let summary: String = format_summary_footer(style, &counts, split.as_deref()); let mut rendered: String = format!("\n{summary}"); if !failures.is_empty() { let mut lines: Vec = vec![style.error_strong("Failures:"), String::new()]; diff --git a/crates/sqlbuild-core/src/test_command/main/render_test_inspection.rs b/crates/sqlbuild-core/src/test_command/main/render_test_inspection.rs index 9787452733..be08f0c521 100644 --- a/crates/sqlbuild-core/src/test_command/main/render_test_inspection.rs +++ b/crates/sqlbuild-core/src/test_command/main/render_test_inspection.rs @@ -1,5 +1,6 @@ //! `sqb test --inspect`: the resolved test plan without executing it. +use crate::run_on::main::run_on_inspection_line::run_on_inspection_line; use crate::test_command::constants::ERROR_SEVERITY; use crate::test_command::models::{TestInspectionEntry, TestPlanWarning}; @@ -21,6 +22,9 @@ pub fn render_test_inspection( let mut text: String = "\nResolved test plan\n\n".to_owned(); for entry in entries { text.push_str(&format!("{}\n", entry.label)); + if let Some(decision) = &entry.run_on { + text.push_str(&run_on_inspection_line(decision)); + } for (label, values) in [ ("mocked sources", &entry.mocked_sources), ("mocked refs", &entry.mocked_refs), diff --git a/crates/sqlbuild-core/src/test_command/models.rs b/crates/sqlbuild-core/src/test_command/models.rs index 0c8b931617..23d4ca4b54 100644 --- a/crates/sqlbuild-core/src/test_command/models.rs +++ b/crates/sqlbuild-core/src/test_command/models.rs @@ -23,6 +23,8 @@ pub struct TestInspectionEntry { pub expected_models: Vec, /// Why `--since` selected the test; empty without `--since`. pub selection_reasons: Vec, + /// Where the test runs and why; `None` when the run did not decide. + pub run_on: Option, } /// One plan warning: its severity value and message. diff --git a/crates/sqlbuild-core/src/test_command/tests/test_test_command.rs b/crates/sqlbuild-core/src/test_command/tests/test_test_command.rs index 47e203b230..832768856e 100644 --- a/crates/sqlbuild-core/src/test_command/tests/test_test_command.rs +++ b/crates/sqlbuild-core/src/test_command/tests/test_test_command.rs @@ -194,7 +194,7 @@ fn given_results_when_completing_then_renders_summary_failures_and_exit_code() { for test_case in test_cases { assert_eq!( - render_test_completion(test_case.counts, &test_case.failures, PLAIN), + render_test_completion(test_case.counts, &test_case.failures, None, PLAIN), test_case.expected_text, "{}", test_case.description diff --git a/crates/sqlbuild-host/src/entries/_helpers/executor.rs b/crates/sqlbuild-host/src/entries/_helpers/executor.rs index 2dc98d5953..7f76a6d8e6 100644 --- a/crates/sqlbuild-host/src/entries/_helpers/executor.rs +++ b/crates/sqlbuild-host/src/entries/_helpers/executor.rs @@ -374,6 +374,26 @@ pub(crate) const ENTRIES: &[HostEntry] = &[ kind: HostKind::Function, edge: HostEdge::Executor, }, + HostEntry { + name: "decide_sql_test_run_on", + kind: HostKind::Function, + edge: HostEdge::Executor, + }, + HostEntry { + name: "local_test_adapter", + kind: HostKind::Function, + edge: HostEdge::Executor, + }, + HostEntry { + name: "report_unplaced_sql_tests", + kind: HostKind::Function, + edge: HostEdge::Executor, + }, + HostEntry { + name: "decide_scenario_run_on", + kind: HostKind::Function, + edge: HostEdge::Executor, + }, HostEntry { name: "select_scenario_snapshot_capture_candidates", kind: HostKind::Function, diff --git a/crates/sqlbuild-host/src/entries/models.rs b/crates/sqlbuild-host/src/entries/models.rs index 586d081e7d..34391fdbf1 100644 --- a/crates/sqlbuild-host/src/entries/models.rs +++ b/crates/sqlbuild-host/src/entries/models.rs @@ -283,6 +283,10 @@ pub enum ExecutorHost { RunScenarioTestPipeline, RunSeedPipeline, RunTestPipeline, + DecideSqlTestRunOn, + LocalTestAdapter, + ReportUnplacedSqlTests, + DecideScenarioRunOn, SelectScenarioSnapshotCaptureCandidates, TestPipelineCallbacks, RunItemTimeouts, diff --git a/crates/sqlbuild-host/src/models.rs b/crates/sqlbuild-host/src/models.rs index af745cb10b..0178bedd98 100644 --- a/crates/sqlbuild-host/src/models.rs +++ b/crates/sqlbuild-host/src/models.rs @@ -320,6 +320,8 @@ pub enum AuditOutcome { Error, Insufficient, Skipped, + /// An end-of-build audit that reads something the target doesn't have: neither a pass nor a failure. + NotRun, } impl ResultEnum for AuditOutcome { @@ -329,6 +331,7 @@ impl ResultEnum for AuditOutcome { Self::Error, Self::Insufficient, Self::Skipped, + Self::NotRun, ]; fn value(self) -> &'static str { @@ -338,6 +341,7 @@ impl ResultEnum for AuditOutcome { Self::Error => "error", Self::Insufficient => "insufficient", Self::Skipped => "skipped", + Self::NotRun => "not_run", } } } @@ -686,6 +690,8 @@ pub struct SqlTestExecutionResult { pub error_message: Option, pub real_model_count: Option, pub timeout: Option, + /// Why a local run failed where the warehouse would not: `test`, `category`, `construct`, `reason`. + pub local_refusal: Option, } /// Everything one build executed, as the executor returns it. Mirrors `sqlbuild.executor.build.models.BuildExecutionResult`; `V` is a host value. @@ -706,6 +712,8 @@ pub struct BuildExecutionResult { pub warning_count: i64, pub insufficient_count: i64, pub ignored_audit_failure_count: i64, + /// End-of-build audits not run because the target lacks a read; in no other count. + pub not_run_count: i64, pub audit_result_projection_attempted_count: i64, pub audit_result_projection_written_count: i64, pub audit_result_projection_failed_count: i64, @@ -778,4 +786,6 @@ pub struct ScenarioRunResult { pub error_help: Option, pub error_message: Option, pub duration_ms: Option, + /// Why a local replay failed where the warehouse would not: `test`, `category`, `construct`, `reason`. + pub local_refusal: Option, } diff --git a/crates/sqlbuild-host/src/tests/test_enum_values.rs b/crates/sqlbuild-host/src/tests/test_enum_values.rs index 1a96bdac08..3adf58f210 100644 --- a/crates/sqlbuild-host/src/tests/test_enum_values.rs +++ b/crates/sqlbuild-host/src/tests/test_enum_values.rs @@ -108,7 +108,14 @@ fn given_result_enums_when_read_by_value_then_they_match_the_python_members() { description: "AuditOutcome round-trips its Python values", values: values::(), parsed: parsed::(), - expected_values: vec!["pass", "warn", "error", "insufficient", "skipped"], + expected_values: vec![ + "pass", + "warn", + "error", + "insufficient", + "skipped", + "not_run", + ], }, EnumValueTestCase { description: "AuditRunScope round-trips its Python values", diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/bearer.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/bearer.rs index ba8eec4603..c78fcc3017 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/bearer.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/bearer.rs @@ -59,6 +59,7 @@ fn unauthorized() -> ApiError { status: StatusCode::UNAUTHORIZED, message: "valid bearer credential required".into(), decision_id: None, + cause: None, } } @@ -89,6 +90,7 @@ pub(crate) async fn local_request( status: StatusCode::FORBIDDEN, message: "development API requires a local authority and origin".into(), decision_id: None, + cause: None, }); } Ok(next.run(request).await) @@ -103,6 +105,7 @@ pub(crate) fn require_location( status: StatusCode::FORBIDDEN, message: "credential does not authorize this location".into(), decision_id: None, + cause: None, }); } Ok(()) @@ -141,6 +144,7 @@ pub(crate) async fn require_resource( status: StatusCode::NOT_FOUND, message: missing.into(), decision_id: None, + cause: None, }); } Ok(()) diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_sessions.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_sessions.rs index 919cda0d3a..a6e2be3915 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_sessions.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_sessions.rs @@ -52,6 +52,10 @@ pub(crate) fn session_routes(store: &ControlStore) -> Router { pub(crate) fn person_routes() -> Router { Router::new() .route("/api/auth/cli/approve", post(super::cli_login::approve)) + .route( + "/api/health/details", + get(crate::api::_helpers::resources::server_health::details), + ) .route( "/api/control/bootstrap", get(crate::api::_helpers::resources::person_bootstrap::read), @@ -260,6 +264,10 @@ pub(crate) fn person_routes() -> Router { "/api/control/locations/{location_id}/targets/{target}/selection/vocabulary", get(crate::api::_helpers::resources::person_selection::vocabulary), ) + .route( + "/api/control/locations/{location_id}/targets/{target}/selection/runs", + get(crate::api::_helpers::resources::person_selection::past_runs), + ) .route( "/api/control/locations/{location_id}/targets/{target}/catalog", get(crate::api::_helpers::resources::person_operations::catalog), diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs index 1f2980695b..44dc9b386f 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/authentication/password_transport.rs @@ -42,6 +42,7 @@ pub(crate) async fn guard( status: StatusCode::INTERNAL_SERVER_ERROR, message: "trusted request peer is unavailable".into(), decision_id: None, + cause: None, })? .0; let context = AuditContext { @@ -66,6 +67,7 @@ pub(crate) async fn guard( [trusted_proxy] allowed_hosts" .into(), decision_id: None, + cause: None, }); } } @@ -155,6 +157,7 @@ pub(crate) async fn authenticate( status: StatusCode::INTERNAL_SERVER_ERROR, message: "trusted authentication context is unavailable".into(), decision_id: None, + cause: None, })?; let access = if request.method().is_safe() || request.headers().contains_key(header::AUTHORIZATION) { diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/application.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/application.rs index 3b6e7875f1..ac2f83bc5b 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/application.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/application.rs @@ -9,10 +9,13 @@ use tower_http::compression::CompressionLayer; use crate::api::_helpers::authentication::bearer::local_request; use crate::api::_helpers::authentication::development_hosts::development_authorities; use crate::api::_helpers::resources::compression::compress_reads_only; +use crate::api::_helpers::resources::request_ids::identify_request; use crate::api::_helpers::resources::router::router; use crate::api::_helpers::resources::server_errors::generic_server_errors; +use crate::api::_helpers::resources::server_health::health_routes; use crate::api::_helpers::resources::ui_assets::{UI_ASSETS, serve_ui}; use crate::api::models::{ChangeFeed, DevelopmentScope, ServerFacts}; +use crate::health::models::ServerHealth; use crate::node_states::models::NodeStateCache; use crate::runs::types::RunHandoff; use crate::store::models::{ChangeMessage, ControlStore}; @@ -26,7 +29,9 @@ pub(crate) fn application_router( ) -> Router { let feed = ChangeFeed { sender, stopped }; router(store, feed.clone()) + .merge(health_routes()) .merge(authentication_routes.layer(Extension(feed))) + .layer(Extension(facts.health.clone())) .layer(Extension(node_states)) .layer(Extension(Arc::new(images))) .layer(Extension(planner)) @@ -38,7 +43,7 @@ pub(crate) fn application_router( /// The development UI, the Host and Origin guard of a development scope, and the response layers. pub(crate) fn development_application( application: Router, - scope: Option, + (scope, health): (Option, &ServerHealth), address: std::net::SocketAddr, ) -> Router { let application = serve_ui(application, UI_ASSETS); @@ -53,6 +58,10 @@ pub(crate) fn development_application( }; application .layer(middleware::map_response(generic_server_errors)) + .layer(middleware::from_fn_with_state( + health.clone(), + identify_request, + )) .layer(CompressionLayer::new()) .layer(middleware::from_fn(compress_reads_only)) } diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/docker_image.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/docker_image.rs index f0e33e5df1..441f8045a6 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/docker_image.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/docker_image.rs @@ -28,6 +28,7 @@ pub(crate) async fn pin( status: StatusCode::CONFLICT, message: "published image differs from the configured Docker location image".into(), decision_id: None, + cause: None, }); } input.image_id = Some(image); @@ -72,5 +73,6 @@ fn unavailable() -> ApiError { status: StatusCode::SERVICE_UNAVAILABLE, message: "cannot inspect the configured Docker location image".into(), decision_id: None, + cause: None, } } diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/location_health.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/location_health.rs index 6876adf7eb..f1e3da2fa2 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/location_health.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/location_health.rs @@ -8,6 +8,7 @@ use crate::api::_helpers::authentication::bearer::require_location; use crate::api::errors::ApiError; use crate::api::models::MutationResponse; use crate::credentials::models::TokenIdentity; +use crate::health::models::ServerHealth; use crate::platform::main::health::location_health::location_health; use crate::platform::main::health::report_location_health::report_location_health; use crate::platform::models::{ @@ -22,14 +23,14 @@ use crate::store::models::ControlStore; security(("bearer" = [])))] pub(crate) async fn report( State(store): State, - Extension(identity): Extension, + (Extension(identity), Extension(health)): (Extension, Extension), Path(location_id): Path, Json(report): Json, ) -> Result, ApiError> { require_location(&identity, location_id)?; - Ok(Json(MutationResponse { - applied: report_location_health(&store, location_id, &report).await?, - })) + let applied = report_location_health(&store, location_id, &report).await?; + health.location_reported(location_id, chrono::Utc::now()); + Ok(Json(MutationResponse { applied })) } #[utoipa::path(get, path = "/api/locations/{location_id}/health", operation_id = "read_location_health", diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/mod.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/mod.rs index cf6038ae5b..fa99f5a792 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/mod.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/mod.rs @@ -21,11 +21,13 @@ pub(crate) mod person_reads; pub(crate) mod person_republish; pub(crate) mod person_selection; pub(crate) mod plain_http; +pub(crate) mod request_ids; pub(crate) mod request_json; pub(crate) mod router; pub(crate) mod run_reads; pub(crate) mod runs; pub(crate) mod server_errors; +pub(crate) mod server_health; pub(crate) mod service_accounts; pub(crate) mod snapshots; pub(crate) mod trigger_reads; diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_bootstrap.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_bootstrap.rs index 5b477f8bd5..09b59bba93 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_bootstrap.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_bootstrap.rs @@ -29,6 +29,7 @@ pub(crate) async fn read( status: StatusCode::UNAUTHORIZED, message: "authenticated active person required".into(), decision_id: None, + cause: None, }); }; let profile = profile diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_checks.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_checks.rs index 7de359e16e..3ccfd4beab 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_checks.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_checks.rs @@ -13,9 +13,9 @@ use crate::credentials::models::{AuditContext, AuthenticatedPerson, DefaultRole} use crate::node_states::main::list_person_checks::list_person_checks; use crate::node_states::models::NodeStateCache; use crate::store::models::ControlStore; -use crate::warehouse_history::main::read_person_check::read_person_check; -use crate::warehouse_history::main::read_person_check_evidence::read_person_check_evidence; -use crate::warehouse_history::main::read_person_check_sql::read_person_check_sql; +use crate::warehouse_history::main::checks::read_person_check::read_person_check; +use crate::warehouse_history::main::checks::read_person_check_evidence::read_person_check_evidence; +use crate::warehouse_history::main::checks::read_person_check_sql::read_person_check_sql; use crate::warehouse_history::models::{CheckEvidence, CheckResult, CheckSql}; #[utoipa::path(get, path = "/api/control/locations/{location_id}/targets/{target}/checks", operation_id = "listPersonChecks", diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_cost.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_cost.rs index 61cb56abd5..5602136ddd 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_cost.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_cost.rs @@ -12,8 +12,8 @@ use crate::credentials::models::{AuditContext, AuthenticatedPerson, DefaultRole} use crate::runs::types::CommandPlanner; use crate::store::errors::ControlError; use crate::store::models::ControlStore; -use crate::warehouse_history::main::read_person_cost_selection::read_person_cost_selection; -use crate::warehouse_history::main::read_person_cost_series::read_person_cost_series; +use crate::warehouse_history::main::costs::read_person_cost_selection::read_person_cost_selection; +use crate::warehouse_history::main::costs::read_person_cost_series::read_person_cost_series; use crate::warehouse_history::models::{CostSelectionRecord, CostSeriesBatch, CostSeriesGroup}; /// Default and largest cost window, in days. diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_maintenance.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_maintenance.rs index 2793482bce..dbb9e4ca59 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_maintenance.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_maintenance.rs @@ -7,8 +7,8 @@ use uuid::Uuid; use crate::api::errors::ApiError; use crate::credentials::models::{AuditContext, AuthenticatedPerson, DefaultRole}; use crate::store::models::ControlStore; -use crate::warehouse_history::main::read_person_maintenance::read_person_maintenance; -use crate::warehouse_history::main::read_person_microbatch_coverage::read_person_microbatch_coverage; +use crate::warehouse_history::main::maintenance::read_person_maintenance::read_person_maintenance; +use crate::warehouse_history::main::maintenance::read_person_microbatch_coverage::read_person_microbatch_coverage; use crate::warehouse_history::models::{ CoverageQuery, MaintenanceHistory, MaintenanceQuery, MicrobatchCoverage, }; diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_plans.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_plans.rs index cb79b3e691..36d0c556cf 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_plans.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_plans.rs @@ -143,5 +143,6 @@ pub(crate) async fn diff( status: axum::http::StatusCode::NOT_FOUND, message: "plan diff not found".into(), decision_id: None, + cause: None, }) } diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_reads.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_reads.rs index 61df78a37f..8dbaffbda1 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_reads.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_reads.rs @@ -24,6 +24,8 @@ use crate::declarations::main::read_person_providers::read_person_providers; use crate::declarations::models::{ JobDetailRecord, JobRecord, PersonTriggerChange, PersonTriggerRecord, ProvidersRead, }; +use crate::health::main::failing_forwarding::failing_forwarding; +use crate::health::models::ServerHealth; use crate::node_states::main::list_person_catalog_nodes::list_person_catalog_nodes; use crate::node_states::main::read_person_node_states::read_person_node_states; use crate::node_states::models::{NodeStateCache, NodeStatesRecord}; @@ -52,16 +54,16 @@ use crate::sensors::models::{PersonSensorState, SensorEventChoice, SensorTrialEv use crate::snapshots::main::reads::list_person_snapshots::list_person_snapshots; use crate::snapshots::models::PublishedSnapshot; use crate::store::models::ControlStore; -use crate::warehouse_history::main::read_person_cost_summary::read_person_cost_summary; -use crate::warehouse_history::main::read_person_node_costs::read_person_node_costs; -use crate::warehouse_history::main::read_person_node_runs::read_person_node_runs; -use crate::warehouse_history::main::read_person_run_cost::read_person_run_cost; -use crate::warehouse_history::main::read_person_run_events::read_person_run_events; -use crate::warehouse_history::main::read_person_run_ignored_audits::read_person_run_ignored_audits; -use crate::warehouse_history::main::read_person_run_node_error::read_person_run_node_error; -use crate::warehouse_history::main::read_person_run_output::read_person_run_output; -use crate::warehouse_history::main::read_person_run_statement_sql::read_person_run_statement_sql; -use crate::warehouse_history::main::read_person_run_statements::read_person_run_statements; +use crate::warehouse_history::main::checks::read_person_run_ignored_audits::read_person_run_ignored_audits; +use crate::warehouse_history::main::costs::read_person_cost_summary::read_person_cost_summary; +use crate::warehouse_history::main::costs::read_person_node_costs::read_person_node_costs; +use crate::warehouse_history::main::costs::read_person_run_cost::read_person_run_cost; +use crate::warehouse_history::main::runs::read_person_node_runs::read_person_node_runs; +use crate::warehouse_history::main::runs::read_person_run_events::read_person_run_events; +use crate::warehouse_history::main::runs::read_person_run_node_error::read_person_run_node_error; +use crate::warehouse_history::main::runs::read_person_run_output::read_person_run_output; +use crate::warehouse_history::main::runs::read_person_run_statement_sql::read_person_run_statement_sql; +use crate::warehouse_history::main::runs::read_person_run_statements::read_person_run_statements; use crate::warehouse_history::models::{CostSummaryRecord, NodeCostRecord}; use crate::warehouse_metadata::models::{CatalogNodeRecord, WarehouseResourceCostRecord}; use futures_util::StreamExt; @@ -774,6 +776,7 @@ pub(crate) async fn sensor_events( status: StatusCode::BAD_REQUEST, message: "choose at most one of latest, event and run".into(), decision_id: None, + cause: None, }); } }; @@ -790,6 +793,7 @@ pub(crate) async fn sensor_events( status: StatusCode::CONFLICT, message, decision_id: None, + cause: None, }) } @@ -843,12 +847,13 @@ pub(crate) async fn health( (status = 401, description = "Session rejected")), security(("session" = []), ("cliSession" = [])))] pub(crate) async fn problems( State(store): State, - Extension(default_role): Extension, + (Extension(default_role), Extension(health)): (Extension, Extension), Extension(AuthenticatedPerson(principal, _)): Extension, ) -> Result, ApiError> { - Ok(Json( - read_person_problems(&store, principal, default_role).await?, - )) + Ok(Json(PlatformProblems { + failing_forwarding: failing_forwarding(&health), + ..read_person_problems(&store, principal, default_role).await? + })) } #[utoipa::path(get, path = "/api/control/platform/events", operation_id = "listPersonPlatformEvents", @@ -877,5 +882,6 @@ fn not_found(message: &str) -> ApiError { status: StatusCode::NOT_FOUND, message: message.into(), decision_id: None, + cause: None, } } diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_selection.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_selection.rs index a3e27db01e..0c09a9492e 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_selection.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/person_selection.rs @@ -1,5 +1,6 @@ -//! A person evaluates a selection, and reads the values its selectors take, against the current publication. +//! A person evaluates a selection, reads the values its selectors take and the past runs they name, against the current publication. +use std::collections::BTreeSet; use std::sync::Arc; use axum::extract::{Path, Query, State}; @@ -9,8 +10,11 @@ use uuid::Uuid; use crate::api::errors::ApiError; use crate::credentials::models::{AuditContext, AuthenticatedPerson, DefaultRole}; use crate::runs::main::requests::evaluate_selection::evaluate_selection; +use crate::runs::main::requests::read_person_past_runs::read_person_past_runs; use crate::runs::main::requests::read_selection_vocabulary::read_selection_vocabulary; -use crate::runs::models::{SelectionEvaluation, SelectionQuery, SelectionVocabulary}; +use crate::runs::models::{ + PastRunsQuery, PastRunsRead, SelectionEvaluation, SelectionQuery, SelectionVocabulary, +}; use crate::runs::types::CommandPlanner; use crate::store::models::ControlStore; @@ -70,3 +74,37 @@ pub(crate) async fn vocabulary( .await?, )) } + +#[utoipa::path(get, path = "/api/control/locations/{location_id}/targets/{target}/selection/runs", + operation_id = "readPastRuns", + params(("location_id" = Uuid, Path), ("target" = String, Path), + ("ids" = Option, Query, description = "Comma-separated run IDs, each full or a unique prefix of at least 8 characters")), + responses((status = 200, body = PastRunsRead, description = "What each run selected, didn't finish and skipped, or why one can't be read"), + (status = 401, description = "Session rejected"), (status = 403, body = crate::api::models::ApiErrorBody)), + security(("session" = []), ("cliSession" = [])))] +pub(crate) async fn past_runs( + (State(store), Extension(context)): (State, Extension), + (Path((location_id, target)), Query(query)): (Path<(Uuid, String)>, Query), + (Extension(AuthenticatedPerson(principal, _)), Extension(planner)): ( + Extension, + Extension>, + ), + Extension(default_role): Extension, +) -> Result, ApiError> { + let ids: BTreeSet = query + .ids + .split(',') + .map(str::trim) + .filter(|id| !id.is_empty()) + .map(str::to_owned) + .collect(); + Ok(Json( + read_person_past_runs( + &store, + (planner.as_ref(), (&context, principal)), + (location_id, &target, &ids), + default_role, + ) + .await?, + )) +} diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/request_ids.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/request_ids.rs new file mode 100644 index 0000000000..ad2de09da1 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/request_ids.rs @@ -0,0 +1,50 @@ +//! Give every request an ID, and finish each error response with it and with its control database cause. + +use axum::body::Body; +use axum::extract::{Request, State}; +use axum::http::{HeaderValue, header}; +use axum::middleware::Next; +use axum::response::Response; +use chrono::Utc; +use uuid::Uuid; + +use crate::api::constants::REQUEST_ID_HEADER; +use crate::api::models::{ErrorCause, ErrorReply, RequestId}; +use crate::health::main::log_cause::log_cause; +use crate::health::models::ServerHealth; + +/// Name every request in `x-request-id`; an error the control database's unavailability caused also names it, its cause and since when in the body, and is recorded and logged. +pub(crate) async fn identify_request( + State(health): State, + mut request: Request, + next: Next, +) -> Response { + let request_id: Uuid = Uuid::now_v7(); + request.extensions_mut().insert(RequestId(request_id)); + let mut response = next.run(request).await; + if let Ok(value) = HeaderValue::from_str(&request_id.to_string()) { + response.headers_mut().insert(REQUEST_ID_HEADER, value); + } + let Some(ErrorReply { + mut body, + cause: Some(cause), + }) = response.extensions_mut().remove::() + else { + return response; + }; + let cause = health.locate(cause); + let since = health.control_failed(&cause, (Utc::now(), Some(request_id))); + log_cause(Some(request_id), &cause); + body.request_id = Some(request_id); + body.error.clone_from(&cause.message); + body.cause = Some(ErrorCause { + case: cause.case, + since, + }); + let Ok(bytes) = serde_json::to_vec(&body) else { + return response; + }; + let (mut parts, _) = response.into_parts(); + parts.headers.remove(header::CONTENT_LENGTH); + Response::from_parts(parts, Body::from(bytes)) +} diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/request_json.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/request_json.rs index 3956a45d37..337e47d97c 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/request_json.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/request_json.rs @@ -121,5 +121,6 @@ fn rejection(status: StatusCode, message: String) -> ApiError { status, message, decision_id: None, + cause: None, } } diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/run_reads.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/run_reads.rs index 8374a9748e..89d81464a0 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/run_reads.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/run_reads.rs @@ -100,6 +100,7 @@ pub(crate) async fn recall( status: StatusCode::NOT_FOUND, message: "run invocation not found".into(), decision_id: None, + cause: None, }); } Ok(Json( diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/runs.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/runs.rs index 7abe929b47..985d7ed4e6 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/runs.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/runs.rs @@ -13,7 +13,7 @@ use uuid::Uuid; use crate::api::errors::ApiError; use crate::api::models::{HeartbeatResponse, MutationResponse}; use crate::credentials::models::{CredentialScope, TokenIdentity}; -use crate::runs::main::execution::change_run::change_run; +use crate::runs::main::execution::change_run_linked::change_run_linked; use crate::runs::main::execution::heartbeat_run::heartbeat_run; use crate::runs::main::execution::publish_run_output::publish_run_output; use crate::runs::main::execution::publish_run_recall::publish_run_recall; @@ -38,6 +38,7 @@ pub(crate) async fn execution( status: StatusCode::UNAUTHORIZED, message: "run claim is no longer active".into(), decision_id: None, + cause: None, })?; Ok(Json(execution)) } @@ -49,7 +50,7 @@ pub(crate) async fn execution( security(("bearer" = [])))] pub(crate) async fn report( State(store): State, - Extension(identity): Extension, + (Extension(identity), Extension(facts)): (Extension, Extension), Path(run_id): Path, Json(request): Json, ) -> Result, ApiError> { @@ -59,9 +60,15 @@ pub(crate) async fn report( status: StatusCode::FORBIDDEN, message: "report does not match the authenticated run and claim".into(), decision_id: None, + cause: None, }); } - let applied = change_run(&store, RunAuthority::Worker { run_id, claim_id }, &request).await?; + let applied = change_run_linked( + &store, + (RunAuthority::Worker { run_id, claim_id }, &request), + facts.origin.as_deref(), + ) + .await?; Ok(Json(MutationResponse { applied })) } @@ -121,6 +128,7 @@ pub(crate) fn no_output_store() -> ApiError { status: StatusCode::SERVICE_UNAVAILABLE, message: "this server keeps no run output store".into(), decision_id: None, + cause: None, } } @@ -154,5 +162,6 @@ fn require_worker(identity: &TokenIdentity, run_id: Uuid) -> Result Response { status: response.status(), message: "internal server error".into(), decision_id: None, + cause: None, } .into_response() } diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/server_health.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/server_health.rs new file mode 100644 index 0000000000..916da1aea6 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/server_health.rs @@ -0,0 +1,61 @@ +//! Liveness and health, which answer from memory without signing in, and health details for administrators. + +use axum::extract::State; +use axum::http::{HeaderValue, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use axum::routing::get; +use axum::{Extension, Json, Router}; + +use crate::api::errors::ApiError; +use crate::credentials::models::{AuditContext, AuthenticatedPerson}; +use crate::health::main::health_report::health_report; +use crate::health::main::read_health_details::read_health_details; +use crate::health::models::{HealthDetails, HealthReport, HealthStatus, ServerHealth}; +use crate::store::models::ControlStore; + +/// `/livez` and `/api/health`, which read only the server's memory. +pub(crate) fn health_routes() -> Router { + Router::new() + .route("/livez", get(livez)) + .route("/api/health", get(health)) +} + +/// The process answers; nothing else is checked. +#[utoipa::path(get, path = "/livez", operation_id = "livez", + responses((status = 200, description = "The server process is running", body = String)))] +pub(crate) async fn livez() -> Response { + no_store((StatusCode::OK, "ok\n").into_response()) +} + +#[utoipa::path(get, path = "/api/health", operation_id = "readHealth", + responses((status = 200, description = "Every component is healthy", body = HealthReport), + (status = 503, description = "A component is degraded or the control database is unavailable", body = HealthReport)))] +pub(crate) async fn health(Extension(health): Extension) -> Response { + let report: HealthReport = health_report(&health, chrono::Utc::now()); + let status = if report.status == HealthStatus::Healthy { + StatusCode::OK + } else { + StatusCode::SERVICE_UNAVAILABLE + }; + no_store((status, Json(report)).into_response()) +} + +#[utoipa::path(get, path = "/api/health/details", operation_id = "readHealthDetails", + responses((status = 200, body = HealthDetails), (status = 401, description = "Session rejected"), + (status = 403, body = crate::api::models::ApiErrorBody)), security(("session" = []), ("cliSession" = [])))] +pub(crate) async fn details( + (State(store), Extension(context)): (State, Extension), + Extension(AuthenticatedPerson(principal, _)): Extension, + Extension(health): Extension, +) -> Result, ApiError> { + Ok(Json( + read_health_details((&store, &health), (&context, principal)).await?, + )) +} + +fn no_store(mut response: Response) -> Response { + response + .headers_mut() + .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + response +} diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/snapshots.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/snapshots.rs index a594d0df9b..7547b7b7cb 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/snapshots.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/snapshots.rs @@ -48,12 +48,14 @@ pub(crate) async fn publish( status: StatusCode::INTERNAL_SERVER_ERROR, message: "snapshot decoding stopped".into(), decision_id: None, + cause: None, })??; if input.location_id != location_id || input.target != target { return Err(ApiError { status: StatusCode::BAD_REQUEST, message: "snapshot does not match the requested location and target".into(), decision_id: None, + cause: None, }); } let pause_new = if let Some(Extension(scope)) = development { @@ -62,6 +64,7 @@ pub(crate) async fn publish( status: StatusCode::FORBIDDEN, message: "snapshot is outside the development scope".into(), decision_id: None, + cause: None, }); } !scope.triggers @@ -93,6 +96,7 @@ pub(crate) async fn current( status: StatusCode::NOT_FOUND, message: "no successful snapshot".into(), decision_id: None, + cause: None, })?; Ok(Json(current)) } @@ -114,6 +118,7 @@ pub(crate) async fn metadata( status: StatusCode::NOT_FOUND, message: "no successful snapshot".into(), decision_id: None, + cause: None, })?; Ok(Json(record)) } diff --git a/crates/sqlbuild-orchestration/src/api/_helpers/resources/ui_assets.rs b/crates/sqlbuild-orchestration/src/api/_helpers/resources/ui_assets.rs index db71da46b4..d7c7b49824 100644 --- a/crates/sqlbuild-orchestration/src/api/_helpers/resources/ui_assets.rs +++ b/crates/sqlbuild-orchestration/src/api/_helpers/resources/ui_assets.rs @@ -8,6 +8,7 @@ use crate::api::constants::{ API_PATH, API_PREFIX, AUTH_PREFIX, ROOT_PATH, UI_DOT_SEGMENTS, UI_DOUBLE_SLASH, UI_FRAME_POLICY, UI_IMMUTABLE_PREFIX, UI_INDEX_PATH, UI_REFUSED_ENCODINGS, }; +use crate::api::errors::ApiError; use crate::api::models::UiAsset; #[cfg(feature = "ui")] @@ -15,21 +16,33 @@ include!(concat!(env!("OUT_DIR"), "/ui_assets.rs")); #[cfg(not(feature = "ui"))] pub(crate) static UI_ASSETS: &[UiAsset] = &[]; +/// Every path no route takes: an API path is a JSON 404, never the UI's page; anything else is a UI file or the UI's page. pub(crate) fn serve_ui(application: Router, assets: &'static [UiAsset]) -> Router { - if assets.is_empty() { - return application; - } application.fallback(move |method: Method, uri: Uri| async move { respond(assets, &method, uri.path()) }) } fn respond(assets: &'static [UiAsset], method: &Method, path: &str) -> Response { + if path == API_PATH || path.starts_with(API_PREFIX) { + return ApiError { + status: StatusCode::NOT_FOUND, + message: "no such API endpoint".into(), + decision_id: None, + cause: None, + } + .into_response(); + } + ui_response(assets, method, path) +} + +/// An embedded UI file, or the UI's page for a client route; 404 outside the UI. +pub(crate) fn ui_response(assets: &'static [UiAsset], method: &Method, path: &str) -> Response { let outside_ui = path == API_PATH || path.starts_with(API_PREFIX) || path.starts_with(AUTH_PREFIX) || !canonical(path); - if outside_ui || (method != Method::GET && method != Method::HEAD) { + if assets.is_empty() || outside_ui || (method != Method::GET && method != Method::HEAD) { return StatusCode::NOT_FOUND.into_response(); } let wanted = if path == ROOT_PATH { diff --git a/crates/sqlbuild-orchestration/src/api/constants.rs b/crates/sqlbuild-orchestration/src/api/constants.rs index 2ce51abd2e..59550a253f 100644 --- a/crates/sqlbuild-orchestration/src/api/constants.rs +++ b/crates/sqlbuild-orchestration/src/api/constants.rs @@ -70,6 +70,8 @@ pub(crate) const UI_INDEX_PATH: &str = "/index.html"; pub(crate) const UI_IMMUTABLE_PREFIX: &str = "/_app/immutable/"; /// The page's own meta policy carries every other directive; a meta tag cannot set frame-ancestors. pub(crate) const UI_FRAME_POLICY: &str = "frame-ancestors 'none'"; +/// The response header that names each request, as its error body and the server log do. +pub(crate) const REQUEST_ID_HEADER: &str = "x-request-id"; pub(crate) const API_PATH: &str = "/api"; pub(crate) const API_PREFIX: &str = "/api/"; pub(crate) const AUTH_PREFIX: &str = "/auth/"; diff --git a/crates/sqlbuild-orchestration/src/api/errors.rs b/crates/sqlbuild-orchestration/src/api/errors.rs index 7c4b118dc1..6426693cc7 100644 --- a/crates/sqlbuild-orchestration/src/api/errors.rs +++ b/crates/sqlbuild-orchestration/src/api/errors.rs @@ -1,11 +1,13 @@ -//! HTTP errors never return database diagnostics, connection strings, or credentials. +//! HTTP errors name the cause when the control database is unavailable; any other error never returns database diagnostics, connection strings or credentials. use axum::Json; use axum::http::{HeaderValue, StatusCode, header}; use axum::response::{IntoResponse, Response}; use uuid::Uuid; -use crate::api::models::ApiErrorBody; +use crate::api::models::{ApiErrorBody, ErrorReply}; +use crate::health::main::control_cause::control_cause; +use crate::health::models::{ControlCause, ControlTarget}; use crate::store::errors::ControlError; #[derive(Debug, thiserror::Error)] @@ -23,60 +25,71 @@ pub struct ApiError { pub(crate) status: StatusCode, pub(crate) message: String, pub(crate) decision_id: Option, + /// The control database failure behind it, which the response names and the server's health records. + pub(crate) cause: Option, } impl From for ApiError { fn from(error: ControlError) -> Self { + let cause: Option = control_cause(&error, (&ControlTarget::default(), false)) + .filter(ControlCause::unavailable); + if let Some(cause) = cause { + return Self { + status: StatusCode::SERVICE_UNAVAILABLE, + message: cause.message.clone(), + decision_id: None, + cause: Some(cause), + }; + } if error.transient() { return Self { status: StatusCode::SERVICE_UNAVAILABLE, message: "control store is busy; retry the request".into(), decision_id: None, + cause: None, }; } + let plain = |status: StatusCode, message: String, decision_id: Option| Self { + status, + message, + decision_id, + cause: None, + }; match error { - ControlError::Invalid(message) => Self { - status: StatusCode::BAD_REQUEST, - message, - decision_id: None, - }, + ControlError::Invalid(message) => plain(StatusCode::BAD_REQUEST, message, None), ControlError::Denied { reason, decision_id, - } => Self { - status: StatusCode::FORBIDDEN, - message: format!("{reason}; decision {decision_id}"), - decision_id: Some(decision_id), - }, - ControlError::UnreadableSnapshot { .. } => Self { - status: StatusCode::CONFLICT, - message: error.to_string(), - decision_id: None, - }, - ControlError::StaleGeneration | ControlError::Fenced => Self { - status: StatusCode::CONFLICT, - message: error.to_string(), - decision_id: None, - }, - _ => Self { - status: StatusCode::INTERNAL_SERVER_ERROR, - message: "control-store operation failed".into(), - decision_id: None, - }, + } => plain( + StatusCode::FORBIDDEN, + format!("{reason}; decision {decision_id}"), + Some(decision_id), + ), + ControlError::UnreadableSnapshot { .. } + | ControlError::StaleGeneration + | ControlError::Fenced => plain(StatusCode::CONFLICT, error.to_string(), None), + _ => plain( + StatusCode::INTERNAL_SERVER_ERROR, + "control-store operation failed".to_owned(), + None, + ), } } } impl IntoResponse for ApiError { fn into_response(self) -> Response { - let mut response = ( - self.status, - Json(ApiErrorBody { - error: self.message, - decision_id: self.decision_id, - }), - ) - .into_response(); + let body = ApiErrorBody { + error: self.message, + decision_id: self.decision_id, + request_id: None, + cause: None, + }; + let mut response = (self.status, Json(body.clone())).into_response(); + response.extensions_mut().insert(ErrorReply { + body, + cause: self.cause, + }); response .headers_mut() .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); diff --git a/crates/sqlbuild-orchestration/src/api/main/mod.rs b/crates/sqlbuild-orchestration/src/api/main/mod.rs index db4d8c57d7..9e8bd024af 100644 --- a/crates/sqlbuild-orchestration/src/api/main/mod.rs +++ b/crates/sqlbuild-orchestration/src/api/main/mod.rs @@ -3,3 +3,4 @@ pub(crate) mod connect_client; pub mod openapi_document; pub mod parse_origin; pub mod serve_api; +pub mod serve_standby; diff --git a/crates/sqlbuild-orchestration/src/api/main/serve_api.rs b/crates/sqlbuild-orchestration/src/api/main/serve_api.rs index 234faa387a..968f8964e0 100644 --- a/crates/sqlbuild-orchestration/src/api/main/serve_api.rs +++ b/crates/sqlbuild-orchestration/src/api/main/serve_api.rs @@ -9,6 +9,7 @@ use crate::api::_helpers::resources::changes; use crate::api::main::openapi_document::openapi_document; use crate::api::models::{ApiAuthentication, GroupRole, ServerFacts}; use crate::authorization::main::roles::publish_group_roles::publish_group_roles; +use crate::health::main::probe_control_database::probe_control_database; use crate::node_states::main::start_node_states::start_node_states; use crate::runs::types::RunHandoff; use crate::store::errors::ControlError; @@ -31,6 +32,10 @@ pub async fn serve_api( prepare_store(&store, &group_roles).await?; let (sender, listener_changes) = subscribe_changes(&store).await?; let (stop, stopped) = tokio::sync::watch::channel(false); + let health = facts.health.clone(); + health.attach_store(&store); + health.control_succeeded(chrono::Utc::now()); + let probe = probe_control_database(store.clone(), health.clone(), stopped.clone()); let (node_states, refresh_node_states) = start_node_states(&store, &sender); let application = application_router( &store, @@ -42,7 +47,7 @@ pub async fn serve_api( "/api/openapi.json", get(|| async { Json(openapi_document()) }), ); - let application = development_application(application, development_scope, address); + let application = development_application(application, (development_scope, &health), address); let server = axum::serve( listener, application.into_make_service_with_connect_info::(), @@ -56,6 +61,7 @@ pub async fn serve_api( result = async { server.await } => { result?; Ok(()) }, result = changes::relay(store.clone(), listener_changes, sender) => result, () = refresh_node_states => Ok(()), + () = probe => Ok(()), } } diff --git a/crates/sqlbuild-orchestration/src/api/main/serve_standby.rs b/crates/sqlbuild-orchestration/src/api/main/serve_standby.rs new file mode 100644 index 0000000000..2aae069545 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/api/main/serve_standby.rs @@ -0,0 +1,56 @@ +//! Before the control database opens, answer liveness, health and the UI, and refuse other API requests with its cause. + +use axum::http::{Method, StatusCode, Uri}; +use axum::response::{IntoResponse, Response}; +use axum::{Extension, Router, middleware}; +use tower_http::compression::CompressionLayer; + +use crate::api::_helpers::resources::request_ids::identify_request; +use crate::api::_helpers::resources::server_health::health_routes; +use crate::api::_helpers::resources::ui_assets::{UI_ASSETS, ui_response}; +use crate::api::constants::{API_PATH, API_PREFIX}; +use crate::api::errors::ApiError; +use crate::health::constants::CONNECTING; +use crate::health::models::{ControlCause, ServerHealth}; +use crate::store::errors::ControlError; + +/// Serve the standby on `listener` until `done` resolves. +pub async fn serve_standby( + listener: tokio::net::TcpListener, + health: ServerHealth, + done: impl Future + Send + 'static, +) -> Result<(), ControlError> { + let application: Router = health_routes() + .fallback(standby_fallback) + .layer(Extension(health.clone())) + .layer(middleware::from_fn_with_state(health, identify_request)) + .layer(CompressionLayer::new()); + axum::serve( + listener, + application.into_make_service_with_connect_info::(), + ) + .with_graceful_shutdown(done) + .await?; + Ok(()) +} + +async fn standby_fallback( + Extension(health): Extension, + method: Method, + uri: Uri, +) -> Response { + let path: &str = uri.path(); + if path != API_PATH && !path.starts_with(API_PREFIX) { + return ui_response(UI_ASSETS, &method, path); + } + let cause: Option = health.control_cause(); + ApiError { + status: StatusCode::SERVICE_UNAVAILABLE, + message: cause + .as_ref() + .map_or_else(|| CONNECTING.to_owned(), |cause| cause.message.clone()), + decision_id: None, + cause, + } + .into_response() +} diff --git a/crates/sqlbuild-orchestration/src/api/models.rs b/crates/sqlbuild-orchestration/src/api/models.rs index 92e3af5a3f..93e196f9b5 100644 --- a/crates/sqlbuild-orchestration/src/api/models.rs +++ b/crates/sqlbuild-orchestration/src/api/models.rs @@ -12,7 +12,7 @@ use crate::api::_helpers::resources::{ administrators, audit, changed_builds, changes, location_health, location_work, person_bootstrap, person_checks, person_cost, person_location_work, person_maintenance, person_node_sql, person_operations, person_plans, person_reads, person_republish, - person_selection, run_reads, runs, service_accounts, snapshots, trigger_reads, + person_selection, run_reads, runs, server_health, service_accounts, snapshots, trigger_reads, warehouse_metadata, }; @@ -99,6 +99,7 @@ use crate::api::_helpers::resources::{ person_plans::diff, person_selection::evaluate, person_selection::vocabulary, + person_selection::past_runs, person_node_sql::read, password_sessions::login, password_sessions::current, @@ -114,6 +115,9 @@ use crate::api::_helpers::resources::{ changes::subscribe_person, location_health::report, location_health::recent, + server_health::livez, + server_health::health, + server_health::details, location_work::poll, location_work::complete, location_work::result, @@ -279,6 +283,30 @@ pub struct ApiErrorBody { /// Existing durable denial audit ID; absent when no decision was recorded. #[serde(default, skip_serializing_if = "Option::is_none")] pub decision_id: Option, + /// This request's ID, as the server log and the `x-request-id` header name it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub request_id: Option, + /// The control database failure behind the error, when one is. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cause: Option, +} + +/// A control database failure as an error response names it: its case and since when it has been failing. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct ErrorCause { + pub case: crate::health::models::ControlCauseCase, + pub since: chrono::DateTime, +} + +/// The ID the request middleware gives each request. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct RequestId(pub(crate) uuid::Uuid); + +/// An error response's body and cause, which the request middleware completes with the request's ID and the cause's place. +#[derive(Clone, Debug)] +pub(crate) struct ErrorReply { + pub(crate) body: ApiErrorBody, + pub(crate) cause: Option, } /// How people sign in to this server. @@ -737,6 +765,8 @@ pub struct ServerFacts { pub origin: Option, /// Where run output is kept; `None` on a server that keeps none, which refuses output reads and batches. pub output: Option, + /// The server's health, kept in memory and shared with its scheduler. + pub health: crate::health::models::ServerHealth, } /// The server's version, storage, sign-in and retention, for administrators. diff --git a/crates/sqlbuild-orchestration/src/declarations/models.rs b/crates/sqlbuild-orchestration/src/declarations/models.rs index 989e33f885..5ff9bd8b55 100644 --- a/crates/sqlbuild-orchestration/src/declarations/models.rs +++ b/crates/sqlbuild-orchestration/src/declarations/models.rs @@ -131,7 +131,7 @@ impl Overlap { } } -/// A failed or partial run reruns from failure up to `retries` times, each `retry_delay_seconds` after the last ended. +/// A failed run reruns from failure up to `retries` times, each `retry_delay_seconds` after the last ended. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] #[serde(deny_unknown_fields)] pub struct OnFailure { diff --git a/crates/sqlbuild-orchestration/src/health/_helpers/cause.rs b/crates/sqlbuild-orchestration/src/health/_helpers/cause.rs new file mode 100644 index 0000000000..aadea3bfff --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/_helpers/cause.rs @@ -0,0 +1,98 @@ +//! How a control database error is classified, and each cause's own message. + +use std::error::Error; + +use crate::health::constants::{ + CONNECTION_CLASS, LOGIN_REJECTED_CODES, NAME_LOOKUP_MESSAGES, RESTARTING_CODES, + TOO_MANY_CONNECTIONS_CODE, +}; +use crate::health::models::ControlCauseCase; + +/// A database error's case; a pool that waited with room to spare was trying to connect, as sqlx retries a refused connection until the wait ends. +pub(crate) fn database_case(error: &sqlx_core::Error, pool_full: bool) -> ControlCauseCase { + match error { + sqlx_core::Error::Io(error) if name_lookup(&error.to_string()) => { + ControlCauseCase::NameLookup + } + sqlx_core::Error::Io(_) => ControlCauseCase::Unreachable, + sqlx_core::Error::PoolTimedOut if pool_full => ControlCauseCase::PoolExhausted, + sqlx_core::Error::PoolTimedOut => ControlCauseCase::Unreachable, + sqlx_core::Error::Database(error) => error + .code() + .map_or(ControlCauseCase::Other, |code| code_case(&code)), + _ => ControlCauseCase::Other, + } +} + +/// A SQLSTATE's case. +pub(crate) fn code_case(code: &str) -> ControlCauseCase { + if LOGIN_REJECTED_CODES.contains(&code) { + return ControlCauseCase::LoginRejected; + } + if code == TOO_MANY_CONNECTIONS_CODE { + return ControlCauseCase::NoFreeConnections; + } + if RESTARTING_CODES.contains(&code) { + return ControlCauseCase::Restarting; + } + if code.starts_with(CONNECTION_CLASS) { + return ControlCauseCase::Unreachable; + } + ControlCauseCase::Other +} + +/// A SQLite error's case: busy or locked, or any other. +pub(crate) fn sqlite_case(error: &rusqlite::Error) -> ControlCauseCase { + match error { + rusqlite::Error::SqliteFailure(failure, _) + if matches!( + failure.code, + rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked + ) => + { + ControlCauseCase::Locked + } + _ => ControlCauseCase::Other, + } +} + +/// Whether a resolver message says the name doesn't resolve. +pub(crate) fn name_lookup(message: &str) -> bool { + let message: String = message.to_ascii_lowercase(); + NAME_LOOKUP_MESSAGES + .iter() + .any(|fragment| message.contains(fragment)) +} + +/// A database error by the database's own message, then its sources. +pub(crate) fn database_chain(error: &sqlx_core::Error) -> Vec { + match error { + sqlx_core::Error::Database(database) => { + let mut messages: Vec = vec![database.message().to_owned()]; + messages.extend(sources(database.source())); + messages + } + sqlx_core::Error::Io(io) => chain(io), + error => chain(error), + } +} + +/// An error by its own message, then each source's. +pub(crate) fn chain(error: &dyn Error) -> Vec { + let mut messages: Vec = vec![error.to_string()]; + messages.extend(sources(error.source())); + messages +} + +/// Each source's own message, without repeats. +pub(crate) fn sources(mut source: Option<&dyn Error>) -> Vec { + let mut messages: Vec = Vec::new(); + while let Some(error) = source { + let message: String = error.to_string(); + if messages.last() != Some(&message) { + messages.push(message); + } + source = error.source(); + } + messages +} diff --git a/crates/sqlbuild-orchestration/src/health/_helpers/details.rs b/crates/sqlbuild-orchestration/src/health/_helpers/details.rs new file mode 100644 index 0000000000..98abc09782 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/_helpers/details.rs @@ -0,0 +1,47 @@ +//! What administrators see beside the health report: where the database is, each cause's message, and the failed requests. + +use crate::health::models::{ + ComponentDetails, ComponentFailure, ComponentState, HealthComponent, HealthDetails, + ServerHealth, +}; + +/// The failing components' details, read from memory only; callers decide who may read them. +#[must_use] +pub(crate) fn health_details(health: &ServerHealth) -> HealthDetails { + let state = health.state(); + let host: Option = state + .target + .host + .as_ref() + .map(|host| match state.target.port { + Some(port) => format!("{host}:{port}"), + None => host.clone(), + }); + let mut components: Vec = vec![ComponentDetails { + host, + ..details(HealthComponent::ControlDatabase, &state.control_database) + }]; + components.extend( + state + .scheduler + .as_ref() + .map(|scheduler| details(HealthComponent::Scheduler, scheduler)), + ); + HealthDetails { components } +} + +fn details(component: HealthComponent, state: &ComponentState) -> ComponentDetails { + let failure: Option<&ComponentFailure> = + state.last_failure.as_ref().filter(|_| state.failing()); + ComponentDetails { + component, + location_id: None, + host: None, + error_chain: failure + .map(|failure| failure.chain.clone()) + .unwrap_or_default(), + request_ids: failure + .map(|failure| failure.request_ids.iter().copied().collect()) + .unwrap_or_default(), + } +} diff --git a/crates/sqlbuild-orchestration/src/health/_helpers/mod.rs b/crates/sqlbuild-orchestration/src/health/_helpers/mod.rs new file mode 100644 index 0000000000..c042c9cfe5 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/_helpers/mod.rs @@ -0,0 +1,5 @@ +pub(crate) mod cause; +pub(crate) mod details; +pub(crate) mod pool; +pub(crate) mod sentence; +pub(crate) mod store_target; diff --git a/crates/sqlbuild-orchestration/src/health/_helpers/pool.rs b/crates/sqlbuild-orchestration/src/health/_helpers/pool.rs new file mode 100644 index 0000000000..768487585a --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/_helpers/pool.rs @@ -0,0 +1,13 @@ +//! Whether a store's connection pool is full, which tells a busy database from one that can't be reached. + +use crate::store::models::ControlStore; + +/// Every pooled PostgreSQL connection is open and in use; a SQLite store has no pool. +pub(crate) fn pool_full(store: &ControlStore) -> bool { + match store { + ControlStore::Postgres(pool) => { + pool.size() >= pool.options().get_max_connections() && pool.num_idle() == 0 + } + ControlStore::Sqlite(_) => false, + } +} diff --git a/crates/sqlbuild-orchestration/src/health/_helpers/sentence.rs b/crates/sqlbuild-orchestration/src/health/_helpers/sentence.rs new file mode 100644 index 0000000000..49a6ad26cf --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/_helpers/sentence.rs @@ -0,0 +1,32 @@ +//! The sentence each case of control database failure reads as. + +use crate::health::constants::{UNNAMED_HOST, UNNAMED_USER}; +use crate::health::models::{ControlCauseCase, ControlTarget}; + +/// What people read for `case` at `target`; `own` is the error's own message, for errors with no case of their own. +pub(crate) fn sentence(case: ControlCauseCase, target: &ControlTarget, own: &str) -> String { + let host: &str = target.host.as_deref().unwrap_or(UNNAMED_HOST); + match case { + ControlCauseCase::NameLookup => { + format!("Can't reach the control database: {host} doesn't resolve (DNS)") + } + ControlCauseCase::Unreachable => match target.port { + Some(port) => format!("Can't reach the control database at {host}:{port}"), + None => format!("Can't reach the control database at {host}"), + }, + ControlCauseCase::LoginRejected => format!( + "The control database rejected the login for {}", + target.user.as_deref().unwrap_or(UNNAMED_USER) + ), + ControlCauseCase::NoFreeConnections => { + "The control database has no free connections".to_owned() + } + ControlCauseCase::Restarting => "The control database is restarting".to_owned(), + ControlCauseCase::PoolExhausted => format!( + "All {} control database connections were busy for {} s", + target.connections, target.wait_seconds + ), + ControlCauseCase::Locked => "The control database is locked by another process".to_owned(), + ControlCauseCase::Other => format!("Control database error: {own}"), + } +} diff --git a/crates/sqlbuild-orchestration/src/health/_helpers/store_target.rs b/crates/sqlbuild-orchestration/src/health/_helpers/store_target.rs new file mode 100644 index 0000000000..3c63a2b830 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/_helpers/store_target.rs @@ -0,0 +1,23 @@ +//! Where an opened control store connects, for the sentences that name it. + +use crate::health::main::control_target::control_target; +use crate::health::models::ControlTarget; +use crate::store::models::ControlStore; + +/// Where an opened `store` connects, with its pool's limits. +#[must_use] +pub(crate) fn store_target(store: &ControlStore) -> ControlTarget { + match store { + ControlStore::Postgres(pool) => { + let options = pool.connect_options(); + ControlTarget { + host: Some(options.get_host().to_owned()), + port: Some(options.get_port()), + user: Some(options.get_username().to_owned()), + connections: pool.options().get_max_connections(), + wait_seconds: pool.options().get_acquire_timeout().as_secs(), + } + } + ControlStore::Sqlite(_) => control_target(""), + } +} diff --git a/crates/sqlbuild-orchestration/src/health/constants.rs b/crates/sqlbuild-orchestration/src/health/constants.rs new file mode 100644 index 0000000000..b8b6b3b3d5 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/constants.rs @@ -0,0 +1,39 @@ +//! Health pacing, and the names and sentences the health report uses. + +use std::time::Duration; + +/// How often each server checks its control database, and how often clients should ask again while it is down. +pub const HEALTH_PROBE_INTERVAL: Duration = Duration::from_secs(10); +/// The failed requests a component keeps for administrators. +pub(crate) const KEPT_REQUEST_IDS: usize = 5; + +pub(crate) const CONTROL_DATABASE_NAME: &str = "Control database"; +pub(crate) const SCHEDULER_NAME: &str = "Scheduler"; +pub(crate) const SERVER_NAME: &str = "Server"; +/// The control database's reason before this server has reached it. +pub(crate) const CONNECTING: &str = "Connecting to the control database"; +/// The scheduler's reason before its first cycle. +pub(crate) const SCHEDULER_STARTING: &str = "Starting"; +/// What any part that reads the control database says while it can't. +pub(crate) const WAITING_FOR_DATABASE: &str = "Waiting for the control database"; + +/// What a host is called when its URL names none, such as a local socket. +pub(crate) const UNNAMED_HOST: &str = "the configured host"; +/// What a login is called when its URL names no user. +pub(crate) const UNNAMED_USER: &str = "the configured user"; +/// Fragments of the resolver's own messages for a name that doesn't resolve, on each platform. +pub(crate) const NAME_LOOKUP_MESSAGES: [&str; 5] = [ + "failed to lookup address", + "name or service not known", + "temporary failure in name resolution", + "nodename nor servname", + "no such host is known", +]; +/// The SQLSTATEs of a refused login. +pub(crate) const LOGIN_REJECTED_CODES: [&str; 2] = ["28P01", "28000"]; +/// The SQLSTATE of a database with no free connections. +pub(crate) const TOO_MANY_CONNECTIONS_CODE: &str = "53300"; +/// The SQLSTATEs of a database shutting down or not yet accepting connections. +pub(crate) const RESTARTING_CODES: [&str; 3] = ["57P01", "57P02", "57P03"]; +/// The SQLSTATE class of a lost or failed connection. +pub(crate) const CONNECTION_CLASS: &str = "08"; diff --git a/crates/sqlbuild-orchestration/src/health/main/control_cause.rs b/crates/sqlbuild-orchestration/src/health/main/control_cause.rs new file mode 100644 index 0000000000..652065ab77 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/main/control_cause.rs @@ -0,0 +1,31 @@ +//! The cause of a failed control database operation, in the words people read. + +use crate::health::_helpers::cause::{chain, database_case, database_chain, sqlite_case}; +use crate::health::_helpers::sentence::sentence; +use crate::health::models::{ControlCause, ControlCauseCase, ControlTarget}; +use crate::store::errors::ControlError; + +/// What `error` says about the control database at `target`, whose pool is `pool_full` or not; `None` for errors that aren't the database's. +#[must_use] +pub fn control_cause( + error: &ControlError, + (target, pool_full): (&ControlTarget, bool), +) -> Option { + let (case, chain): (ControlCauseCase, Vec) = match error { + ControlError::Database(error) => (database_case(error, pool_full), database_chain(error)), + ControlError::Sqlite(error) => (sqlite_case(error), chain(error)), + ControlError::Worker(error) => (ControlCauseCase::Other, chain(error)), + ControlError::Io(error) => (ControlCauseCase::Other, chain(error)), + _ => return None, + }; + Some(ControlCause { + case, + message: sentence(case, target, &chain[0]), + chain, + transient: error.transient(), + waited_for_pool: matches!( + error, + ControlError::Database(sqlx_core::Error::PoolTimedOut) + ), + }) +} diff --git a/crates/sqlbuild-orchestration/src/health/main/control_target.rs b/crates/sqlbuild-orchestration/src/health/main/control_target.rs new file mode 100644 index 0000000000..3b5e05776d --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/main/control_target.rs @@ -0,0 +1,28 @@ +//! Where a control database URL points, for the sentences that name it. + +use std::str::FromStr; + +use crate::health::models::ControlTarget; +use crate::store::constants::{POOL_CONNECTIONS, POOL_WAIT_SECONDS}; + +/// The host, port and user of a PostgreSQL `url`, and the pool's limits; a SQLite path names none of them. +#[must_use] +pub fn control_target(url: &str) -> ControlTarget { + let limits = ControlTarget { + connections: POOL_CONNECTIONS, + wait_seconds: POOL_WAIT_SECONDS, + ..ControlTarget::default() + }; + if !(url.starts_with("postgres://") || url.starts_with("postgresql://")) { + return limits; + } + match sqlx_postgres::PgConnectOptions::from_str(url) { + Ok(options) => ControlTarget { + host: Some(options.get_host().to_owned()), + port: Some(options.get_port()), + user: Some(options.get_username().to_owned()), + ..limits + }, + Err(_) => limits, + } +} diff --git a/crates/sqlbuild-orchestration/src/health/main/failing_forwarding.rs b/crates/sqlbuild-orchestration/src/health/main/failing_forwarding.rs new file mode 100644 index 0000000000..93fbd8628e --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/main/failing_forwarding.rs @@ -0,0 +1,27 @@ +//! This server's event webhooks that can't deliver, as live problems. + +use crate::health::models::ServerHealth; +use crate::platform::models::FailingForwarding; + +/// Each webhook whose newest attempt failed, since its first failure in a row. +#[must_use] +pub fn failing_forwarding(health: &ServerHealth) -> Vec { + let state = health.state(); + let mut failing: Vec = Vec::new(); + for (name, forwarding) in &state.forwarding { + let Some(failure) = forwarding + .last_failure + .as_ref() + .filter(|_| forwarding.failing()) + else { + continue; + }; + failing.push(FailingForwarding { + name: name.clone(), + since: failure.since, + reason: failure.reason.clone(), + last_success_at: forwarding.last_success, + }); + } + failing +} diff --git a/crates/sqlbuild-orchestration/src/health/main/health_report.rs b/crates/sqlbuild-orchestration/src/health/main/health_report.rs new file mode 100644 index 0000000000..6d11b644d3 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/main/health_report.rs @@ -0,0 +1,146 @@ +//! The health report anyone may read: each component's state, since when, and a short reason. + +use chrono::{DateTime, TimeDelta, Utc}; + +use crate::health::constants::{ + CONNECTING, CONTROL_DATABASE_NAME, HEALTH_PROBE_INTERVAL, SCHEDULER_NAME, SCHEDULER_STARTING, + SERVER_NAME, +}; +use crate::health::models::{ + ComponentHealth, ComponentState, HealthComponent, HealthReport, HealthStatus, SeenLocation, + ServerHealth, ServerSummary, +}; +use crate::platform::constants::LOCATION_SILENCE_SECONDS; + +/// The server's health at `now`, read from memory only. +#[must_use] +pub fn health_report(health: &ServerHealth, now: DateTime) -> HealthReport { + let state = health.state(); + let mut components: Vec = vec![ + ComponentHealth { + component: HealthComponent::Server, + name: SERVER_NAME.to_owned(), + location_id: None, + status: HealthStatus::Healthy, + since: Some(health.started_at), + reason: None, + case: None, + last_success: Some(now), + last_failure: None, + }, + component( + (HealthComponent::ControlDatabase, CONTROL_DATABASE_NAME), + &state.control_database, + (HealthStatus::Unavailable, CONNECTING, health.started_at), + ), + ]; + components.extend(state.scheduler.as_ref().map(|scheduler| { + component( + (HealthComponent::Scheduler, SCHEDULER_NAME), + scheduler, + ( + HealthStatus::Degraded, + SCHEDULER_STARTING, + health.started_at, + ), + ) + })); + components.extend(state.forwarding.iter().map(|(name, forwarding)| { + component( + (HealthComponent::EventForwarding, name), + forwarding, + (HealthStatus::Degraded, "", health.started_at), + ) + })); + components.extend( + state + .locations + .iter() + .map(|(location_id, location)| ComponentHealth { + location_id: Some(*location_id), + ..location_health(location, now) + }), + ); + let status: HealthStatus = components + .iter() + .map(|component| component.status) + .max() + .unwrap_or(HealthStatus::Healthy); + HealthReport { + status, + checked_at: now, + retry_seconds: HEALTH_PROBE_INTERVAL.as_secs(), + server: ServerSummary { + version: health.version.clone(), + started_at: health.started_at, + uptime_seconds: (now - health.started_at).num_seconds().max(0), + }, + components, + } +} + +/// A component from its state: failing is `failing`'s status; never succeeded nor failed is `starting`'s. +fn component( + (kind, name): (HealthComponent, &str), + state: &ComponentState, + (failing, starting, started_at): (HealthStatus, &str, DateTime), +) -> ComponentHealth { + let failure = state.last_failure.as_ref(); + let base = ComponentHealth { + component: kind, + name: name.to_owned(), + location_id: None, + status: HealthStatus::Healthy, + since: state.last_success, + reason: None, + case: None, + last_success: state.last_success, + last_failure: failure.map(|failure| failure.at), + }; + match failure { + Some(failure) if state.failing() => ComponentHealth { + status: failing, + since: Some(failure.since), + reason: Some(failure.reason.clone()), + case: failure.case, + ..base + }, + None if state.last_success.is_none() => ComponentHealth { + status: failing, + since: Some(started_at), + reason: Some(starting.to_owned()), + ..base + }, + _ => base, + } +} + +/// A location is degraded once it hasn't reported for the silence a location is allowed. +fn location_health(location: &SeenLocation, now: DateTime) -> ComponentHealth { + let silent = location + .last_report + .is_some_and(|last| now - last > TimeDelta::seconds(LOCATION_SILENCE_SECONDS)); + ComponentHealth { + component: HealthComponent::Location, + name: location.name.clone(), + location_id: None, + status: if silent { + HealthStatus::Degraded + } else { + HealthStatus::Healthy + }, + since: location.last_report, + reason: silent.then(|| { + format!( + "Hasn't reported since {}", + location + .last_report + .unwrap_or(now) + .format("%Y-%m-%d %H:%M UTC") + ) + }), + case: None, + last_success: location.last_report, + last_failure: None, + } +} diff --git a/crates/sqlbuild-orchestration/src/health/main/log_cause.rs b/crates/sqlbuild-orchestration/src/health/main/log_cause.rs new file mode 100644 index 0000000000..5afe794d2b --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/main/log_cause.rs @@ -0,0 +1,9 @@ +//! Write a control database failure to the server log by each cause's own message, never a stack trace. + +use crate::health::models::ControlCause; + +/// One log line for `cause`, naming the request that met it when one did. +pub fn log_cause(request_id: Option, cause: &ControlCause) { + let request: String = request_id.map_or_else(String::new, |id| format!(" (request {id})")); + eprintln!("{}{request}: {}", cause.message, cause.chain.join(": ")); +} diff --git a/crates/sqlbuild-orchestration/src/health/main/mod.rs b/crates/sqlbuild-orchestration/src/health/main/mod.rs new file mode 100644 index 0000000000..77db1cdc38 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/main/mod.rs @@ -0,0 +1,7 @@ +pub mod control_cause; +pub mod control_target; +pub mod failing_forwarding; +pub mod health_report; +pub mod log_cause; +pub mod probe_control_database; +pub mod read_health_details; diff --git a/crates/sqlbuild-orchestration/src/health/main/probe_control_database.rs b/crates/sqlbuild-orchestration/src/health/main/probe_control_database.rs new file mode 100644 index 0000000000..aa7c175c4c --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/main/probe_control_database.rs @@ -0,0 +1,63 @@ +//! Check the control database every few seconds, and read which locations there are, so health is current without a request. + +use chrono::Utc; +use tokio::sync::watch; + +use crate::health::constants::HEALTH_PROBE_INTERVAL; +use crate::health::main::control_cause::control_cause; +use crate::health::main::log_cause::log_cause; +use crate::health::models::{ServerHealth, StoredLocationReport}; +use crate::store::errors::ControlError; +use crate::store::main::query_records::query_records; +use crate::store::main::{begin::begin, commit::commit}; +use crate::store::models::{ControlStore, TransactionMode}; + +/// Probe `store` until `stopped` turns true, recording each result in `health`. +pub async fn probe_control_database( + store: ControlStore, + health: ServerHealth, + mut stopped: watch::Receiver, +) { + health.attach_store(&store); + let mut failing = false; + while !*stopped.borrow() { + match active_locations(&store).await { + Ok(locations) => { + health.control_succeeded(Utc::now()); + health.locations_seen(locations); + failing = false; + } + Err(error) => { + if let Some(cause) = control_cause(&error, (&Default::default(), false)) { + let cause = health.locate(cause); + if cause.unavailable() { + health.control_failed(&cause, (Utc::now(), None)); + } + if !failing { + log_cause(None, &cause); + } + failing = true; + } + } + } + tokio::select! { + () = tokio::time::sleep(HEALTH_PROBE_INTERVAL) => {}, + changed = stopped.changed() => if changed.is_err() { break }, + } + } +} + +/// Every active location with its instances' newest report. +async fn active_locations(store: &ControlStore) -> Result, ControlError> { + let transaction = begin(store, TransactionMode::Read).await?; + let (transaction, locations) = query_records( + transaction, + "SELECT l.location_id, l.name, \ + (SELECT MAX(i.last_seen_at) FROM sqb_location_instances i WHERE i.location_id=l.location_id) AS last_seen_at \ + FROM sqb_locations l WHERE l.archived_at IS NULL ORDER BY l.name", + Vec::new(), + ) + .await?; + commit(transaction).await?; + Ok(locations) +} diff --git a/crates/sqlbuild-orchestration/src/health/main/read_health_details.rs b/crates/sqlbuild-orchestration/src/health/main/read_health_details.rs new file mode 100644 index 0000000000..e6b51b7eb3 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/main/read_health_details.rs @@ -0,0 +1,27 @@ +//! Health details for a person who may manage people, as the server settings are. + +use uuid::Uuid; + +use crate::authorization::main::decisions::begin_authorized::begin_authorized; +use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; +use crate::health::_helpers::details::health_details; +use crate::health::models::{HealthDetails, ServerHealth}; +use crate::store::errors::ControlError; +use crate::store::main::commit::commit; +use crate::store::models::ControlStore; + +/// `health`'s details, once the person is authorized to manage people. +pub async fn read_health_details( + (store, health): (&ControlStore, &ServerHealth), + credentials: (&AuditContext, Uuid), +) -> Result { + let (transaction, _) = begin_authorized( + store, + credentials, + &PermissionScope::action(Action::UserManage, None), + DefaultRole::None, + ) + .await?; + commit(transaction).await?; + Ok(health_details(health)) +} diff --git a/crates/sqlbuild-orchestration/src/health/mod.rs b/crates/sqlbuild-orchestration/src/health/mod.rs new file mode 100644 index 0000000000..3260a7ecdb --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/mod.rs @@ -0,0 +1,9 @@ +//! Each server's own health, kept in memory so it answers while the control database is unreachable, with the real cause of each failure. + +pub(crate) mod _helpers; +pub mod constants; +pub mod main; +pub mod models; +#[cfg(test)] +#[path = "../../tests/health/test_contracts.rs"] +mod tests; diff --git a/crates/sqlbuild-orchestration/src/health/models.rs b/crates/sqlbuild-orchestration/src/health/models.rs new file mode 100644 index 0000000000..4979aaa1bd --- /dev/null +++ b/crates/sqlbuild-orchestration/src/health/models.rs @@ -0,0 +1,440 @@ +//! What a server knows of its own health, kept in memory so it answers while the control database can't. + +use std::collections::{BTreeMap, VecDeque}; +use std::sync::{Arc, Mutex}; + +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::store::models::ControlStore; + +/// Which kind of control database failure an error is; the sentence people read follows from it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum ControlCauseCase { + /// The database host's name doesn't resolve. + NameLookup, + /// The connection was refused, timed out or dropped. + Unreachable, + /// The database refused the configured login. + LoginRejected, + /// The database has no free connections for this server. + NoFreeConnections, + /// The database is shutting down or starting up. + Restarting, + /// Every pooled connection stayed busy for the whole wait. + PoolExhausted, + /// Another process holds the SQLite database's lock. + Locked, + /// Any other control database error, read by its own message. + Other, +} + +/// A failed control database operation as it is reported: the sentence, its case and each cause's own message. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ControlCause { + pub case: ControlCauseCase, + /// What people read, such as "Can't reach the control database: db.internal doesn't resolve (DNS)". + pub message: String, + /// The error and each of its sources, by their own messages; for administrators and the server log. + pub chain: Vec, + /// Whether the same operation may succeed when retried. + pub transient: bool, + /// The pool's wait ran out, which is a full pool or a database that can't be reached. + pub(crate) waited_for_pool: bool, +} + +impl ControlCause { + /// This cause at `target`, whose pool is `pool_full` or not, with the sentence that names it. + #[must_use] + pub fn at(self, target: &ControlTarget, pool_full: bool) -> Self { + let case = match self.case { + ControlCauseCase::Unreachable | ControlCauseCase::PoolExhausted + if self.waited_for_pool => + { + if pool_full { + ControlCauseCase::PoolExhausted + } else { + ControlCauseCase::Unreachable + } + } + case => case, + }; + Self { + case, + message: crate::health::_helpers::sentence::sentence(case, target, &self.chain[0]), + ..self + } + } + + /// Whether the control database can't be used while this lasts: a failure a retry may outlast, or a refused login. + #[must_use] + pub fn unavailable(&self) -> bool { + self.transient || self.case == ControlCauseCase::LoginRejected + } +} + +/// Where the control database is, for the sentences that name it; read from its URL, never its password. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ControlTarget { + pub host: Option, + pub port: Option, + pub user: Option, + /// The pool's connection limit. + pub connections: u32, + /// How long a request waits for a pooled connection, in seconds. + pub wait_seconds: u64, +} + +/// A part of the server whose health is reported. +#[derive( + Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, utoipa::ToSchema, +)] +#[serde(rename_all = "snake_case")] +pub enum HealthComponent { + Server, + ControlDatabase, + Scheduler, + Location, + /// The server forwarding platform or security audit events to a webhook. + EventForwarding, +} + +/// How a component, or the server as a whole, stands. +#[derive( + Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, utoipa::ToSchema, +)] +#[serde(rename_all = "snake_case")] +pub enum HealthStatus { + Healthy, + /// Working, with a part that isn't: pages work and say what is affected. + Degraded, + /// The control database can't be used, so nothing that reads it works. + Unavailable, +} + +/// The newest failure of a component and the failures since it last worked. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ComponentFailure { + pub(crate) at: DateTime, + /// The first failure since the component last worked. + pub(crate) since: DateTime, + pub(crate) reason: String, + pub(crate) case: Option, + pub(crate) chain: Vec, + /// The newest requests that failed this way, for finding them in the server log. + pub(crate) request_ids: VecDeque, +} + +/// One component's last success and last failure; it is failing while the failure is newer. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct ComponentState { + pub(crate) last_success: Option>, + pub(crate) last_failure: Option, +} + +/// A location as this server last saw it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct SeenLocation { + pub(crate) name: String, + /// When any of its instances last reported; `None` before its first report. + pub(crate) last_report: Option>, +} + +/// Everything the health report is made from. +#[derive(Debug, Default)] +pub(crate) struct HealthState { + pub(crate) target: ControlTarget, + pub(crate) store: Option, + pub(crate) control_database: ComponentState, + /// `None` when this server runs no scheduler. + pub(crate) scheduler: Option, + pub(crate) locations: BTreeMap, + /// Each webhook this server forwards events to, by its name. + pub(crate) forwarding: BTreeMap, +} + +/// One server's in-memory health, shared by its API, scheduler and control database probe. +#[derive(Clone, Debug)] +pub struct ServerHealth { + pub(crate) state: Arc>, + pub(crate) version: String, + pub(crate) started_at: DateTime, +} + +/// The server row of the health report. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct ServerSummary { + pub version: String, + pub started_at: DateTime, + pub uptime_seconds: i64, +} + +/// One component as anyone may see it: its state, since when, and a short reason. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct ComponentHealth { + pub component: HealthComponent, + /// What people call it: "Control database", "Scheduler", or a location's name. + pub name: String, + /// The location this row is about. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location_id: Option, + pub status: HealthStatus, + /// When it stopped being healthy. + pub since: Option>, + pub reason: Option, + /// The control database failure's case, when that is the reason. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub case: Option, + /// When it last worked; for a location, its last report. + pub last_success: Option>, + pub last_failure: Option>, +} + +/// `GET /api/health`: every component's state, readable without signing in and without the control database. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct HealthReport { + /// The worst component's: unavailable when the control database is, degraded when anything else isn't healthy. + pub status: HealthStatus, + pub checked_at: DateTime, + /// How often a client should ask again while the server isn't healthy, in seconds. + pub retry_seconds: u64, + pub server: ServerSummary, + pub components: Vec, +} + +/// One component's details for administrators: where it is, each cause's message, and the failed requests. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct ComponentDetails { + pub component: HealthComponent, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location_id: Option, + /// The control database's host and port. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub host: Option, + pub error_chain: Vec, + pub request_ids: Vec, +} + +/// `GET /api/health/details`: what administrators see beside the public report. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct HealthDetails { + pub components: Vec, +} + +/// An active location and its instances' last report, as the control database probe reads them. +#[derive(Debug, Deserialize)] +pub(crate) struct StoredLocationReport { + pub(crate) location_id: Uuid, + pub(crate) name: String, + pub(crate) last_seen_at: Option>, +} + +impl ComponentState { + /// Whether its newest failure is newer than its newest success. + pub(crate) fn failing(&self) -> bool { + self.last_failure + .as_ref() + .is_some_and(|failure| self.last_success.is_none_or(|success| failure.at > success)) + } + + pub(crate) fn succeed(&mut self, at: DateTime) { + self.last_success = Some(self.last_success.map_or(at, |success| success.max(at))); + } + + /// Record a failure and return since when the component has been failing. + pub(crate) fn fail(&mut self, failure: ComponentFailure) -> DateTime { + let failing = self.failing(); + let mut failure = failure; + if let Some(previous) = self.last_failure.take().filter(|_| failing) { + failure.since = previous.since; + let mut request_ids = previous.request_ids; + request_ids.extend(failure.request_ids); + while request_ids.len() > crate::health::constants::KEPT_REQUEST_IDS { + request_ids.pop_front(); + } + failure.request_ids = request_ids; + } + let since = failure.since; + self.last_failure = Some(failure); + since + } +} + +impl Default for ServerHealth { + fn default() -> Self { + Self::new("", false) + } +} + +impl ServerHealth { + /// A server's health from its start, with a scheduler row when it runs one. + #[must_use] + pub fn new(version: &str, scheduler: bool) -> Self { + Self { + state: Arc::new(Mutex::new(HealthState { + scheduler: scheduler.then(ComponentState::default), + ..HealthState::default() + })), + version: version.to_owned(), + started_at: Utc::now(), + } + } + + pub(crate) fn state(&self) -> std::sync::MutexGuard<'_, HealthState> { + self.state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Name the control database the sentences mention. + pub fn set_target(&self, target: ControlTarget) { + self.state().target = target; + } + + /// The opened store, which names the database and whose pool tells a full pool from an unreachable database. + pub fn attach_store(&self, store: &ControlStore) { + let mut state = self.state(); + state.target = crate::health::_helpers::store_target::store_target(store); + state.store = Some(store.clone()); + } + + /// `cause` at this server's control database. + #[must_use] + pub fn locate(&self, cause: ControlCause) -> ControlCause { + let state = self.state(); + let pool_full = state + .store + .as_ref() + .is_some_and(crate::health::_helpers::pool::pool_full); + cause.at(&state.target, pool_full) + } + + pub fn control_succeeded(&self, at: DateTime) { + self.state().control_database.succeed(at); + } + + /// Record a control database failure, from `request_id` when a request met it; returns since when it has been failing. + pub fn control_failed( + &self, + cause: &ControlCause, + (at, request_id): (DateTime, Option), + ) -> DateTime { + self.state().control_database.fail(ComponentFailure { + at, + since: at, + reason: cause.message.clone(), + case: Some(cause.case), + chain: cause.chain.clone(), + request_ids: request_id.into_iter().collect(), + }) + } + + /// The control database's failure while it is failing, as a cause a response can carry. + #[must_use] + pub fn control_cause(&self) -> Option { + let state = self.state(); + let database = &state.control_database; + let failure = database + .last_failure + .as_ref() + .filter(|_| database.failing())?; + Some(ControlCause { + case: failure.case.unwrap_or(ControlCauseCase::Other), + message: failure.reason.clone(), + chain: failure.chain.clone(), + transient: true, + waited_for_pool: false, + }) + } + + /// Since when the control database has been failing, if it is. + #[must_use] + pub fn control_failing_since(&self) -> Option> { + let state = self.state(); + let database = &state.control_database; + database + .failing() + .then(|| database.last_failure.as_ref().map(|failure| failure.since)) + .flatten() + } + + pub fn scheduler_succeeded(&self, at: DateTime) { + if let Some(scheduler) = self.state().scheduler.as_mut() { + scheduler.succeed(at); + } + } + + /// Record a failed scheduler cycle, with the control database's cause when it was the reason. + pub fn scheduler_failed( + &self, + reason: &str, + (at, cause): (DateTime, Option<&ControlCause>), + ) { + if let Some(scheduler) = self.state().scheduler.as_mut() { + scheduler.fail(ComponentFailure { + at, + since: at, + reason: reason.to_owned(), + case: cause.map(|cause| cause.case), + chain: cause.map(|cause| cause.chain.clone()).unwrap_or_default(), + request_ids: VecDeque::new(), + }); + } + } + + /// The webhook `name` delivered what it had at `at`. + pub fn forwarding_succeeded(&self, name: &str, at: DateTime) { + self.state() + .forwarding + .entry(name.to_owned()) + .or_default() + .succeed(at); + } + + /// The webhook `name` couldn't deliver at `at`, because of `reason`; its events stay queued. + pub fn forwarding_failed(&self, name: &str, (reason, at): (&str, DateTime)) { + self.state() + .forwarding + .entry(name.to_owned()) + .or_default() + .fail(ComponentFailure { + at, + since: at, + reason: reason.to_owned(), + case: None, + chain: Vec::new(), + request_ids: VecDeque::new(), + }); + } + + /// A location's instance reported at `at`. + pub fn location_reported(&self, location_id: Uuid, at: DateTime) { + if let Some(location) = self.state().locations.get_mut(&location_id) { + location.last_report = Some(location.last_report.map_or(at, |last| last.max(at))); + } + } + + /// The active locations as the control database has them, keeping any newer report seen here. + pub(crate) fn locations_seen(&self, stored: Vec) { + let mut state = self.state(); + let previous = std::mem::take(&mut state.locations); + state.locations = stored + .into_iter() + .map(|location| { + let seen = previous + .get(&location.location_id) + .and_then(|seen| seen.last_report); + let last_report = seen.max(location.last_seen_at); + ( + location.location_id, + SeenLocation { + name: location.name, + last_report, + }, + ) + }) + .collect(); + } +} diff --git a/crates/sqlbuild-orchestration/src/lib.rs b/crates/sqlbuild-orchestration/src/lib.rs index 092a3d470a..9ac3dd1c9a 100644 --- a/crates/sqlbuild-orchestration/src/lib.rs +++ b/crates/sqlbuild-orchestration/src/lib.rs @@ -11,6 +11,8 @@ pub mod credentials; pub mod declarations; +pub mod health; + pub mod dev_events; pub mod discovered_sets; diff --git a/crates/sqlbuild-orchestration/src/node_states/_helpers/reads.rs b/crates/sqlbuild-orchestration/src/node_states/_helpers/reads.rs index 887cd2c1cc..7e7a2c0672 100644 --- a/crates/sqlbuild-orchestration/src/node_states/_helpers/reads.rs +++ b/crates/sqlbuild-orchestration/src/node_states/_helpers/reads.rs @@ -14,7 +14,7 @@ use crate::snapshots::models::SnapshotNode; use crate::store::errors::ControlError; use crate::store::main::{begin::begin, commit::commit, query::query}; use crate::store::models::{ControlStore, ControlTransaction, Parameter, TransactionMode}; -use crate::warehouse_history::main::read_node_check_counts::read_node_check_counts; +use crate::warehouse_history::main::checks::read_node_check_counts::read_node_check_counts; use crate::warehouse_metadata::main::node_reads::{ catalog_node::catalog_node, definition_evidences::definition_evidences, destination::destination, last_outcome::last_outcome, latest_attempts::latest_attempts, diff --git a/crates/sqlbuild-orchestration/src/node_states/main/list_person_checks.rs b/crates/sqlbuild-orchestration/src/node_states/main/list_person_checks.rs index 64f540249c..abfc0ac865 100644 --- a/crates/sqlbuild-orchestration/src/node_states/main/list_person_checks.rs +++ b/crates/sqlbuild-orchestration/src/node_states/main/list_person_checks.rs @@ -12,7 +12,7 @@ use crate::node_states::models::{CachedJson, HeldCheckList, NodeStateCache}; use crate::snapshots::main::reads::listing_read::listing_read; use crate::snapshots::main::reads::read_current_record::read_current_record; use crate::store::errors::ControlError; -use crate::warehouse_history::main::read_latest_checks::read_latest_checks; +use crate::warehouse_history::main::checks::read_latest_checks::read_latest_checks; /// Authorizes every read; a held list of the current snapshot is served as it is, otherwise the results are read and the list kept unless a signal arrived meanwhile. pub async fn list_person_checks( diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/health/failing_locations.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/health/failing_locations.rs index 1ad31d980b..0422331081 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/health/failing_locations.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/health/failing_locations.rs @@ -4,10 +4,12 @@ use chrono::TimeDelta; use uuid::Uuid; use crate::discovered_sets::models::DiscoveredSetStatus; +use crate::platform::_helpers::health::failing_syncs::failing_sync; use crate::platform::_helpers::health::recent_health::recent_health; use crate::platform::constants::LOCATION_SILENCE_SECONDS; use crate::platform::models::{ - DiscoveryHealth, FailingLocation, LocationHealth, LocationHealthObservation, LocationState, + DiscoveryHealth, FailingLocation, FailingSync, LocationFailures, LocationHealth, + LocationHealthObservation, LocationState, }; use crate::snapshots::main::reads::read_current_record::read_current_record; use crate::store::errors::ControlError; @@ -21,7 +23,7 @@ const CONNECTION_FAILED: &str = "the warehouse connection check after its last l /// Every live location target whose state is a failure, with the report that decided it and the snapshot it serves. pub(crate) async fn failing_locations( transaction: ControlTransaction, -) -> Result<(ControlTransaction, Vec), ControlError> { +) -> Result<(ControlTransaction, LocationFailures), ControlError> { let now = transaction.now; let (mut transaction, rows) = query( transaction, @@ -34,6 +36,7 @@ pub(crate) async fn failing_locations( ) .await?; let mut failing: Vec = Vec::new(); + let mut syncs: Vec = Vec::new(); for row in rows { let LiveTarget { location_id, @@ -43,6 +46,10 @@ pub(crate) async fn failing_locations( let target: &str = ⌖ let observations; (transaction, observations) = recent_health(transaction, location_id, Some(target)).await?; + syncs.extend(failing_sync( + &observations, + (location_id, &location_name, target), + )); let state = LocationState::of(&observations, (target, now)); let Some((failed_at, error)) = deciding_report(&observations, state) else { continue; @@ -59,7 +66,13 @@ pub(crate) async fn failing_locations( serving, }); } - Ok((transaction, failing)) + Ok(( + transaction, + LocationFailures { + locations: failing, + syncs, + }, + )) } /// When the failure that decided `state` was reported and its text; `None` for a state that isn't a failure here. diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/health/failing_sinks.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/health/failing_sinks.rs new file mode 100644 index 0000000000..6f837f8554 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/health/failing_sinks.rs @@ -0,0 +1,216 @@ +//! Lifecycle event sinks whose newest run lost events, from the runs' sink delivery reports. + +use std::collections::BTreeMap; + +use chrono::TimeDelta; +use uuid::Uuid; + +use crate::platform::constants::{ + LOCATION_SINK_KIND, SINK_PROVIDERS, SINK_REPORT_LIMIT, SINK_REPORT_WINDOW_DAYS, +}; +use crate::platform::models::{ + ActiveLocation, FailingSink, LocationHealth, LocationSinkRow, SinkReport, SinkReportRow, + SinkStreak, +}; +use crate::runs::constants::SINK_DELIVERIES_EVENT; +use crate::runs::models::{RunChange, SinkDelivery}; +use crate::store::errors::ControlError; +use crate::store::main::decode_row::decode_row; +use crate::store::main::query::query; +use crate::store::models::{ControlTransaction, Parameter}; + +/// The sink delivery reports of the last week's runs at live locations, newest first. +pub(crate) async fn sink_reports( + transaction: ControlTransaction, +) -> Result<(ControlTransaction, Vec), ControlError> { + let since = transaction.now - TimeDelta::days(SINK_REPORT_WINDOW_DAYS); + let (transaction, rows) = query( + transaction, + "SELECT e.occurred_at, e.payload, r.location_id, l.name AS location_name, r.target \ + FROM recall_events e JOIN sqb_runs r ON CAST(r.run_id AS TEXT)=e.run_id \ + JOIN sqb_locations l ON l.location_id=r.location_id \ + WHERE e.event_type=$1 AND e.occurred_at>=$2 AND l.archived_at IS NULL \ + ORDER BY e.storage_id DESC LIMIT $3", + vec![ + Parameter::Text(SINK_DELIVERIES_EVENT.to_owned()), + Parameter::Time(since), + Parameter::Integer(SINK_REPORT_LIMIT), + ], + ) + .await?; + let rows: Vec = rows.into_iter().map(decode_row).collect::>()?; + let (transaction, located) = location_sink_reports(transaction, since).await?; + let mut reports: Vec = rows.into_iter().filter_map(sink_report).collect(); + reports.extend(located); + reports.sort_by_key(|report| std::cmp::Reverse(report.at)); + Ok((transaction, reports)) +} + +/// The sink delivery reports of the active locations' own interpreters since `since`, newest first. +async fn location_sink_reports( + transaction: ControlTransaction, + since: chrono::DateTime, +) -> Result<(ControlTransaction, Vec), ControlError> { + let (transaction, rows) = query( + transaction, + "SELECT occurred_at, payload FROM recall_events WHERE event_type='location_health' \ + AND occurred_at>=$1 AND payload->'report'->'health'->>'kind'=$2 \ + ORDER BY storage_id DESC LIMIT $3", + vec![ + Parameter::Time(since), + Parameter::Text(LOCATION_SINK_KIND.to_owned()), + Parameter::Integer(SINK_REPORT_LIMIT), + ], + ) + .await?; + let (transaction, locations) = query( + transaction, + "SELECT location_id, name FROM sqb_locations WHERE archived_at IS NULL", + vec![], + ) + .await?; + let mut names: BTreeMap = BTreeMap::new(); + for location in locations { + let location: ActiveLocation = decode_row(location)?; + names.insert(location.location_id, location.name); + } + let rows: Vec = rows.into_iter().map(decode_row).collect::>()?; + Ok(( + transaction, + rows.into_iter() + .filter_map(|row| location_sink_report(row, &names)) + .collect(), + )) +} + +/// A location's report as a sink report; another kind, or an archived location's, is none. +fn location_sink_report( + row: LocationSinkRow, + names: &BTreeMap, +) -> Option { + let LocationHealth::SinkDeliveries { sinks } = row.payload.report.health else { + return None; + }; + Some(SinkReport { + location_id: row.payload.location_id, + location_name: names.get(&row.payload.location_id)?.clone(), + target: row.payload.report.target, + run_id: None, + at: row.occurred_at, + sinks, + teardown_failures: Vec::new(), + }) +} + +/// A row as a report; a stored change that isn't a sink delivery report is none. +fn sink_report(row: SinkReportRow) -> Option { + let RunChange::SinkDeliveries { + sinks, + teardown_failures, + } = row.payload.change.change + else { + return None; + }; + Some(SinkReport { + location_id: row.location_id, + location_name: row.location_name, + target: row.target, + run_id: Some(row.payload.change.run_id), + at: row.occurred_at, + sinks, + teardown_failures, + }) +} + +/// Each sink whose newest report lost events, since the first lossy report after its newest lossless one. +pub(crate) fn failing_sinks(reports: &[SinkReport]) -> Vec { + let mut streaks: BTreeMap<(Uuid, String, String), SinkStreak> = BTreeMap::new(); + for report in reports { + for (name, reason) in losses(report) { + let key = (report.location_id, report.target.clone(), name.clone()); + let streak = streaks.remove(&key).map_or_else( + || SinkStreak::first(report, (name, reason.clone())), + |streak| streak.older(report.at, reason.is_some()), + ); + streaks.insert(key, streak); + } + } + streaks + .into_values() + .filter_map(SinkStreak::failing) + .collect() +} + +/// Each sink in `report` with what it lost, then the sink providers with their teardown failures. +fn losses(report: &SinkReport) -> Vec<(String, Option)> { + let providers: Option = (!report.teardown_failures.is_empty()).then(|| { + format!( + "closing failed, so events they held may be lost: {}", + report.teardown_failures.join(", ") + ) + }); + report + .sinks + .iter() + .map(|sink| (sink.name.clone(), loss_reason(sink))) + .chain([(SINK_PROVIDERS.to_owned(), providers)]) + .collect() +} + +/// `8 of 8 events not delivered (8 failed)`; `None` when the sink delivered every event. +fn loss_reason(sink: &SinkDelivery) -> Option { + let parts: Vec = [(sink.dropped, "dropped"), (sink.failed, "failed")] + .into_iter() + .filter(|(count, _)| *count > 0) + .map(|(count, label)| format!("{count} {label}")) + .collect(); + (!parts.is_empty()).then(|| { + format!( + "{} of {} events not delivered ({})", + sink.dropped + sink.failed, + sink.accepted, + parts.join(", ") + ) + }) +} + +impl SinkStreak { + /// A sink's newest report: failing when it lost events. + fn first(report: &SinkReport, (sink, reason): (String, Option)) -> Self { + reason.map_or(Self::Clear, |reason| { + Self::Failing(FailingSink { + location_id: report.location_id, + location_name: report.location_name.clone(), + target: report.target.clone(), + sink, + since: report.at, + reason, + run_id: report.run_id, + last_success_at: None, + }) + }) + } + + /// The streak with an older report at `at` added: a lossy one moves its start back, a lossless one ends it. + fn older(self, at: chrono::DateTime, lossy: bool) -> Self { + match self { + Self::Failing(failing) if lossy => Self::Failing(FailingSink { + since: at, + ..failing + }), + Self::Failing(failing) => Self::Ended(FailingSink { + last_success_at: Some(at), + ..failing + }), + other => other, + } + } + + /// The sink's problem, if its newest report lost events. + fn failing(self) -> Option { + match self { + Self::Failing(failing) | Self::Ended(failing) => Some(failing), + Self::Clear => None, + } + } +} diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/health/failing_syncs.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/health/failing_syncs.rs new file mode 100644 index 0000000000..151f6b275f --- /dev/null +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/health/failing_syncs.rs @@ -0,0 +1,79 @@ +//! A location's run-history sync as its newest reports describe it: failing since when, why, and when it tries again. + +use uuid::Uuid; + +use crate::platform::models::{ + FailingSync, LocationHealth, LocationHealthObservation, WarehouseReadFailure, + WarehouseSyncFailure, WarehouseSyncProgress, +}; + +/// The sync of `place`, newest report first, while its newest report is a failure; a waiting sync isn't one. +pub(crate) fn failing_sync( + observations: &[LocationHealthObservation], + (location_id, location_name, target): (Uuid, &str, &str), +) -> Option { + let syncs: Vec<(&LocationHealthObservation, Option)> = observations + .iter() + .filter(|observation| observation.report.target == target) + .filter_map(|observation| match &observation.report.health { + LocationHealth::WarehouseSync { failure, .. } => Some((observation, *failure)), + _ => None, + }) + .collect(); + let (newest, failure) = *syncs.first()?; + let failure = failure.filter(|failure| *failure != WarehouseSyncFailure::Busy)?; + let LocationHealth::WarehouseSync { + error, + read_failure, + progress, + failing_since, + retry_at, + retry_seconds, + .. + } = &newest.report.health + else { + return None; + }; + let failing: Vec<&LocationHealthObservation> = syncs + .iter() + .take_while(|(_, failure)| { + failure.is_some_and(|failure| failure != WarehouseSyncFailure::Busy) + }) + .map(|(observation, _)| *observation) + .collect(); + let first_reported = failing + .last() + .map_or(newest.received_at, |observation| observation.received_at); + let halted: bool = progress + .as_ref() + .is_some_and(|progress: &WarehouseSyncProgress| progress.halted); + Some(FailingSync { + location_id, + location_name: location_name.to_owned(), + target: target.to_owned(), + since: failing_since.map_or(first_reported, |since| since.min(first_reported)), + reason: error + .clone() + .unwrap_or_else(|| stage_words(failure).to_owned()), + unreachable: matches!(read_failure, Some(WarehouseReadFailure::Unreachable {})), + halted, + retry_at: retry_at.filter(|_| !halted), + retry_seconds: retry_seconds.filter(|_| !halted), + last_success_at: syncs + .iter() + .find(|(_, failure)| failure.is_none()) + .map(|(observation, _)| observation.received_at), + }) +} + +/// What failed when the report has no error text of its own. +fn stage_words(failure: WarehouseSyncFailure) -> &'static str { + match failure { + WarehouseSyncFailure::Watermark => { + "the location couldn't read where the sync had got to from the server" + } + WarehouseSyncFailure::Read => "the warehouse read failed", + WarehouseSyncFailure::Delivery => "the location couldn't deliver history to the server", + WarehouseSyncFailure::Busy => "the warehouse file is in use", + } +} diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/health/mod.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/health/mod.rs index 2f3b98c7b1..b638bab81f 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/health/mod.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/health/mod.rs @@ -3,6 +3,8 @@ pub(crate) mod current_instance; pub(crate) mod event_history; pub(crate) mod failing_locations; +pub(crate) mod failing_sinks; +pub(crate) mod failing_syncs; pub(crate) mod observations; pub(crate) mod pool_cap_warnings; pub(crate) mod problems; diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/health/problems.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/health/problems.rs index e789c8561f..4da827235d 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/health/problems.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/health/problems.rs @@ -5,6 +5,7 @@ use uuid::Uuid; use crate::declarations::models::Schedule; use crate::platform::_helpers::health::failing_locations::failing_locations; +use crate::platform::_helpers::health::failing_sinks::{failing_sinks, sink_reports}; use crate::platform::constants::LOCATION_SILENCE_SECONDS; use std::collections::BTreeSet; @@ -61,6 +62,7 @@ pub(crate) async fn scan_problems(store: &ControlStore) -> Result = schedules .into_iter() @@ -92,7 +94,9 @@ pub(crate) async fn scan_problems(store: &ControlStore) -> Result>()?, - failing, + failing: failing.locations, + failing_syncs: failing.syncs, + failing_sinks: failing_sinks(&sinks), late_targets: late_targets .into_iter() .map(|row| { diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/health/recent_health.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/health/recent_health.rs index 9cfabbef7c..f7f99960ed 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/health/recent_health.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/health/recent_health.rs @@ -3,6 +3,9 @@ use uuid::Uuid; use crate::platform::constants::{LOCATION_RETENTION_DAYS, RECENT_HEALTH_LIMIT}; + +/// Sink delivery reports say nothing of the location's state and would crowd out the reports that do. +const SINK_REPORTS_EXCLUDED: &str = " AND payload->'report'->'health'->>'kind'<>'sink_deliveries'"; use crate::platform::models::{LocationHealth, LocationHealthObservation, LocationHealthReport}; use crate::store::errors::ControlError; use crate::store::main::decode_row::decode_row; @@ -33,7 +36,7 @@ pub(crate) async fn recent_health( .clone() .map(|day| { format!("SELECT * FROM (SELECT occurred_at AS received_at, invocation_sequence, payload FROM recall_events \ - WHERE invocation_id=${} AND event_type='location_health'{event_target} ORDER BY invocation_sequence DESC LIMIT 100) day_{day}", day + 1) + WHERE invocation_id=${} AND event_type='location_health'{event_target}{SINK_REPORTS_EXCLUDED} ORDER BY invocation_sequence DESC LIMIT 100) day_{day}", day + 1) }) .collect::>() .join(" UNION ALL "); diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/location/liveness.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/location/liveness.rs index 9e847be678..0c7ab2b74b 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/location/liveness.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/location/liveness.rs @@ -72,7 +72,7 @@ pub(crate) async fn observe_failing_locations( ) -> Result<(), ControlError> { let (mut transaction, failing) = failing_locations(begin(store, TransactionMode::Write).await?).await?; - for location in failing { + for location in failing.locations { let incident = Some(location.failed_at); transaction = observe( transaction, diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/location/reported_generation.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/location/reported_generation.rs index 8f6adda9fa..4989dfb487 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/location/reported_generation.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/location/reported_generation.rs @@ -13,7 +13,7 @@ pub(crate) fn reported_generation( )); } let generation = match report.health { - LocationHealth::Heartbeat {} => None, + LocationHealth::Heartbeat {} | LocationHealth::SinkDeliveries { .. } => None, LocationHealth::CompileFailed { generation, .. } | LocationHealth::Connection { generation, .. } | LocationHealth::ProviderSecrets { generation, .. } diff --git a/crates/sqlbuild-orchestration/src/platform/_helpers/maintenance/retention.rs b/crates/sqlbuild-orchestration/src/platform/_helpers/maintenance/retention.rs index 5750dbc598..fe851268f8 100644 --- a/crates/sqlbuild-orchestration/src/platform/_helpers/maintenance/retention.rs +++ b/crates/sqlbuild-orchestration/src/platform/_helpers/maintenance/retention.rs @@ -64,7 +64,7 @@ const EXPIRED_CLAIMS: &str = "WITH logged AS (\ WHERE event_type = 'run_claimed' AND producer = 'scheduler'), \ ranked AS (SELECT CAST(run_id AS TEXT) AS run_id, ended_at, ROW_NUMBER() OVER (PARTITION BY location_id, target \ ORDER BY ended_at DESC, run_id DESC) AS newest FROM sqb_runs \ - WHERE ended_at IS NOT NULL AND status IN ('success', 'warn', 'partial', 'failed', 'cancelled', 'skipped')) \ + WHERE ended_at IS NOT NULL AND status IN ('success', 'warn', 'failed', 'cancelled', 'skipped')) \ SELECT logged.claim FROM ranked JOIN claimed ON claimed.run_id = ranked.run_id \ JOIN logged ON logged.claim = claimed.claim \ WHERE ranked.newest > $1 OR ranked.ended_at < $2 ORDER BY ranked.ended_at LIMIT $3"; diff --git a/crates/sqlbuild-orchestration/src/platform/constants.rs b/crates/sqlbuild-orchestration/src/platform/constants.rs index df0ee1a34e..d4aafb1365 100644 --- a/crates/sqlbuild-orchestration/src/platform/constants.rs +++ b/crates/sqlbuild-orchestration/src/platform/constants.rs @@ -74,3 +74,18 @@ pub const MAX_REPUBLISH_WAIT_SECONDS: u64 = 60; pub(crate) const REPUBLISH_POLL_MILLISECONDS: u64 = 250; /// The longest publish error the server keeps. pub(crate) const MAX_PUBLISH_ERROR_CHARS: usize = 4000; + +/// How far back the newest sink delivery reports are read for failing sinks. +pub(crate) const SINK_REPORT_WINDOW_DAYS: i64 = 7; + +/// At most this many newest sink delivery reports are read for failing sinks. +pub(crate) const SINK_REPORT_LIMIT: i64 = 1000; + +/// What a failing sink's attention names the sink providers whose teardown failed. +pub(crate) const SINK_PROVIDERS: &str = "sink providers"; + +/// The request a location asks its interpreter for its sinks' delivery totals with. +pub const SINK_DELIVERIES_REQUEST: &str = "sink_deliveries"; + +/// The kind a location's sink delivery health report is stored under. +pub(crate) const LOCATION_SINK_KIND: &str = "sink_deliveries"; diff --git a/crates/sqlbuild-orchestration/src/platform/main/health/report_location_health.rs b/crates/sqlbuild-orchestration/src/platform/main/health/report_location_health.rs index 32682eb088..64c7adb4fc 100644 --- a/crates/sqlbuild-orchestration/src/platform/main/health/report_location_health.rs +++ b/crates/sqlbuild-orchestration/src/platform/main/health/report_location_health.rs @@ -9,7 +9,7 @@ use crate::platform::_helpers::location::published_generation::require_published use crate::platform::_helpers::location::reported_generation::reported_generation; use crate::platform::_helpers::location::rule_findings::check_rule_findings; use crate::platform::_helpers::plans::load_failure::fail_plans_on_failed_load; -use crate::platform::models::LocationHealthReport; +use crate::platform::models::{LocationHealth, LocationHealthReport}; use crate::store::errors::ControlError; use crate::store::main::append_control_event::append_control_event; use crate::store::main::begin::begin; @@ -22,10 +22,10 @@ pub async fn report_location_health( location_id: Uuid, report: &LocationHealthReport, ) -> Result { - let generation = reported_generation(report)?; + reported_generation(report)?; check_rule_findings(report)?; let transaction = begin(store, TransactionMode::Write).await?; - if generation.is_none() { + if matches!(report.health, LocationHealth::Heartbeat {}) { let (transaction, applied) = location_heartbeat(transaction, location_id, report).await?; commit(transaction).await?; return Ok(applied); diff --git a/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_problems.rs b/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_problems.rs index e26518951f..c143274f89 100644 --- a/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_problems.rs +++ b/crates/sqlbuild-orchestration/src/platform/main/person_reads/read_person_problems.rs @@ -79,6 +79,17 @@ pub async fn read_person_problems( .into_iter() .filter(|location| listed.contains(&(location.location_id, location.target.clone()))) .collect(), + failing_syncs: scan + .failing_syncs + .into_iter() + .filter(|sync| listed.contains(&(sync.location_id, sync.target.clone()))) + .collect(), + failing_sinks: scan + .failing_sinks + .into_iter() + .filter(|sink| listed.contains(&(sink.location_id, sink.target.clone()))) + .collect(), + failing_forwarding: Vec::new(), low_calendars: scan .low_calendars .into_iter() diff --git a/crates/sqlbuild-orchestration/src/platform/models.rs b/crates/sqlbuild-orchestration/src/platform/models.rs index 68e80b10ff..902b225e98 100644 --- a/crates/sqlbuild-orchestration/src/platform/models.rs +++ b/crates/sqlbuild-orchestration/src/platform/models.rs @@ -5,7 +5,10 @@ use crate::credentials::models::AuditRetention; use crate::declarations::models::TriggerDefinition; use crate::discovered_sets::models::DiscoveredSetStatus; use crate::platform::_helpers::health::current_instance::{CurrentInstance, current_instance}; -use crate::runs::models::{RunKind, RunLogRetention, RunNodeFailure, RunOutcome}; +use crate::runs::models::{ + RunAuditFailure, RunFailureCause, RunKind, RunLogRetention, RunNodeFailure, RunOutcome, + RunTrigger, +}; use crate::sensors::models::{SensorEvaluationRequest, SensorFunctionOutcome}; use crate::snapshots::models::{SnapshotRecord, SnapshotRetention}; use crate::warehouse_metadata::models::StateHistoryRetention; @@ -79,6 +82,10 @@ pub enum LocationHealth { generation: i64, reason: String, }, + /// What each lifecycle event sink of one of the location's interpreters delivered since its last report. + SinkDeliveries { + sinks: Vec, + }, /// Jobs and groups this server's `pool_caps` clamp, derived by the server, never reported by a location. PoolCapped { generation: i64, @@ -109,6 +116,14 @@ pub enum LocationHealth { /// On the report of a table's last delivered page, the records the server then mirrored of that table across the target's state locations. #[serde(default, skip_serializing_if = "Option::is_none")] mirrored_records: Option, + /// While the sync fails, when its first failure in a row was; absent once it works and from older locations. + #[serde(default, skip_serializing_if = "Option::is_none")] + failing_since: Option>, + /// On a failure the sync retries, when it tries again and how many seconds it waits. + #[serde(default, skip_serializing_if = "Option::is_none")] + retry_at: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + retry_seconds: Option, }, } @@ -547,18 +562,8 @@ pub enum PlatformEvent { claim_id: Uuid, code: String, }, - /// A job, group or ad-hoc run ended failed or partial; only the webhook receives it, never person reads. - RunFailed { - run_id: Uuid, - run_kind: RunKind, - job_key: Option, - location_id: Uuid, - target: String, - outcome: RunOutcome, - /// The first failed nodes by key, with redacted and bounded error text. - failed_nodes: Vec, - failed_node_count: i64, - }, + /// A job, group or ad-hoc run ended failed; only the webhook and platform sensors receive it, never person reads. + RunFailed(Box), /// A trigger was skipped because its stored job or pinned snapshot can't be read, or a sensor because its check failed; `reason` says which. TriggerSkipped { trigger_id: Uuid, @@ -579,6 +584,35 @@ pub enum PlatformEvent { }, } +/// What a `run_failed` event says: the run, what started it, when, what failed and why, with UI links. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct RunFailureEvent { + pub run_id: Uuid, + pub run_kind: RunKind, + pub job_key: Option, + pub location_id: Uuid, + pub target: String, + pub outcome: RunOutcome, + /// The run's UI page; null when the server has no origin. + pub url: Option, + pub trigger: RunTrigger, + pub started_at: Option>, + pub ended_at: Option>, + pub duration_ms: Option, + /// Why the run failed outside any node; null when its failed nodes or audits say why. + pub error: Option, + /// The first failed nodes by key, with redacted and bounded error text. + pub failed_nodes: Vec, + pub failed_node_count: i64, + /// The first error-severity audit failures by name. + pub failed_audits: Vec, + pub failed_audit_count: i64, + pub succeeded_node_count: i64, + /// The first skipped nodes by key. + pub skipped_nodes: Vec, + pub skipped_node_count: i64, +} + impl PlatformEvent { #[must_use] pub const fn kind(&self) -> PlatformEventKind { @@ -590,7 +624,7 @@ impl PlatformEvent { Self::LocationBroken { .. } => PlatformEventKind::LocationBroken, Self::LocationFailing { .. } => PlatformEventKind::LocationFailing, Self::LaunchFailed { .. } => PlatformEventKind::LaunchFailed, - Self::RunFailed { .. } => PlatformEventKind::RunFailed, + Self::RunFailed(_) => PlatformEventKind::RunFailed, Self::TriggerSkipped { .. } => PlatformEventKind::TriggerSkipped, Self::SensorRechecked { .. } => PlatformEventKind::SensorRechecked, Self::CalendarTimesDropped { .. } => PlatformEventKind::CalendarTimesDropped, @@ -607,7 +641,7 @@ impl PlatformEvent { Self::LocationBroken { .. } => "platform_location_broken", Self::LocationFailing { .. } => "platform_location_failing", Self::LaunchFailed { .. } => "platform_launch_failed", - Self::RunFailed { .. } => "platform_run_failed", + Self::RunFailed(_) => "platform_run_failed", Self::TriggerSkipped { .. } => "platform_trigger_skipped", Self::SensorRechecked { .. } => "platform_sensor_rechecked", Self::CalendarTimesDropped { .. } => "platform_calendar_times_dropped", @@ -688,6 +722,15 @@ pub struct PlatformProblems { /// Checking-in locations whose latest load, plan of what changed, discovery or connection check failed. #[serde(default)] pub failing_locations: Vec, + /// Checking-in locations whose run-history sync is failing, until a sync report succeeds. + #[serde(default)] + pub failing_syncs: Vec, + /// Lifecycle event sinks whose newest run lost events, until a run delivers all of its events. + #[serde(default)] + pub failing_sinks: Vec, + /// This server's event webhooks that can't deliver, until one delivers again. + #[serde(default)] + pub failing_forwarding: Vec, pub overdue_ticks: Vec, /// Running calendar schedules whose dates run out within a day. #[serde(default)] @@ -809,6 +852,125 @@ pub struct FailingLocation { pub serving: Option, } +/// Every checking-in location's failing load, plan, discovery or connection check, and failing run-history sync. +#[derive(Clone, Debug, Default)] +pub(crate) struct LocationFailures { + pub(crate) locations: Vec, + pub(crate) syncs: Vec, +} + +/// A checking-in location whose run-history sync is failing: since when, why, and when it tries again. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct FailingSync { + pub location_id: Uuid, + pub location_name: String, + pub target: String, + /// The first failure in a row. + pub since: DateTime, + /// What failed, redacted. + pub reason: String, + /// The location couldn't reach the warehouse, so no compute ran. + pub unreachable: bool, + /// Failed reads stopped the sync; it resumes on request, after the next run or a publish. + pub halted: bool, + /// When the location tries again, and how many seconds it waits between tries. + pub retry_at: Option>, + pub retry_seconds: Option, + /// The newest report of a sync that worked. + pub last_success_at: Option>, +} + +/// An event webhook this server can't deliver to: since when, and why; its events stay queued. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct FailingForwarding { + /// Such as `Platform event forwarding`. + pub name: String, + pub since: DateTime, + pub reason: String, + pub last_success_at: Option>, +} + +/// A lifecycle event sink whose runs lose events: since its first lossy run in a row, and why. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct FailingSink { + pub location_id: Uuid, + pub location_name: String, + pub target: String, + /// The sink's name in the project. + pub sink: String, + /// The first run in a row whose events it lost. + pub since: DateTime, + /// What it lost, such as `8 of 8 events not delivered (8 failed)`. + pub reason: String, + /// The newest run whose events it lost; `None` when the location's own interpreter lost them. + pub run_id: Option, + /// The newest run before that whose events it all delivered. + pub last_success_at: Option>, +} + +/// A run's report of its sinks' deliveries, with where the run ran. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct SinkReport { + pub(crate) location_id: Uuid, + pub(crate) location_name: String, + pub(crate) target: String, + pub(crate) run_id: Option, + pub(crate) at: DateTime, + pub(crate) sinks: Vec, + pub(crate) teardown_failures: Vec, +} + +/// A stored sink delivery report and where its run ran. +#[derive(Debug, Deserialize)] +pub(crate) struct SinkReportRow { + pub(crate) occurred_at: DateTime, + pub(crate) payload: SinkReportPayload, + pub(crate) location_id: Uuid, + pub(crate) location_name: String, + pub(crate) target: String, +} + +/// A location's stored sink delivery report and its location. +#[derive(Debug, Deserialize)] +pub(crate) struct LocationSinkRow { + pub(crate) occurred_at: DateTime, + pub(crate) payload: LocationSinkPayload, +} + +/// A stored location health event's payload. +#[derive(Debug, Deserialize)] +pub(crate) struct LocationSinkPayload { + pub(crate) location_id: Uuid, + pub(crate) report: LocationHealthReport, +} + +/// An active location's ID and name. +#[derive(Debug, Deserialize)] +pub(crate) struct ActiveLocation { + pub(crate) location_id: Uuid, + pub(crate) name: String, +} + +/// A location interpreter's reply to `sink_deliveries`: each sink's totals since the interpreter started. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SinkDeliveryTotals { + pub sinks: Vec, +} + +/// A stored run change's payload. +#[derive(Debug, Deserialize)] +pub(crate) struct SinkReportPayload { + pub(crate) change: crate::runs::models::RunChangeRequest, +} + +/// A sink's reports read newest first: failing so far, failing before a lossless report, or never failing. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum SinkStreak { + Failing(FailingSink), + Ended(FailingSink), + Clear, +} + /// A running schedule whose next tick is more than 30 seconds late. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] pub struct OverdueTick { @@ -838,6 +1000,8 @@ pub(crate) struct ProblemScan { pub(crate) lease: Option, pub(crate) broken: Vec, pub(crate) failing: Vec, + pub(crate) failing_syncs: Vec, + pub(crate) failing_sinks: Vec, pub(crate) late_targets: std::collections::BTreeSet<(Uuid, String)>, pub(crate) low_calendars: Vec, pub(crate) skipped_triggers: Vec, @@ -919,8 +1083,10 @@ pub struct WarehouseSyncProgress { #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] pub enum WarehouseReadFailure { - /// The reader did not start or connect to the warehouse, or the read raised an error. + /// The reader did not start, or the read raised an error after connecting. ReadError {}, + /// The reader could not reach the warehouse, so no compute ran; these never stop the sync. + Unreachable {}, /// The reader did not answer within this many seconds. TimedOut { seconds: u64 }, } diff --git a/crates/sqlbuild-orchestration/src/run_output/main/download_person_output.rs b/crates/sqlbuild-orchestration/src/run_output/main/download_person_output.rs index 88c305d930..1ab7c690b2 100644 --- a/crates/sqlbuild-orchestration/src/run_output/main/download_person_output.rs +++ b/crates/sqlbuild-orchestration/src/run_output/main/download_person_output.rs @@ -10,7 +10,7 @@ use crate::run_output::models::{OutputDownloadQuery, OutputStore, OutputView}; use crate::run_output::types::PersonRunRead; use crate::store::errors::ControlError; use crate::store::models::ControlStore; -use crate::warehouse_history::main::read_run_evidence::read_run_evidence; +use crate::warehouse_history::main::runs::read_run_evidence::read_run_evidence; /// `None` when the run is not in this location and target. pub async fn download_person_output( diff --git a/crates/sqlbuild-orchestration/src/run_output/main/read_person_output_index.rs b/crates/sqlbuild-orchestration/src/run_output/main/read_person_output_index.rs index f4dab7c80f..5b372c928b 100644 --- a/crates/sqlbuild-orchestration/src/run_output/main/read_person_output_index.rs +++ b/crates/sqlbuild-orchestration/src/run_output/main/read_person_output_index.rs @@ -9,7 +9,7 @@ use crate::run_output::types::PersonRunRead; use crate::runs::constants::REPEATED_READ_AUDIT; use crate::store::errors::ControlError; use crate::store::models::ControlStore; -use crate::warehouse_history::main::read_run_evidence::read_run_evidence; +use crate::warehouse_history::main::runs::read_run_evidence::read_run_evidence; /// `None` when the run is not in this location and target; `node` names whose marks to include; each read is audited. pub async fn read_person_output_index( diff --git a/crates/sqlbuild-orchestration/src/run_output/main/read_person_output_page.rs b/crates/sqlbuild-orchestration/src/run_output/main/read_person_output_page.rs index a193627e62..f72ec794ce 100644 --- a/crates/sqlbuild-orchestration/src/run_output/main/read_person_output_page.rs +++ b/crates/sqlbuild-orchestration/src/run_output/main/read_person_output_page.rs @@ -11,7 +11,7 @@ use crate::run_output::types::PersonRunRead; use crate::runs::constants::REPEATED_READ_AUDIT; use crate::store::errors::ControlError; use crate::store::models::ControlStore; -use crate::warehouse_history::main::read_run_evidence::read_run_evidence; +use crate::warehouse_history::main::runs::read_run_evidence::read_run_evidence; /// `None` when the run is not in this location and target; output nobody printed is an empty page. pub async fn read_person_output_page( diff --git a/crates/sqlbuild-orchestration/src/run_output/main/search_person_output.rs b/crates/sqlbuild-orchestration/src/run_output/main/search_person_output.rs index c17d81961b..773fc021f7 100644 --- a/crates/sqlbuild-orchestration/src/run_output/main/search_person_output.rs +++ b/crates/sqlbuild-orchestration/src/run_output/main/search_person_output.rs @@ -12,7 +12,7 @@ use crate::run_output::models::{ use crate::run_output::types::PersonRunRead; use crate::store::errors::ControlError; use crate::store::models::ControlStore; -use crate::warehouse_history::main::read_run_evidence::read_run_evidence; +use crate::warehouse_history::main::runs::read_run_evidence::read_run_evidence; /// `None` when the run is not in this location and target; output small enough is searched whole, with a count, and a larger one a bounded part at a time. pub async fn search_person_output( diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/groups/lifecycle.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/groups/lifecycle.rs index ecf00c55d8..818b2f2030 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/groups/lifecycle.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/groups/lifecycle.rs @@ -27,8 +27,8 @@ use crate::store::types::Row; /// Callers have already checked leadership; the surrounding transaction fences the entire advance. pub(crate) async fn group_change( transaction: ControlTransaction, - run_id: Uuid, - change: RunChange, + (run_id, change): (Uuid, RunChange), + origin: Option<&str>, ) -> Result { let (transaction, rows) = query(transaction, "SELECT r.status, r.cancel_requested_at, r.node_counts_json, r.worker_instance FROM sqb_runs r WHERE r.run_id=$1", @@ -44,20 +44,24 @@ pub(crate) async fn group_change( ); publish_change( transaction, - &RunChangeRequest { - event_id, - run_id, - claim_id: state.worker_instance, - change, - }, - &state, + ( + &RunChangeRequest { + event_id, + run_id, + claim_id: state.worker_instance, + change, + }, + &state, + ), + origin, ) .await } +/// `origin` links the group's run failure, if advancing ends it failed. pub(crate) async fn advance_group( transaction: ControlTransaction, - parent_id: Uuid, + (parent_id, origin): (Uuid, Option<&str>), limits: &BTreeMap, eligible: Option<&BTreeSet<(Uuid, String)>>, ) -> Result { @@ -73,22 +77,25 @@ pub(crate) async fn advance_group( if !child.state.status.is_terminal() && child.state.cancel_requested_at.is_none() { transaction = group_change( transaction, - child.request_json.run_id, - RunChange::CancelRequested { - actor: "system:group".into(), - reason: if stopped { - "group stopped after a child failure" - } else { - "parent group cancellation requested" - } - .into(), - }, + ( + child.request_json.run_id, + RunChange::CancelRequested { + actor: "system:group".into(), + reason: if stopped { + "group stopped after a child failure" + } else { + "parent group cancellation requested" + } + .into(), + }, + ), + origin, ) .await?; } } } else if parent.state.status == RunStatus::Running { - transaction = skip_blocked_members(transaction, &group).await?; + transaction = skip_blocked_members(transaction, &group, origin).await?; } else if parent.state.status == RunStatus::Queued && parent.request_json.due(transaction.now) { let admission = admitted( &parent.request_json, @@ -114,7 +121,8 @@ pub(crate) async fn advance_group( (transaction, _) = query(transaction, "ROLLBACK TO SAVEPOINT group_claim", vec![]).await?; } else { - transaction = group_change(transaction, parent_id, RunChange::Started).await?; + transaction = + group_change(transaction, (parent_id, RunChange::Started), origin).await?; } (transaction, _) = query(transaction, "RELEASE SAVEPOINT group_claim", vec![]).await?; } @@ -123,7 +131,7 @@ pub(crate) async fn advance_group( .iter() .all(|child| child.state.status.is_terminal()) { - transaction = finish_group(transaction, &group, stopped).await?; + transaction = finish_group(transaction, (&group, stopped), origin).await?; } Ok(transaction) } @@ -132,6 +140,7 @@ pub(crate) async fn advance_group( async fn skip_blocked_members( mut transaction: ControlTransaction, group: &GroupContext, + origin: Option<&str>, ) -> Result { let Some(declaration) = group .parent @@ -171,28 +180,35 @@ async fn skip_blocked_members( for node_key in &request.selection { transaction = group_change( transaction, - request.run_id, - RunChange::NodeFinished { - node_key: node_key.clone(), - outcome: NodeOutcome::Skipped, - rows_affected: None, - table_rows: None, - no_change_reason: None, - error_code: None, - skipped_because_of: cause.clone(), - error_message: None, - }, + ( + request.run_id, + RunChange::NodeFinished { + node_key: node_key.clone(), + outcome: NodeOutcome::Skipped, + rows_affected: None, + table_rows: None, + no_change_reason: None, + error_code: None, + skipped_because_of: cause.clone(), + error_message: None, + phase: None, + }, + ), + origin, ) .await?; } transaction = group_change( transaction, - request.run_id, - RunChange::Finished { - outcome: RunOutcome::Skipped, - reason: format!("skipped because {failed_job} did not succeed"), - exit_code: None, - }, + ( + request.run_id, + RunChange::Finished { + outcome: RunOutcome::Skipped, + reason: format!("skipped because {failed_job} did not succeed"), + exit_code: None, + }, + ), + origin, ) .await?; } @@ -201,8 +217,8 @@ async fn skip_blocked_members( async fn finish_group( transaction: ControlTransaction, - group: &GroupContext, - stopped: bool, + (group, stopped): (&GroupContext, bool), + origin: Option<&str>, ) -> Result { let parent = &group.parent; let parent_id = parent.request_json.run_id; @@ -254,30 +270,30 @@ async fn finish_group( } } let mut outcomes: BTreeSet = BTreeSet::new(); - let mut good = false; - let build = parent.request_json.command.is_build(); - let source_needs_no_run = |key: &str| build && key.starts_with("source:"); for key in &parent.request_json.selection { let node = nodes .get(key) .ok_or_else(|| ControlError::Invalid("group node has no child evidence".into()))?; outcomes.insert(node.status.clone()); - good |= matches!(node.status.as_str(), "success" | "warn") && !source_needs_no_run(key); let outcome: NodeOutcome = serde_json::from_value(serde_json::json!(node.status)) .map_err(|error| ControlError::Invalid(error.to_string()))?; transaction = group_change( transaction, - parent_id, - RunChange::NodeFinished { - node_key: key.clone(), - outcome, - rows_affected: node.rows_affected, - table_rows: node.table_rows, - no_change_reason: node.no_change_reason.clone(), - error_code: node.error_code.clone(), - skipped_because_of: node.skipped_because_of.clone(), - error_message: None, - }, + ( + parent_id, + RunChange::NodeFinished { + node_key: key.clone(), + outcome, + rows_affected: node.rows_affected, + table_rows: node.table_rows, + no_change_reason: node.no_change_reason.clone(), + error_code: node.error_code.clone(), + skipped_because_of: node.skipped_because_of.clone(), + error_message: None, + phase: None, + }, + ), + origin, ) .await?; } @@ -290,11 +306,7 @@ async fn finish_group( .any(|status| !matches!(status.as_str(), "success" | "warn")); let outcome = if parent.state.cancel_requested_at.is_some() { RunOutcome::Cancelled - } else if stopped { - RunOutcome::Failed - } else if bad && good { - RunOutcome::Partial - } else if bad { + } else if stopped || bad { RunOutcome::Failed } else if outcomes.contains("warn") || group @@ -315,21 +327,27 @@ async fn finish_group( if ignored > 0 { transaction = group_change( transaction, - parent_id, - RunChange::AuditFailuresIgnored { - count: u32::try_from(ignored).unwrap_or(u32::MAX), - }, + ( + parent_id, + RunChange::AuditFailuresIgnored { + count: u32::try_from(ignored).unwrap_or(u32::MAX), + }, + ), + origin, ) .await?; } group_change( transaction, - parent_id, - RunChange::Finished { - outcome, - reason: "all group children have durable terminal outcomes".into(), - exit_code: None, - }, + ( + parent_id, + RunChange::Finished { + outcome, + reason: "all group children have durable terminal outcomes".into(), + exit_code: None, + }, + ), + origin, ) .await } diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/change_run.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/change_run.rs index 64b822b237..ac2831358e 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/change_run.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/change_run.rs @@ -14,11 +14,11 @@ use crate::store::main::decode_row::decode_row; use crate::store::main::query::query; use crate::store::models::{ControlTransaction, Parameter}; -/// Use authenticated authority and record unclaimed cancellation as terminal in the same transaction. +/// Use authenticated authority, terminal unclaimed cancellation and `origin` (else the lease's) for failure links, in one transaction. pub(crate) async fn change_run_in( mut transaction: ControlTransaction, - authority: RunAuthority<'_>, - request: &RunChangeRequest, + (authority, request): (RunAuthority<'_>, &RunChangeRequest), + origin: Option<&str>, ) -> Result<(ControlTransaction, bool), ControlError> { validate_authority(authority, request)?; if let RunAuthority::Scheduler(lease) = authority { @@ -51,7 +51,11 @@ pub(crate) async fn change_run_in( } else { validate_change(&state, request)?; } - let mut transaction = publish_change(transaction, request, &state).await?; + let origin = match authority { + RunAuthority::Scheduler(lease) => lease.origin.as_deref().or(origin), + _ => origin, + }; + let mut transaction = publish_change(transaction, (request, &state), origin).await?; if let (RunAuthority::Operator(context), RunChange::CancelRequested { reason, .. }) = (authority, &request.change) { diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/changes.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/changes.rs index adecced069..3acde4cb9f 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/changes.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/changes.rs @@ -93,10 +93,10 @@ pub(crate) fn validate_authority( | RunChange::Compiled { .. } | RunChange::Recovered | RunChange::AuditFailuresIgnored { .. } + | RunChange::SinkDeliveries { .. } | RunChange::Finished { outcome: RunOutcome::Success | RunOutcome::Warn - | RunOutcome::Partial | RunOutcome::Failed | RunOutcome::Cancelled, .. @@ -145,7 +145,8 @@ pub(crate) fn validate_change( | RunChange::CheckStarted { .. } | RunChange::CheckFinished { .. } | RunChange::Compiled { .. } - | RunChange::AuditFailuresIgnored { .. } => { + | RunChange::AuditFailuresIgnored { .. } + | RunChange::SinkDeliveries { .. } => { matches!(state.status, Running | Unresponsive) } RunChange::Unresponsive => state.status == Running, @@ -162,7 +163,7 @@ pub(crate) fn validate_change( )); } if let RunChange::Finished { - outcome: RunOutcome::Success | RunOutcome::Warn | RunOutcome::Partial, + outcome: RunOutcome::Success | RunOutcome::Warn, .. } = request.change { @@ -173,11 +174,8 @@ pub(crate) fn validate_change( .copied() .unwrap_or_default() }; - let good = count("success") + count("warn"); let bad = count("failed") + count("skipped") + count("cancelled") + count("not_run"); - let expected = if bad > 0 && good > 0 { - RunOutcome::Partial - } else if bad > 0 { + let expected = if bad > 0 { RunOutcome::Failed } else if count("warn") > 0 { RunOutcome::Warn diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/checks.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/checks.rs index 560a5c8395..1eac0c7389 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/checks.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/checks.rs @@ -44,7 +44,9 @@ pub(crate) async fn check_execution_history( let previous = previous.first().and_then(|row| row["status"].as_str()); let valid = match outcome { None => previous.is_none(), - Some(NodeOutcome::Skipped) => previous.is_none() || previous == Some(NODE_RUNNING), + Some(NodeOutcome::Skipped | NodeOutcome::NotRun) => { + previous.is_none() || previous == Some(NODE_RUNNING) + } Some(_) => previous == Some(NODE_RUNNING), }; if !valid { diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/error_text.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/error_text.rs index 8d316dfe63..3873773353 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/error_text.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/error_text.rs @@ -8,24 +8,48 @@ use sqlbuild_core::redaction::main::redact_error_text::redact_error_text; use crate::runs::models::{RunChange, RunChangeRequest}; use crate::store::errors::ControlError; +/// The longest failure phase token a worker may report. +const MAX_PHASE_LENGTH: usize = 32; + pub(crate) fn bounded_error_text<'de, D: Deserializer<'de>>( deserializer: D, ) -> Result, D::Error> { Ok(Option::::deserialize(deserializer)?.map(|text| redact_error_text(&text))) } -/// The error text of a stored node-finished fact; `None` when there is no fact or it carries none. -pub(crate) fn finished_error_message(payload: &Value) -> Result, ControlError> { +/// A failure phase as a worker reports it: kept only as a short lowercase token, so it can't carry text. +pub(crate) fn failure_phase<'de, D: Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + Ok(Option::::deserialize(deserializer)?.filter(|phase| is_phase_token(phase))) +} + +fn is_phase_token(phase: &str) -> bool { + (1..=MAX_PHASE_LENGTH).contains(&phase.len()) && phase.bytes().all(is_phase_byte) +} + +const fn is_phase_byte(byte: u8) -> bool { + byte.is_ascii_lowercase() || byte == b'_' +} + +/// The error text and failure phase of a stored node-finished fact; both `None` when there is no fact. +pub(crate) fn finished_failure( + payload: &Value, +) -> Result<(Option, Option), ControlError> { if payload.is_null() { - return Ok(None); + return Ok((None, None)); } Ok( match serde_json::from_value::(payload["change"].clone()) .map_err(|error| ControlError::Invalid(error.to_string()))? .change { - RunChange::NodeFinished { error_message, .. } => error_message, - _ => None, + RunChange::NodeFinished { + error_message, + phase, + .. + } => (error_message, phase), + _ => (None, None), }, ) } diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/missing_secrets.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/missing_secrets.rs index e6333054dc..4a75d1788d 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/missing_secrets.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/missing_secrets.rs @@ -4,7 +4,7 @@ use std::collections::BTreeMap; use uuid::Uuid; -use crate::runs::_helpers::lifecycle::error_text::finished_error_message; +use crate::runs::_helpers::lifecycle::error_text::finished_failure; use crate::runs::constants::{ MISSING_SECRET_ERROR_CODE, MISSING_SECRET_PHRASE, MISSING_SECRET_PREFIX, }; @@ -42,7 +42,7 @@ pub(in crate::runs) async fn with_missing_secrets( for row in rows { let (Some(key), Ok(Some(message))) = ( row["node_key"].as_str(), - finished_error_message(&row["payload"]), + finished_failure(&row["payload"]).map(|(message, _)| message), ) else { continue; }; diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/narrowing.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/narrowing.rs index 0052e6827b..b29947a05c 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/narrowing.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/narrowing.rs @@ -57,6 +57,23 @@ pub(crate) fn frozen_member_attempt<'de, D: Deserializer<'de>>( .transpose() } +/// The command tokens of a stored authored request, or of an already projected record; `None` when the request has none. +pub(crate) fn authored_command<'de, D: Deserializer<'de>>( + deserializer: D, +) -> Result>, D::Error> { + let value: Value = frozen(deserializer)?; + let command: &Value = value + .get("request") + .and_then(|request| request.get("command")) + .unwrap_or(&value); + Ok(command.as_array().and_then(|tokens| { + tokens + .iter() + .map(|token| token.as_str().map(str::to_owned)) + .collect() + })) +} + /// A JSON column, which SQLite returns as text and PostgreSQL as JSON. fn frozen<'de, D: Deserializer<'de>>(deserializer: D) -> Result { let value: Value = Option::::deserialize(deserializer)?.unwrap_or(Value::Null); diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/projection.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/projection.rs index 6440fe7d23..2668c24f5a 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/projection.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/projection.rs @@ -60,7 +60,8 @@ pub(crate) async fn project_run_state( RunChange::LaunchFailed { .. } | RunChange::CheckStarted { .. } | RunChange::CheckFinished { .. } - | RunChange::Compiled { .. } => {} + | RunChange::Compiled { .. } + | RunChange::SinkDeliveries { .. } => {} RunChange::NodeStarted { .. } | RunChange::NodeFinished { .. } => { return project_node(transaction, request, &state.node_counts_json).await; } diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/publish_change.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/publish_change.rs index bd03320cd7..9323ef2870 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/publish_change.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/publish_change.rs @@ -27,10 +27,11 @@ fn change_payload(request: &RunChangeRequest) -> Value { payload } +/// `origin` is the address people reach the UI at, which a run failure links under. pub(crate) async fn publish_change( transaction: ControlTransaction, - request: &RunChangeRequest, - state: &ChangingRun, + (request, state): (&RunChangeRequest, &ChangingRun), + origin: Option<&str>, ) -> Result { let (mut transaction, mut cursor) = append_run_event( transaction, @@ -71,13 +72,13 @@ pub(crate) async fn publish_change( let mut transaction = project_change(transaction, request, state).await?; match request.change { RunChange::Finished { - outcome: outcome @ (RunOutcome::Failed | RunOutcome::Partial), + outcome: outcome @ RunOutcome::Failed, .. } => { let retried; (transaction, retried) = queue_retry(transaction, request.run_id).await?; if retried != QueuedRetry::Member { - transaction = publish_run_failure(transaction, request, outcome).await?; + transaction = publish_run_failure(transaction, (request, outcome), origin).await?; } } RunChange::Finished { diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/reads.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/reads.rs index ccdf164e8f..ecc508a0bd 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/reads.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/reads.rs @@ -41,7 +41,7 @@ pub(crate) async fn list_runs_in( s.git_dirty, s.sqb_version, r.image_id, r.job_key, r.kind, r.origin, r.parent_run_id, r.root_run_id, \ r.trigger_id, t.name AS trigger_name, r.tick_id, r.rerun_of_run_id, r.requested_by, p.name AS requester_name, r.priority, \ r.rewrite_history, r.status, r.status_reason, r.queued_at, r.launched_at, r.started_at, r.ended_at, r.cancel_requested_at, \ - r.selection_json, r.node_counts_json, r.ignored_audit_failures, r.last_event_storage_id, r.request_json AS narrowing, r.request_json AS backfill_window, r.request_json AS member_attempt \ + r.selection_json, r.node_counts_json, r.ignored_audit_failures, r.last_event_storage_id, r.request_json AS narrowing, r.request_json AS backfill_window, r.request_json AS member_attempt, r.authored_json AS command \ FROM sqb_runs r LEFT JOIN sqb_triggers t ON t.trigger_id=r.trigger_id \ LEFT JOIN sqb_snapshots s ON s.snapshot_id=r.snapshot_id \ LEFT JOIN sqb_principals p ON 'principal:' || CAST(p.principal_id AS TEXT)=r.requested_by \ diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/run_failure.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/run_failure.rs index 4c614cf418..211147c57a 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/run_failure.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/run_failure.rs @@ -1,29 +1,44 @@ -//! A failed or partial run becomes one platform event naming its job, scope and first failed nodes. +//! A failed run becomes one platform event saying what failed, where and why, with links to the UI. use std::collections::BTreeSet; +use chrono::{DateTime, Utc}; use serde_json::{Value, json}; +use sqlbuild_core::redaction::main::redact_error_text::redact_error_text; use crate::platform::constants::RUN_FAILURE_NODE_LIMIT; -use crate::platform::models::PlatformEvent; -use crate::runs::_helpers::lifecycle::error_text::finished_error_message; -use crate::runs::models::{RunChangeRequest, RunNodeFailure, RunOutcome}; +use crate::platform::models::{PlatformEvent, RunFailureEvent}; +use crate::runs::_helpers::lifecycle::error_text::finished_failure; +use crate::runs::models::{ + RunChangeRequest, RunFailureCause, RunFailurePhase, RunNodeFailure, RunOrigin, RunOutcome, + RunTrigger, RunTriggerKind, +}; use crate::snapshots::main::reads::read_snapshot_nodes::read_snapshot_nodes; use crate::store::errors::ControlError; use crate::store::main::append_control_event::append_control_event; use crate::store::main::query::query; use crate::store::models::{ControlEvent, ControlTransaction, Parameter}; +use crate::store::types::Row; +use crate::warehouse_history::main::runs::read_run_failure_recall::read_run_failure_recall; + +/// The worker phase that ends loading the project, and the one that starts building. +const COMPILED_PHASE: &str = "compiled"; +const EXECUTION_PHASE: &str = "started_execution"; /// Runs after the terminal projection, so nodes left running already read as failed. pub(crate) async fn publish_run_failure( transaction: ControlTransaction, - request: &RunChangeRequest, - outcome: RunOutcome, + (request, outcome): (&RunChangeRequest, RunOutcome), + origin: Option<&str>, ) -> Result { let invalid = |error: serde_json::Error| ControlError::Invalid(error.to_string()); let (transaction, runs) = query( transaction, - "SELECT kind, job_key, location_id, target, snapshot_id FROM sqb_runs WHERE run_id=$1", + "SELECT r.kind, r.job_key, r.location_id, r.target, r.snapshot_id, r.origin, t.name AS trigger_name, \ + p.name AS requester_name, s.principal_id AS service_account, r.status_reason, r.launched_at, r.started_at, r.ended_at \ + FROM sqb_runs r LEFT JOIN sqb_triggers t ON t.trigger_id=r.trigger_id \ + LEFT JOIN sqb_principals p ON 'principal:' || CAST(p.principal_id AS TEXT)=r.requested_by \ + LEFT JOIN sqb_service_accounts s ON s.principal_id=p.principal_id WHERE r.run_id=$1", vec![Parameter::Id(request.run_id)], ) .await?; @@ -31,12 +46,19 @@ pub(crate) async fn publish_run_failure( .into_iter() .next() .ok_or_else(|| ControlError::Invalid("finished run is missing".into()))?; - let (transaction, counted) = query( + let (transaction, counts) = query( transaction, - "SELECT COUNT(*) AS count FROM sqb_run_nodes WHERE run_id=$1 AND kind='node' AND status='failed'", + "SELECT status, COUNT(*) AS count FROM sqb_run_nodes WHERE run_id=$1 AND kind='node' GROUP BY status", vec![Parameter::Id(request.run_id)], ) .await?; + let counted = |statuses: &[&str]| -> i64 { + counts + .iter() + .filter(|row| statuses.contains(&row["status"].as_str().unwrap_or_default())) + .filter_map(|row| row["count"].as_i64()) + .sum() + }; let (transaction, rows) = query( transaction, "SELECT n.node_key, n.error_code, e.payload FROM sqb_run_nodes n \ @@ -48,6 +70,24 @@ pub(crate) async fn publish_run_failure( ], ) .await?; + let (transaction, skipped) = query( + transaction, + "SELECT node_key FROM sqb_run_nodes WHERE run_id=$1 AND kind='node' AND status='skipped' \ + ORDER BY node_key LIMIT $2", + vec![ + Parameter::Id(request.run_id), + Parameter::Integer(RUN_FAILURE_NODE_LIMIT), + ], + ) + .await?; + let (transaction, recall) = read_run_failure_recall( + transaction, + ( + request.run_id, + usize::try_from(RUN_FAILURE_NODE_LIMIT).unwrap_or_default(), + ), + ) + .await?; let keys: BTreeSet = rows .iter() .filter_map(|row| row["node_key"].as_str().map(str::to_owned)) @@ -55,33 +95,70 @@ pub(crate) async fn publish_run_failure( let snapshot_id = serde_json::from_value(run["snapshot_id"].clone()).map_err(invalid)?; let (mut transaction, nodes) = read_snapshot_nodes(transaction, snapshot_id, Some(&keys)).await?; + let links = Links { + origin, + run_id: request.run_id, + }; let mut failed_nodes: Vec = Vec::new(); for row in rows { let node_key = row["node_key"].as_str().unwrap_or_default().to_owned(); + let (message, phase) = finished_failure(&row["payload"])?; failed_nodes.push(RunNodeFailure { error_code: row["error_code"].as_str().map(str::to_owned), - message: finished_error_message(&row["payload"])?, + message, path: nodes .get(&node_key) .and_then(|node| node.definition.get("path")) .and_then(Value::as_str) .map(|path| path.replace('\\', "/")), + phase, + url: links.node(&node_key, false), + logs_url: links.node(&node_key, true), node_key, }); } - let platform = PlatformEvent::RunFailed { + let failed_node_count = counted(&["failed"]); + let time = |column: &str| -> Result>, ControlError> { + serde_json::from_value(run[column].clone()).map_err(invalid) + }; + let (started_at, ended_at) = (time("started_at")?, time("ended_at")?); + let error = (failed_node_count == 0 && recall.audit_count == 0).then(|| { + let (code, message) = recall.invocation_error.clone().unwrap_or_default(); + RunFailureCause { + phase: failure_phase( + (run["launched_at"].is_null(), started_at.is_none()), + &recall.phases, + ), + code, + message: message.or_else(|| run["status_reason"].as_str().map(redact_error_text)), + } + }); + let platform = PlatformEvent::RunFailed(Box::new(RunFailureEvent { run_id: request.run_id, run_kind: serde_json::from_value(run["kind"].clone()).map_err(invalid)?, job_key: run["job_key"].as_str().map(str::to_owned), location_id: serde_json::from_value(run["location_id"].clone()).map_err(invalid)?, target: run["target"].as_str().unwrap_or_default().to_owned(), outcome, + url: links.run(), + trigger: trigger(&run).map_err(invalid)?, + started_at, + ended_at, + duration_ms: started_at + .zip(ended_at) + .map(|(start, end)| (end - start).num_milliseconds()), + error, failed_nodes, - failed_node_count: counted - .first() - .and_then(|row| row["count"].as_i64()) - .unwrap_or_default(), - }; + failed_node_count, + failed_audits: recall.audits, + failed_audit_count: recall.audit_count, + succeeded_node_count: counted(&["success", "warn"]), + skipped_nodes: skipped + .iter() + .filter_map(|row| row["node_key"].as_str().map(str::to_owned)) + .collect(), + skipped_node_count: counted(&["skipped"]), + })); let occurred_at = transaction.now; let appended; (transaction, appended) = append_control_event( @@ -104,3 +181,87 @@ pub(crate) async fn publish_run_failure( } Ok(transaction) } + +/// UI links under the server's origin, as sensor events build theirs; none without one. +struct Links<'a> { + origin: Option<&'a str>, + run_id: uuid::Uuid, +} + +impl Links<'_> { + fn run(&self) -> Option { + self.origin + .map(|origin| format!("{}/runs/{}", origin.trim_end_matches('/'), self.run_id)) + } + + /// The node on the run's page (`?node=`), or its output (`/output/`). + fn node(&self, node_key: &str, logs: bool) -> Option { + let key = percent_encoded(node_key); + self.run().map(|run| { + if logs { + format!("{run}/output/{key}") + } else { + format!("{run}?node={key}") + } + }) + } +} + +/// `text` with everything but unreserved URL characters percent-encoded. +fn percent_encoded(text: &str) -> String { + let mut encoded = String::with_capacity(text.len()); + for byte in text.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { + encoded.push(char::from(byte)); + } else { + encoded.push_str(&format!("%{byte:02X}")); + } + } + encoded +} + +/// Where a run failed outside any node: before launch, before its worker started, or after its last reported phase. +fn failure_phase( + (never_launched, never_started): (bool, bool), + phases: &BTreeSet, +) -> RunFailurePhase { + if never_launched { + RunFailurePhase::Launch + } else if never_started { + RunFailurePhase::WorkerStart + } else if phases.contains(EXECUTION_PHASE) { + RunFailurePhase::Build + } else if phases.contains(COMPILED_PHASE) { + RunFailurePhase::Planning + } else { + RunFailurePhase::Load + } +} + +/// What started the run: its schedule or sensor by name, else the person or service account who asked. +fn trigger(run: &Row) -> Result { + let origin: RunOrigin = serde_json::from_value(run["origin"].clone())?; + let name = run["trigger_name"].as_str().map(str::to_owned); + let person = run["requester_name"].as_str().map(str::to_owned); + Ok(match origin { + RunOrigin::Schedule => RunTrigger { + kind: RunTriggerKind::Schedule, + name, + person: None, + }, + RunOrigin::Sensor => RunTrigger { + kind: RunTriggerKind::Sensor, + name, + person: None, + }, + RunOrigin::Manual | RunOrigin::Rerun | RunOrigin::Backfill => RunTrigger { + kind: if run["service_account"].is_null() { + RunTriggerKind::Manual + } else { + RunTriggerKind::Api + }, + name: None, + person, + }, + }) +} diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/unreadable.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/unreadable.rs index 30a27c5040..b357117d95 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/unreadable.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/lifecycle/unreadable.rs @@ -30,13 +30,16 @@ pub(crate) async fn fail_unreadable_run( let transaction = check_lease(begin(store, TransactionMode::Write).await?, lease).await?; let (transaction, _) = change_run_in( transaction, - RunAuthority::Scheduler(lease), - &RunChangeRequest { - event_id: Uuid::new_v5(&run_id, b"unreadable-snapshot"), - run_id, - claim_id: None, - change: failed(), - }, + ( + RunAuthority::Scheduler(lease), + &RunChangeRequest { + event_id: Uuid::new_v5(&run_id, b"unreadable-snapshot"), + run_id, + claim_id: None, + change: failed(), + }, + ), + None, ) .await?; commit(check_lease(transaction, lease).await?).await @@ -62,11 +65,14 @@ pub(crate) async fn fail_unreadable_group( .map_err(|error| ControlError::Invalid(error.to_string()))?; transaction = group_change( transaction, - member_id, - RunChange::CancelRequested { - actor: "system:group".into(), - reason: UNREADABLE_SNAPSHOT.into(), - }, + ( + member_id, + RunChange::CancelRequested { + actor: "system:group".into(), + reason: UNREADABLE_SNAPSHOT.into(), + }, + ), + lease.origin.as_deref(), ) .await?; } @@ -80,7 +86,8 @@ pub(crate) async fn fail_unreadable_group( ) .await?; if !open.is_empty() { - transaction = group_change(transaction, group_id, failed()).await?; + transaction = + group_change(transaction, (group_id, failed()), lease.origin.as_deref()).await?; } commit(check_lease(transaction, lease).await?).await } diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/adhoc.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/adhoc.rs index 1da450a36e..c8f12f8751 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/adhoc.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/adhoc.rs @@ -11,6 +11,7 @@ use crate::credentials::main::audit::append_audit::append_audit; use crate::credentials::models::{Action, AuditContext, DefaultRole, PermissionScope}; use crate::runs::_helpers::lifecycle::pinned_jobs::build_settings; use crate::runs::_helpers::lifecycle::publications::{cached_publication, current_publication}; +use crate::runs::_helpers::requests::past_runs::read_past_runs; use crate::runs::_helpers::requests::permissions::{ authorize_execution, execution_scopes, job_denial, }; @@ -59,7 +60,10 @@ pub(crate) async fn frozen_publication_request( (snapshot_id, publication): (Uuid, &CachedPublication), (request, run_id): (&AdhocCheckRequest, Uuid), ) -> Result<(ControlTransaction, Result<(String, RunRequest), String>), ControlError> { - let plan = match publication.prepared.plan(&request.command) { + let ids = publication.prepared.run_selector_ids(&request.command); + let (transaction, past) = + read_past_runs(transaction, (request.location_id, &request.target), &ids).await?; + let plan = match past.and_then(|past| publication.prepared.plan(&request.command, &past)) { Ok(plan) => plan, Err(refusal) => return Ok((transaction, Err(refusal))), }; @@ -137,7 +141,12 @@ pub(crate) async fn publication_plan( ) -> Result<(ControlTransaction, Result), ControlError> { let (transaction, publication) = cached_publication(transaction, planner, (scope, snapshot_id)).await?; - Ok((transaction, publication.prepared.plan(command))) + let ids = publication.prepared.run_selector_ids(command); + let (transaction, past) = read_past_runs(transaction, scope, &ids).await?; + Ok(( + transaction, + past.and_then(|past| publication.prepared.plan(command, &past)), + )) } /// Every permission launching `frozen` needs, decided as the launch would but without recording a denial. diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/cancel.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/cancel.rs index a4181b4e44..310b185a79 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/cancel.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/cancel.rs @@ -40,16 +40,19 @@ pub(crate) async fn cancel_person_run( authorize_execution(transaction, credentials, (&frozen, Action::RunCancel)).await?; let (transaction, applied) = change_run_in( transaction, - RunAuthority::Operator(&context), - &RunChangeRequest { - run_id: request.run_id, - event_id: request.event_id, - claim_id: None, - change: RunChange::CancelRequested { - actor: context.actor.clone(), - reason: request.reason.clone(), + ( + RunAuthority::Operator(&context), + &RunChangeRequest { + run_id: request.run_id, + event_id: request.event_id, + claim_id: None, + change: RunChange::CancelRequested { + actor: context.actor.clone(), + reason: request.reason.clone(), + }, }, - }, + ), + None, ) .await?; commit(transaction).await?; diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/mod.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/mod.rs index 419cf76bf9..47f1c9c832 100644 --- a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/mod.rs +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/mod.rs @@ -3,6 +3,7 @@ pub(in crate::runs) mod cancel; pub(in crate::runs) mod job; pub(in crate::runs) mod manual_job; pub(in crate::runs) mod manual_rerun; +pub(in crate::runs) mod past_runs; pub(in crate::runs) mod permissions; pub(in crate::runs) mod plan; pub(in crate::runs) mod publication; diff --git a/crates/sqlbuild-orchestration/src/runs/_helpers/requests/past_runs.rs b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/past_runs.rs new file mode 100644 index 0000000000..e8f0ed3ba9 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/runs/_helpers/requests/past_runs.rs @@ -0,0 +1,171 @@ +//! The past runs `run:`, `failed:` and `skipped:` name, found by full ID or unique prefix in one location and target. + +use std::collections::BTreeSet; + +use uuid::Uuid; + +use crate::runs::constants::{ + CHECK_KIND, FAILED_RUN_NODE_STATUSES, MAX_LISTED_RUN_MATCHES, MIN_RUN_ID_PREFIX, + NOT_RUN_STATUS, PAST_RUN_AUDIT_LIMIT, SKIPPED_RUN_NODE_STATUS, +}; +use crate::runs::models::{PastRunResults, SelectionProblem}; +use crate::runs::types::PastRuns; +use crate::runs::types::PreparedPublication; +use crate::store::errors::ControlError; +use crate::store::main::begin::begin; +use crate::store::main::commit::commit; +use crate::store::main::query::query; +use crate::store::models::{ControlStore, ControlTransaction, Parameter, TransactionMode}; +use crate::warehouse_history::main::runs::read_run_failure_recall::read_run_failure_recall; + +/// Each run `ids` names in `(location_id, target)`, or why one can't be read: too short, unknown or ambiguous. +pub(crate) async fn read_past_runs( + mut transaction: ControlTransaction, + (location_id, target): (Uuid, &str), + ids: &BTreeSet, +) -> Result<(ControlTransaction, Result), ControlError> { + let mut past = PastRuns::new(); + for id in ids { + let found; + (transaction, found) = matching_run(transaction, (location_id, target), id).await?; + let run_id = match found { + Ok(run_id) => run_id, + Err(refusal) => return Ok((transaction, Err(refusal))), + }; + let results; + (transaction, results) = run_results(transaction, run_id).await?; + past.insert(id.clone(), results); + } + Ok((transaction, Ok(past))) +} + +/// The past runs `select` and `exclude` name, read in their own transaction; a run that can't be read is a selection problem. +pub(crate) async fn read_selected_past_runs( + store: &ControlStore, + (location_id, target): (Uuid, &str), + (prepared, select, exclude): (&dyn PreparedPublication, &str, &str), +) -> Result>, ControlError> { + let ids = prepared.run_selector_ids(&[select.to_owned(), exclude.to_owned()]); + if ids.is_empty() { + return Ok(Ok(PastRuns::new())); + } + let transaction = begin(store, TransactionMode::Read).await?; + let (transaction, past) = read_past_runs(transaction, (location_id, target), &ids).await?; + commit(transaction).await?; + Ok(past.map_err(|message| { + Box::new(SelectionProblem { + code: None, + message, + help: None, + location: None, + suggestions: Vec::new(), + refused: None, + }) + })) +} + +/// The one run whose ID is or starts with `id`, or why there isn't exactly one. +async fn matching_run( + transaction: ControlTransaction, + (location_id, target): (Uuid, &str), + id: &str, +) -> Result<(ControlTransaction, Result), ControlError> { + let prefix = id.to_ascii_lowercase(); + if prefix.len() < MIN_RUN_ID_PREFIX { + return Ok(( + transaction, + Err(format!( + "run ID '{id}' is too short: give the full ID or at least {MIN_RUN_ID_PREFIX} characters of it" + )), + )); + } + if !prefix + .bytes() + .all(|byte| byte.is_ascii_hexdigit() || byte == b'-') + { + return Ok((transaction, Err(format!("'{id}' is not a run ID")))); + } + let (transaction, rows) = query( + transaction, + &format!( + "SELECT run_id FROM sqb_runs WHERE location_id=$1 AND target=$2 \ + AND CAST(run_id AS TEXT) LIKE $3 ORDER BY run_id LIMIT {}", + MAX_LISTED_RUN_MATCHES + 1 + ), + vec![ + Parameter::Id(location_id), + Parameter::Text(target.to_owned()), + Parameter::Text(format!("{prefix}%")), + ], + ) + .await?; + let matches: Vec = rows + .iter() + .filter_map(|row| row["run_id"].as_str().map(str::to_owned)) + .collect(); + let refusal = match matches.as_slice() { + [only] => { + let run_id = Uuid::parse_str(only) + .map_err(|error| ControlError::Schema(format!("stored run ID: {error}")))?; + return Ok((transaction, Ok(run_id))); + } + [] => format!("no run '{id}' in this location and target"), + many => { + let shown: Vec<&str> = many + .iter() + .take(MAX_LISTED_RUN_MATCHES) + .map(String::as_str) + .collect(); + let more = if many.len() > MAX_LISTED_RUN_MATCHES { + ", and more" + } else { + "" + }; + format!( + "run ID '{id}' is ambiguous: it starts {}{more}; give more of the ID", + shown.join(", ") + ) + } + }; + Ok((transaction, Err(refusal))) +} + +/// What one run selected, didn't finish and skipped, with its failed audits as `audit:`. +async fn run_results( + transaction: ControlTransaction, + run_id: Uuid, +) -> Result<(ControlTransaction, PastRunResults), ControlError> { + let (transaction, rows) = query( + transaction, + "SELECT node_key, status, kind FROM sqb_run_nodes WHERE run_id=$1", + vec![Parameter::Id(run_id)], + ) + .await?; + let mut results = PastRunResults { + run_id, + ..PastRunResults::default() + }; + for row in rows { + let (Some(key), Some(status)) = (row["node_key"].as_str(), row["status"].as_str()) else { + continue; + }; + if row["kind"].as_str() == Some(CHECK_KIND) && status == NOT_RUN_STATUS { + continue; + } + results.selected.insert(key.to_owned()); + if FAILED_RUN_NODE_STATUSES.contains(&status) { + results.failed.insert(key.to_owned()); + } else if status == SKIPPED_RUN_NODE_STATUS { + results.skipped.insert(key.to_owned()); + } + } + let (transaction, recall) = + read_run_failure_recall(transaction, (run_id, PAST_RUN_AUDIT_LIMIT)).await?; + results.failed.extend( + recall + .audits + .into_iter() + .map(|audit| format!("audit:{}", audit.name)), + ); + Ok((transaction, results)) +} diff --git a/crates/sqlbuild-orchestration/src/runs/constants.rs b/crates/sqlbuild-orchestration/src/runs/constants.rs index 3416a41a12..bef10d934b 100644 --- a/crates/sqlbuild-orchestration/src/runs/constants.rs +++ b/crates/sqlbuild-orchestration/src/runs/constants.rs @@ -56,6 +56,8 @@ pub(crate) const SUPERSEDED_CHILD: &str = "EXISTS(SELECT 1 FROM sqb_runs s WHERE pub(crate) const MEMBER_RETRYING_EVENT: &str = "run_member_retrying"; /// The scheduler's launch fact, which names the container a worker started in, if any. pub(crate) const RUN_LAUNCHED_EVENT: &str = "run_launched"; +/// A run's report of what its lifecycle event sinks delivered. +pub(crate) const SINK_DELIVERIES_EVENT: &str = "run_sink_deliveries"; /// The group run event recorded when a retried member succeeds. pub(crate) const MEMBER_RECOVERED_EVENT: &str = "run_member_recovered"; @@ -65,6 +67,8 @@ pub(crate) const PUBLICATIONS_PER_TARGET: usize = 2; /// Selected keys per page of a selection evaluation, and the most a request may ask for. pub(crate) const SELECTION_PAGE_DEFAULT: u32 = 1_000; pub(crate) const SELECTION_PAGE_MAX: u32 = 10_000; +/// The key prefix of an audit a selection picks, singular or attached. +pub(crate) const AUDIT_KEY_PREFIX: &str = "audit:"; /// A followed run's repeated output reads are audited at most once per person, run and kind in this window, on each server. pub(crate) const REPEATED_READ_AUDIT: std::time::Duration = std::time::Duration::from_secs(600); @@ -74,3 +78,17 @@ pub(crate) const MISSING_SECRET_ERROR_CODE: &str = "D012"; /// How a worker's message for such a node starts, and the phrase after its variables. pub(crate) const MISSING_SECRET_PREFIX: &str = "provider "; pub(crate) const MISSING_SECRET_PHRASE: &str = " not set (missing from "; +/// The fewest characters of a run ID `run:`, `failed:` and `skipped:` take, like a short git hash. +pub(crate) const MIN_RUN_ID_PREFIX: usize = 8; +/// How many runs an ambiguous run ID prefix lists. +pub(crate) const MAX_LISTED_RUN_MATCHES: usize = 5; +/// The most failed audits `failed:` reads from one run. +pub(crate) const PAST_RUN_AUDIT_LIMIT: usize = 10_000; +/// Run node statuses `failed:` selects: what failed, was cancelled or was never reached. +pub(crate) const FAILED_RUN_NODE_STATUSES: [&str; 3] = ["failed", "cancelled", "not_run"]; +/// The run node status `skipped:` selects. +pub(crate) const SKIPPED_RUN_NODE_STATUS: &str = "skipped"; +/// An audit check that was not run because the target lacks a read: neither run nor failed, so run selectors leave it out. +pub(crate) const NOT_RUN_STATUS: &str = "not_run"; +/// The kind of a run node row that records an attached check. +pub(crate) const CHECK_KIND: &str = "check"; diff --git a/crates/sqlbuild-orchestration/src/runs/main/execution/advance_groups.rs b/crates/sqlbuild-orchestration/src/runs/main/execution/advance_groups.rs index 844a1a613d..7c991591bf 100644 --- a/crates/sqlbuild-orchestration/src/runs/main/execution/advance_groups.rs +++ b/crates/sqlbuild-orchestration/src/runs/main/execution/advance_groups.rs @@ -44,7 +44,14 @@ pub async fn advance_groups<'a>( .map_err(|error| ControlError::Invalid(error.to_string()))?; let transaction = check_lease(begin(store, TransactionMode::Write).await?, lease).await?; - match advance_group(transaction, run_id, limits, dispatch.eligible).await { + match advance_group( + transaction, + (run_id, lease.origin.as_deref()), + limits, + dispatch.eligible, + ) + .await + { Ok(transaction) => commit(check_lease(transaction, lease).await?).await?, Err(ControlError::UnreadableSnapshot { .. }) => { fail_unreadable_group(store, lease, run_id).await?; diff --git a/crates/sqlbuild-orchestration/src/runs/main/execution/change_run.rs b/crates/sqlbuild-orchestration/src/runs/main/execution/change_run.rs index f6c2418b15..6a2eb87aa9 100644 --- a/crates/sqlbuild-orchestration/src/runs/main/execution/change_run.rs +++ b/crates/sqlbuild-orchestration/src/runs/main/execution/change_run.rs @@ -1,18 +1,15 @@ //! Lifecycle changes share one transaction owner across trusted callers and person operations. -use crate::runs::_helpers::lifecycle::change_run::change_run_in; +use crate::runs::main::execution::change_run_linked::change_run_linked; use crate::runs::models::{RunAuthority, RunChangeRequest}; use crate::store::errors::ControlError; -use crate::store::main::write::write; use crate::store::models::ControlStore; +/// A change made under the scheduler lease links a failed run under the lease's origin; others link nothing. pub async fn change_run( store: &ControlStore, authority: RunAuthority<'_>, request: &RunChangeRequest, ) -> Result { - write(store, |transaction| { - change_run_in(transaction, authority, request) - }) - .await + change_run_linked(store, (authority, request), None).await } diff --git a/crates/sqlbuild-orchestration/src/runs/main/execution/change_run_linked.rs b/crates/sqlbuild-orchestration/src/runs/main/execution/change_run_linked.rs new file mode 100644 index 0000000000..238ed9d48d --- /dev/null +++ b/crates/sqlbuild-orchestration/src/runs/main/execution/change_run_linked.rs @@ -0,0 +1,19 @@ +//! A lifecycle change whose run failure links under the address people reach the UI at. + +use crate::runs::_helpers::lifecycle::change_run::change_run_in; +use crate::runs::models::{RunAuthority, RunChangeRequest}; +use crate::store::errors::ControlError; +use crate::store::main::write::write; +use crate::store::models::ControlStore; + +/// A change whose run failure links under `origin`, the address people reach the UI at, as a worker's report through the API. +pub async fn change_run_linked( + store: &ControlStore, + (authority, request): (RunAuthority<'_>, &RunChangeRequest), + origin: Option<&str>, +) -> Result { + write(store, |transaction| { + change_run_in(transaction, (authority, request), origin) + }) + .await +} diff --git a/crates/sqlbuild-orchestration/src/runs/main/execution/mod.rs b/crates/sqlbuild-orchestration/src/runs/main/execution/mod.rs index 18ac562fb8..53c250259d 100644 --- a/crates/sqlbuild-orchestration/src/runs/main/execution/mod.rs +++ b/crates/sqlbuild-orchestration/src/runs/main/execution/mod.rs @@ -1,5 +1,6 @@ pub mod advance_groups; pub mod change_run; +pub mod change_run_linked; pub mod claim_next_run; pub mod heartbeat_run; pub mod monitor_runs; diff --git a/crates/sqlbuild-orchestration/src/runs/main/execution/monitor_runs.rs b/crates/sqlbuild-orchestration/src/runs/main/execution/monitor_runs.rs index 48263740f6..42ac51dbb6 100644 --- a/crates/sqlbuild-orchestration/src/runs/main/execution/monitor_runs.rs +++ b/crates/sqlbuild-orchestration/src/runs/main/execution/monitor_runs.rs @@ -47,7 +47,8 @@ pub async fn monitor_runs( claim_id: state.worker_instance, change: RunChange::Unresponsive, }; - transaction = publish_change(transaction, &request, &state).await?; + transaction = + publish_change(transaction, (&request, &state), lease.origin.as_deref()).await?; } commit(check_lease(transaction, lease).await?).await?; Ok(observed) diff --git a/crates/sqlbuild-orchestration/src/runs/main/requests/evaluate_selection.rs b/crates/sqlbuild-orchestration/src/runs/main/requests/evaluate_selection.rs index 302221da97..5e00f98ebd 100644 --- a/crates/sqlbuild-orchestration/src/runs/main/requests/evaluate_selection.rs +++ b/crates/sqlbuild-orchestration/src/runs/main/requests/evaluate_selection.rs @@ -4,7 +4,8 @@ use uuid::Uuid; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::runs::_helpers::lifecycle::publications::viewed_publication; -use crate::runs::constants::{SELECTION_PAGE_DEFAULT, SELECTION_PAGE_MAX}; +use crate::runs::_helpers::requests::past_runs::read_selected_past_runs; +use crate::runs::constants::{AUDIT_KEY_PREFIX, SELECTION_PAGE_DEFAULT, SELECTION_PAGE_MAX}; use crate::runs::models::{SelectionEvaluation, SelectionProblem, SelectionQuery}; use crate::runs::types::CommandPlanner; use crate::store::errors::ControlError; @@ -28,6 +29,7 @@ pub async fn evaluate_selection( return Ok(SelectionEvaluation { snapshot_id: None, count: 0, + audits: 0, keys: Vec::new(), next_offset: None, error: Some(SelectionProblem { @@ -40,12 +42,23 @@ pub async fn evaluate_selection( }), }); }; - let keys = match publication.prepared.evaluate(&query.select, &query.exclude) { + let past = read_selected_past_runs( + store, + (location_id, target), + (publication.prepared.as_ref(), &query.select, &query.exclude), + ) + .await?; + let keys = match past.and_then(|past| { + publication + .prepared + .evaluate((&query.select, &query.exclude), &past) + }) { Ok(keys) => keys, Err(problem) => { return Ok(SelectionEvaluation { snapshot_id: Some(snapshot.snapshot_id), count: 0, + audits: 0, keys: Vec::new(), next_offset: None, error: Some(*problem), @@ -67,6 +80,10 @@ pub async fn evaluate_selection( Ok(SelectionEvaluation { snapshot_id: Some(snapshot.snapshot_id), count: keys.len() as u64, + audits: keys + .iter() + .filter(|key| key.starts_with(AUDIT_KEY_PREFIX)) + .count() as u64, next_offset: ((end as usize) < keys.len()).then_some(end), keys: page, error: None, diff --git a/crates/sqlbuild-orchestration/src/runs/main/requests/mod.rs b/crates/sqlbuild-orchestration/src/runs/main/requests/mod.rs index f5173a1677..60d9e36cdf 100644 --- a/crates/sqlbuild-orchestration/src/runs/main/requests/mod.rs +++ b/crates/sqlbuild-orchestration/src/runs/main/requests/mod.rs @@ -2,6 +2,7 @@ pub mod check_adhoc_run; pub mod evaluate_selection; pub(crate) mod frozen_job_request; pub(crate) mod queue_run; +pub mod read_person_past_runs; pub mod read_selection_vocabulary; pub mod request_job_run; pub mod request_person_run; diff --git a/crates/sqlbuild-orchestration/src/runs/main/requests/read_person_past_runs.rs b/crates/sqlbuild-orchestration/src/runs/main/requests/read_person_past_runs.rs new file mode 100644 index 0000000000..ef662ac26c --- /dev/null +++ b/crates/sqlbuild-orchestration/src/runs/main/requests/read_person_past_runs.rs @@ -0,0 +1,42 @@ +//! A person who may view a target reads past runs' results for the run selectors of a command they run elsewhere. + +use std::collections::BTreeSet; + +use uuid::Uuid; + +use crate::credentials::models::{AuditContext, DefaultRole}; +use crate::runs::_helpers::lifecycle::publications::viewed_publication; +use crate::runs::_helpers::requests::past_runs::read_past_runs; +use crate::runs::models::PastRunsRead; +use crate::runs::types::CommandPlanner; +use crate::runs::types::PastRuns; +use crate::store::errors::ControlError; +use crate::store::main::begin::begin; +use crate::store::main::commit::commit; +use crate::store::models::{ControlStore, TransactionMode}; + +/// The runs `ids` name in the location and target, each by the ID as given, for a person who may view the target. +pub async fn read_person_past_runs( + store: &ControlStore, + (planner, credentials): (&dyn CommandPlanner, (&AuditContext, Uuid)), + (location_id, target, ids): (Uuid, &str, &BTreeSet), + default_role: DefaultRole, +) -> Result { + viewed_publication( + store, + (planner, credentials), + (location_id, target), + default_role, + ) + .await?; + let transaction = begin(store, TransactionMode::Read).await?; + let (transaction, past) = read_past_runs(transaction, (location_id, target), ids).await?; + commit(transaction).await?; + Ok(match past { + Ok(runs) => PastRunsRead { runs, error: None }, + Err(error) => PastRunsRead { + runs: PastRuns::new(), + error: Some(error), + }, + }) +} diff --git a/crates/sqlbuild-orchestration/src/runs/main/requests/select_viewed_nodes.rs b/crates/sqlbuild-orchestration/src/runs/main/requests/select_viewed_nodes.rs index 44ba381f7d..23787de57c 100644 --- a/crates/sqlbuild-orchestration/src/runs/main/requests/select_viewed_nodes.rs +++ b/crates/sqlbuild-orchestration/src/runs/main/requests/select_viewed_nodes.rs @@ -6,6 +6,7 @@ use uuid::Uuid; use crate::credentials::models::{AuditContext, DefaultRole}; use crate::runs::_helpers::lifecycle::publications::viewed_publication; +use crate::runs::_helpers::requests::past_runs::read_selected_past_runs; use crate::runs::models::{SelectionProblem, ViewedSelection}; use crate::runs::types::CommandPlanner; use crate::store::errors::ControlError; @@ -47,16 +48,24 @@ pub async fn select_viewed_nodes( }), }); }; - Ok(match publication.prepared.evaluate(select, exclude) { - Ok(keys) => ViewedSelection { - snapshot_id, - keys: Some(keys.into_iter().collect()), - error: None, - }, - Err(problem) => ViewedSelection { - snapshot_id, - keys: Some(BTreeSet::new()), - error: Some(*problem), + let past = read_selected_past_runs( + store, + (location_id, target), + (publication.prepared.as_ref(), select, exclude), + ) + .await?; + Ok( + match past.and_then(|past| publication.prepared.evaluate((select, exclude), &past)) { + Ok(keys) => ViewedSelection { + snapshot_id, + keys: Some(keys.into_iter().collect()), + error: None, + }, + Err(problem) => ViewedSelection { + snapshot_id, + keys: Some(BTreeSet::new()), + error: Some(*problem), + }, }, - }) + ) } diff --git a/crates/sqlbuild-orchestration/src/runs/models.rs b/crates/sqlbuild-orchestration/src/runs/models.rs index c166f8f6ad..6994f1dc16 100644 --- a/crates/sqlbuild-orchestration/src/runs/models.rs +++ b/crates/sqlbuild-orchestration/src/runs/models.rs @@ -9,7 +9,7 @@ use uuid::Uuid; use crate::credentials::models::Action; use crate::declarations::models::PoolSlots; -use crate::runs::constants::RUN_LAUNCHED_EVENT; +use crate::runs::constants::{RUN_LAUNCHED_EVENT, SINK_DELIVERIES_EVENT}; use crate::runs::types::{CommandPlanner, PreparedPublication}; use crate::snapshots::models::WriterNode; @@ -109,7 +109,6 @@ pub enum RunStatus { Unresponsive, Success, Warn, - Partial, Failed, Cancelled, /// A group member the group did not run because a job it depends on failed. @@ -323,6 +322,13 @@ pub struct RunRecord { deserialize_with = "crate::runs::_helpers::lifecycle::narrowing::frozen_member_attempt" )] pub member_attempt: Option, + /// An ad-hoc run's command as the person typed it, as argument tokens after `sqb`; absent for every other run. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "crate::runs::_helpers::lifecycle::narrowing::authored_command" + )] + pub command: Option>, } /// A queued run's place in claim order within its location and target, and what holds it back. @@ -481,7 +487,7 @@ pub struct RunEventRecord { pub outcome: Option, pub row_count: Option, pub affected_rows: Option, - /// A summary of what an event names, such as a member retry or the command a worker started; never error or SQL text. + /// A summary of what an event names, such as a member retry, the command a worker started or why an audit was not run; never error or SQL text. #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option, /// For a check's result: its name as declared, its ID and this result's, and the rows it found; never its SQL or rows. @@ -587,6 +593,69 @@ pub struct RunNodeFailure { pub message: Option, /// Relative to the project root, with `/` separators; null when the run's snapshot is gone. pub path: Option, + /// Where a model failed, such as `staging`, `audit` or `post_hook`; null for other nodes or when not reported. + pub phase: Option, + /// The node in the run's UI page; null when the server has no origin. + pub url: Option, + /// The node's output in the UI; null when the server has no origin. + pub logs_url: Option, +} + +/// An error-severity audit failure in one run: its name, the warehouse's SQLSTATE and redacted error text, or its failing rows. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct RunAuditFailure { + pub name: String, + /// The node it checks; null for an end-of-build singular audit. + pub node_key: Option, + /// The warehouse's SQLSTATE when the audit's query could not run, such as `42S02`. + pub sqlstate: Option, + /// The warehouse's error when the query could not run, redacted and bounded like a node's. + pub message: Option, + /// The rows that failed it, when its query ran. + pub failing_rows: Option, +} + +/// What started a run: a schedule or sensor by name, or a person or service account (`api`). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct RunTrigger { + pub kind: RunTriggerKind, + /// The schedule's or sensor's name; null for manual and API runs. + pub name: Option, + /// Who asked for a manual or API run, by display name. + pub person: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum RunTriggerKind { + Schedule, + Sensor, + Manual, + Api, +} + +/// Where a run failed outside any node. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum RunFailurePhase { + /// The launcher could not start a worker. + Launch, + /// A worker was started but never reported starting the run. + WorkerStart, + /// The worker failed loading the project, before compiling it. + Load, + /// The worker failed compiling, inspecting the warehouse or planning. + Planning, + /// The worker failed while building, outside any node. + Build, +} + +/// Why a run failed outside any node: where, the error's type or code, and its redacted, bounded text. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct RunFailureCause { + pub phase: RunFailurePhase, + pub code: Option, + pub message: Option, } /// One build attempt of a node by a run in this target; the same metadata as the run's node list. @@ -638,7 +707,6 @@ pub(crate) struct ExecutionMetadata { pub enum RunOutcome { Success, Warn, - Partial, Failed, Cancelled, /// Only a group sets it, on a member it did not run because a job the member depends on failed. @@ -651,7 +719,6 @@ impl RunOutcome { match self { Self::Success => "success", Self::Warn => "warn", - Self::Partial => "partial", Self::Failed => "failed", Self::Cancelled => "cancelled", Self::Skipped => "skipped", @@ -704,6 +771,13 @@ pub enum RunChange { deserialize_with = "crate::runs::_helpers::lifecycle::error_text::bounded_error_text" )] error_message: Option, + /// Where a failed model failed, such as `staging` or `post_hook`; a short lowercase token or absent. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "crate::runs::_helpers::lifecycle::error_text::failure_phase" + )] + phase: Option, }, /// Observational attached-check facts never expand the frozen execution selection. CheckStarted { @@ -733,6 +807,26 @@ pub enum RunChange { AuditFailuresIgnored { count: u32, }, + /// What each lifecycle event sink delivered, counted when the worker's command closed; sent before `Finished`. + SinkDeliveries { + sinks: Vec, + /// Each sink provider whose teardown raised, such as `'kafka' (KafkaProducer) raised KafkaException`. + #[serde(default)] + teardown_failures: Vec, + }, +} + +/// One lifecycle event sink's deliveries in a run. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(deny_unknown_fields)] +pub struct SinkDelivery { + pub name: String, + pub accepted: u64, + pub delivered: u64, + /// Events the sink never got: its queue was full or it was too slow. + pub dropped: u64, + /// Events the sink raised on. + pub failed: u64, } impl RunChange { @@ -753,6 +847,7 @@ impl RunChange { Self::CancelRequested { .. } => "run_cancel_requested", Self::Finished { .. } => "run_terminated", Self::AuditFailuresIgnored { .. } => "run_audit_failures_ignored", + Self::SinkDeliveries { .. } => SINK_DELIVERIES_EVENT, } } @@ -1110,8 +1205,11 @@ pub struct SelectionQuery { pub struct SelectionEvaluation { /// The publication evaluated; `None` before the first one. pub snapshot_id: Option, - /// Every selected node, across all pages. + /// Every selected node and audit, across all pages. pub count: u64, + /// How many of them are audits, keyed `audit:[:…]`. + #[serde(default)] + pub audits: u64, /// One page of the selected `kind:name` keys, sorted. pub keys: Vec, /// The offset of the next page, when there is one. @@ -1119,6 +1217,36 @@ pub struct SelectionEvaluation { pub error: Option, } +/// A past run's results as node keys, for `run:`, `failed:` and `skipped:`; failed audits are `audit:`. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct PastRunResults { + /// The run the typed ID names. + pub run_id: Uuid, + /// Every node the run selected. + pub selected: BTreeSet, + /// Its failed, cancelled and never-reached nodes, and its failed audits. + pub failed: BTreeSet, + /// The nodes it skipped because something they depend on failed. + pub skipped: BTreeSet, +} + +/// The past runs to read for a command's `run:`, `failed:` and `skipped:` selectors. +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PastRunsQuery { + /// Comma-separated run IDs, full or a unique prefix of at least 8 characters. + #[serde(default)] + pub ids: String, +} + +/// The past runs read, or why one can't be: too short, unknown or ambiguous. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +pub struct PastRunsRead { + /// Each run by the ID as given; empty when `error` is set. + pub runs: crate::runs::types::PastRuns, + pub error: Option, +} + /// Why `sqb` refuses a selection, where, and what might have been meant. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] pub struct SelectionProblem { @@ -1183,6 +1311,9 @@ pub struct SelectionVocabulary { pub seeds: Vec, /// `kind:` values: the nodes of each kind. pub kinds: Vec, + /// `audit:` names: the audits each name selects, one per target it is attached to. + #[serde(default)] + pub audits: Vec, } /// One selector value and the number of nodes it selects. diff --git a/crates/sqlbuild-orchestration/src/runs/types.rs b/crates/sqlbuild-orchestration/src/runs/types.rs index b04a12a2d5..ed8d4a89c1 100644 --- a/crates/sqlbuild-orchestration/src/runs/types.rs +++ b/crates/sqlbuild-orchestration/src/runs/types.rs @@ -1,11 +1,16 @@ //! The command planner the server is built with; the CLI owns the grammar and the selector resolver. use crate::credentials::models::PermissionScope; +use std::collections::{BTreeMap, BTreeSet}; + use crate::runs::models::{ - CommandPlan, PlannerResource, PublicationCache, PublishedJobs, SelectionProblem, - SelectionVocabulary, + CommandPlan, PastRunResults, PlannerResource, PublicationCache, PublishedJobs, + SelectionProblem, SelectionVocabulary, }; +/// Each past run a command's selectors name, by the run ID as typed. +pub type PastRuns = BTreeMap; + /// Index a publication once with the CLI's selector graph, then parse and resolve commands against it. pub trait CommandPlanner: Send + Sync { /// One publication's nodes and jobs, indexed for repeated planning; pure and side-effect free. @@ -21,11 +26,18 @@ pub trait CommandPlanner: Send + Sync { /// One indexed publication: parse `command` with the CLI's grammar and resolve its selectors over it. pub trait PreparedPublication: std::fmt::Debug + Send + Sync { - /// The verb, exact node keys and validated settings, or why the command is refused; `job:` selects published jobs. - fn plan(&self, command: &[String]) -> Result; + /// The run IDs, as typed, that `run:`, `failed:` and `skipped:` selectors in `texts` name, so the caller can read those runs. + fn run_selector_ids(&self, texts: &[String]) -> BTreeSet; - /// The sorted keys `sqb build --select --exclude ` selects, given `(select, exclude)`, or why it refuses them; each text holds space-separated selectors. + fn evaluate( + &self, + selectors: (&str, &str), + past: &PastRuns, + ) -> Result, Box>; /// Every value each selector type takes here, with its node count; `snapshot_id` is left for the caller. fn vocabulary(&self) -> SelectionVocabulary; diff --git a/crates/sqlbuild-orchestration/src/scheduler/main/_acquire_lease.rs b/crates/sqlbuild-orchestration/src/scheduler/main/_acquire_lease.rs index 20b4286e1b..154343c412 100644 --- a/crates/sqlbuild-orchestration/src/scheduler/main/_acquire_lease.rs +++ b/crates/sqlbuild-orchestration/src/scheduler/main/_acquire_lease.rs @@ -14,7 +14,7 @@ use crate::store::models::{ControlStore, Parameter, TransactionMode}; /// An existing live lease is never stolen, including by a duplicate caller with the same holder. pub(crate) async fn acquire_lease( store: &ControlStore, - holder: Uuid, + (holder, origin): (Uuid, Option<&str>), ) -> Result, ControlError> { let transaction = begin(store, TransactionMode::Write).await?; let now = transaction.now; @@ -31,6 +31,7 @@ pub(crate) async fn acquire_lease( holder, epoch, expires_at, + origin: origin.map(str::to_owned), }); commit(transaction).await?; Ok(lease) diff --git a/crates/sqlbuild-orchestration/src/scheduler/main/_scheduler_cycle.rs b/crates/sqlbuild-orchestration/src/scheduler/main/_scheduler_cycle.rs index fc2d23f1e6..455de68f0c 100644 --- a/crates/sqlbuild-orchestration/src/scheduler/main/_scheduler_cycle.rs +++ b/crates/sqlbuild-orchestration/src/scheduler/main/_scheduler_cycle.rs @@ -30,7 +30,7 @@ pub(crate) async fn scheduler_cycle( let phase = Instant::now(); let renewal = match state.lease.as_ref() { Some(lease) => renew_lease(store, lease).await.map(Some), - None => acquire_lease(store, state.holder).await, + None => acquire_lease(store, (state.holder, state.origin.as_deref())).await, }; state.lease = match renewal { Ok(lease) => lease, diff --git a/crates/sqlbuild-orchestration/src/scheduler/main/run_scheduler.rs b/crates/sqlbuild-orchestration/src/scheduler/main/run_scheduler.rs index 220a4d506e..bce758a9e9 100644 --- a/crates/sqlbuild-orchestration/src/scheduler/main/run_scheduler.rs +++ b/crates/sqlbuild-orchestration/src/scheduler/main/run_scheduler.rs @@ -5,6 +5,9 @@ use std::time::Duration; use tokio::sync::watch; use tokio::time::Instant; +use crate::health::constants::WAITING_FOR_DATABASE; +use crate::health::main::control_cause::control_cause; +use crate::health::models::{ControlTarget, ServerHealth}; use crate::scheduler::main::_scheduler_cycle::scheduler_cycle; use crate::scheduler::models::SchedulerState; use crate::scheduler::types::RunLauncher; @@ -33,6 +36,7 @@ pub async fn run_scheduler( } Err(error) => Err(error), }; + report_cycle(state.health.as_ref(), polled.as_ref().map(|_| ())); let retry = Instant::now() + Duration::from_secs(1); let due = match polled { Ok(due) => due.min(retry), @@ -53,3 +57,24 @@ pub async fn run_scheduler( let stopped = launcher.shutdown(store, last_lease.as_ref()).await; result.and(stopped) } + +/// A cycle's result in the server's health: the lease moving to another server is no failure. +fn report_cycle(health: Option<&ServerHealth>, result: Result<(), &ControlError>) { + let Some(health) = health else { + return; + }; + let now = chrono::Utc::now(); + match result { + Ok(()) | Err(ControlError::Fenced) => health.scheduler_succeeded(now), + Err(error) => { + let cause = control_cause(error, (&ControlTarget::default(), false)) + .map(|cause| health.locate(cause)); + let reason = match &cause { + Some(cause) if cause.unavailable() => WAITING_FOR_DATABASE.to_owned(), + Some(cause) => cause.message.clone(), + None => error.to_string(), + }; + health.scheduler_failed(&reason, (now, cause.as_ref())); + } + } +} diff --git a/crates/sqlbuild-orchestration/src/scheduler/models.rs b/crates/sqlbuild-orchestration/src/scheduler/models.rs index c80142e140..bd3bf988fe 100644 --- a/crates/sqlbuild-orchestration/src/scheduler/models.rs +++ b/crates/sqlbuild-orchestration/src/scheduler/models.rs @@ -12,6 +12,9 @@ pub struct SchedulerLease { pub holder: Uuid, pub epoch: i64, pub expires_at: DateTime, + /// The address people reach the UI at, carried so changes made under the lease link runs under it. + #[serde(default)] + pub origin: Option, } /// Process identity survives cycles; the database remains authoritative for leadership. @@ -22,6 +25,8 @@ pub struct SchedulerState { pub(crate) pruned_at: Option, /// The address people reach the UI at, which sensor events link runs under. pub(crate) origin: Option, + /// The server's health, which each cycle reports to. + pub(crate) health: Option, } impl SchedulerState { @@ -32,6 +37,16 @@ impl SchedulerState { lease: None, pruned_at: None, origin: None, + health: None, + } + } + + /// The state whose cycles report to the server's `health`. + #[must_use] + pub fn with_health(self, health: crate::health::models::ServerHealth) -> Self { + Self { + health: Some(health), + ..self } } diff --git a/crates/sqlbuild-orchestration/src/sensors/_helpers/events/runs.rs b/crates/sqlbuild-orchestration/src/sensors/_helpers/events/runs.rs index 45c214226f..ad01498c66 100644 --- a/crates/sqlbuild-orchestration/src/sensors/_helpers/events/runs.rs +++ b/crates/sqlbuild-orchestration/src/sensors/_helpers/events/runs.rs @@ -33,7 +33,7 @@ pub(crate) async fn scan_run_events( transaction, &format!("SELECT r.run_id,r.status,r.last_event_storage_id FROM sqb_runs r \ WHERE r.location_id=$1 AND r.target=$2 AND r.job_key=$3 \ - AND r.status IN ('success','warn','partial','failed','cancelled','skipped') AND NOT {SUPERSEDED_CHILD} \ + AND r.status IN ('success','warn','failed','cancelled','skipped') AND NOT {SUPERSEDED_CHILD} \ AND {clause} LIMIT {EVENT_PAGE_SIZE}"), vec![ Parameter::Id(scope.location_id), diff --git a/crates/sqlbuild-orchestration/src/sensors/models.rs b/crates/sqlbuild-orchestration/src/sensors/models.rs index 13fcda983e..8c97a94098 100644 --- a/crates/sqlbuild-orchestration/src/sensors/models.rs +++ b/crates/sqlbuild-orchestration/src/sensors/models.rs @@ -83,7 +83,6 @@ pub enum RunEventKind { Completed, Success, Warn, - Partial, Failed, Cancelled, /// A group member the group did not run because a job it depends on failed. @@ -97,7 +96,6 @@ impl RunEventKind { Self::Completed => "completed", Self::Success => "success", Self::Warn => "warn", - Self::Partial => "partial", Self::Failed => "failed", Self::Cancelled => "cancelled", Self::Skipped => "skipped", @@ -111,7 +109,6 @@ impl RunEventKind { (Self::Completed, _) | (Self::Success, RunOutcome::Success) | (Self::Warn, RunOutcome::Warn) - | (Self::Partial, RunOutcome::Partial) | (Self::Failed, RunOutcome::Failed) | (Self::Cancelled, RunOutcome::Cancelled) | (Self::Skipped, RunOutcome::Skipped) diff --git a/crates/sqlbuild-orchestration/src/store/constants.rs b/crates/sqlbuild-orchestration/src/store/constants.rs index 58c1539b80..f0515d2b81 100644 --- a/crates/sqlbuild-orchestration/src/store/constants.rs +++ b/crates/sqlbuild-orchestration/src/store/constants.rs @@ -1,5 +1,10 @@ //! Control-store limits and schema. +/// The PostgreSQL pool's connection limit. +pub(crate) const POOL_CONNECTIONS: u32 = 10; +/// How long a request waits for a pooled PostgreSQL connection, in seconds. +pub(crate) const POOL_WAIT_SECONDS: u64 = 30; + /// A SQLite WAL past this size is reset right after the commit that grew it. pub(crate) const LARGE_WAL_BYTES: u64 = 64 * 1024 * 1024; diff --git a/crates/sqlbuild-orchestration/src/store/main/open_store.rs b/crates/sqlbuild-orchestration/src/store/main/open_store.rs index 37905528d2..629ae7caaf 100644 --- a/crates/sqlbuild-orchestration/src/store/main/open_store.rs +++ b/crates/sqlbuild-orchestration/src/store/main/open_store.rs @@ -3,6 +3,7 @@ use std::time::Duration; use crate::store::_helpers::open_sqlite::{open_sqlite, sqlite_path}; +use crate::store::constants::{POOL_CONNECTIONS, POOL_WAIT_SECONDS}; use crate::store::errors::ControlError; use crate::store::models::ControlStore; @@ -11,8 +12,8 @@ pub async fn open_store(url: &str) -> Result { if url.starts_with("postgres://") || url.starts_with("postgresql://") { return Ok(ControlStore::Postgres( sqlx_postgres::PgPoolOptions::new() - .max_connections(10) - .acquire_timeout(Duration::from_secs(30)) + .max_connections(POOL_CONNECTIONS) + .acquire_timeout(Duration::from_secs(POOL_WAIT_SECONDS)) .connect(url) .await?, )); diff --git a/crates/sqlbuild-orchestration/src/store/schema.sql b/crates/sqlbuild-orchestration/src/store/schema.sql index 117718fc8d..211e0b5238 100644 --- a/crates/sqlbuild-orchestration/src/store/schema.sql +++ b/crates/sqlbuild-orchestration/src/store/schema.sql @@ -156,7 +156,7 @@ CREATE TABLE sqb_runs ( authored_json {json}, write_set_digest TEXT NOT NULL, rewrite_history BOOLEAN NOT NULL DEFAULT FALSE, - status TEXT NOT NULL CHECK (status IN ('queued', 'launched', 'running', 'unresponsive', 'success', 'warn', 'partial', 'failed', 'cancelled', 'skipped')), + status TEXT NOT NULL CHECK (status IN ('queued', 'launched', 'running', 'unresponsive', 'success', 'warn', 'failed', 'cancelled', 'skipped')), status_reason TEXT, queued_at {time} NOT NULL, launched_at {time}, @@ -381,7 +381,7 @@ CREATE TABLE sqb_run_requests ( PRIMARY KEY (trigger_id, job_key, run_key) ); CREATE INDEX sqb_runs_terminal_cursor ON sqb_runs(location_id, target, job_key, last_event_storage_id) -WHERE status IN ('success', 'warn', 'partial', 'failed', 'cancelled', 'skipped'); +WHERE status IN ('success', 'warn', 'failed', 'cancelled', 'skipped'); CREATE INDEX sqb_runs_parent ON sqb_runs(parent_run_id) WHERE parent_run_id IS NOT NULL; CREATE TABLE sqb_warehouse_freshness ( event_id {uuid} PRIMARY KEY, diff --git a/crates/sqlbuild-orchestration/src/store_migrations/_helpers/failed_run_sensors.rs b/crates/sqlbuild-orchestration/src/store_migrations/_helpers/failed_run_sensors.rs new file mode 100644 index 0000000000..f7fdf0830c --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/_helpers/failed_run_sensors.rs @@ -0,0 +1,100 @@ +//! Migration 0012's data step: sensors watching `partial` runs watch `failed` ones, in `triggers` documents and trigger rows. + +use std::collections::BTreeSet; +use std::future::Future; +use std::pin::Pin; + +use serde_json::Value; + +use crate::sensors::models::RunEventKind; +use crate::store::errors::ControlError; +use crate::store::main::query::query; +use crate::store::models::{ControlTransaction, Parameter}; +use crate::store_migrations::_helpers::trigger_documents::rewrite_trigger_documents; + +/// The run outcome 0012 folds into `failed`. +const PARTIAL: &str = "partial"; + +/// Rewrite each stored `triggers` document and sensor row whose `run_event` condition watches `partial` to watch `failed`. +pub(crate) fn watch_failed_runs( + transaction: ControlTransaction, +) -> Pin> + Send>> { + Box::pin(rewrite_sensors(transaction)) +} + +async fn rewrite_sensors( + transaction: ControlTransaction, +) -> Result { + let transaction = rewrite_documents(transaction).await?; + let (mut transaction, rows) = query( + transaction, + "SELECT trigger_id, definition_json FROM sqb_triggers WHERE kind='sensor'", + Vec::new(), + ) + .await?; + for row in rows { + let mut definition = json_value(&row["definition_json"])?; + if !watch_failed(&mut definition)? { + continue; + } + let trigger_id = uuid::Uuid::parse_str(row["trigger_id"].as_str().unwrap_or_default()) + .map_err(|error| ControlError::Schema(format!("stored trigger ID: {error}")))?; + (transaction, _) = query( + transaction, + "UPDATE sqb_triggers SET definition_json=$2 WHERE trigger_id=$1", + vec![Parameter::Id(trigger_id), Parameter::Json(definition)], + ) + .await?; + } + Ok(transaction) +} + +async fn rewrite_documents( + transaction: ControlTransaction, +) -> Result { + rewrite_trigger_documents(transaction, |entries| { + let mut changed = false; + for entry in entries.values_mut() { + changed |= watch_failed(entry)?; + } + Ok(changed) + }) + .await +} + +/// A JSON column as read back: a value, or its text on a store that returns JSON as text. +fn json_value(column: &Value) -> Result { + match column.as_str() { + Some(text) => { + serde_json::from_str(text).map_err(|error| ControlError::Invalid(error.to_string())) + } + None => Ok(column.clone()), + } +} + +/// Whether `sensor`'s `run_event` condition watched `partial`; it then watches `failed` in its place. +fn watch_failed(sensor: &mut Value) -> Result { + let watches_partial = sensor.pointer("/when/kind").and_then(Value::as_str) == Some("run_event") + && sensor + .pointer("/when/kinds") + .and_then(Value::as_array) + .is_some_and(|kinds| kinds.iter().any(|kind| kind.as_str() == Some(PARTIAL))); + let Some(kinds) = sensor + .pointer_mut("/when/kinds") + .filter(|_| watches_partial) + else { + return Ok(false); + }; + let watched: BTreeSet = kinds + .as_array() + .into_iter() + .flatten() + .filter(|kind| kind.as_str() != Some(PARTIAL)) + .map(|kind| serde_json::from_value(kind.clone())) + .chain([Ok(RunEventKind::Failed)]) + .collect::>() + .map_err(|error| ControlError::Invalid(error.to_string()))?; + *kinds = + serde_json::to_value(watched).map_err(|error| ControlError::Invalid(error.to_string()))?; + Ok(true) +} diff --git a/crates/sqlbuild-orchestration/src/store_migrations/_helpers/migration.rs b/crates/sqlbuild-orchestration/src/store_migrations/_helpers/migration.rs index 69f1bd6955..baaa38bd12 100644 --- a/crates/sqlbuild-orchestration/src/store_migrations/_helpers/migration.rs +++ b/crates/sqlbuild-orchestration/src/store_migrations/_helpers/migration.rs @@ -5,6 +5,7 @@ use sqlbuild_recall::records::main::sha256_hex::sha256_hex; use crate::store::errors::ControlError; use crate::store::main::query::query; use crate::store::models::{ControlStore, ControlTransaction}; +use crate::store_migrations::_helpers::failed_run_sensors::watch_failed_runs; use crate::store_migrations::_helpers::old_form_sensors::drop_old_form_sensors; use crate::store_migrations::_helpers::recall_schema::recall_schema; use crate::store_migrations::constants::{ @@ -76,6 +77,12 @@ pub(crate) const MIGRATIONS: &[StoreMigration] = &[ postgres: include_str!("../sql/0011_discovered_assets_document.postgres.sql"), step: None, }, + StoreMigration { + name: "failed_run_outcome", + sqlite: include_str!("../sql/0012_failed_run_outcome.sqlite.sql"), + postgres: include_str!("../sql/0012_failed_run_outcome.postgres.sql"), + step: Some(watch_failed_runs), + }, ]; /// The schema version a store created by this build has. diff --git a/crates/sqlbuild-orchestration/src/store_migrations/_helpers/mod.rs b/crates/sqlbuild-orchestration/src/store_migrations/_helpers/mod.rs index be0e62581a..3e53456bcf 100644 --- a/crates/sqlbuild-orchestration/src/store_migrations/_helpers/mod.rs +++ b/crates/sqlbuild-orchestration/src/store_migrations/_helpers/mod.rs @@ -1,4 +1,6 @@ +pub(crate) mod failed_run_sensors; pub(crate) mod migration; pub(crate) mod migration_run; pub(crate) mod old_form_sensors; pub(crate) mod recall_schema; +pub(crate) mod trigger_documents; diff --git a/crates/sqlbuild-orchestration/src/store_migrations/_helpers/old_form_sensors.rs b/crates/sqlbuild-orchestration/src/store_migrations/_helpers/old_form_sensors.rs index 4605f81d1c..000f3a1942 100644 --- a/crates/sqlbuild-orchestration/src/store_migrations/_helpers/old_form_sensors.rs +++ b/crates/sqlbuild-orchestration/src/store_migrations/_helpers/old_form_sensors.rs @@ -3,12 +3,9 @@ use std::future::Future; use std::pin::Pin; -use crate::snapshots::main::publication::stored_document::stored_document; use crate::store::errors::ControlError; -use crate::store::main::decompress::decompress; -use crate::store::main::query::query; -use crate::store::models::{ControlTransaction, Parameter}; -use serde_json::Value; +use crate::store::models::ControlTransaction; +use crate::store_migrations::_helpers::trigger_documents::rewrite_trigger_documents; /// Rewrite each stored `triggers` document without its old-form sensors, which have neither a `function` nor a `schedule`; their `sqb_triggers` rows stay, hidden by the migration's SQL. pub(crate) fn drop_old_form_sensors( @@ -20,39 +17,11 @@ pub(crate) fn drop_old_form_sensors( async fn rewrite_documents( transaction: ControlTransaction, ) -> Result { - let (mut transaction, rows) = query( - transaction, - "SELECT document_hash, body FROM sqb_documents WHERE document_hash IN \ - (SELECT document_hash FROM sqb_snapshot_documents WHERE kind='triggers')", - Vec::new(), - ) - .await?; - for row in rows { - let invalid = |error: serde_json::Error| ControlError::Invalid(error.to_string()); - let mut document: Value = - serde_json::from_slice(&decompress(&row["body"])?).map_err(invalid)?; - let Some(entries) = document.as_object_mut() else { - continue; - }; + rewrite_trigger_documents(transaction, |entries| { let before = entries.len(); entries .retain(|_, entry| entry.get("function").is_some() || entry.get("schedule").is_some()); - if entries.len() == before { - continue; - } - let (hash, body) = stored_document(&document)?; - (transaction, _) = query( - transaction, - "INSERT INTO sqb_documents (document_hash, body) VALUES ($1, $2) ON CONFLICT DO NOTHING", - vec![Parameter::Text(hash.clone()), Parameter::Bytes(body)], - ) - .await?; - (transaction, _) = query( - transaction, - "UPDATE sqb_snapshot_documents SET document_hash=$2 WHERE kind='triggers' AND document_hash=$1", - vec![Parameter::Text(row["document_hash"].as_str().unwrap_or_default().to_owned()), Parameter::Text(hash)], - ) - .await?; - } - Ok(transaction) + Ok(entries.len() != before) + }) + .await } diff --git a/crates/sqlbuild-orchestration/src/store_migrations/_helpers/trigger_documents.rs b/crates/sqlbuild-orchestration/src/store_migrations/_helpers/trigger_documents.rs new file mode 100644 index 0000000000..ac8b276850 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/_helpers/trigger_documents.rs @@ -0,0 +1,50 @@ +//! Rewrite the stored `triggers` documents a migration's data step changes, keeping the others as they are. + +use serde_json::{Map, Value}; + +use crate::snapshots::main::publication::stored_document::stored_document; +use crate::store::errors::ControlError; +use crate::store::main::decompress::decompress; +use crate::store::main::query::query; +use crate::store::models::{ControlTransaction, Parameter}; + +/// Store each `triggers` document that `edit` changes, by trigger name, under its new hash, and point the snapshots holding it there. +pub(crate) async fn rewrite_trigger_documents( + transaction: ControlTransaction, + edit: impl Fn(&mut Map) -> Result + Send, +) -> Result { + let (mut transaction, rows) = query( + transaction, + "SELECT document_hash, body FROM sqb_documents WHERE document_hash IN \ + (SELECT document_hash FROM sqb_snapshot_documents WHERE kind='triggers')", + Vec::new(), + ) + .await?; + for row in rows { + let mut document: Value = serde_json::from_slice(&decompress(&row["body"])?) + .map_err(|error| ControlError::Invalid(error.to_string()))?; + let Some(entries) = document.as_object_mut() else { + continue; + }; + if !edit(entries)? { + continue; + } + let (hash, body) = stored_document(&document)?; + (transaction, _) = query( + transaction, + "INSERT INTO sqb_documents (document_hash, body) VALUES ($1, $2) ON CONFLICT DO NOTHING", + vec![Parameter::Text(hash.clone()), Parameter::Bytes(body)], + ) + .await?; + (transaction, _) = query( + transaction, + "UPDATE sqb_snapshot_documents SET document_hash=$2 WHERE kind='triggers' AND document_hash=$1", + vec![ + Parameter::Text(row["document_hash"].as_str().unwrap_or_default().to_owned()), + Parameter::Text(hash), + ], + ) + .await?; + } + Ok(transaction) +} diff --git a/crates/sqlbuild-orchestration/src/store_migrations/sql/0012_failed_run_outcome.postgres.sql b/crates/sqlbuild-orchestration/src/store_migrations/sql/0012_failed_run_outcome.postgres.sql new file mode 100644 index 0000000000..3670ec5491 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/sql/0012_failed_run_outcome.postgres.sql @@ -0,0 +1,26 @@ +-- 'partial' is no longer a run outcome: a run that built some nodes and not others ended `failed`. +-- Stored runs, their terminal facts, run_failed events and sensor ticks say `failed` instead, and +-- the data step makes sensors watching `partial` runs watch `failed` ones. +UPDATE sqb_runs SET status = 'failed' WHERE status = 'partial'; + +ALTER TABLE sqb_runs DROP CONSTRAINT sqb_runs_status_check; + +ALTER TABLE sqb_runs ADD CONSTRAINT sqb_runs_status_check CHECK (status IN ('queued', 'launched', 'running', 'unresponsive', 'success', 'warn', 'failed', 'cancelled', 'skipped')); + +DROP INDEX sqb_runs_terminal_cursor; + +CREATE INDEX sqb_runs_terminal_cursor ON sqb_runs(location_id, target, job_key, last_event_storage_id) +WHERE status IN ('success', 'warn', 'failed', 'cancelled', 'skipped'); + +UPDATE recall_events SET payload = jsonb_set(payload, '{change,change,outcome}', '"failed"') +WHERE event_type = 'run_terminated' AND payload #>> '{change,change,outcome}' = 'partial'; + +UPDATE recall_events SET payload = jsonb_set(payload, '{platform,outcome}', '"failed"') +WHERE event_type = 'platform_run_failed' AND payload #>> '{platform,outcome}' = 'partial'; + +UPDATE sqb_sensor_evaluation_events SET fact_json = jsonb_set(fact_json, '{request,event,status}', '"failed"') +WHERE fact_json #>> '{request,event,status}' = 'partial'; + +UPDATE sqb_sensor_evaluation_events +SET fact_json = jsonb_set(fact_json, '{request,event,details,outcome}', '"failed"') +WHERE fact_json #>> '{request,event,details,outcome}' = 'partial'; diff --git a/crates/sqlbuild-orchestration/src/store_migrations/sql/0012_failed_run_outcome.sqlite.sql b/crates/sqlbuild-orchestration/src/store_migrations/sql/0012_failed_run_outcome.sqlite.sql new file mode 100644 index 0000000000..401df64fa2 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/store_migrations/sql/0012_failed_run_outcome.sqlite.sql @@ -0,0 +1,75 @@ +-- 'partial' is no longer a run outcome: a run that built some nodes and not others ended `failed`. +-- Stored runs, their terminal facts, run_failed events and sensor ticks say `failed` instead, and +-- the data step makes sensors watching `partial` runs watch `failed` ones. +CREATE TABLE sqb_runs_v2 ( + run_id {uuid} PRIMARY KEY, + location_id {uuid} NOT NULL REFERENCES sqb_locations(location_id), + target TEXT NOT NULL, + snapshot_id {uuid} NOT NULL REFERENCES sqb_snapshots(snapshot_id), + image_id TEXT, + kind TEXT NOT NULL CHECK (kind IN ('job', 'group', 'adhoc')), + origin TEXT NOT NULL CHECK (origin IN ('manual', 'schedule', 'sensor', 'rerun', 'backfill')), + job_key TEXT, + parent_run_id {uuid} REFERENCES sqb_runs(run_id), + root_run_id {uuid} NOT NULL, + trigger_id {uuid} REFERENCES sqb_triggers(trigger_id), + tick_id {uuid} REFERENCES sqb_ticks(tick_id), + rerun_of_run_id {uuid} REFERENCES sqb_runs(run_id), + requested_by TEXT NOT NULL, + priority BIGINT NOT NULL DEFAULT 0, + selection_json {json} NOT NULL, + request_json {json} NOT NULL, + authored_json {json}, + write_set_digest TEXT NOT NULL, + rewrite_history BOOLEAN NOT NULL DEFAULT FALSE, + status TEXT NOT NULL CHECK (status IN ('queued', 'launched', 'running', 'unresponsive', 'success', 'warn', 'failed', 'cancelled', 'skipped')), + status_reason TEXT, + queued_at {time} NOT NULL, + launched_at {time}, + started_at {time}, + ended_at {time}, + cancel_requested_at {time}, + node_counts_json {json} NOT NULL, + ignored_audit_failures BIGINT NOT NULL DEFAULT 0, + last_event_storage_id BIGINT NOT NULL, + worker_instance {uuid}, + container_id TEXT, + claimed_at {time}, + last_heartbeat_at {time} +); + +INSERT INTO sqb_runs_v2 (run_id, location_id, target, snapshot_id, image_id, kind, origin, job_key, parent_run_id, root_run_id, trigger_id, tick_id, rerun_of_run_id, requested_by, priority, selection_json, request_json, authored_json, write_set_digest, rewrite_history, status, status_reason, queued_at, launched_at, started_at, ended_at, cancel_requested_at, node_counts_json, ignored_audit_failures, last_event_storage_id, worker_instance, container_id, claimed_at, last_heartbeat_at) SELECT run_id, location_id, target, snapshot_id, image_id, kind, origin, job_key, parent_run_id, root_run_id, trigger_id, tick_id, rerun_of_run_id, requested_by, priority, selection_json, request_json, authored_json, write_set_digest, rewrite_history, CASE WHEN status = 'partial' THEN 'failed' ELSE status END, status_reason, queued_at, launched_at, started_at, ended_at, cancel_requested_at, node_counts_json, ignored_audit_failures, last_event_storage_id, worker_instance, container_id, claimed_at, last_heartbeat_at FROM sqb_runs; + +DROP TABLE sqb_runs; + +ALTER TABLE sqb_runs_v2 RENAME TO sqb_runs; + +CREATE INDEX sqb_runs_location_time ON sqb_runs(location_id, target, queued_at); + +CREATE INDEX sqb_runs_location_ended ON sqb_runs(location_id, target, ended_at); + +CREATE INDEX sqb_runs_queue ON sqb_runs(priority DESC, queued_at) WHERE status = 'queued'; + +CREATE INDEX sqb_runs_active ON sqb_runs(location_id, target, job_key) WHERE status IN ('queued', 'launched', 'running', 'unresponsive'); + +CREATE INDEX sqb_runs_terminal_cursor ON sqb_runs(location_id, target, job_key, last_event_storage_id) +WHERE status IN ('success', 'warn', 'failed', 'cancelled', 'skipped'); + +CREATE INDEX sqb_runs_parent ON sqb_runs(parent_run_id) WHERE parent_run_id IS NOT NULL; + +CREATE INDEX IF NOT EXISTS sqb_runs_tick ON sqb_runs(tick_id); + +CREATE INDEX IF NOT EXISTS sqb_runs_snapshot ON sqb_runs(snapshot_id); + +UPDATE recall_events SET payload = json_set(payload, '$.change.change.outcome', 'failed') +WHERE event_type = 'run_terminated' AND json_extract(payload, '$.change.change.outcome') = 'partial'; + +UPDATE recall_events SET payload = json_set(payload, '$.platform.outcome', 'failed') +WHERE event_type = 'platform_run_failed' AND json_extract(payload, '$.platform.outcome') = 'partial'; + +UPDATE sqb_sensor_evaluation_events SET fact_json = json_set(fact_json, '$.request.event.status', 'failed') +WHERE json_extract(fact_json, '$.request.event.status') = 'partial'; + +UPDATE sqb_sensor_evaluation_events +SET fact_json = json_set(fact_json, '$.request.event.details.outcome', 'failed') +WHERE json_extract(fact_json, '$.request.event.details.outcome') = 'partial'; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/checks.rs b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/checks.rs index e7997ea2bf..3181f8e6cd 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/checks.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/checks.rs @@ -1,5 +1,6 @@ //! Check reads over the audit-result mirror, keyed by binding key on its own index. +use sqlbuild_core::redaction::main::redact_error_text::redact_error_text; use std::collections::BTreeSet; use serde::Deserialize; @@ -90,6 +91,7 @@ pub(crate) fn evidence(row: AuditRow) -> Result { columns, rows, truncated: row.record.evidence_truncated, + execution_error: row.record.execution_error.as_deref().map(redact_error_text), }) } diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/mod.rs b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/mod.rs index 720f1514ca..9e3c4d9d0d 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/mod.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/mod.rs @@ -6,4 +6,5 @@ pub(crate) mod costs; pub(crate) mod coverage; pub(crate) mod maintenance; pub(crate) mod node_runs; +pub(crate) mod run_failures; pub(crate) mod run_recall; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_failures.rs b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_failures.rs new file mode 100644 index 0000000000..a3bc7b4978 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_failures.rs @@ -0,0 +1,81 @@ +//! One run's Recall facts for its `run_failed` event: error-severity audit failures, the failing invocation's error and reported phases. + +use sqlbuild_core::redaction::main::redact_error_text::redact_error_text; +use uuid::Uuid; + +use crate::runs::main::listings::run_invocations::run_invocations; +use crate::runs::models::RunAuditFailure; +use crate::store::errors::ControlError; +use crate::store::main::query::query; +use crate::store::models::ControlTransaction; +use crate::warehouse_history::_helpers::run_recall::{RunRecallScope, invocation_filter, sqlstate}; +use crate::warehouse_history::constants::INVOCATION_PHASE_EVENT; +use crate::warehouse_history::models::RunFailureRecall; + +/// One run's error-severity audit failures, latest invocation error and reported phases. +pub(crate) async fn read_member_failure_recall( + mut transaction: ControlTransaction, + member: Uuid, +) -> Result<(ControlTransaction, RunFailureRecall), ControlError> { + let mut recall = RunFailureRecall::default(); + let namespaces; + (transaction, namespaces) = run_invocations(transaction, member).await?; + let scope = RunRecallScope::of_invocations(namespaces); + let (filter, parameters) = invocation_filter(&scope, 1); + let audits; + (transaction, audits) = query( + transaction, + &format!( + "SELECT audit_name, attached_target_kind, attached_target_name, violation_count, execution_error \ + FROM audit_results WHERE {filter} AND outcome='error' AND ignored=0 ORDER BY audit_name" + ), + parameters.clone(), + ) + .await?; + for row in audits { + recall.audit_count += 1; + let text = |column: &str| row[column].as_str().map(str::to_owned); + let message = text("execution_error").map(|error| redact_error_text(&error)); + recall.audits.push(RunAuditFailure { + name: text("audit_name").unwrap_or_default(), + node_key: text("attached_target_kind") + .zip(text("attached_target_name")) + .map(|(kind, name)| format!("{kind}:{name}")), + sqlstate: message.as_deref().and_then(sqlstate), + message, + failing_rows: row["violation_count"].as_i64(), + }); + } + let errors; + (transaction, errors) = query( + transaction, + &format!( + "SELECT error_type, error_message FROM invocations \ + WHERE {filter} AND error_message IS NOT NULL ORDER BY ended_at DESC LIMIT 1" + ), + parameters.clone(), + ) + .await?; + if let Some(row) = errors.first() { + recall.invocation_error = Some(( + row["error_type"].as_str().map(str::to_owned), + row["error_message"].as_str().map(redact_error_text), + )); + } + let phases; + (transaction, phases) = query( + transaction, + &format!( + "SELECT DISTINCT payload->>'phase' AS phase FROM recall_events \ + WHERE {filter} AND event_type='{INVOCATION_PHASE_EVENT}'" + ), + parameters, + ) + .await?; + recall.phases.extend( + phases + .iter() + .filter_map(|row| row["phase"].as_str().map(str::to_owned)), + ); + Ok((transaction, recall)) +} diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_recall.rs b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_recall.rs index f5cab31c54..2cf267480f 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_recall.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/_helpers/run_recall.rs @@ -57,6 +57,16 @@ pub(crate) struct RunRecallScope { selection: BTreeSet, } +impl RunRecallScope { + /// A run's invocations, for reads that authorize nothing by node. + pub(crate) const fn of_invocations(namespaces: Vec) -> Self { + Self { + namespaces, + selection: BTreeSet::new(), + } + } +} + /// The run's transaction and scope, plus the deciding context and granted scope of a sensitive read. pub(crate) type RunRecallRead = ( ControlTransaction, @@ -268,6 +278,7 @@ pub(crate) async fn run_events_in( CASE WHEN event_type='{AUDIT_COMPLETED_EVENT}' THEN payload->>'binding_key' END AS check_binding_key, \ CASE WHEN event_type='{AUDIT_COMPLETED_EVENT}' THEN payload->>'result_id' END AS check_result_id, \ CASE WHEN event_type='{AUDIT_COMPLETED_EVENT}' THEN CAST(payload->>'violation_count' AS BIGINT) END AS check_rows, \ + CASE WHEN event_type='{AUDIT_COMPLETED_EVENT}' THEN payload->>'not_run_reason' END AS not_run_reason, \ CASE WHEN event_type='{INVOCATION_PHASE_EVENT}' THEN payload->>'phase' END AS phase, \ CASE WHEN event_type='{INVOCATION_PHASE_EVENT}' THEN CAST(payload->>'count' AS BIGINT) END AS phase_count, \ CASE WHEN event_type='{INVOCATION_PHASE_EVENT}' THEN payload->>'name' END AS phase_name, \ @@ -286,10 +297,13 @@ pub(crate) async fn run_events_in( for (column, _) in START_FIELDS { row.remove(column); } + let not_run_reason: Option = row + .remove("not_run_reason") + .and_then(|reason| reason.as_str().map(str::to_owned)); let message = if launched { launch_message(&payload)? } else { - started.or(member_message(&payload)?) + started.or(not_run_reason).or(member_message(&payload)?) }; if let Some(message) = message { row.insert("message".into(), Value::String(message)); @@ -573,7 +587,7 @@ pub(crate) async fn run_output_in( } /// Exact scheduler and worker invocations, plus the worker's nested invocations. -fn invocation_filter(scope: &RunRecallScope, first: usize) -> (String, Vec) { +pub(crate) fn invocation_filter(scope: &RunRecallScope, first: usize) -> (String, Vec) { let mut clauses: Vec = Vec::new(); let mut parameters: Vec = Vec::new(); for namespace in &scope.namespaces { @@ -599,3 +613,23 @@ fn display_text(value: &Value) -> Result, ControlError> { } } } + +/// A warehouse error's SQLSTATE: the five characters in brackets, as in `002003 (42S02): ...`. +pub(crate) fn sqlstate(text: &str) -> Option { + for (start, _) in text.match_indices('(') { + let (Some(code), Some(")")) = ( + text.get(start + 1..start + 6), + text.get(start + 6..start + 7), + ) else { + continue; + }; + if code.bytes().all(is_sqlstate_byte) { + return Some(code.to_owned()); + } + } + None +} + +const fn is_sqlstate_byte(byte: u8) -> bool { + byte.is_ascii_digit() || byte.is_ascii_uppercase() +} diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/constants.rs b/crates/sqlbuild-orchestration/src/warehouse_history/constants.rs index 7263cac60f..4bc6e5adce 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/constants.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/constants.rs @@ -8,3 +8,6 @@ pub(crate) const CONFIG_PRICE_SOURCE: &str = "config"; pub(crate) const LIST_PRICE_SOURCE: &str = "list_price"; /// The source of a total whose rows were priced from different sources, none an estimate. pub(crate) const MIXED_PRICE_SOURCE: &str = "mixed"; + +/// The invocation event that records a worker phase, such as `compiled`. +pub(crate) const INVOCATION_PHASE_EVENT: &str = "invocation_phase"; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/checks/mod.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/checks/mod.rs new file mode 100644 index 0000000000..5ee804dae1 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/checks/mod.rs @@ -0,0 +1,6 @@ +pub mod read_latest_checks; +pub mod read_node_check_counts; +pub mod read_person_check; +pub mod read_person_check_evidence; +pub mod read_person_check_sql; +pub mod read_person_run_ignored_audits; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_latest_checks.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/checks/read_latest_checks.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_latest_checks.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/checks/read_latest_checks.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_node_check_counts.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/checks/read_node_check_counts.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_node_check_counts.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/checks/read_node_check_counts.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_check.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/checks/read_person_check.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_check.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/checks/read_person_check.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_check_evidence.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/checks/read_person_check_evidence.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_check_evidence.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/checks/read_person_check_evidence.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_check_sql.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/checks/read_person_check_sql.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_check_sql.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/checks/read_person_check_sql.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_ignored_audits.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/checks/read_person_run_ignored_audits.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_ignored_audits.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/checks/read_person_run_ignored_audits.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/costs/mod.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/costs/mod.rs new file mode 100644 index 0000000000..a0d1c9e95b --- /dev/null +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/costs/mod.rs @@ -0,0 +1,5 @@ +pub mod read_person_cost_selection; +pub mod read_person_cost_series; +pub mod read_person_cost_summary; +pub mod read_person_node_costs; +pub mod read_person_run_cost; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_selection.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/costs/read_person_cost_selection.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_selection.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/costs/read_person_cost_selection.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_series.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/costs/read_person_cost_series.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_series.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/costs/read_person_cost_series.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_summary.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/costs/read_person_cost_summary.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_cost_summary.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/costs/read_person_cost_summary.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_node_costs.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/costs/read_person_node_costs.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_node_costs.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/costs/read_person_node_costs.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_cost.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/costs/read_person_run_cost.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_cost.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/costs/read_person_run_cost.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/maintenance/mod.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/maintenance/mod.rs new file mode 100644 index 0000000000..5ad9e4df5d --- /dev/null +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/maintenance/mod.rs @@ -0,0 +1,2 @@ +pub mod read_person_maintenance; +pub mod read_person_microbatch_coverage; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_maintenance.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/maintenance/read_person_maintenance.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_maintenance.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/maintenance/read_person_maintenance.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_microbatch_coverage.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/maintenance/read_person_microbatch_coverage.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_microbatch_coverage.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/maintenance/read_person_microbatch_coverage.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/mod.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/mod.rs index bb0e548fd0..fd87cc95f6 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/main/mod.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/mod.rs @@ -1,20 +1,4 @@ -pub mod read_latest_checks; -pub mod read_node_check_counts; -pub mod read_person_check; -pub mod read_person_check_evidence; -pub mod read_person_check_sql; -pub mod read_person_cost_selection; -pub mod read_person_cost_series; -pub mod read_person_cost_summary; -pub mod read_person_maintenance; -pub mod read_person_microbatch_coverage; -pub mod read_person_node_costs; -pub mod read_person_node_runs; -pub mod read_person_run_cost; -pub mod read_person_run_events; -pub mod read_person_run_ignored_audits; -pub mod read_person_run_node_error; -pub mod read_person_run_output; -pub mod read_person_run_statement_sql; -pub mod read_person_run_statements; -pub mod read_run_evidence; +pub mod checks; +pub mod costs; +pub mod maintenance; +pub mod runs; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/mod.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/mod.rs new file mode 100644 index 0000000000..2506f121fb --- /dev/null +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/mod.rs @@ -0,0 +1,8 @@ +pub mod read_person_node_runs; +pub mod read_person_run_events; +pub mod read_person_run_node_error; +pub mod read_person_run_output; +pub mod read_person_run_statement_sql; +pub mod read_person_run_statements; +pub mod read_run_evidence; +pub mod read_run_failure_recall; diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_node_runs.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_person_node_runs.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_node_runs.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_person_node_runs.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_events.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_person_run_events.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_events.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_person_run_events.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_node_error.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_person_run_node_error.rs similarity index 89% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_node_error.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_person_run_node_error.rs index c11547dd32..8572d8c4ec 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_node_error.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_person_run_node_error.rs @@ -43,14 +43,18 @@ pub async fn read_person_run_node_error( .await?; let mut result = None; if let Some(row) = rows.into_iter().next() { - let message = match &row["payload"] { - Value::Null => None, + let (message, phase) = match &row["payload"] { + Value::Null => (None, None), payload => match serde_json::from_value::(payload["change"].clone()) .map_err(|error| ControlError::Invalid(error.to_string()))? .change { - RunChange::NodeFinished { error_message, .. } => error_message, - _ => None, + RunChange::NodeFinished { + error_message, + phase, + .. + } => (error_message, phase), + _ => (None, None), }, }; let snapshot_id: Uuid = serde_json::from_value(row["snapshot_id"].clone()) @@ -67,6 +71,9 @@ pub async fn read_person_run_node_error( .and_then(|node| node.definition.get("path")) .and_then(Value::as_str) .map(|path| path.replace('\\', "/")), + phase, + url: None, + logs_url: None, }); } let transaction = append_audit( diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_output.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_person_run_output.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_output.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_person_run_output.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_statement_sql.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_person_run_statement_sql.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_statement_sql.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_person_run_statement_sql.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_statements.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_person_run_statements.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_person_run_statements.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_person_run_statements.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/read_run_evidence.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_run_evidence.rs similarity index 100% rename from crates/sqlbuild-orchestration/src/warehouse_history/main/read_run_evidence.rs rename to crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_run_evidence.rs diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_run_failure_recall.rs b/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_run_failure_recall.rs new file mode 100644 index 0000000000..34365cc082 --- /dev/null +++ b/crates/sqlbuild-orchestration/src/warehouse_history/main/runs/read_run_failure_recall.rs @@ -0,0 +1,42 @@ +//! A failed run's Recall facts for its `run_failed` event: audit failures, the failing invocation's error and the phases it reported. + +use uuid::Uuid; + +use crate::runs::constants::SUPERSEDED_CHILD; +use crate::store::errors::ControlError; +use crate::store::main::query::query; +use crate::store::models::{ControlTransaction, Parameter}; +use crate::warehouse_history::_helpers::run_failures::read_member_failure_recall; +use crate::warehouse_history::models::RunFailureRecall; + +/// A failed run's audit failures, failing invocation and reported phases, over the run and its current group members. +pub(crate) async fn read_run_failure_recall( + transaction: ControlTransaction, + (run_id, limit): (Uuid, usize), +) -> Result<(ControlTransaction, RunFailureRecall), ControlError> { + let (mut transaction, runs) = query( + transaction, + &format!( + "SELECT r.run_id FROM sqb_runs r \ + WHERE r.run_id=$1 OR (r.parent_run_id=$1 AND NOT {SUPERSEDED_CHILD}) ORDER BY r.run_id" + ), + vec![Parameter::Id(run_id)], + ) + .await?; + let mut recall = RunFailureRecall::default(); + for run in runs { + let member = Uuid::parse_str(run["run_id"].as_str().unwrap_or_default()) + .map_err(|error| ControlError::Schema(format!("stored run ID: {error}")))?; + let found; + (transaction, found) = read_member_failure_recall(transaction, member).await?; + recall.audit_count += found.audit_count; + recall.audits.extend(found.audits); + recall.phases.extend(found.phases); + recall.invocation_error = recall.invocation_error.or(found.invocation_error); + } + recall + .audits + .sort_by(|left, right| left.name.cmp(&right.name)); + recall.audits.truncate(limit); + Ok((transaction, recall)) +} diff --git a/crates/sqlbuild-orchestration/src/warehouse_history/models.rs b/crates/sqlbuild-orchestration/src/warehouse_history/models.rs index f8c659a7df..82ae03a9b3 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_history/models.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_history/models.rs @@ -98,6 +98,8 @@ pub struct CheckEvidence { #[schema(value_type = Vec>)] pub rows: Vec>, pub truncated: Option, + /// The warehouse's error, SQLSTATE included, when the audit's query could not run; redacted like a node's. + pub execution_error: Option, } /// One old-name view step as people read it: copied grants are counted, never returned as statements. @@ -326,3 +328,15 @@ pub struct CostSeriesBatch { pub dates: Vec, pub series: Vec>, } + +/// A failed run's facts from its Recall history, for its `run_failed` event. +#[derive(Debug, Default)] +pub(crate) struct RunFailureRecall { + /// The first error-severity audit failures that weren't let through, by name. + pub(crate) audits: Vec, + pub(crate) audit_count: i64, + /// The error type and redacted text of the run's failing invocation, if one reported an error. + pub(crate) invocation_error: Option<(Option, Option)>, + /// The worker phases the run reported, such as `compiled` and `started_execution`. + pub(crate) phases: std::collections::BTreeSet, +} diff --git a/crates/sqlbuild-orchestration/src/warehouse_metadata/_helpers/catalog_nodes.rs b/crates/sqlbuild-orchestration/src/warehouse_metadata/_helpers/catalog_nodes.rs index 78dfb2346c..4a88e3c5ee 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_metadata/_helpers/catalog_nodes.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_metadata/_helpers/catalog_nodes.rs @@ -120,7 +120,7 @@ pub(crate) async fn latest_attempts( let (transaction, attempts): (_, Vec) = query_records(transaction, &format!("SELECT n.node_key,n.run_id,n.status,n.ended_at,n.finished_storage_id FROM (\ SELECT run_id FROM ({newest} LIMIT $3) AS latest UNION \ - SELECT run_id FROM (SELECT run_id FROM ({newest} LIMIT $4) AS recent WHERE status IN ('failed','partial','warn') \ + SELECT run_id FROM (SELECT run_id FROM ({newest} LIMIT $4) AS recent WHERE status IN ('failed','warn') \ ORDER BY queued_at DESC, run_id DESC LIMIT $3) AS failures) AS r \ JOIN sqb_run_nodes n ON n.run_id=r.run_id WHERE n.kind='node' AND n.finished_storage_id IS NOT NULL \ AND n.started_at IS NOT NULL AND n.status IN ('success','warn','failed')"), diff --git a/crates/sqlbuild-orchestration/src/warehouse_metadata/models.rs b/crates/sqlbuild-orchestration/src/warehouse_metadata/models.rs index 2b15a4023c..8727ea23d9 100644 --- a/crates/sqlbuild-orchestration/src/warehouse_metadata/models.rs +++ b/crates/sqlbuild-orchestration/src/warehouse_metadata/models.rs @@ -729,6 +729,9 @@ pub struct WarehouseHistoryFailure { pub reason: String, /// The read ran out of memory or time, so a smaller page may succeed; any other error repeats. pub page_size: bool, + /// The reader never reached the warehouse, such as a host that doesn't resolve, so no billed compute ran. + #[serde(default)] + pub connection: bool, } /// A dynamic model a completed sync resumed: the run whose hold expired, and its dotted relation. diff --git a/crates/sqlbuild-orchestration/src/webhooks/_helpers/delivery.rs b/crates/sqlbuild-orchestration/src/webhooks/_helpers/delivery.rs index 1e39cc0409..cdfc0ec5b6 100644 --- a/crates/sqlbuild-orchestration/src/webhooks/_helpers/delivery.rs +++ b/crates/sqlbuild-orchestration/src/webhooks/_helpers/delivery.rs @@ -35,10 +35,10 @@ pub(crate) async fn deliver_webhook( .json(&event) .send() .await - .map_err(|_| ControlError::Invalid("webhook delivery failed; event retained".into()))?; + .map_err(|error| ControlError::Invalid(transport_failure(&error).into()))?; if !response.status().is_success() { return Err(ControlError::Invalid(format!( - "webhook returned HTTP {}; event retained", + "the webhook answered HTTP {}", response.status().as_u16() ))); } @@ -62,3 +62,14 @@ pub(crate) async fn deliver_webhook( } Ok(count) } + +/// A failed request in words that never name the endpoint, which may hold credentials. +fn transport_failure(error: &reqwest::Error) -> &'static str { + if error.is_timeout() { + "the webhook didn't answer in time" + } else if error.is_connect() { + "can't connect to the webhook" + } else { + "the request to the webhook failed" + } +} diff --git a/crates/sqlbuild-orchestration/src/webhooks/main/run_webhook.rs b/crates/sqlbuild-orchestration/src/webhooks/main/run_webhook.rs index 2eeda4a457..7ef3068ca6 100644 --- a/crates/sqlbuild-orchestration/src/webhooks/main/run_webhook.rs +++ b/crates/sqlbuild-orchestration/src/webhooks/main/run_webhook.rs @@ -4,34 +4,45 @@ use std::time::Duration; use tokio::sync::watch; +use crate::health::models::ServerHealth; use crate::store::errors::ControlError; use crate::store::models::ControlStore; use crate::webhooks::_helpers::delivery::deliver_webhook; use crate::webhooks::constants::POLL_SECONDS; use crate::webhooks::models::Webhook; +/// Deliver `sink`'s events until `shutdown`, recording each outcome in `health` so a failing webhook is seen. pub async fn run_webhook( - store: &ControlStore, + (store, health): (ControlStore, Option), sink: Webhook, mut shutdown: watch::Receiver, ) -> Result<(), ControlError> { let mut failed = false; + let name: &str = sink.source.forwarding(); while !*shutdown.borrow() { tokio::select! { - result = deliver_webhook(store, &sink) => { + result = deliver_webhook(&store, &sink) => { + let now = chrono::Utc::now(); match result { Ok(count) => { if failed { eprintln!("{} webhook delivery recovered", sink.source.label()); } failed = false; + health.iter().for_each(|health| health.forwarding_succeeded(name, now)); if count > 0 { continue; } }, - Err(_) => { + Err(error) => { if !failed { eprintln!("{} webhook delivery failed; retaining events and retrying", sink.source.label()); } failed = true; + let reason = format!( + "Can't deliver {} events: {}; they are kept and retried every {POLL_SECONDS} s", + sink.source.label().to_lowercase(), + failure_text(&error) + ); + health.iter().for_each(|health| health.forwarding_failed(name, (&reason, now))); }, } }, @@ -46,3 +57,11 @@ pub async fn run_webhook( } Ok(()) } + +/// Why delivery failed: the webhook's own failure, or the control database it reads the events from. +fn failure_text(error: &ControlError) -> &str { + match error { + ControlError::Invalid(message) => message, + _ => "the events to forward can't be read from the control database", + } +} diff --git a/crates/sqlbuild-orchestration/src/webhooks/models.rs b/crates/sqlbuild-orchestration/src/webhooks/models.rs index d71271a5c3..dc29de5ffc 100644 --- a/crates/sqlbuild-orchestration/src/webhooks/models.rs +++ b/crates/sqlbuild-orchestration/src/webhooks/models.rs @@ -23,6 +23,14 @@ impl WebhookSource { Self::SecurityAudit => "Security audit", } } + + /// Its health component's name, such as `Platform event forwarding`. + pub(crate) const fn forwarding(self) -> &'static str { + match self { + Self::Platform => "Platform event forwarding", + Self::SecurityAudit => "Security audit event forwarding", + } + } } /// Neither errors nor Debug may expose an operator endpoint containing credentials. diff --git a/crates/sqlbuild-orchestration/tests/api/denials/helpers.rs b/crates/sqlbuild-orchestration/tests/api/denials/helpers.rs index 548a653b95..a151124192 100644 --- a/crates/sqlbuild-orchestration/tests/api/denials/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/api/denials/helpers.rs @@ -7,14 +7,24 @@ use uuid::Uuid; use crate::store::main::{begin::begin, commit::commit, query::query}; use crate::store::models::{ControlStore, TransactionMode}; -/// Status, the headers that could tell cases apart, and the body with its decision ID masked. +/// Status, the headers that could tell cases apart with the per-request `x-request-id` masked, and the body with its decision ID masked. pub(crate) async fn masked(response: reqwest::Response) -> (Value, Uuid) { let status = response.status().as_u16(); + let request_id: String = response.headers()["x-request-id"] + .to_str() + .expect("request ID") + .to_owned(); let headers: Vec<(String, String)> = response .headers() .iter() .filter(|(name, _)| *name != header::DATE) - .map(|(name, value)| (name.to_string(), value.to_str().unwrap_or("").to_owned())) + .map(|(name, value)| { + let value = value + .to_str() + .unwrap_or("") + .replace(&request_id, ""); + (name.to_string(), value) + }) .collect(); let text = response.text().await.expect("denial body"); let body: Value = serde_json::from_str(&text).expect("JSON denial"); diff --git a/crates/sqlbuild-orchestration/tests/api/test_changes.rs b/crates/sqlbuild-orchestration/tests/api/test_changes.rs index 14d7d473e5..9679baee32 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_changes.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_changes.rs @@ -201,7 +201,7 @@ fn given_independent_http_observers_when_committed_state_changes_then_scoped_sse .await .expect("trigger")[0] .trigger_id; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("acquire lease") .expect("scheduler elected"); diff --git a/crates/sqlbuild-orchestration/tests/api/test_checks.rs b/crates/sqlbuild-orchestration/tests/api/test_checks.rs index c645d30808..c5a19b29d7 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_checks.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_checks.rs @@ -2,6 +2,7 @@ use reqwest::StatusCode; use serde_json::{Value, json}; +use sqlbuild_core::redaction::main::redact_error_text::redact_error_text; use uuid::Uuid; use crate::api::tests::helpers::stop_api; @@ -248,7 +249,8 @@ fn given_checks_sharing_an_audit_name_when_people_read_them_then_binding_keys_an evidence, json!({"event_id": failed_id, "binding_key": orders_key, "columns": ["amount", "is_late", "order_id"], - "rows": [[1.5, null, "o-1"], [null, true, "o-2"]], "truncated": "false"}), + "rows": [[1.5, null, "o-1"], [null, true, "o-2"]], "truncated": "false", + "execution_error": null}), "sorted keys become columns; missing keys become null cells" ); let read = latest_audit(store).await; @@ -261,6 +263,29 @@ fn given_checks_sharing_an_audit_name_when_people_read_them_then_binding_keys_an !read.to_string().contains("o-1"), "the audit never holds evidence" ); + let (_, customer_history) = get( + &client, + (&api.url, &viewer), + &format!("{base_path}/{customers_key}"), + ) + .await; + let errored_id = customer_history[0]["event_id"].as_str().expect("event"); + let (status, errored) = get( + &client, + (&api.url, &administrator), + &format!("{base_path}/{customers_key}/results/{errored_id}/evidence"), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + errored["execution_error"], + json!(redact_error_text( + data["results"][2]["execution_error"] + .as_str() + .expect("error") + )), + "an audit whose query could not run keeps the warehouse's error, behind view.evidence" + ); let (status, mismatched) = get( &client, (&api.url, &administrator), diff --git a/crates/sqlbuild-orchestration/tests/api/test_contract.rs b/crates/sqlbuild-orchestration/tests/api/test_contract.rs index 178fa78ecd..ef68abf0fb 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_contract.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_contract.rs @@ -238,7 +238,7 @@ fn given_a_real_http_server_when_locations_and_workers_report_then_scopes_retrie &request((location_id, published.snapshot_id), 1, 0, &["orders"]), ) .await; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/api/test_newer_server.rs b/crates/sqlbuild-orchestration/tests/api/test_newer_server.rs index 63a23c0a51..20f4baac73 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_newer_server.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_newer_server.rs @@ -136,7 +136,7 @@ fn given_a_newer_server_when_a_worker_fetches_its_execution_then_an_unreadable_p &request((location, publication.snapshot_id), 1, 0, &["orders"]), ) .await; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("acquire") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/api/test_person_sessions.rs b/crates/sqlbuild-orchestration/tests/api/test_person_sessions.rs index 5155b9e9d5..da828c6421 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_person_sessions.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_person_sessions.rs @@ -152,7 +152,7 @@ fn given_browser_session_roles_when_work_is_requested_then_scope_revocation_and_ request_run(store, &seed_run) .await .expect("nonempty metadata control"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("election") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/api/test_reads.rs b/crates/sqlbuild-orchestration/tests/api/test_reads.rs index e1374f9042..c9119cc476 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_reads.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_reads.rs @@ -9,10 +9,10 @@ use crate::snapshots::main::reads::list_person_snapshots::list_person_snapshots; use crate::store::errors::ControlError; use crate::store::main::{begin::begin, commit::commit, query::query}; use crate::store::models::{Parameter, TransactionMode}; -use crate::warehouse_history::main::read_person_run_events::read_person_run_events; -use crate::warehouse_history::main::read_person_run_output::read_person_run_output; -use crate::warehouse_history::main::read_person_run_statement_sql::read_person_run_statement_sql; -use crate::warehouse_history::main::read_person_run_statements::read_person_run_statements; +use crate::warehouse_history::main::runs::read_person_run_events::read_person_run_events; +use crate::warehouse_history::main::runs::read_person_run_output::read_person_run_output; +use crate::warehouse_history::main::runs::read_person_run_statement_sql::read_person_run_statement_sql; +use crate::warehouse_history::main::runs::read_person_run_statements::read_person_run_statements; use std::collections::BTreeMap; use std::time::Duration; @@ -116,7 +116,7 @@ fn given_published_locations_and_scheduled_work_when_read_through_http_then_reso publish_snapshot(store, &another_target) .await .expect("publish second target"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/api/test_types.rs b/crates/sqlbuild-orchestration/tests/api/test_types.rs index 59623dfbd3..099fad20a7 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_types.rs @@ -312,6 +312,8 @@ pub(crate) struct UiAssetTestCase { pub(crate) expected_status: u16, pub(crate) expected_body: &'static str, pub(crate) expected_cache: Option<&'static str>, + /// Whether the response carries the UI's content security policy. + pub(crate) expected_policy: bool, } pub(crate) struct UiPathTestCase { diff --git a/crates/sqlbuild-orchestration/tests/api/test_ui_assets.rs b/crates/sqlbuild-orchestration/tests/api/test_ui_assets.rs index afe9dd40f7..dcdb714def 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_ui_assets.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_ui_assets.rs @@ -34,6 +34,7 @@ fn given_embedded_ui_when_requesting_pages_assets_and_api_paths_then_only_ui_pat expected_status: 200, expected_body: "shell", expected_cache: Some("no-cache"), + expected_policy: true, }, UiAssetTestCase { description: "client route falls back to the shell", @@ -42,6 +43,7 @@ fn given_embedded_ui_when_requesting_pages_assets_and_api_paths_then_only_ui_pat expected_status: 200, expected_body: "shell", expected_cache: Some("no-cache"), + expected_policy: true, }, UiAssetTestCase { description: "hashed asset is immutable", @@ -50,6 +52,7 @@ fn given_embedded_ui_when_requesting_pages_assets_and_api_paths_then_only_ui_pat expected_status: 200, expected_body: "start()", expected_cache: Some("public, max-age=31536000, immutable"), + expected_policy: true, }, UiAssetTestCase { description: "unhashed asset revalidates", @@ -58,6 +61,7 @@ fn given_embedded_ui_when_requesting_pages_assets_and_api_paths_then_only_ui_pat expected_status: 200, expected_body: "theme()", expected_cache: Some("no-cache"), + expected_policy: true, }, UiAssetTestCase { description: "missing file is not the shell", @@ -66,22 +70,25 @@ fn given_embedded_ui_when_requesting_pages_assets_and_api_paths_then_only_ui_pat expected_status: 404, expected_body: "", expected_cache: None, + expected_policy: false, }, UiAssetTestCase { - description: "unknown API path is not the shell", + description: "unknown API path is a JSON 404, not the shell", method: reqwest::Method::GET, path: "/api/unknown", expected_status: 404, - expected_body: "", - expected_cache: None, + expected_body: r#"{"error":"no such API endpoint"}"#, + expected_cache: Some("no-store"), + expected_policy: false, }, UiAssetTestCase { - description: "bare API prefix is not the shell", + description: "bare API prefix is a JSON 404, not the shell", method: reqwest::Method::GET, path: "/api", expected_status: 404, - expected_body: "", - expected_cache: None, + expected_body: r#"{"error":"no such API endpoint"}"#, + expected_cache: Some("no-store"), + expected_policy: false, }, UiAssetTestCase { description: "unknown auth path is not the shell", @@ -90,6 +97,7 @@ fn given_embedded_ui_when_requesting_pages_assets_and_api_paths_then_only_ui_pat expected_status: 404, expected_body: "", expected_cache: None, + expected_policy: false, }, UiAssetTestCase { description: "writes never reach the shell", @@ -98,6 +106,7 @@ fn given_embedded_ui_when_requesting_pages_assets_and_api_paths_then_only_ui_pat expected_status: 404, expected_body: "", expected_cache: None, + expected_policy: false, }, UiAssetTestCase { description: "API routes keep precedence", @@ -106,6 +115,7 @@ fn given_embedded_ui_when_requesting_pages_assets_and_api_paths_then_only_ui_pat expected_status: 200, expected_body: "api", expected_cache: None, + expected_policy: false, }, ]; run(async { @@ -145,7 +155,7 @@ fn given_embedded_ui_when_requesting_pages_assets_and_api_paths_then_only_ui_pat ); assert_eq!( header("content-security-policy").is_some(), - test_case.expected_cache.is_some(), + test_case.expected_policy, "{}", test_case.description ); @@ -178,7 +188,7 @@ fn given_embedded_ui_when_paths_carry_dot_segments_encodings_or_extra_slashes_th description: "parent segment after the API prefix", path: "/api/../theme.js", expected_status: 404, - expected_body: "", + expected_body: r#"{"error":"no such API endpoint"}"#, }, UiPathTestCase { description: "parent segment inside a client route", @@ -256,13 +266,13 @@ fn given_embedded_ui_when_paths_carry_dot_segments_encodings_or_extra_slashes_th description: "bare API prefix", path: "/api", expected_status: 404, - expected_body: "", + expected_body: r#"{"error":"no such API endpoint"}"#, }, UiPathTestCase { description: "API prefix with a trailing slash", path: "/api/", expected_status: 404, - expected_body: "", + expected_body: r#"{"error":"no such API endpoint"}"#, }, UiPathTestCase { description: "auth prefix with a trailing slash", diff --git a/crates/sqlbuild-orchestration/tests/api/test_worker.rs b/crates/sqlbuild-orchestration/tests/api/test_worker.rs index 344524d5e8..1b0dd1dc21 100644 --- a/crates/sqlbuild-orchestration/tests/api/test_worker.rs +++ b/crates/sqlbuild-orchestration/tests/api/test_worker.rs @@ -65,7 +65,7 @@ fn given_a_claimed_run_when_a_worker_connects_then_verification_precedes_start_a &request((location, publication.snapshot_id), 1, 0, &["orders"]), ) .await; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("acquire") .expect("leader"); @@ -202,6 +202,7 @@ fn given_a_claimed_run_when_a_worker_connects_then_verification_precedes_start_a error_code: None, skipped_because_of: None, error_message: None, + phase: None, }, ) .await @@ -450,6 +451,7 @@ fn given_an_older_server_when_a_worker_reports_error_text_then_the_refusal_asks_ error_code: Some("R002".into()), skipped_because_of: None, error_message: test_case.error_message.map(str::to_owned), + phase: None, }, ) .await; @@ -578,6 +580,7 @@ fn given_a_server_older_than_node_results_when_a_worker_reports_them_then_the_re error_code: None, skipped_because_of: None, error_message: None, + phase: None, }; let test_cases = [ PreviousServerTestCase { diff --git a/crates/sqlbuild-orchestration/tests/credentials/test_contract.rs b/crates/sqlbuild-orchestration/tests/credentials/test_contract.rs index 6b0b9169c8..e8d677d117 100644 --- a/crates/sqlbuild-orchestration/tests/credentials/test_contract.rs +++ b/crates/sqlbuild-orchestration/tests/credentials/test_contract.rs @@ -308,7 +308,7 @@ fn given_scoped_tokens_when_revoked_or_the_run_ends_then_all_replicas_reject_the &request((location_id, published.snapshot_id), 1, 0, &["orders"]), ) .await; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/health/helpers.rs b/crates/sqlbuild-orchestration/tests/health/helpers.rs new file mode 100644 index 0000000000..96506327c4 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/health/helpers.rs @@ -0,0 +1,67 @@ +use crate::health::models::ControlTarget; +use crate::health::tests::test_types::CodedError; +use crate::store::errors::ControlError; + +/// The control database the tests' sentences name. +pub(crate) fn target() -> ControlTarget { + ControlTarget { + host: Some("db.internal".into()), + port: Some(5432), + user: Some("sqb".into()), + connections: 10, + wait_seconds: 30, + } +} + +pub(crate) fn coded(code: &'static str, message: &'static str) -> ControlError { + ControlError::Database(sqlx_core::Error::Database(Box::new(CodedError { + code, + message, + }))) +} + +pub(crate) fn io(kind: std::io::ErrorKind, message: &'static str) -> ControlError { + ControlError::Database(sqlx_core::Error::Io(std::io::Error::new(kind, message))) +} + +pub(crate) fn sqlite_busy() -> ControlError { + ControlError::Sqlite(rusqlite::Error::SqliteFailure( + rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_BUSY), + Some("database is locked".into()), + )) +} + +pub(crate) const DNS: &str = "Can't reach the control database: db.internal doesn't resolve (DNS)"; + +/// Record a failure to resolve the control database's host at `at`. +pub(crate) fn unresolved( + health: &crate::health::models::ServerHealth, + at: chrono::DateTime, +) { + let error = io( + std::io::ErrorKind::Other, + "failed to lookup address information: Name or service not known", + ); + let cause = crate::health::main::control_cause::control_cause(&error, (&target(), false)) + .expect("a database cause"); + health.control_failed(&cause, (at, None)); +} + +/// Two active locations: one that reported 20 seconds ago, one silent for 20 minutes. +pub(crate) fn locations( + health: &crate::health::models::ServerHealth, + at: chrono::DateTime, +) { + health.locations_seen(vec![ + crate::health::models::StoredLocationReport { + location_id: uuid::Uuid::from_u128(1), + name: "orders".into(), + last_seen_at: Some(at - chrono::TimeDelta::seconds(20)), + }, + crate::health::models::StoredLocationReport { + location_id: uuid::Uuid::from_u128(2), + name: "finance".into(), + last_seen_at: Some(at - chrono::TimeDelta::minutes(20)), + }, + ]); +} diff --git a/crates/sqlbuild-orchestration/tests/health/test_causes.rs b/crates/sqlbuild-orchestration/tests/health/test_causes.rs new file mode 100644 index 0000000000..8d0fec979b --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/health/test_causes.rs @@ -0,0 +1,66 @@ +//! A pool that waited full is exhausted; one that waited with room was trying to connect. + +use crate::health::main::control_cause::control_cause; +use crate::health::models::ControlCauseCase; +use crate::health::tests::helpers::target; +use crate::health::tests::test_types::{ForeignErrorTestCase, PoolTimeoutTestCase}; +use crate::store::errors::ControlError; + +#[test] +fn given_a_pool_timeout_when_described_then_a_full_pool_is_busy_and_a_pool_with_room_is_unreachable() + { + let test_cases = [ + PoolTimeoutTestCase { + description: "every connection was busy", + pool_full: true, + expected_cause: Some(( + ControlCauseCase::PoolExhausted, + "All 10 control database connections were busy for 30 s", + true, + )), + }, + PoolTimeoutTestCase { + description: "the pool had room, so it was connecting", + pool_full: false, + expected_cause: Some(( + ControlCauseCase::Unreachable, + "Can't reach the control database at db.internal:5432", + true, + )), + }, + ]; + for test_case in test_cases { + let described = control_cause( + &ControlError::Database(sqlx_core::Error::PoolTimedOut), + (&target(), test_case.pool_full), + ) + .map(|cause| (cause.case, cause.message, cause.transient)); + assert_eq!( + described, + test_case.expected_cause.map(|(case, message, transient)| ( + case, + message.to_owned(), + transient + )), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_an_error_that_is_not_the_databases_when_described_then_it_has_no_cause() { + let test_cases = [ForeignErrorTestCase { + description: "a refused request", + error: || ControlError::Invalid("bad request".into()), + expected_cause: None, + }]; + for test_case in test_cases { + assert_eq!( + control_cause(&(test_case.error)(), (&target(), false)).map(|cause| cause.case), + test_case.expected_cause, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-orchestration/tests/health/test_contracts.rs b/crates/sqlbuild-orchestration/tests/health/test_contracts.rs new file mode 100644 index 0000000000..7801a4e44f --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/health/test_contracts.rs @@ -0,0 +1,12 @@ +#[path = "helpers.rs"] +pub(crate) mod helpers; +#[path = "test_causes.rs"] +mod test_causes; +#[path = "test_forwarding.rs"] +mod test_forwarding; +#[path = "test_report.rs"] +mod test_report; +#[path = "test_responses.rs"] +mod test_responses; +#[path = "test_types.rs"] +pub(crate) mod test_types; diff --git a/crates/sqlbuild-orchestration/tests/health/test_forwarding.rs b/crates/sqlbuild-orchestration/tests/health/test_forwarding.rs new file mode 100644 index 0000000000..4c5192e597 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/health/test_forwarding.rs @@ -0,0 +1,54 @@ +//! A webhook that can't deliver degrades the server from its first failure, with why; a delivery clears it. + +use chrono::{DateTime, TimeDelta, Utc}; + +use crate::health::main::health_report::health_report; +use crate::health::models::{HealthComponent, HealthStatus, ServerHealth}; +use crate::health::tests::test_types::ForwardingTestCase; + +#[test] +fn given_webhook_outcomes_when_reporting_health_then_failing_forwarding_degrades_the_server() { + const NAME: &str = "Platform event forwarding"; + const REASON: &str = "Can't deliver platform events: the webhook answered HTTP 503"; + let test_cases = [ + ForwardingTestCase { + description: "two failures after a delivery", + outcomes: vec![(0, true), (5, false), (10, false)], + expected_state: (HealthStatus::Degraded, Some(5), Some(REASON)), + }, + ForwardingTestCase { + description: "a delivery after the failures", + outcomes: vec![(5, false), (10, true)], + expected_state: (HealthStatus::Healthy, Some(10), None), + }, + ]; + let start: DateTime = "2026-11-25T17:42:00Z".parse().expect("time"); + for test_case in test_cases { + let health = ServerHealth::new("1.0.0", false); + health.control_succeeded(start); + for (seconds, delivered) in &test_case.outcomes { + let at = start + TimeDelta::seconds(*seconds); + let outcomes: [fn(&ServerHealth, DateTime); 2] = [ + |health, at| health.forwarding_succeeded(NAME, at), + |health, at| health.forwarding_failed(NAME, (REASON, at)), + ]; + outcomes[usize::from(!*delivered)](&health, at); + } + let report = health_report(&health, start + TimeDelta::seconds(20)); + let forwarding = report + .components + .iter() + .find(|component| component.component == HealthComponent::EventForwarding) + .expect("a forwarding row"); + assert_eq!( + ( + report.status, + forwarding.since.map(|since| (since - start).num_seconds()), + forwarding.reason.as_deref(), + ), + test_case.expected_state, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-orchestration/tests/health/test_report.rs b/crates/sqlbuild-orchestration/tests/health/test_report.rs new file mode 100644 index 0000000000..af740e1165 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/health/test_report.rs @@ -0,0 +1,139 @@ +//! The control database decides unavailable, any other part degraded, and a success after a failure clears it. + +use chrono::{DateTime, TimeDelta, Utc}; + +use crate::health::main::health_report::health_report; +use crate::health::models::{HealthStatus, ServerHealth}; +use crate::health::tests::helpers::{DNS, locations, unresolved}; +use crate::health::tests::test_types::{FailingStreakTestCase, ReportTestCase}; + +#[test] +fn given_component_events_when_reporting_health_then_the_worst_component_decides() { + let test_cases = [ + ReportTestCase { + description: "before the control database is reached", + events: |_, _| {}, + expected_status: HealthStatus::Unavailable, + expected_components: vec![ + ("Server", HealthStatus::Healthy, None), + ( + "Control database", + HealthStatus::Unavailable, + Some("Connecting to the control database"), + ), + ("Scheduler", HealthStatus::Degraded, Some("Starting")), + ], + }, + ReportTestCase { + description: "everything working", + events: |health, at| { + health.control_succeeded(at); + health.scheduler_succeeded(at); + }, + expected_status: HealthStatus::Healthy, + expected_components: vec![ + ("Server", HealthStatus::Healthy, None), + ("Control database", HealthStatus::Healthy, None), + ("Scheduler", HealthStatus::Healthy, None), + ], + }, + ReportTestCase { + description: "the control database host stops resolving", + events: |health, at| { + health.control_succeeded(at - TimeDelta::minutes(5)); + health.scheduler_succeeded(at - TimeDelta::minutes(5)); + unresolved(health, at); + health.scheduler_failed("Waiting for the control database", (at, None)); + }, + expected_status: HealthStatus::Unavailable, + expected_components: vec![ + ("Server", HealthStatus::Healthy, None), + ("Control database", HealthStatus::Unavailable, Some(DNS)), + ( + "Scheduler", + HealthStatus::Degraded, + Some("Waiting for the control database"), + ), + ], + }, + ReportTestCase { + description: "the control database recovers", + events: |health, at| { + unresolved(health, at - TimeDelta::minutes(1)); + health.control_succeeded(at); + health.scheduler_succeeded(at); + }, + expected_status: HealthStatus::Healthy, + expected_components: vec![ + ("Server", HealthStatus::Healthy, None), + ("Control database", HealthStatus::Healthy, None), + ("Scheduler", HealthStatus::Healthy, None), + ], + }, + ReportTestCase { + description: "a location that stopped reporting", + events: |health, at| { + health.control_succeeded(at); + health.scheduler_succeeded(at); + locations(health, at); + }, + expected_status: HealthStatus::Degraded, + expected_components: vec![ + ("Server", HealthStatus::Healthy, None), + ("Control database", HealthStatus::Healthy, None), + ("Scheduler", HealthStatus::Healthy, None), + ("orders", HealthStatus::Healthy, None), + ( + "finance", + HealthStatus::Degraded, + Some("Hasn't reported since 2026-11-25 13:45 UTC"), + ), + ], + }, + ]; + let at: DateTime = "2026-11-25T14:05:00Z".parse().expect("time"); + for test_case in test_cases { + let health = ServerHealth::new("1.0.0", true); + (test_case.events)(&health, at); + let report = health_report(&health, at); + let components: Vec<(String, HealthStatus, Option)> = report + .components + .into_iter() + .map(|component| (component.name, component.status, component.reason)) + .collect(); + let expected: Vec<(String, HealthStatus, Option)> = test_case + .expected_components + .into_iter() + .map(|(name, status, reason)| (name.to_owned(), status, reason.map(str::to_owned))) + .collect(); + assert_eq!( + (report.status, components), + (test_case.expected_status, expected), + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_failing_database_when_it_keeps_failing_then_since_stays_at_the_first_failure() { + let test_cases = [FailingStreakTestCase { + description: "half an hour of failures since the first", + failures_after: vec![0, 30], + expected_since_minutes: 0, + }]; + let first: DateTime = "2026-11-25T14:05:00Z".parse().expect("time"); + for test_case in test_cases { + let health = ServerHealth::new("1.0.0", false); + health.control_succeeded(first - TimeDelta::minutes(1)); + for minutes in &test_case.failures_after { + unresolved(&health, first + TimeDelta::minutes(*minutes)); + } + assert_eq!( + health.control_failing_since(), + Some(first + TimeDelta::minutes(test_case.expected_since_minutes)), + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-orchestration/tests/health/test_responses.rs b/crates/sqlbuild-orchestration/tests/health/test_responses.rs new file mode 100644 index 0000000000..eeffa92a87 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/health/test_responses.rs @@ -0,0 +1,197 @@ +//! Each control database failure reaches the API by its own sentence, case, since and request ID; health records it. + +use axum::routing::get; +use axum::{Router, middleware}; +use tower::ServiceExt; + +use crate::api::_helpers::resources::request_ids::identify_request; +use crate::api::errors::ApiError; +use crate::health::_helpers::details::health_details; +use crate::health::models::{ControlCauseCase, ServerHealth}; +use crate::health::tests::helpers::{coded, io, sqlite_busy, target}; +use crate::health::tests::test_types::CauseResponseTestCase; +use crate::store::errors::ControlError; +use crate::store::tests::store_helpers::run; + +#[test] +fn given_each_control_database_failure_when_a_request_meets_it_then_the_response_names_its_cause() { + let test_cases = [ + CauseResponseTestCase { + description: "a host name that doesn't resolve", + error: || { + io( + std::io::ErrorKind::Other, + "failed to lookup address information: Temporary failure in name resolution", + ) + }, + expected_status: 503, + expected_message: "Can't reach the control database: db.internal doesn't resolve (DNS)", + expected_case: Some(ControlCauseCase::NameLookup), + expected_unavailable: true, + }, + CauseResponseTestCase { + description: "a refused connection", + error: || { + io( + std::io::ErrorKind::ConnectionRefused, + "Connection refused (os error 111)", + ) + }, + expected_status: 503, + expected_message: "Can't reach the control database at db.internal:5432", + expected_case: Some(ControlCauseCase::Unreachable), + expected_unavailable: true, + }, + CauseResponseTestCase { + description: "a timed-out connection", + error: || io(std::io::ErrorKind::TimedOut, "connection timed out"), + expected_status: 503, + expected_message: "Can't reach the control database at db.internal:5432", + expected_case: Some(ControlCauseCase::Unreachable), + expected_unavailable: true, + }, + CauseResponseTestCase { + description: "a pool wait that ran out while connecting", + error: || ControlError::Database(sqlx_core::Error::PoolTimedOut), + expected_status: 503, + expected_message: "Can't reach the control database at db.internal:5432", + expected_case: Some(ControlCauseCase::Unreachable), + expected_unavailable: true, + }, + CauseResponseTestCase { + description: "a rejected login", + error: || coded("28P01", "password authentication failed for user \"sqb\""), + expected_status: 503, + expected_message: "The control database rejected the login for sqb", + expected_case: Some(ControlCauseCase::LoginRejected), + expected_unavailable: true, + }, + CauseResponseTestCase { + description: "too many connections", + error: || coded("53300", "sorry, too many clients already"), + expected_status: 503, + expected_message: "The control database has no free connections", + expected_case: Some(ControlCauseCase::NoFreeConnections), + expected_unavailable: true, + }, + CauseResponseTestCase { + description: "a database shutting down", + error: || { + coded( + "57P01", + "terminating connection due to administrator command", + ) + }, + expected_status: 503, + expected_message: "The control database is restarting", + expected_case: Some(ControlCauseCase::Restarting), + expected_unavailable: true, + }, + CauseResponseTestCase { + description: "a database starting up", + error: || coded("57P03", "the database system is starting up"), + expected_status: 503, + expected_message: "The control database is restarting", + expected_case: Some(ControlCauseCase::Restarting), + expected_unavailable: true, + }, + CauseResponseTestCase { + description: "a locked SQLite database", + error: sqlite_busy, + expected_status: 503, + expected_message: "The control database is locked by another process", + expected_case: Some(ControlCauseCase::Locked), + expected_unavailable: true, + }, + CauseResponseTestCase { + description: "any other database error keeps its old response, without the database's message", + error: || { + coded( + "XX001", + "could not read block 7 in file \"base/16384/2619\"", + ) + }, + expected_status: 500, + expected_message: "control-store operation failed", + expected_case: None, + expected_unavailable: false, + }, + CauseResponseTestCase { + description: "an unknown transient error keeps its own message", + error: || ControlError::Database(sqlx_core::Error::WorkerCrashed), + expected_status: 503, + expected_message: "Control database error: attempted to communicate with a crashed background worker", + expected_case: Some(ControlCauseCase::Other), + expected_unavailable: true, + }, + ]; + run(async { + for test_case in test_cases { + let health = ServerHealth::new("1.0.0", false); + health.set_target(target()); + let error = test_case.error; + let application = Router::new() + .route( + "/api/thing", + get(move || async move { Err::<(), ApiError>(error().into()) }), + ) + .layer(middleware::from_fn_with_state( + health.clone(), + identify_request, + )); + let response = application + .oneshot( + axum::http::Request::get("/api/thing") + .body(axum::body::Body::empty()) + .expect("request"), + ) + .await + .expect("response"); + let status = response.status().as_u16(); + let request_id = response + .headers() + .get("x-request-id") + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .expect("body"); + let body: serde_json::Value = serde_json::from_slice(&bytes).expect("JSON body"); + let failing_since = health + .control_failing_since() + .map(|since| serde_json::json!(since)); + let recorded_requests = health_details(&health).components[0] + .request_ids + .iter() + .map(ToString::to_string) + .collect::>(); + assert_eq!( + ( + status, + body["error"].clone(), + body["cause"]["case"].clone(), + body["cause"]["since"].is_string(), + body["request_id"].as_str().map(str::to_owned), + failing_since.is_some(), + failing_since + .clone() + .unwrap_or_else(|| body["cause"]["since"].clone()) + == body["cause"]["since"], + recorded_requests.len() == usize::from(test_case.expected_unavailable), + ), + ( + test_case.expected_status, + serde_json::json!(test_case.expected_message), + serde_json::json!(test_case.expected_case), + test_case.expected_unavailable, + request_id.filter(|_| test_case.expected_unavailable), + test_case.expected_unavailable, + true, + true, + ), + "{}", + test_case.description + ); + } + }); +} diff --git a/crates/sqlbuild-orchestration/tests/health/test_types.rs b/crates/sqlbuild-orchestration/tests/health/test_types.rs new file mode 100644 index 0000000000..7c3eaf31c2 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/health/test_types.rs @@ -0,0 +1,90 @@ +use std::borrow::Cow; + +use crate::health::models::{ControlCauseCase, HealthStatus}; +use crate::store::errors::ControlError; + +pub(crate) struct CauseResponseTestCase { + pub(crate) description: &'static str, + pub(crate) error: fn() -> ControlError, + pub(crate) expected_status: u16, + pub(crate) expected_message: &'static str, + pub(crate) expected_case: Option, + /// Whether the server's health turns unavailable with it. + pub(crate) expected_unavailable: bool, +} + +pub(crate) struct ReportTestCase { + pub(crate) description: &'static str, + pub(crate) events: fn(&crate::health::models::ServerHealth, chrono::DateTime), + pub(crate) expected_status: HealthStatus, + /// Each component's name, status and reason. + pub(crate) expected_components: Vec<(&'static str, HealthStatus, Option<&'static str>)>, +} + +/// A database error with a SQLSTATE, as PostgreSQL returns one. +#[derive(Debug)] +pub(crate) struct CodedError { + pub(crate) code: &'static str, + pub(crate) message: &'static str, +} + +impl std::fmt::Display for CodedError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(self.message) + } +} + +impl std::error::Error for CodedError {} + +impl sqlx_core::error::DatabaseError for CodedError { + fn message(&self) -> &str { + self.message + } + + fn code(&self) -> Option> { + Some(Cow::Borrowed(self.code)) + } + + fn as_error(&self) -> &(dyn std::error::Error + Send + Sync + 'static) { + self + } + + fn as_error_mut(&mut self) -> &mut (dyn std::error::Error + Send + Sync + 'static) { + self + } + + fn into_error(self: Box) -> Box { + self + } + + fn kind(&self) -> sqlx_core::error::ErrorKind { + sqlx_core::error::ErrorKind::Other + } +} + +pub(crate) struct PoolTimeoutTestCase { + pub(crate) description: &'static str, + pub(crate) pool_full: bool, + pub(crate) expected_cause: Option<(ControlCauseCase, &'static str, bool)>, +} + +pub(crate) struct ForeignErrorTestCase { + pub(crate) description: &'static str, + pub(crate) error: fn() -> ControlError, + pub(crate) expected_cause: Option, +} + +pub(crate) struct FailingStreakTestCase { + pub(crate) description: &'static str, + /// Minutes after the first failure at which the database fails again. + pub(crate) failures_after: Vec, + pub(crate) expected_since_minutes: i64, +} + +pub(crate) struct ForwardingTestCase { + pub(crate) description: &'static str, + /// Each delivery attempt: seconds after the start, and whether it delivered. + pub(crate) outcomes: Vec<(i64, bool)>, + /// The server's status, the forwarding row's since in seconds after the start, and its reason. + pub(crate) expected_state: (HealthStatus, Option, Option<&'static str>), +} diff --git a/crates/sqlbuild-orchestration/tests/platform/helpers.rs b/crates/sqlbuild-orchestration/tests/platform/helpers.rs index 1cf689184c..245a441527 100644 --- a/crates/sqlbuild-orchestration/tests/platform/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/platform/helpers.rs @@ -183,7 +183,7 @@ pub(crate) async fn publish_platform_impostor(store: &ControlStore, identity: (U let mut requested = request(identity, 42, 0, &["orders"]); requested.image_id = None; queue(store, &requested).await; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -348,3 +348,122 @@ pub(crate) const fn secrets(_generation: i64) -> LocationHealth { providers: Vec::new(), } } + +pub(crate) const UNREACHED: &str = + "250001 Could not connect to Snowflake backend after 2 attempt(s)"; + +pub(crate) fn at(minutes: i64) -> chrono::DateTime { + "2026-11-25T18:29:00Z" + .parse::>() + .expect("time") + + TimeDelta::minutes(minutes) +} + +/// A sync report received at `minutes`, failed by `failure` with `read`, stopped or not. +pub(crate) fn sync( + minutes: i64, + failure: Option, + (read, halted): (Option, bool), +) -> crate::platform::models::LocationHealthObservation { + crate::platform::models::LocationHealthObservation { + received_at: at(minutes), + report: LocationHealthReport { + event_id: uuid::Uuid::now_v7(), + session_id: uuid::Uuid::nil(), + target: "prod".into(), + health: crate::platform::models::LocationHealth::WarehouseSync { + generation: 1, + location: crate::warehouse_metadata::models::WarehouseStateLocation { + database: None, + schema: "ops".into(), + }, + table: crate::warehouse_metadata::models::WarehouseHistoryKind::ALL[0], + failure, + records_sent: 0, + elapsed_millis: 10, + error: read.map(|_| UNREACHED.to_owned()), + read_failure: read, + page_limit: None, + progress: Some(crate::platform::models::WarehouseSyncProgress { + position: 1, + kinds: 14, + rows: 0, + elapsed_millis: 10, + completed: false, + halted, + }), + next_sync_at: None, + mirrored_records: None, + failing_since: failure.map(|_| at(0)), + retry_at: (failure.is_some() && !halted).then(|| at(minutes + 1)), + retry_seconds: (failure.is_some() && !halted).then_some(60), + }, + }, + } +} + +/// The problem a failing sync of `orders` makes, stopped or not, reaching the warehouse or not. +pub(crate) fn failing_sync_of( + halted: bool, + unreachable: bool, +) -> crate::platform::models::FailingSync { + crate::platform::models::FailingSync { + location_id: uuid::Uuid::nil(), + location_name: "orders".into(), + target: "prod".into(), + since: at(0), + reason: UNREACHED.into(), + unreachable, + halted, + retry_at: (!halted).then(|| at(4)), + retry_seconds: (!halted).then_some(60), + last_success_at: Some(at(-30)), + } +} + +/// A sink that accepted, dropped and failed the given numbers of events. +pub(crate) fn delivered( + name: &str, + (accepted, dropped, failed): (u64, u64, u64), +) -> crate::runs::models::SinkDelivery { + crate::runs::models::SinkDelivery { + name: name.into(), + accepted, + delivered: accepted - dropped - failed, + dropped, + failed, + } +} + +/// A run's sink report at `minutes`, from the `orders` location's `prod` target. +pub(crate) fn report( + minutes: i64, + sinks: Vec, + teardown_failures: Vec, +) -> crate::platform::models::SinkReport { + crate::platform::models::SinkReport { + location_id: uuid::Uuid::nil(), + location_name: "orders".into(), + target: "prod".into(), + run_id: Some(uuid::Uuid::from_u128( + u128::try_from(minutes).unwrap_or_default(), + )), + at: at(minutes), + sinks, + teardown_failures, + } +} + +/// The problem `sink` of the newest report, at minute 3, makes for `reason`. +pub(crate) fn failing_sink_of(sink: &str, reason: &str) -> crate::platform::models::FailingSink { + crate::platform::models::FailingSink { + location_id: uuid::Uuid::nil(), + location_name: "orders".into(), + target: "prod".into(), + sink: sink.into(), + since: at(3), + reason: reason.into(), + run_id: Some(uuid::Uuid::from_u128(3)), + last_success_at: None, + } +} diff --git a/crates/sqlbuild-orchestration/tests/platform/test_contracts.rs b/crates/sqlbuild-orchestration/tests/platform/test_contracts.rs index e4d424b344..14e6f1d9ef 100644 --- a/crates/sqlbuild-orchestration/tests/platform/test_contracts.rs +++ b/crates/sqlbuild-orchestration/tests/platform/test_contracts.rs @@ -6,6 +6,10 @@ mod helpers; mod test_compile_failure; #[path = "test_failing_locations.rs"] mod test_failing_locations; +#[path = "test_failing_sinks.rs"] +mod test_failing_sinks; +#[path = "test_failing_syncs.rs"] +mod test_failing_syncs; #[path = "test_installation.rs"] mod test_installation; #[path = "test_location_state.rs"] diff --git a/crates/sqlbuild-orchestration/tests/platform/test_failing_sinks.rs b/crates/sqlbuild-orchestration/tests/platform/test_failing_sinks.rs new file mode 100644 index 0000000000..9094cb0916 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/platform/test_failing_sinks.rs @@ -0,0 +1,200 @@ +//! A sink is failing while its newest run lost events, since the first lossy run in a row; a clean run clears it. + +use uuid::Uuid; + +use crate::credentials::tests::location_helpers::create_location; +use crate::platform::_helpers::health::failing_sinks::{failing_sinks, sink_reports}; +use crate::platform::main::health::report_location_health::report_location_health; +use crate::platform::models::FailingSink; +use crate::platform::models::{LocationHealth, LocationHealthReport}; +use crate::platform::tests::helpers::{delivered, failing_sink_of, report}; +use crate::platform::tests::test_types::{ + FailingSinkTestCase, LocationSinkTestCase, StoredSinkTestCase, +}; +use crate::run_output::tests::helpers::claimed_run; +use crate::runs::main::execution::change_run::change_run; +use crate::runs::models::{RunAuthority, RunChange, RunChangeRequest}; +use crate::store::main::begin::begin; +use crate::store::main::commit::commit; +use crate::store::main::migrate_store::migrate_store; +use crate::store::models::TransactionMode; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; + +#[test] +fn given_sink_reports_when_scanning_then_a_sink_fails_from_its_first_lossy_run_in_a_row() { + let test_cases = [ + FailingSinkTestCase { + description: "two lossy runs after a clean one, newest first", + reports: vec![ + report(3, vec![delivered("kafka", (8, 0, 8))], vec![]), + report(2, vec![delivered("kafka", (5, 1, 0))], vec![]), + report(1, vec![delivered("kafka", (4, 0, 0))], vec![]), + ], + expected_sinks: vec![FailingSink { + since: crate::platform::tests::helpers::at(2), + last_success_at: Some(crate::platform::tests::helpers::at(1)), + ..failing_sink_of("kafka", "8 of 8 events not delivered (8 failed)") + }], + }, + FailingSinkTestCase { + description: "a clean newest run clears it", + reports: vec![ + report(3, vec![delivered("kafka", (8, 0, 0))], vec![]), + report(2, vec![delivered("kafka", (8, 0, 8))], vec![]), + ], + expected_sinks: vec![], + }, + FailingSinkTestCase { + description: "a provider whose teardown failed may have lost what it held", + reports: vec![report( + 3, + vec![delivered("kafka", (8, 0, 0))], + vec!["'kafka' (KafkaProducer) raised KafkaException".into()], + )], + expected_sinks: vec![failing_sink_of( + "sink providers", + "closing failed, so events they held may be lost: 'kafka' (KafkaProducer) raised KafkaException", + )], + }, + ]; + for test_case in test_cases { + assert_eq!( + failing_sinks(&test_case.reports), + test_case.expected_sinks, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_run_whose_sink_failed_when_the_store_is_scanned_then_the_sink_is_failing() { + let test_cases = [ + StoredSinkTestCase { + description: "SQLite", + backend: Backend::Sqlite, + expected_sinks: vec![( + "kafka".into(), + "8 of 8 events not delivered (8 failed)".into(), + )], + }, + StoredSinkTestCase { + description: "PostgreSQL", + backend: Backend::Postgres, + expected_sinks: vec![( + "kafka".into(), + "8 of 8 events not delivered (8 failed)".into(), + )], + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + let (_, claim) = claimed_run(store).await; + for change in [ + RunChange::Started, + RunChange::SinkDeliveries { + sinks: vec![delivered("kafka", (8, 0, 8))], + teardown_failures: vec![], + }, + ] { + change_run( + store, + RunAuthority::Worker { + run_id: claim.request.run_id, + claim_id: claim.claim_id, + }, + &RunChangeRequest { + event_id: Uuid::now_v7(), + run_id: claim.request.run_id, + claim_id: Some(claim.claim_id), + change, + }, + ) + .await + .expect("worker fact"); + } + let transaction = begin(store, TransactionMode::Read).await.expect("read"); + let (transaction, reports) = sink_reports(transaction).await.expect("sink reports"); + commit(transaction).await.expect("commit"); + let failing: Vec<(String, String)> = failing_sinks(&reports) + .into_iter() + .map(|sink| (sink.sink, sink.reason)) + .collect(); + assert_eq!( + failing, test_case.expected_sinks, + "{}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} + +#[test] +fn given_a_locations_sink_intervals_when_the_store_is_scanned_then_its_newest_interval_decides() { + let test_cases = [ + LocationSinkTestCase { + description: "SQLite: a clean interval, then one that lost every event", + backend: Backend::Sqlite, + intervals: vec![(4, 0, 0), (116, 0, 116)], + expected_sinks: vec![( + "kafka".into(), + "116 of 116 events not delivered (116 failed)".into(), + None, + )], + }, + LocationSinkTestCase { + description: "PostgreSQL: a lossy interval cleared by a clean one", + backend: Backend::Postgres, + intervals: vec![(116, 0, 116), (4, 0, 0)], + expected_sinks: vec![], + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let location = create_location(store, "orders", "test-admin") + .await + .expect("location"); + let session_id = Uuid::now_v7(); + for interval in &test_case.intervals { + report_location_health( + store, + location, + &LocationHealthReport { + event_id: Uuid::now_v7(), + session_id, + target: "development".into(), + health: LocationHealth::SinkDeliveries { + sinks: vec![delivered("kafka", (interval.0, interval.1, interval.2))], + }, + }, + ) + .await + .expect("report"); + } + let transaction = begin(store, TransactionMode::Read).await.expect("read"); + let (transaction, reports) = sink_reports(transaction).await.expect("sink reports"); + commit(transaction).await.expect("commit"); + let failing: Vec<(String, String, Option)> = failing_sinks(&reports) + .into_iter() + .map(|sink| (sink.sink, sink.reason, sink.run_id)) + .collect(); + assert_eq!( + failing, test_case.expected_sinks, + "{}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/platform/test_failing_syncs.rs b/crates/sqlbuild-orchestration/tests/platform/test_failing_syncs.rs new file mode 100644 index 0000000000..8977a9b3cb --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/platform/test_failing_syncs.rs @@ -0,0 +1,57 @@ +//! A run-history sync is a problem while its newest report fails, since its first failure in a row; a success clears it. + +use uuid::Uuid; + +use crate::platform::_helpers::health::failing_syncs::failing_sync; +use crate::platform::models::{FailingSync, WarehouseReadFailure, WarehouseSyncFailure}; +use crate::platform::tests::helpers::{failing_sync_of, sync}; +use crate::platform::tests::test_types::FailingSyncTestCase; + +#[test] +fn given_sync_reports_when_scanning_then_only_a_failing_newest_report_is_a_problem() { + let unreached = Some(WarehouseReadFailure::Unreachable {}); + let read = Some(WarehouseSyncFailure::Read); + let test_cases = [ + FailingSyncTestCase { + description: "reads that never reach the warehouse, newest first, after a success", + observations: vec![ + sync(3, read, (unreached, false)), + sync(1, read, (unreached, false)), + sync(-30, None, (None, false)), + ], + expected_sync: Some(failing_sync_of(false, true)), + }, + FailingSyncTestCase { + description: "failed reads stopped the sync, so it tries again only when resumed", + observations: vec![ + sync(3, read, (Some(WarehouseReadFailure::ReadError {}), true)), + sync(-30, None, (None, false)), + ], + expected_sync: Some(FailingSync { + retry_at: None, + ..failing_sync_of(true, false) + }), + }, + FailingSyncTestCase { + description: "a newer success clears it", + observations: vec![ + sync(5, None, (None, false)), + sync(3, read, (unreached, false)), + ], + expected_sync: None, + }, + FailingSyncTestCase { + description: "waiting for a build that holds the warehouse file is no failure", + observations: vec![sync(3, Some(WarehouseSyncFailure::Busy), (None, false))], + expected_sync: None, + }, + ]; + for test_case in test_cases { + assert_eq!( + failing_sync(&test_case.observations, (Uuid::nil(), "orders", "prod")), + test_case.expected_sync, + "{}", + test_case.description + ); + } +} diff --git a/crates/sqlbuild-orchestration/tests/platform/test_problems.rs b/crates/sqlbuild-orchestration/tests/platform/test_problems.rs index 9b9dbce5a3..9131f2fb8d 100644 --- a/crates/sqlbuild-orchestration/tests/platform/test_problems.rs +++ b/crates/sqlbuild-orchestration/tests/platform/test_problems.rs @@ -114,7 +114,7 @@ fn given_broken_locations_and_late_ticks_when_people_read_problems_then_only_lis .await .expect("developer on inventory only"); for _ in 0..test_case.leaders { - acquire_lease(store, Uuid::now_v7()) + acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("acquire lease") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/platform/test_types.rs b/crates/sqlbuild-orchestration/tests/platform/test_types.rs index 496cebf9b4..b635725ee3 100644 --- a/crates/sqlbuild-orchestration/tests/platform/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/platform/test_types.rs @@ -121,3 +121,33 @@ pub(crate) struct FailingLocationTestCase { pub(crate) backend: crate::store::tests::store_test_types::Backend, pub(crate) expected_error: &'static str, } + +pub(crate) struct FailingSyncTestCase { + pub(crate) description: &'static str, + /// Newest first, as `recent_health` returns them. + pub(crate) observations: Vec, + pub(crate) expected_sync: Option, +} + +pub(crate) struct FailingSinkTestCase { + pub(crate) description: &'static str, + /// Newest first, as the scan reads them. + pub(crate) reports: Vec, + pub(crate) expected_sinks: Vec, +} + +pub(crate) struct StoredSinkTestCase { + pub(crate) description: &'static str, + pub(crate) backend: crate::store::tests::store_test_types::Backend, + /// Each failing sink with its reason. + pub(crate) expected_sinks: Vec<(String, String)>, +} + +pub(crate) struct LocationSinkTestCase { + pub(crate) description: &'static str, + pub(crate) backend: crate::store::tests::store_test_types::Backend, + /// Each reported interval's accepted, dropped and failed events, oldest first. + pub(crate) intervals: Vec<(u64, u64, u64)>, + /// Each failing sink with its reason and run. + pub(crate) expected_sinks: Vec<(String, String, Option)>, +} diff --git a/crates/sqlbuild-orchestration/tests/platform/test_watchdog.rs b/crates/sqlbuild-orchestration/tests/platform/test_watchdog.rs index ab20eec76c..b6c8ff3cd3 100644 --- a/crates/sqlbuild-orchestration/tests/platform/test_watchdog.rs +++ b/crates/sqlbuild-orchestration/tests/platform/test_watchdog.rs @@ -91,7 +91,7 @@ fn given_two_server_replicas_when_scheduling_is_stalled_then_health_facts_are_du .await .expect("current definition"); for _ in 0..test_case.leaders { - acquire_lease(store, Uuid::now_v7()) + acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("acquire lease") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/platform/test_webhook.rs b/crates/sqlbuild-orchestration/tests/platform/test_webhook.rs index e57b7d7a5c..8ec45f4dfe 100644 --- a/crates/sqlbuild-orchestration/tests/platform/test_webhook.rs +++ b/crates/sqlbuild-orchestration/tests/platform/test_webhook.rs @@ -134,11 +134,11 @@ fn given_a_location_outage_when_webhook_delivery_retries_then_all_health_facts_s let restarted = connect_webhook(&endpoint, WebhookSource::Platform) .expect("restart webhook client"); let (sink_stop, sink_shutdown) = tokio::sync::watch::channel(false); - let sink_store = second.clone(); - let dispatcher = - tokio::spawn( - async move { run_webhook(&sink_store, restarted, sink_shutdown).await }, - ); + let dispatcher = tokio::spawn(run_webhook( + (second.clone(), None), + restarted, + sink_shutdown, + )); wait_for_webhook(&receiver, &dispatcher, test_case.expected_events + 2).await; sink_stop.send(true).expect("stop dispatcher"); tokio::time::timeout(Duration::from_secs(2), dispatcher) diff --git a/crates/sqlbuild-orchestration/tests/run_output/helpers.rs b/crates/sqlbuild-orchestration/tests/run_output/helpers.rs index cd8dea6dd0..aab11407be 100644 --- a/crates/sqlbuild-orchestration/tests/run_output/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/run_output/helpers.rs @@ -38,7 +38,7 @@ pub(crate) async fn claimed_run(store: &ControlStore) -> (Uuid, RunClaim) { &request((location, published.snapshot_id), 61, 0, &["orders"]), ) .await; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/claims/helpers.rs b/crates/sqlbuild-orchestration/tests/runs/claims/helpers.rs index 6549ca86d7..b615e27d7a 100644 --- a/crates/sqlbuild-orchestration/tests/runs/claims/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/runs/claims/helpers.rs @@ -154,6 +154,7 @@ async fn finish_reporting( error_code: None, skipped_because_of: None, error_message: None, + phase: None, }), ); changes.extend(reported); diff --git a/crates/sqlbuild-orchestration/tests/runs/failure_events/helpers.rs b/crates/sqlbuild-orchestration/tests/runs/failure_events/helpers.rs new file mode 100644 index 0000000000..2389a7ea7e --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/runs/failure_events/helpers.rs @@ -0,0 +1,156 @@ +//! A claimed run's worker reports for `run_failed` tests: node results, an end-of-build audit that can't run, links under an origin. + +use std::collections::BTreeMap; + +use serde_json::json; +use sqlbuild_recall::records::models::RecallValue; +use sqlbuild_recall::schema::models::Table; +use uuid::Uuid; + +use crate::platform::models::RunFailureEvent; +use crate::runs::main::execution::change_run_linked::change_run_linked; +use crate::runs::main::execution::publish_run_recall::publish_run_recall; +use crate::runs::models::{ + NodeOutcome, RecallBatch, RecallRecord, RunAuthority, RunChange, RunChangeRequest, RunClaim, +}; +use crate::runs::tests::test_types::{ReportedNode, RunFailureSummary}; +use crate::store::models::ControlStore; + +pub(crate) const ORIGIN: &str = "https://sqlbuild.example.com"; +pub(crate) const MISSING: &str = "002003 (42S02): SQL compilation error: Object 'SHOP.RECON.ORDER_PAYMENTS' does not exist or not authorized."; + +/// The worker reports `change` for the claimed run, linking a run failure under `ORIGIN`. +pub(crate) async fn report(store: &ControlStore, claim: &RunClaim, change: RunChange) { + change_run_linked( + store, + ( + RunAuthority::Worker { + run_id: claim.request.run_id, + claim_id: claim.claim_id, + }, + &RunChangeRequest { + event_id: Uuid::now_v7(), + run_id: claim.request.run_id, + claim_id: Some(claim.claim_id), + change, + }, + ), + Some(ORIGIN), + ) + .await + .expect("report"); +} + +pub(crate) fn finished(node_key: &str, outcome: NodeOutcome, phase: Option<&str>) -> RunChange { + RunChange::NodeFinished { + node_key: node_key.into(), + outcome, + rows_affected: None, + table_rows: None, + no_change_reason: None, + error_code: (outcome == NodeOutcome::Failed).then(|| "E100".into()), + skipped_because_of: None, + error_message: None, + phase: phase.map(str::to_owned), + } +} + +/// An error-severity end-of-build singular audit whose query could not run. +pub(crate) async fn fail_end_audit(store: &ControlStore, claim: &RunClaim, audit: &str) { + let payload = json!({"audit_name": audit, "audit_definition_name": audit, + "evaluation_mode": "violations", "outcome": "error", "severity": "error", "run_scope_phase": "final", + "attachment_kind": "end", "binding_key": format!("end.{audit}"), "executed_sql": "select 1", + "execution_error": MISSING}); + let record = RecallRecord { + table: Table::Events, + values: BTreeMap::from([ + ( + "event_id".into(), + RecallValue::Text(format!("audit-{audit}")), + ), + ( + "event_type".into(), + RecallValue::Text("audit_completed".into()), + ), + ("event_schema_version".into(), RecallValue::Integer(1)), + ("event_kind".into(), RecallValue::Text("lifecycle".into())), + ("severity".into(), RecallValue::Text("error".into())), + ("outcome".into(), RecallValue::Text("error".into())), + ( + "occurred_at".into(), + RecallValue::Text("2026-01-01T00:00:00Z".into()), + ), + ("producer".into(), RecallValue::Text("sqb".into())), + ("run_id".into(), RecallValue::Text("sqb-run".into())), + ("invocation_sequence".into(), RecallValue::Integer(0)), + ("payload".into(), RecallValue::Text(payload.to_string())), + ]), + }; + publish_run_recall( + store, + (claim.request.run_id, claim.claim_id), + &RecallBatch { + invocation_id: "execution".into(), + records: vec![record], + }, + ) + .await + .expect("publish the audit result"); +} + +/// The worker reports `nodes` finishing, then `failed_end_audits` that couldn't run, then a failed finish. +pub(crate) async fn end_run( + store: &ControlStore, + claim: &RunClaim, + (nodes, failed_end_audits): (&[ReportedNode], &[&str]), +) { + for (node, outcome, phase) in nodes { + report(store, claim, finished(node, *outcome, *phase)).await; + } + for audit in failed_end_audits { + fail_end_audit(store, claim, audit).await; + } + report( + store, + claim, + RunChange::Finished { + outcome: crate::runs::models::RunOutcome::Failed, + reason: "project could not be loaded".into(), + exit_code: Some(2), + }, + ) + .await; +} + +/// What a test compares of a `run_failed` event, with links relative to the run's own page. +pub(crate) fn summarize(failure: &RunFailureEvent) -> RunFailureSummary { + let run_url = format!("{ORIGIN}/runs/{}", failure.run_id); + let relative = |link: &Option| { + link.as_deref() + .and_then(|link| link.strip_prefix(run_url.as_str())) + .map(str::to_owned) + }; + RunFailureSummary { + links_to_run: failure.url.as_deref() == Some(run_url.as_str()), + first_node: failure.failed_nodes.first().map(|node| { + ( + node.phase.clone(), + relative(&node.url), + relative(&node.logs_url), + ) + }), + first_audit: failure.failed_audits.first().map(|audit| { + ( + audit.name.clone(), + audit.sqlstate.clone(), + audit.message.clone(), + ) + }), + failed_audit_count: failure.failed_audit_count, + succeeded_node_count: failure.succeeded_node_count, + error: failure + .error + .as_ref() + .map(|error| (error.phase, error.message.clone())), + } +} diff --git a/crates/sqlbuild-orchestration/tests/runs/helpers.rs b/crates/sqlbuild-orchestration/tests/runs/helpers.rs index 56739a87ec..f3069c814e 100644 --- a/crates/sqlbuild-orchestration/tests/runs/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/runs/helpers.rs @@ -411,7 +411,7 @@ pub(crate) async fn seed_logged_runs( scope: (Uuid, Uuid), ended_hours_ago: &[Value], ) { - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -564,3 +564,45 @@ pub(crate) async fn age_stored_requests(store: &ControlStore) { commit(transaction).await.expect("commit"); } } + +/// Set a queued run's node to `status`, as a worker's report would have left it. +pub(crate) async fn set_node_status( + store: &ControlStore, + (run_id, node_key): (Uuid, &str), + status: &str, +) { + let transaction = begin(store, TransactionMode::Write).await.expect("begin"); + let (transaction, _) = query( + transaction, + "UPDATE sqb_run_nodes SET status=$3 WHERE run_id=$1 AND node_key=$2", + vec![ + Parameter::Id(run_id), + Parameter::Text(node_key.to_owned()), + Parameter::Text(status.to_owned()), + ], + ) + .await + .expect("set the node status"); + commit(transaction).await.expect("commit"); +} + +/// Record an attached check of `run_id` that finished with `status`, as a worker's check result does. +pub(crate) async fn insert_check( + store: &ControlStore, + (run_id, node_key): (Uuid, &str), + status: &str, +) { + let transaction = begin(store, TransactionMode::Write).await.expect("begin"); + let (transaction, _) = query( + transaction, + "INSERT INTO sqb_run_nodes (run_id, node_key, status, writes, kind) VALUES ($1,$2,$3,FALSE,'check')", + vec![ + Parameter::Id(run_id), + Parameter::Text(node_key.to_owned()), + Parameter::Text(status.to_owned()), + ], + ) + .await + .expect("record the check"); + commit(transaction).await.expect("commit"); +} diff --git a/crates/sqlbuild-orchestration/tests/runs/test_adhoc.rs b/crates/sqlbuild-orchestration/tests/runs/test_adhoc.rs index b214462916..6183e2d203 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_adhoc.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_adhoc.rs @@ -4,6 +4,7 @@ use serde_json::{Value, json}; use uuid::Uuid; use crate::credentials::models::AuditContext; +use crate::runs::main::listings::list_runs::list_runs; use crate::runs::main::requests::check_adhoc_run::check_adhoc_run; use crate::runs::main::requests::request_person_run::request_person_run; use crate::runs::models::PersonRunRequest; @@ -359,6 +360,27 @@ fn given_ad_hoc_commands_when_people_check_and_launch_them_then_each_gated_flag_ vec![None, None, Some(json!("test"))], "{backend:?}: the worker receives the command, a load runs as a build, and a build request is serialized as before" ); + let listed = list_runs(store, (location_id, "development"), 100) + .await + .expect("list runs"); + let typed = [run_ids[0], run_ids[position("test")]].map(|run_id| { + listed + .iter() + .find(|run| run.run_id == run_id) + .and_then(|run| run.command.clone()) + }); + assert_eq!( + typed, + [ + Some(vec![ + "build".to_owned(), + "model:orders".to_owned(), + "source:shop.orders".to_owned() + ]), + Some(vec!["test".to_owned(), "model:orders".to_owned()]), + ], + "{backend:?}: an ad-hoc run's record carries its command as the person typed it" + ); let audit = rows( store, "SELECT after_json FROM sqb_security_audit WHERE action='run.adhoc_requested' \ diff --git a/crates/sqlbuild-orchestration/tests/runs/test_checks.rs b/crates/sqlbuild-orchestration/tests/runs/test_checks.rs index 4b093b7f3a..2f610aa175 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_checks.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_checks.rs @@ -56,6 +56,7 @@ fn given_attached_checks_when_a_claim_reports_observations_then_frozen_membershi "cancelled", "passed", "blocked", + "unread", ] { input.nodes.insert( format!("check:{name}"), @@ -88,7 +89,7 @@ fn given_attached_checks_when_a_claim_reports_observations_then_frozen_membershi .nodes .insert("check:products".into(), input.nodes["products"].clone()); let published = publish_snapshot(store, &input).await.expect("snapshot"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -217,6 +218,16 @@ fn given_attached_checks_when_a_claim_reports_observations_then_frozen_membershi ) .await .expect("blocked check was not executed"); + change_run( + store, + worker, + &report(RunChange::CheckFinished { + node_key: "check:unread".into(), + outcome: NodeOutcome::NotRun, + }), + ) + .await + .expect("a check whose reads the target lacks finishes not run, never having started"); let nodes = list_run_nodes(store, claim.request.run_id) .await .expect("frozen nodes"); @@ -238,7 +249,7 @@ fn given_attached_checks_when_a_claim_reports_observations_then_frozen_membershi .iter() .filter(|row| row["event_type"] == "run_check_finished") .count(), - 8 + 9 ); for change in [ RunChange::NodeStarted { @@ -253,6 +264,7 @@ fn given_attached_checks_when_a_claim_reports_observations_then_frozen_membershi error_code: None, skipped_because_of: None, error_message: None, + phase: None, }, RunChange::Finished { outcome: RunOutcome::Failed, diff --git a/crates/sqlbuild-orchestration/tests/runs/test_claims.rs b/crates/sqlbuild-orchestration/tests/runs/test_claims.rs index db4c844343..41df63431c 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_claims.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_claims.rs @@ -77,7 +77,7 @@ fn given_higher_priority_work_for_other_scopes_when_a_local_launcher_claims_then for input in [&wanted, &other_target, &other_location] { queue(store, input).await; } - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -187,7 +187,7 @@ fn given_overlapping_priority_queues_when_two_launchers_claim_then_conflicts_rol .await .expect("publish snapshot"); let scope = (location, published.snapshot_id); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -314,7 +314,7 @@ fn given_named_group_limits_when_capacity_is_lowered_then_active_high_slots_stil let published = publish_snapshot(store, &snapshot(location)) .await .expect("publish snapshot"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -400,7 +400,7 @@ fn given_more_than_one_page_of_blocked_runs_when_claiming_then_lower_priority_in .await .expect("snapshot"); let scope = (location, published.snapshot_id); - let elected = acquire_lease(store, Uuid::now_v7()) + let elected = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -483,7 +483,7 @@ fn given_a_blocked_multi_limit_waiter_when_younger_work_arrives_then_shared_limi .collect(); queue(store, &input).await; } - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -567,7 +567,7 @@ fn given_claimed_work_here_and_elsewhere_when_listing_the_queue_then_each_run_sh .expect("other snapshot"); let limits = BTreeMap::from([("warehouse".to_owned(), NonZeroU32::new(2).expect("limit"))]); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_coalesce.rs b/crates/sqlbuild-orchestration/tests/runs/test_coalesce.rs index 6d811497dc..0244dfb871 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_coalesce.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_coalesce.rs @@ -58,7 +58,7 @@ fn given_coalescing_triggers_when_a_previous_run_has_been_claimed_then_new_ticks .await .expect("trigger")[0] .trigger_id; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -152,7 +152,7 @@ fn given_a_skip_overlap_job_when_a_tick_falls_due_during_its_run_then_the_tick_i .await .expect("trigger")[0] .trigger_id; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_contracts.rs b/crates/sqlbuild-orchestration/tests/runs/test_contracts.rs index cf697c3970..4b6eac28b2 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_contracts.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_contracts.rs @@ -1,5 +1,7 @@ #[path = "claims/helpers.rs"] pub(crate) mod claim_helpers; +#[path = "failure_events/helpers.rs"] +pub(crate) mod failure_event_helpers; #[path = "helpers.rs"] pub(crate) mod helpers; #[path = "monitor/helpers.rs"] @@ -44,6 +46,8 @@ mod test_node_errors; mod test_node_event_resources; #[path = "test_node_results.rs"] mod test_node_results; +#[path = "test_past_runs.rs"] +mod test_past_runs; #[path = "test_permissions.rs"] mod test_permissions; #[path = "test_pinned_jobs.rs"] @@ -58,6 +62,8 @@ mod test_requests; mod test_reruns; #[path = "test_retries.rs"] mod test_retries; +#[path = "test_run_failure_event.rs"] +mod test_run_failure_event; #[path = "test_run_logs.rs"] mod test_run_logs; #[path = "test_selection.rs"] diff --git a/crates/sqlbuild-orchestration/tests/runs/test_faults.rs b/crates/sqlbuild-orchestration/tests/runs/test_faults.rs index 5cf5a3f632..47be6ed745 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_faults.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_faults.rs @@ -57,7 +57,7 @@ fn given_failures_during_claim_publication_when_retried_then_claims_slots_livene ); input.pools.insert("warehouse".into(), pool_slots(1, 100)); queue(store, &input).await; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -141,7 +141,7 @@ fn given_failures_during_claim_publication_when_retried_then_claims_slots_livene .is_none() ); expire_lease(store).await; - let next = acquire_lease(store, Uuid::now_v7()) + let next = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("take over") .expect("new leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_group_admission.rs b/crates/sqlbuild-orchestration/tests/runs/test_group_admission.rs index 207fe334a2..eb4e72d37c 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_group_admission.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_group_admission.rs @@ -101,7 +101,7 @@ fn given_mixed_physical_and_parent_waiters_when_admitting_then_priority_and_queu ) .await .expect("queue group"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -203,7 +203,7 @@ fn given_group_children_sharing_a_limit_of_one_when_claiming_then_they_run_one_a ) .await .expect("queue group"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -308,7 +308,7 @@ fn given_an_unserved_queued_group_when_dispatching_an_eligible_scope_then_unknow .await .expect("queue group"); } - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -517,7 +517,7 @@ fn given_capacity_and_multistage_cycles_when_replicas_admit_and_resume_groups_th publish_snapshot(store, &input) .await .expect("publish groups"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -703,7 +703,7 @@ fn given_an_older_blocked_allow_group_when_an_independent_generation_is_queued_t .pools .insert("orders_limit".into(), pool_slots(1, 100)); queue(store, &physical).await; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -827,7 +827,7 @@ fn given_a_large_healthy_project_with_blocked_groups_when_claiming_then_unrelate let published = publish_snapshot(store, &input) .await .expect("publish large project"); - let elected = acquire_lease(store, Uuid::now_v7()) + let elected = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_group_dependencies.rs b/crates/sqlbuild-orchestration/tests/runs/test_group_dependencies.rs index a62c083840..09d16dae8e 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_group_dependencies.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_group_dependencies.rs @@ -116,7 +116,7 @@ fn given_a_failed_member_when_its_dependents_react_then_each_dependency_policy_a ) .await .expect("request group"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -166,7 +166,7 @@ fn given_a_failed_member_when_its_dependents_react_then_each_dependency_policy_a .find(|record| record.run_id == group) .expect("group"); assert!( - matches!(parent.status, RunStatus::Failed | RunStatus::Partial), + parent.status == RunStatus::Failed, "{}: {:?}", test_case.description, parent.status diff --git a/crates/sqlbuild-orchestration/tests/runs/test_group_retries.rs b/crates/sqlbuild-orchestration/tests/runs/test_group_retries.rs index 77e4d706ca..17b83f32ca 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_group_retries.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_group_retries.rs @@ -25,7 +25,7 @@ use crate::store::main::{begin::begin, commit::commit, migrate_store::migrate_st use crate::store::models::TransactionMode; use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; use crate::store::tests::store_test_types::Backend; -use crate::warehouse_history::main::read_person_run_events::read_person_run_events; +use crate::warehouse_history::main::runs::read_person_run_events::read_person_run_events; #[test] fn given_a_member_with_retry_when_it_fails_in_a_group_then_it_retries_inside_the_group_while_dependents_wait() @@ -124,7 +124,7 @@ fn given_a_member_with_retry_when_it_fails_in_a_group_then_it_retries_inside_the ) .await .expect("request group"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_group_round_trips.rs b/crates/sqlbuild-orchestration/tests/runs/test_group_round_trips.rs index c3e544bbc1..1cf5afed40 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_group_round_trips.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_group_round_trips.rs @@ -139,7 +139,7 @@ fn given_a_round_trip_split_across_jobs_when_the_group_runs_then_members_follow_ ) .await .expect("request group"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_groups.rs b/crates/sqlbuild-orchestration/tests/runs/test_groups.rs index 6123868cf9..782d3be7f6 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_groups.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_groups.rs @@ -17,7 +17,7 @@ use crate::scheduler::tests::contracts::helpers::acquire_lease; use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; use crate::store::main::migrate_store::migrate_store; use crate::store::tests::helpers::read_recall_events; -use crate::warehouse_history::main::read_person_run_ignored_audits::read_person_run_ignored_audits; +use crate::warehouse_history::main::checks::read_person_run_ignored_audits::read_person_run_ignored_audits; use serde_json::json; use uuid::Uuid; @@ -100,7 +100,7 @@ fn given_a_pinned_group_when_redeployed_and_cancelled_then_children_keep_scope_a .await .expect("retry group") ); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -138,6 +138,7 @@ fn given_a_pinned_group_when_redeployed_and_cancelled_then_children_keep_scope_a error_code: None, skipped_because_of: None, error_message: None, + phase: None, }, RunChange::Finished { outcome: RunOutcome::Success, @@ -379,7 +380,7 @@ fn given_opposing_parent_and_child_limits_when_advancing_groups_then_both_groups .await .expect("request group"); } - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -518,7 +519,7 @@ fn given_group_members_with_different_audit_settings_when_run_then_each_keeps_it request_job_run(store, (&context, None), &request) .await .expect("request group"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_job_detail.rs b/crates/sqlbuild-orchestration/tests/runs/test_job_detail.rs index b1c3439ec7..dc2977395f 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_job_detail.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_job_detail.rs @@ -355,7 +355,7 @@ fn given_published_jobs_when_people_read_and_launch_them_then_listing_view_and_r ) .await .expect("ordinary launch"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_launch_events.rs b/crates/sqlbuild-orchestration/tests/runs/test_launch_events.rs index ac2b3a5dd2..9f7e527e47 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_launch_events.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_launch_events.rs @@ -18,7 +18,7 @@ use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; use crate::store::main::migrate_store::migrate_store; use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; use crate::store::tests::store_test_types::Backend; -use crate::warehouse_history::main::read_person_run_events::read_person_run_events; +use crate::warehouse_history::main::runs::read_person_run_events::read_person_run_events; #[test] fn given_a_launched_run_when_its_events_are_read_then_the_launch_names_a_container_or_a_local_worker() @@ -61,7 +61,7 @@ fn given_a_launched_run_when_its_events_are_read_then_the_launch_names_a_contain &request((location, published.snapshot_id), 51, 0, &["orders"]), ) .await; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_lifecycle.rs b/crates/sqlbuild-orchestration/tests/runs/test_lifecycle.rs index 81ad4c2986..ffcd9c4a49 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_lifecycle.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_lifecycle.rs @@ -1,7 +1,7 @@ use std::collections::BTreeMap; use crate::credentials::models::AuditContext; -use crate::platform::models::PlatformEvent; +use crate::platform::models::{PlatformEvent, RunFailureEvent}; use crate::runs::main::execution::change_run::change_run; use crate::runs::main::execution::claim_next_run::claim_next_run; use crate::runs::main::execution::heartbeat_run::heartbeat_run; @@ -9,7 +9,7 @@ use crate::runs::main::listings::list_run_nodes::list_run_nodes; use crate::runs::main::listings::list_runs::list_runs; use crate::runs::models::{ NodeOutcome, RunAuthority, RunChange, RunChangeRequest, RunKind, RunNodeFailure, RunOutcome, - RunStatus, + RunStatus, RunTrigger, RunTriggerKind, }; use crate::scheduler::tests::contracts::helpers::acquire_lease; use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; @@ -33,12 +33,12 @@ fn given_a_claimed_worker_when_reports_are_retried_and_fail_between_writes_then_ RunLifecycleTestCase { description: "SQLite preserves facts, outcomes and claims through worker failures", backend: Backend::Sqlite, - expected_status: RunStatus::Partial, + expected_status: RunStatus::Failed, }, RunLifecycleTestCase { description: "PostgreSQL preserves facts, outcomes and claims through worker failures", backend: Backend::Postgres, - expected_status: RunStatus::Partial, + expected_status: RunStatus::Failed, }, ]; for test_case in test_cases { @@ -55,7 +55,7 @@ fn given_a_claimed_worker_when_reports_are_retried_and_fail_between_writes_then_ .await .expect("snapshot"); let scope = (location, published.snapshot_id); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -250,6 +250,7 @@ fn given_a_claimed_worker_when_reports_are_retried_and_fail_between_writes_then_ error_code: (outcome == NodeOutcome::Failed).then(|| "E100".into()), skipped_because_of: None, error_message: None, + phase: None, }, ..started.clone() }; @@ -301,12 +302,12 @@ fn given_a_claimed_worker_when_reports_are_retried_and_fail_between_writes_then_ } assert!( change_run(store, worker, &success).await.is_err(), - "mixed node outcomes are partial, not success" + "mixed node outcomes fail the run, not succeed it" ); - let partial = RunChangeRequest { + let failed = RunChangeRequest { event_id: Uuid::now_v7(), change: RunChange::Finished { - outcome: RunOutcome::Partial, + outcome: RunOutcome::Failed, reason: "independent customer work completed".into(), exit_code: Some(1), }, @@ -330,7 +331,7 @@ fn given_a_claimed_worker_when_reports_are_retried_and_fail_between_writes_then_ }; install_fault(store, &point).await; assert!( - change_run(store, worker, &partial).await.is_err(), + change_run(store, worker, &failed).await.is_err(), "{} at {table} must roll back the complete transition", point.description ); @@ -394,16 +395,16 @@ fn given_a_claimed_worker_when_reports_are_retried_and_fail_between_writes_then_ .is_none() ); assert!( - change_run(store, worker, &partial) + change_run(store, worker, &failed) .await .expect("terminal report atomically releases claims") ); assert!( - !change_run(store, worker, &partial) + !change_run(store, worker, &failed) .await .expect("terminal retry after liveness cleanup") ); - let mut changed = partial.clone(); + let mut changed = failed.clone(); changed.change = RunChange::Finished { outcome: RunOutcome::Success, reason: "changed retry".into(), @@ -451,24 +452,89 @@ fn given_a_claimed_worker_when_reports_are_retried_and_fail_between_writes_then_ .expect("typed run failure") }) .collect(); + let [PlatformEvent::RunFailed(failure)] = failures.as_slice() else { + panic!( + "a run with a failed node publishes one failure event, surviving rolled-back attempts and retries: {failures:?}" + ); + }; + let RunFailureEvent { + run_id, + run_kind, + job_key, + location_id, + outcome, + url, + trigger, + started_at, + ended_at, + duration_ms, + error, + failed_nodes, + failed_node_count, + failed_audits, + failed_audit_count, + succeeded_node_count, + skipped_nodes, + skipped_node_count, + .. + } = failure.as_ref(); assert_eq!( - failures, - vec![PlatformEvent::RunFailed { - run_id: started.run_id, - run_kind: RunKind::Adhoc, - job_key: None, - location_id: location, - target: "development".into(), - outcome: RunOutcome::Partial, - failed_nodes: vec![RunNodeFailure { - node_key: "orders".into(), - error_code: Some("E100".into()), - message: None, - path: None, - }], - failed_node_count: 1, + ( + *run_id, + *run_kind, + job_key.as_deref(), + *location_id, + *outcome + ), + ( + started.run_id, + RunKind::Adhoc, + None, + location, + RunOutcome::Failed + ) + ); + assert_eq!( + failed_nodes, + &vec![RunNodeFailure { + node_key: "orders".into(), + error_code: Some("E100".into()), + message: None, + path: None, + phase: None, + url: None, + logs_url: None, }], - "a partial run publishes one failure event, surviving rolled-back attempts and retries" + "no origin, no links" + ); + assert_eq!( + ( + *failed_node_count, + *succeeded_node_count, + *skipped_node_count + ), + (1, 1, 0) + ); + assert!( + skipped_nodes.is_empty() && failed_audits.is_empty() && *failed_audit_count == 0 + ); + assert_eq!(*error, None, "a failed node says why the run failed"); + assert_eq!(*url, None); + assert_eq!( + *trigger, + RunTrigger { + kind: RunTriggerKind::Manual, + name: None, + person: None + }, + "an operator's ad-hoc run, by no known person" + ); + assert!(started_at.is_some() && ended_at.is_some()); + assert_eq!( + *duration_ms, + started_at + .zip(*ended_at) + .map(|(start, end)| (end - start).num_milliseconds()) ); let late_failure = RunChangeRequest { event_id: Uuid::now_v7(), @@ -583,7 +649,7 @@ fn given_a_claimed_worker_when_reports_are_retried_and_fail_between_writes_then_ ), "even duplicate observations require a live leader" ); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect successor") .expect("successor"); @@ -709,7 +775,7 @@ fn given_unclaimed_work_when_an_operator_cancels_then_a_terminal_fact_prevents_l .is_err(), "retry identity includes the cancellation reason" ); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_monitor.rs b/crates/sqlbuild-orchestration/tests/runs/test_monitor.rs index 83d2f805f2..8c8a91eb77 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_monitor.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_monitor.rs @@ -70,7 +70,7 @@ fn given_silent_and_live_workers_when_the_scheduler_monitors_then_fenced_atomic_ .expect("snapshot"); let scope = (location, published.snapshot_id); let holder = Uuid::now_v7(); - let lease = acquire_lease(store, holder) + let lease = acquire_lease(store, (holder, None)) .await .expect("elect") .expect("leader"); @@ -240,7 +240,7 @@ fn given_silent_and_live_workers_when_the_scheduler_monitors_then_fenced_atomic_ .expect("fenced monitor"), events ); - let successor = acquire_lease(store, Uuid::now_v7()) + let successor = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("takeover") .expect("successor"); @@ -286,7 +286,7 @@ fn given_a_silent_worker_backlog_when_monitoring_then_bounded_transactions_conti .await .expect("snapshot"); let holder = Uuid::now_v7(); - let elected = acquire_lease(store, holder) + let elected = acquire_lease(store, (holder, None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_node_errors.rs b/crates/sqlbuild-orchestration/tests/runs/test_node_errors.rs index f885532543..42f0b612df 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_node_errors.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_node_errors.rs @@ -18,7 +18,7 @@ use crate::store::main::migrate_store::migrate_store; use crate::store::models::Parameter; use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; use crate::store::tests::store_test_types::Backend; -use crate::warehouse_history::main::read_person_run_node_error::read_person_run_node_error; +use crate::warehouse_history::main::runs::read_person_run_node_error::read_person_run_node_error; const EXPECTED_MESSAGE: &str = "Conversion Error: could not convert 'n/a' to INT32 \ (password=[REDACTED], url=postgres://orders:[REDACTED]@warehouse.example.test/orders, \ @@ -71,7 +71,7 @@ fn given_a_failed_node_when_people_read_its_error_then_only_evidence_on_that_nod ), ) .await; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -230,7 +230,7 @@ fn given_a_nul_in_a_failed_nodes_error_when_reported_then_its_failure_and_messag ), ) .await; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_node_event_resources.rs b/crates/sqlbuild-orchestration/tests/runs/test_node_event_resources.rs index 39b4ab1f88..b51b59a789 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_node_event_resources.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_node_event_resources.rs @@ -21,7 +21,7 @@ use crate::store::tests::store_helpers::{close_test_store, open_test_store, run} use crate::store::tests::store_test_types::Backend; use crate::store::types::Row; use crate::warehouse_history::_helpers::run_recall::node_of; -use crate::warehouse_history::main::read_person_run_events::read_person_run_events; +use crate::warehouse_history::main::runs::read_person_run_events::read_person_run_events; const NODE_EVENTS: [&str; 4] = [ "run_node_started", @@ -48,6 +48,9 @@ fn given_node_and_check_reports_when_stored_and_read_then_each_event_names_its_n Some("r-1".into()), Some(14), ), + stored_outcome: "warn", + not_run_reason: None, + expected_message: None, }, NodeEventResourcesTestCase { description: "PostgreSQL node and check events", @@ -64,6 +67,47 @@ fn given_node_and_check_reports_when_stored_and_read_then_each_event_names_its_n Some("r-1".into()), Some(14), ), + stored_outcome: "warn", + not_run_reason: None, + expected_message: None, + }, + NodeEventResourcesTestCase { + description: "SQLite: an audit that was not run says why", + backend: Backend::Sqlite, + expected_named: [ + ("run_node_started", "model", "payments"), + ("run_check_started", "check", "payments_positive"), + ("run_check_finished", "check", "payments_positive"), + ("run_node_finished", "model", "payments"), + ], + expected_check: ( + Some("payments_positive".into()), + Some("b-payments-positive".into()), + Some("r-1".into()), + Some(14), + ), + stored_outcome: "not_run", + not_run_reason: Some("reads payments, which doesn't exist in the target"), + expected_message: Some("reads payments, which doesn't exist in the target"), + }, + NodeEventResourcesTestCase { + description: "PostgreSQL: an audit that was not run says why", + backend: Backend::Postgres, + expected_named: [ + ("run_node_started", "model", "payments"), + ("run_check_started", "check", "payments_positive"), + ("run_check_finished", "check", "payments_positive"), + ("run_node_finished", "model", "payments"), + ], + expected_check: ( + Some("payments_positive".into()), + Some("b-payments-positive".into()), + Some("r-1".into()), + Some(14), + ), + stored_outcome: "not_run", + not_run_reason: Some("reads payments, which doesn't exist in the target"), + expected_message: Some("reads payments, which doesn't exist in the target"), }, ]; for test_case in test_cases { @@ -88,7 +132,7 @@ fn given_node_and_check_reports_when_stored_and_read_then_each_event_names_its_n snapshot_node("check", json!({"name": "payments_positive"})), ); let published = publish_snapshot(store, &input).await.expect("snapshot"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -134,6 +178,7 @@ fn given_node_and_check_reports_when_stored_and_read_then_each_event_names_its_n error_code: None, skipped_because_of: None, error_message: None, + phase: None, }), ] { assert!(change_run(store, worker, &request).await.expect("report")); @@ -236,17 +281,19 @@ fn given_node_and_check_reports_when_stored_and_read_then_each_event_names_its_n let transaction = begin(store, TransactionMode::Write).await.expect("begin"); let (transaction, _) = query( transaction, - "UPDATE recall_events SET event_type='audit_completed', outcome='warn', payload=$1 WHERE event_id=$2", + "UPDATE recall_events SET event_type='audit_completed', outcome=$3, payload=$1 WHERE event_id=$2", vec![ Parameter::Json(json!({ "audit_name": "payments_positive", "binding_key": "b-payments-positive", "result_id": "r-1", - "outcome": "warn", + "outcome": test_case.stored_outcome, "violation_count": 14, "executed_sql": "SELECT 1", + "not_run_reason": test_case.not_run_reason, })), Parameter::Text(check_finished.event_id.to_string()), + Parameter::Text(test_case.stored_outcome.to_owned()), ], ) .await @@ -279,6 +326,17 @@ fn given_node_and_check_reports_when_stored_and_read_then_each_event_names_its_n "{}: a check result names its check and the rows it found, never its SQL", test_case.description ); + let messages: Vec> = events + .iter() + .filter(|event| event.event_type == "audit_completed") + .map(|event| event.message.clone()) + .collect(); + assert_eq!( + messages, + vec![test_case.expected_message.map(str::to_owned)], + "{}: a check result's summary is why it wasn't run, if it wasn't", + test_case.description + ); close_test_store(fixture).await; }); } diff --git a/crates/sqlbuild-orchestration/tests/runs/test_node_results.rs b/crates/sqlbuild-orchestration/tests/runs/test_node_results.rs index 34d2203685..90fffa8253 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_node_results.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_node_results.rs @@ -113,7 +113,7 @@ fn given_a_run_reporting_what_each_node_did_when_its_nodes_are_listed_then_rows_ &["customers", "inventory", "orders", "products"], ); queue(store, &pinned).await; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -132,6 +132,7 @@ fn given_a_run_reporting_what_each_node_did_when_its_nodes_are_listed_then_rows_ error_code: None, skipped_because_of: None, error_message: None, + phase: None, } }; for change in [ @@ -249,7 +250,7 @@ fn given_nodes_failed_for_missing_secrets_when_listed_then_only_those_unstarted_ &["customers", "inventory", "orders", "products"], ); queue(store, &pinned).await; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_past_runs.rs b/crates/sqlbuild-orchestration/tests/runs/test_past_runs.rs new file mode 100644 index 0000000000..4225d662d6 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/runs/test_past_runs.rs @@ -0,0 +1,160 @@ +use std::collections::BTreeSet; + +use uuid::Uuid; + +use crate::credentials::tests::location_helpers::create_location; +use crate::runs::_helpers::requests::past_runs::read_past_runs; +use crate::runs::models::PastRunResults; +use crate::runs::tests::helpers::{insert_check, queue, request, set_node_status, snapshot}; +use crate::runs::tests::test_types::PastRunLookupTestCase; +use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; +use crate::store::main::begin::begin; +use crate::store::main::commit::commit; +use crate::store::main::migrate_store::migrate_store; +use crate::store::models::TransactionMode; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; + +const FIRST: u128 = 0x01a1_d3b9_0000_7000_8000_0000_0000_0001; +const SECOND: u128 = 0x01a1_d3b9_0000_7000_8000_0000_0000_0002; +const THIRD: u128 = 0x01a1_d3c0_0000_7000_8000_0000_0000_0003; + +#[test] +fn given_runs_when_run_selectors_name_them_then_full_ids_and_unique_prefixes_read_their_results() { + let test_cases = [ + PastRunLookupTestCase { + description: "SQLite: a full ID and a unique 8-character prefix each name their run, with what it selected, failed and skipped, and no audit it didn't run", + backend: Backend::Sqlite, + ids: &["01a1d3b9-0000-7000-8000-000000000001", "01a1d3c0"], + expected_runs: Ok(vec![ + ( + "01a1d3b9-0000-7000-8000-000000000001", + FIRST, + [&["customers", "orders"], &["orders"], &["customers"]], + ), + ("01a1d3c0", THIRD, [&["customers", "orders"], &[], &[]]), + ]), + }, + PastRunLookupTestCase { + description: "SQLite: an ambiguous prefix lists the runs it matches", + backend: Backend::Sqlite, + ids: &["01a1d3b9"], + expected_runs: Err( + "run ID '01a1d3b9' is ambiguous: it starts 01a1d3b9-0000-7000-8000-000000000001, 01a1d3b9-0000-7000-8000-000000000002; give more of the ID", + ), + }, + PastRunLookupTestCase { + description: "SQLite: a prefix shorter than 8 characters is refused", + backend: Backend::Sqlite, + ids: &["01a1d3c"], + expected_runs: Err( + "run ID '01a1d3c' is too short: give the full ID or at least 8 characters of it", + ), + }, + PastRunLookupTestCase { + description: "SQLite: an ID no run has is refused", + backend: Backend::Sqlite, + ids: &["ffffffff"], + expected_runs: Err("no run 'ffffffff' in this location and target"), + }, + PastRunLookupTestCase { + description: "PostgreSQL: a full ID and a unique 8-character prefix each name their run, with what it selected, failed and skipped, and no audit it didn't run", + backend: Backend::Postgres, + ids: &["01a1d3b9-0000-7000-8000-000000000001", "01a1d3c0"], + expected_runs: Ok(vec![ + ( + "01a1d3b9-0000-7000-8000-000000000001", + FIRST, + [&["customers", "orders"], &["orders"], &["customers"]], + ), + ("01a1d3c0", THIRD, [&["customers", "orders"], &[], &[]]), + ]), + }, + PastRunLookupTestCase { + description: "PostgreSQL: an ambiguous prefix lists the runs it matches", + backend: Backend::Postgres, + ids: &["01a1d3b9"], + expected_runs: Err( + "run ID '01a1d3b9' is ambiguous: it starts 01a1d3b9-0000-7000-8000-000000000001, 01a1d3b9-0000-7000-8000-000000000002; give more of the ID", + ), + }, + PastRunLookupTestCase { + description: "PostgreSQL: a prefix shorter than 8 characters is refused", + backend: Backend::Postgres, + ids: &["01a1d3c"], + expected_runs: Err( + "run ID '01a1d3c' is too short: give the full ID or at least 8 characters of it", + ), + }, + PastRunLookupTestCase { + description: "PostgreSQL: an ID no run has is refused", + backend: Backend::Postgres, + ids: &["ffffffff"], + expected_runs: Err("no run 'ffffffff' in this location and target"), + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let location = create_location(store, "orders", "test-admin") + .await + .expect("location"); + let published = publish_snapshot(store, &snapshot(location)) + .await + .expect("snapshot"); + for id in [FIRST, SECOND, THIRD] { + queue( + store, + &request( + (location, published.snapshot_id), + id, + 1, + &["customers", "orders"], + ), + ) + .await; + } + set_node_status(store, (Uuid::from_u128(FIRST), "orders"), "failed").await; + set_node_status(store, (Uuid::from_u128(FIRST), "customers"), "skipped").await; + insert_check( + store, + (Uuid::from_u128(FIRST), "audit:orders_have_payments"), + "not_run", + ) + .await; + let ids: BTreeSet = test_case.ids.iter().map(|id| (*id).to_owned()).collect(); + let transaction = begin(store, TransactionMode::Read).await.expect("read"); + let (transaction, past) = read_past_runs(transaction, (location, "development"), &ids) + .await + .expect("read past runs"); + commit(transaction).await.expect("commit"); + let keys = |keys: &[&str]| keys.iter().map(|key| (*key).to_owned()).collect(); + assert_eq!( + past, + test_case + .expected_runs + .clone() + .map(|runs| runs + .into_iter() + .map(|(id, run_id, [selected, failed, skipped])| ( + id.to_owned(), + PastRunResults { + run_id: Uuid::from_u128(run_id), + selected: keys(selected), + failed: keys(failed), + skipped: keys(skipped), + } + )) + .collect()) + .map_err(str::to_owned), + "{}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/runs/test_permissions.rs b/crates/sqlbuild-orchestration/tests/runs/test_permissions.rs index daadb28d2a..b74ec75fd9 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_permissions.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_permissions.rs @@ -185,7 +185,7 @@ fn given_scoped_person_roles_when_jobs_request_sensitive_settings_then_only_admi .expect("built-in metadata access") .is_empty() ); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_project_limits.rs b/crates/sqlbuild-orchestration/tests/runs/test_project_limits.rs index 2921cf2c5a..8443887d3d 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_project_limits.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_project_limits.rs @@ -49,7 +49,7 @@ fn given_a_project_limit_and_a_server_cap_when_claiming_then_each_location_runs_ }; let store = &fixture.store; migrate_store(store).await.expect("migrate run store"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -145,7 +145,7 @@ fn given_pool_amounts_when_claiming_then_a_run_takes_all_its_slots_at_once_or_no }; let store = &fixture.store; migrate_store(store).await.expect("migrate run store"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_requests.rs b/crates/sqlbuild-orchestration/tests/runs/test_requests.rs index 816485dbf3..0242afe4bb 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_requests.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_requests.rs @@ -191,7 +191,7 @@ fn given_a_published_job_when_requested_and_retried_after_redeploy_then_audit_an .expect("no duplicate facts"), facts ); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_reruns.rs b/crates/sqlbuild-orchestration/tests/runs/test_reruns.rs index a3f77fe773..7c16b4c6a3 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_reruns.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_reruns.rs @@ -29,7 +29,7 @@ use crate::store::tests::store_helpers::{close_test_store, open_test_store, run} use crate::store::tests::store_test_types::Backend; #[test] -fn given_a_partial_group_when_rerun_after_redeploy_then_only_unfinished_nodes_retry_atomically() { +fn given_a_failed_group_when_rerun_after_redeploy_then_only_unfinished_nodes_retry_atomically() { let test_cases = [ RunLifecycleTestCase { description: "SQLite pinned group rerun", @@ -121,7 +121,7 @@ fn given_a_partial_group_when_rerun_after_redeploy_then_only_unfinished_nodes_re .is_err(), "a live source cannot be rerun" ); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -169,6 +169,7 @@ fn given_a_partial_group_when_rerun_after_redeploy_then_only_unfinished_nodes_re skipped_because_of: (outcome == NodeOutcome::Skipped) .then(|| "orders".into()), error_message: None, + phase: None, }); } changes.push(RunChange::Finished { @@ -205,7 +206,7 @@ fn given_a_partial_group_when_rerun_after_redeploy_then_only_unfinished_nodes_re .find(|run| run.run_id == source_id) .expect("source exists") .status, - RunStatus::Partial + RunStatus::Failed ); input.generation = 2; input.image_id = Some("sha256:synthetic-orders-image-2".into()); @@ -421,7 +422,7 @@ fn given_cancelled_nodes_when_rerunning_from_failure_then_every_unfinished_node_ NodeOutcome::Failed, NodeOutcome::Cancelled, ], - run_outcome: RunOutcome::Partial, + run_outcome: RunOutcome::Failed, cancel_requests: 1, expected_retried: vec![], expected_rerun: vec!["inventory", "orders"], @@ -439,13 +440,13 @@ fn given_cancelled_nodes_when_rerunning_from_failure_then_every_unfinished_node_ expected_rerun: vec!["customers", "inventory", "orders"], }, CancelledRerunTestCase { - description: "a partial run nobody cancelled retries failed and cancelled nodes", + description: "a run with a success nobody cancelled retries failed and cancelled nodes", outcomes: [ NodeOutcome::Success, NodeOutcome::Failed, NodeOutcome::Cancelled, ], - run_outcome: RunOutcome::Partial, + run_outcome: RunOutcome::Failed, cancel_requests: 0, expected_retried: vec!["inventory", "orders"], expected_rerun: vec!["inventory", "orders"], @@ -457,7 +458,7 @@ fn given_cancelled_nodes_when_rerunning_from_failure_then_every_unfinished_node_ NodeOutcome::Cancelled, NodeOutcome::Cancelled, ], - run_outcome: RunOutcome::Partial, + run_outcome: RunOutcome::Failed, cancel_requests: 0, expected_retried: vec!["inventory", "orders"], expected_rerun: vec!["inventory", "orders"], @@ -488,7 +489,7 @@ fn given_cancelled_nodes_when_rerunning_from_failure_then_every_unfinished_node_ "on_failure": {"retries": 1, "retry_delay_seconds": 0}}}), ); publish_snapshot(store, &input).await.expect("publish"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -554,6 +555,7 @@ fn given_cancelled_nodes_when_rerunning_from_failure_then_every_unfinished_node_ error_code: None, skipped_because_of: None, error_message: None, + phase: None, }; change_run(store, worker(), &change(claimed, finished)) .await diff --git a/crates/sqlbuild-orchestration/tests/runs/test_retries.rs b/crates/sqlbuild-orchestration/tests/runs/test_retries.rs index fee7bb50e3..457eda0340 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_retries.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_retries.rs @@ -72,7 +72,7 @@ fn given_a_job_with_on_failure_when_its_runs_fail_then_retries_rerun_failed_work }), ); publish_snapshot(store, &input).await.expect("publish"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_run_failure_event.rs b/crates/sqlbuild-orchestration/tests/runs/test_run_failure_event.rs new file mode 100644 index 0000000000..7216cb45d9 --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/runs/test_run_failure_event.rs @@ -0,0 +1,204 @@ +use std::collections::BTreeMap; + +use uuid::Uuid; + +use crate::credentials::tests::location_helpers::create_location; +use crate::platform::models::PlatformEvent; +use crate::runs::main::execution::claim_next_run::claim_next_run; +use crate::runs::models::{NodeOutcome, RunChange, RunFailurePhase}; +use crate::runs::tests::failure_event_helpers::{MISSING, end_run, report, summarize}; +use crate::runs::tests::helpers::{queue, request, snapshot}; +use crate::runs::tests::test_types::{RunFailureEventTestCase, RunFailureSummary}; +use crate::scheduler::tests::contracts::helpers::acquire_lease; +use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; +use crate::store::main::migrate_store::migrate_store; +use crate::store::tests::helpers::read_recall_events; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store::tests::store_test_types::Backend; + +#[test] +fn given_a_failed_run_when_it_finishes_then_its_run_failed_event_says_why_where_and_links_to_it() { + let test_cases = [ + RunFailureEventTestCase { + description: "SQLite: a model failing in its post-hook names the phase and links to the node and its output", + backend: Backend::Sqlite, + nodes: &[ + ("customers", NodeOutcome::Success, None), + ("orders", NodeOutcome::Failed, Some("post_hook")), + ], + failed_end_audits: &[], + expected_summary: RunFailureSummary { + links_to_run: true, + first_node: Some(( + Some("post_hook".into()), + Some("?node=orders".into()), + Some("/output/orders".into()), + )), + first_audit: None, + failed_audit_count: 0, + succeeded_node_count: 1, + error: None, + }, + }, + RunFailureEventTestCase { + description: "SQLite: a run failed only by an end-of-build audit names it, with the warehouse's error", + backend: Backend::Sqlite, + nodes: &[ + ("customers", NodeOutcome::Success, None), + ("orders", NodeOutcome::Success, None), + ], + failed_end_audits: &["orders_match_payments"], + expected_summary: RunFailureSummary { + links_to_run: true, + first_node: None, + first_audit: Some(( + "orders_match_payments".into(), + Some("42S02".into()), + Some(MISSING.into()), + )), + failed_audit_count: 1, + succeeded_node_count: 2, + error: None, + }, + }, + RunFailureEventTestCase { + description: "SQLite: a run that failed before any node says where and why", + backend: Backend::Sqlite, + nodes: &[], + failed_end_audits: &[], + expected_summary: RunFailureSummary { + links_to_run: true, + first_node: None, + first_audit: None, + failed_audit_count: 0, + succeeded_node_count: 0, + error: Some(( + RunFailurePhase::Load, + Some("project could not be loaded".into()), + )), + }, + }, + RunFailureEventTestCase { + description: "PostgreSQL: a model failing in its post-hook names the phase and links to the node and its output", + backend: Backend::Postgres, + nodes: &[ + ("customers", NodeOutcome::Success, None), + ("orders", NodeOutcome::Failed, Some("post_hook")), + ], + failed_end_audits: &[], + expected_summary: RunFailureSummary { + links_to_run: true, + first_node: Some(( + Some("post_hook".into()), + Some("?node=orders".into()), + Some("/output/orders".into()), + )), + first_audit: None, + failed_audit_count: 0, + succeeded_node_count: 1, + error: None, + }, + }, + RunFailureEventTestCase { + description: "PostgreSQL: a run failed only by an end-of-build audit names it, with the warehouse's error", + backend: Backend::Postgres, + nodes: &[ + ("customers", NodeOutcome::Success, None), + ("orders", NodeOutcome::Success, None), + ], + failed_end_audits: &["orders_match_payments"], + expected_summary: RunFailureSummary { + links_to_run: true, + first_node: None, + first_audit: Some(( + "orders_match_payments".into(), + Some("42S02".into()), + Some(MISSING.into()), + )), + failed_audit_count: 1, + succeeded_node_count: 2, + error: None, + }, + }, + RunFailureEventTestCase { + description: "PostgreSQL: a run that failed before any node says where and why", + backend: Backend::Postgres, + nodes: &[], + failed_end_audits: &[], + expected_summary: RunFailureSummary { + links_to_run: true, + first_node: None, + first_audit: None, + failed_audit_count: 0, + succeeded_node_count: 0, + error: Some(( + RunFailurePhase::Load, + Some("project could not be loaded".into()), + )), + }, + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.backend).await else { + return; + }; + let store = &fixture.store; + migrate_store(store).await.expect("migrate"); + let location = create_location(store, "orders", "test-admin") + .await + .expect("location"); + let published = publish_snapshot(store, &snapshot(location)) + .await + .expect("snapshot"); + let lease = acquire_lease(store, (Uuid::now_v7(), None)) + .await + .expect("elect") + .expect("leader"); + queue( + store, + &request( + (location, published.snapshot_id), + 1, + 1, + &["customers", "orders"], + ), + ) + .await; + let claim = claim_next_run(store, &lease, &BTreeMap::new(), None) + .await + .expect("claim") + .expect("available"); + report(store, &claim, RunChange::Started).await; + end_run( + store, + &claim, + (test_case.nodes, test_case.failed_end_audits), + ) + .await; + let events: Vec = read_recall_events(store, 0, 200) + .await + .expect("facts") + .into_iter() + .filter(|row| row["event_type"] == "platform_run_failed") + .map(|row| { + serde_json::from_value(row["payload"]["platform"].clone()) + .expect("typed run failure") + }) + .collect(); + let [PlatformEvent::RunFailed(failure)] = events.as_slice() else { + panic!( + "{}: one run_failed event, got {events:?}", + test_case.description + ); + }; + assert_eq!( + summarize(failure), + test_case.expected_summary, + "{}", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/runs/test_stored_requests.rs b/crates/sqlbuild-orchestration/tests/runs/test_stored_requests.rs index 4bfa714246..ff92f1abd4 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_stored_requests.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_stored_requests.rs @@ -66,7 +66,7 @@ fn given_requests_stored_before_0_245_when_the_server_reads_them_then_runs_claim "on_failure": {"retries": 1, "retry_delay_seconds": 0}}}), ); publish_snapshot(store, &input).await.expect("publish"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/runs/test_types.rs b/crates/sqlbuild-orchestration/tests/runs/test_types.rs index b9b6195e52..fc5c3e4560 100644 --- a/crates/sqlbuild-orchestration/tests/runs/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/runs/test_types.rs @@ -191,11 +191,16 @@ pub(crate) struct ExactKeyPublication { } impl crate::runs::types::PreparedPublication for ExactKeyPublication { + /// Exact keys never name a past run. + fn run_selector_ids(&self, _texts: &[String]) -> std::collections::BTreeSet { + std::collections::BTreeSet::new() + } + /// Exact keys only: each token names one published key, and an unknown one is refused with its position. fn evaluate( &self, - select: &str, - exclude: &str, + (select, exclude): (&str, &str), + _past: &crate::runs::types::PastRuns, ) -> Result, Box> { let known = |field: crate::runs::models::SelectionField, text: &str| { let mut keys: std::collections::BTreeSet = Default::default(); @@ -249,7 +254,11 @@ impl crate::runs::types::PreparedPublication for ExactKeyPublication { } } - fn plan(&self, command: &[String]) -> Result { + fn plan( + &self, + command: &[String], + _past: &crate::runs::types::PastRuns, + ) -> Result { let (resources, jobs) = (&self.resources, &self.jobs); let mut plan = crate::runs::models::CommandPlan { verb: command.first().cloned().unwrap_or_default(), @@ -565,6 +574,11 @@ pub(crate) struct NodeEventResourcesTestCase { pub(crate) expected_named: [(&'static str, &'static str, &'static str); 4], /// The check result's name, check ID, result ID and rows found, as the run's events report them. pub(crate) expected_check: CheckFields, + /// The check result's outcome, and why it didn't run when it is `not_run`. + pub(crate) stored_outcome: &'static str, + pub(crate) not_run_reason: Option<&'static str>, + /// The check event's summary: the reason a not-run audit gives, never error text. + pub(crate) expected_message: Option<&'static str>, } /// A check result's name, check ID, result ID and rows found. @@ -633,3 +647,43 @@ pub(crate) struct StartMessageTestCase { pub(crate) fields: Vec<(&'static str, serde_json::Value)>, pub(crate) expected_message: Option<&'static str>, } + +/// A node the worker reports finished: its key, outcome and failure phase. +pub(crate) type ReportedNode = ( + &'static str, + crate::runs::models::NodeOutcome, + Option<&'static str>, +); + +pub(crate) struct RunFailureEventTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + pub(crate) nodes: &'static [ReportedNode], + pub(crate) failed_end_audits: &'static [&'static str], + pub(crate) expected_summary: RunFailureSummary, +} + +/// The parts of a `run_failed` event a test compares; node links are relative to the run's page. +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct RunFailureSummary { + pub(crate) links_to_run: bool, + /// The first failed node's phase, link and output link. + pub(crate) first_node: Option<(Option, Option, Option)>, + /// The first failed audit's name, SQLSTATE and message. + pub(crate) first_audit: Option<(String, Option, Option)>, + pub(crate) failed_audit_count: i64, + pub(crate) succeeded_node_count: i64, + pub(crate) error: Option<(crate::runs::models::RunFailurePhase, Option)>, +} + +/// A typed run ID's run, and the keys it selected, failed and skipped. +pub(crate) type ExpectedPastRun = (&'static str, u128, [&'static [&'static str]; 3]); + +pub(crate) struct PastRunLookupTestCase { + pub(crate) description: &'static str, + pub(crate) backend: Backend, + /// The run IDs as typed. + pub(crate) ids: &'static [&'static str], + /// Each typed ID's run, or the refusal. + pub(crate) expected_runs: Result, &'static str>, +} diff --git a/crates/sqlbuild-orchestration/tests/scheduler/helpers.rs b/crates/sqlbuild-orchestration/tests/scheduler/helpers.rs index 3b5a141a10..e634237008 100644 --- a/crates/sqlbuild-orchestration/tests/scheduler/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/scheduler/helpers.rs @@ -50,8 +50,8 @@ pub(crate) async fn leadership_contract(backend: Backend) -> Option { .expect("migrate leadership store"); let second = second_store(store).await; let (first, other) = tokio::join!( - acquire_lease(store, Uuid::now_v7()), - acquire_lease(&second, Uuid::now_v7()) + acquire_lease(store, (Uuid::now_v7(), None)), + acquire_lease(&second, (Uuid::now_v7(), None)) ); let first = first.expect("first contender completes"); let other = other.expect("second contender completes"); @@ -67,7 +67,7 @@ pub(crate) async fn leadership_contract(backend: Backend) -> Option { assert_eq!(renewed.epoch, lease.epoch); assert!(renewed.expires_at >= lease.expires_at); assert!( - acquire_lease(store, lease.holder) + acquire_lease(store, (lease.holder, None)) .await .expect("duplicate acquisition completes") .is_none() @@ -83,7 +83,7 @@ pub(crate) async fn leadership_contract(backend: Backend) -> Option { matches!(renew_lease(store, &lease).await, Err(ControlError::Fenced)), "even an uncontested expired holder must reacquire a new epoch" ); - let successor = acquire_lease(&second, Uuid::now_v7()) + let successor = acquire_lease(&second, (Uuid::now_v7(), None)) .await .expect("acquire expired lease") .expect("successor elected"); @@ -254,6 +254,7 @@ pub(crate) async fn report_run( error_code: None, skipped_because_of: None, error_message: None, + phase: None, }), ); changes.push(RunChange::Finished { diff --git a/crates/sqlbuild-orchestration/tests/scheduler/test_concurrency_source.rs b/crates/sqlbuild-orchestration/tests/scheduler/test_concurrency_source.rs index c3ce2e79b1..f7a81358bc 100644 --- a/crates/sqlbuild-orchestration/tests/scheduler/test_concurrency_source.rs +++ b/crates/sqlbuild-orchestration/tests/scheduler/test_concurrency_source.rs @@ -341,7 +341,7 @@ fn given_a_job_published_before_0004_when_its_run_fails_before_a_republish_then_ request_job_run(store, (&operator(), None), &manual_run(location, "orders")) .await .expect("a manual run of the migrated job"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -423,7 +423,7 @@ fn given_a_group_pinned_to_a_snapshot_document_in_the_old_form_when_advancing_it ) .await .expect("request the group"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -493,7 +493,7 @@ fn given_a_group_member_pinned_to_an_old_document_when_claiming_then_it_fails_an ) .await .expect("request the group"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -656,7 +656,7 @@ fn given_a_running_member_when_its_group_snapshot_becomes_unreadable_then_the_gr ) .await .expect("request the group"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/scheduler/ticks/helpers.rs b/crates/sqlbuild-orchestration/tests/scheduler/ticks/helpers.rs index 0546953fdf..0bdda2ee73 100644 --- a/crates/sqlbuild-orchestration/tests/scheduler/ticks/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/scheduler/ticks/helpers.rs @@ -211,7 +211,7 @@ pub(crate) async fn transaction_contract(backend: Backend) -> Option<(usize, usi .await .expect("published triggers")[0] .trigger_id; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("acquire lease") .expect("elected"); @@ -302,7 +302,7 @@ pub(crate) async fn transaction_contract(backend: Backend) -> Option<(usize, usi events[1]["storage_id"].as_i64().expect("event cursor") ); expire_lease(store).await; - let successor = acquire_lease(&second, Uuid::now_v7()) + let successor = acquire_lease(&second, (Uuid::now_v7(), None)) .await .expect("takeover") .expect("new leader"); diff --git a/crates/sqlbuild-orchestration/tests/scheduler/ticks/test_precision.rs b/crates/sqlbuild-orchestration/tests/scheduler/ticks/test_precision.rs index df7b6da1ed..8d4f1b4f28 100644 --- a/crates/sqlbuild-orchestration/tests/scheduler/ticks/test_precision.rs +++ b/crates/sqlbuild-orchestration/tests/scheduler/ticks/test_precision.rs @@ -72,7 +72,7 @@ fn given_a_sub_second_trigger_start_or_cursor_when_evaluated_then_cron_ticks_lan set_trigger_state(store, trigger_id, "UPDATE sqb_trigger_state SET started_at=$1, last_tick_for=NULL, next_due_at=NULL WHERE trigger_id=$2", started).await; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("election") .expect("lease"); diff --git a/crates/sqlbuild-orchestration/tests/scheduler/ticks/test_progress.rs b/crates/sqlbuild-orchestration/tests/scheduler/ticks/test_progress.rs index 5a1fdf9e71..1a8bd9103b 100644 --- a/crates/sqlbuild-orchestration/tests/scheduler/ticks/test_progress.rs +++ b/crates/sqlbuild-orchestration/tests/scheduler/ticks/test_progress.rs @@ -51,7 +51,7 @@ fn given_reset_existing_ticks_when_re_evaluated_then_cursor_and_due_time_are_exa .await .expect("trigger")[0] .trigger_id; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("election") .expect("lease"); diff --git a/crates/sqlbuild-orchestration/tests/scheduler/ticks/test_retention.rs b/crates/sqlbuild-orchestration/tests/scheduler/ticks/test_retention.rs index d243a9c5a6..8a7844d882 100644 --- a/crates/sqlbuild-orchestration/tests/scheduler/ticks/test_retention.rs +++ b/crates/sqlbuild-orchestration/tests/scheduler/ticks/test_retention.rs @@ -65,7 +65,7 @@ fn given_expired_covered_ticks_when_pruned_and_cursor_reset_then_run_linked_and_ .await .expect("trigger")[0] .trigger_id; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("election") .expect("lease"); @@ -243,7 +243,7 @@ fn given_an_old_yearly_schedule_when_first_evaluated_then_latest_catch_up_ticks_ .await .expect("trigger")[0] .trigger_id; - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("election") .expect("lease"); diff --git a/crates/sqlbuild-orchestration/tests/scheduler/ticks/test_triggers.rs b/crates/sqlbuild-orchestration/tests/scheduler/ticks/test_triggers.rs index 0801175ede..b90a578b46 100644 --- a/crates/sqlbuild-orchestration/tests/scheduler/ticks/test_triggers.rs +++ b/crates/sqlbuild-orchestration/tests/scheduler/ticks/test_triggers.rs @@ -80,7 +80,7 @@ fn given_operator_changes_when_retried_and_republished_then_facts_and_effective_ test_case.description ); assert!(paused.next_due_at.is_none()); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("election") .expect("lease"); @@ -316,7 +316,7 @@ fn given_a_calendar_with_unprocessed_due_times_when_refreshed_then_due_ticks_sur test_case.description ); assert_eq!(trigger.next_due_at, Some(calendar_time(0))); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("election") .expect("lease"); diff --git a/crates/sqlbuild-orchestration/tests/sensors/helpers.rs b/crates/sqlbuild-orchestration/tests/sensors/helpers.rs index af28222321..7f5bc7b49d 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/helpers.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/helpers.rs @@ -301,6 +301,7 @@ async fn finish_checked_run( error_code: None, skipped_because_of: None, error_message: None, + phase: None, }); } for (check, finished) in checks { @@ -361,6 +362,7 @@ pub(crate) fn node_finished(node_key: &str, outcome: NodeOutcome) -> RunChange { error_code: None, skipped_because_of: None, error_message: None, + phase: None, } } @@ -643,3 +645,63 @@ pub(crate) fn republished_tick() -> crate::sensors::models::SensorEvaluationOutc pub(crate) fn cursor_reset_tick() -> crate::sensors::models::SensorEvaluationOutcome { abandoned_tick(crate::sensors::models::AbandonReason::CursorReset) } + +/// Make each named sensor of `snapshot` watch `kinds`, in its `triggers` document and its trigger row, bypassing validation. +pub(crate) async fn watch_kinds( + store: &ControlStore, + snapshot: &crate::snapshots::models::SnapshotRecord, + watched: &[(&str, &[&str])], +) { + let (mut transaction, rows) = query( + begin(store, TransactionMode::Write).await.expect("seed"), + "SELECT d.body FROM sqb_snapshot_documents s JOIN sqb_documents d ON d.document_hash=s.document_hash \ + WHERE s.snapshot_id=$1 AND s.kind='triggers'", + vec![Parameter::Id(snapshot.snapshot_id)], + ) + .await + .expect("read triggers document"); + let mut document: serde_json::Value = serde_json::from_slice( + &crate::store::main::decompress::decompress(&rows[0]["body"]).expect("decompress"), + ) + .expect("triggers document"); + for (name, kinds) in watched { + document[*name]["when"]["kinds"] = json!(kinds); + let definition = document[*name].clone(); + (transaction, _) = query( + transaction, + "UPDATE sqb_triggers SET definition_json=$2 WHERE name=$1 AND kind='sensor'", + vec![Parameter::Text((*name).into()), Parameter::Json(definition)], + ) + .await + .expect("store the trigger row"); + } + let (hash, body) = + crate::snapshots::main::publication::stored_document::stored_document(&document) + .expect("stored document"); + (transaction, _) = query( + transaction, + "INSERT INTO sqb_documents (document_hash, body) VALUES ($1, $2) ON CONFLICT DO NOTHING", + vec![Parameter::Text(hash.clone()), Parameter::Bytes(body)], + ) + .await + .expect("store the document"); + (transaction, _) = query( + transaction, + "UPDATE sqb_snapshot_documents SET document_hash=$2 WHERE snapshot_id=$1 AND kind='triggers'", + vec![Parameter::Id(snapshot.snapshot_id), Parameter::Text(hash)], + ) + .await + .expect("point the snapshot at it"); + commit(transaction).await.expect("commit"); +} + +/// The run outcomes a sensor's `run_event` condition watches; none for another condition. +pub(crate) fn watched_run_kinds( + definition: &crate::sensors::models::SensorDefinition, +) -> Vec { + let Some(crate::sensors::models::SensorCondition::RunEvent { kinds, .. }) = &definition.when + else { + return Vec::new(); + }; + kinds.iter().copied().collect() +} diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_checks.rs b/crates/sqlbuild-orchestration/tests/sensors/test_checks.rs index 2f7019adf6..3c9cafe3cb 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_checks.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_checks.rs @@ -117,7 +117,7 @@ fn given_a_successful_run_with_a_failed_check_and_a_warned_audit_when_a_check_se .await .expect("triggers") .remove(0); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_contracts.rs b/crates/sqlbuild-orchestration/tests/sensors/test_contracts.rs index 096e404e0f..81c21f0a73 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_contracts.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_contracts.rs @@ -18,6 +18,8 @@ mod test_function_cursor; mod test_group_members; #[path = "test_nodes.rs"] mod test_nodes; +#[path = "test_partial_upgrade.rs"] +mod test_partial_upgrade; #[path = "test_permissions.rs"] mod test_permissions; #[path = "test_person_state.rs"] diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_custom.rs b/crates/sqlbuild-orchestration/tests/sensors/test_custom.rs index e5399d2570..7673e9ac19 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_custom.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_custom.rs @@ -109,7 +109,7 @@ fn given_custom_sensor_work_when_results_retry_then_cursor_runs_and_outcome_comm ) .await .expect("register location instance"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -434,7 +434,7 @@ fn given_custom_sensor_work_when_results_retry_then_cursor_runs_and_outcome_comm complete_sensor(store, &lease, &stale).await, Err(ControlError::Fenced) )); - let successor = acquire_lease(&replica, Uuid::now_v7()) + let successor = acquire_lease(&replica, (Uuid::now_v7(), None)) .await .expect("takeover") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_delivery.rs b/crates/sqlbuild-orchestration/tests/sensors/test_delivery.rs index e748590ec4..efc1e58843 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_delivery.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_delivery.rs @@ -58,7 +58,7 @@ fn given_paged_platform_events_when_sensor_publication_fails_then_retry_is_atomi .await .expect("triggers") .remove(0); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -244,7 +244,7 @@ fn given_a_skip_overlap_job_with_an_active_run_when_a_sensor_matches_then_it_rec ) .await .expect("a person's run queues regardless of overlap"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_execution_bounds.rs b/crates/sqlbuild-orchestration/tests/sensors/test_execution_bounds.rs index 8ca6a7f377..4a7d65720f 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_execution_bounds.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_execution_bounds.rs @@ -77,7 +77,7 @@ fn given_a_wide_group_when_only_the_last_node_has_not_started_then_all_chunks_mu publish_snapshot(store, &input) .await .expect("publish wide predicate"); - let elected = acquire_lease(store, Uuid::now_v7()) + let elected = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -136,6 +136,7 @@ fn given_a_wide_group_when_only_the_last_node_has_not_started_then_all_chunks_mu error_code: None, skipped_because_of: None, error_message: None, + phase: None, })) .chain(std::iter::once(RunChange::Finished { outcome: RunOutcome::Success, diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_failing.rs b/crates/sqlbuild-orchestration/tests/sensors/test_failing.rs index 30e68114f1..d9086f45f4 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_failing.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_failing.rs @@ -75,7 +75,7 @@ fn given_a_long_failing_streak_when_reading_whether_a_sensor_fails_then_since_is .await .expect("triggers") .remove(0); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_function_cursor.rs b/crates/sqlbuild-orchestration/tests/sensors/test_function_cursor.rs index 3d8cf95272..619564d87d 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_function_cursor.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_function_cursor.rs @@ -46,7 +46,7 @@ fn given_a_stored_scan_position_when_a_tick_calls_the_function_then_only_a_polli .await .expect("triggers") .remove(0); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_group_members.rs b/crates/sqlbuild-orchestration/tests/sensors/test_group_members.rs index 4e3d994144..9f36dedb91 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_group_members.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_group_members.rs @@ -136,7 +136,7 @@ fn given_a_member_job_watched_by_a_sensor_when_its_group_runs_then_the_member_ou ) .await .expect("request group"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -310,7 +310,7 @@ fn given_a_member_retried_inside_its_group_when_sensors_watch_it_then_only_its_f ) .await .expect("request group"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -338,7 +338,7 @@ fn given_a_member_retried_inside_its_group_when_sensors_watch_it_then_only_its_f }, node_finished("customers", NodeOutcome::Failed), RunChange::Finished { - outcome: RunOutcome::Partial, + outcome: RunOutcome::Failed, reason: "customers failed".into(), exit_code: Some(1), }, @@ -503,7 +503,7 @@ fn given_a_member_the_group_skips_when_sensors_and_alerts_watch_it_then_it_is_sk ) .await .expect("request group"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_nodes.rs b/crates/sqlbuild-orchestration/tests/sensors/test_nodes.rs index 1e2a59d2c9..e9cf8e0ec0 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_nodes.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_nodes.rs @@ -83,7 +83,7 @@ fn given_any_run_rebuilds_when_consuming_then_only_genuine_scoped_successes_queu publish_snapshot(store, &isolated) .await .expect("other target snapshot"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -102,7 +102,7 @@ fn given_any_run_rebuilds_when_consuming_then_only_genuine_scoped_successes_queu ), (RunOutcome::Failed, [NodeOutcome::Failed; 2], [true; 2]), ( - RunOutcome::Partial, + RunOutcome::Failed, [NodeOutcome::Skipped, NodeOutcome::Success], [false, true], ), @@ -210,6 +210,7 @@ fn given_any_run_rebuilds_when_consuming_then_only_genuine_scoped_successes_queu error_code: None, skipped_because_of: None, error_message: None, + phase: None, }, ]; for change in changes { @@ -303,6 +304,7 @@ fn given_any_run_rebuilds_when_consuming_then_only_genuine_scoped_successes_queu error_code: None, skipped_because_of: None, error_message: None, + phase: None, }, ] { change_run( diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_partial_upgrade.rs b/crates/sqlbuild-orchestration/tests/sensors/test_partial_upgrade.rs new file mode 100644 index 0000000000..11bed9a99f --- /dev/null +++ b/crates/sqlbuild-orchestration/tests/sensors/test_partial_upgrade.rs @@ -0,0 +1,211 @@ +//! A store from before 0012 holds `partial` runs, facts and sensors; the upgrade makes them all `failed`. + +use serde_json::json; +use uuid::Uuid; + +use crate::credentials::tests::location_helpers::create_location; +use crate::declarations::main::frozen_definitions::frozen_definitions; +use crate::runs::models::{NodeOutcome, RunOutcome}; +use crate::runs::tests::helpers::{json_column, snapshot}; +use crate::scheduler::tests::contracts::helpers::acquire_lease; +use crate::sensors::models::{RunEventKind, SensorDefinition}; +use crate::sensors::tests::helpers::{finish_run, watch_kinds, watched_run_kinds}; +use crate::sensors::tests::test_types::PartialOutcomeUpgradeTestCase; +use crate::snapshots::main::publication::publish_snapshot::publish_snapshot; +use crate::store::main::migrate_store::migrate_store; +use crate::store::main::{begin::begin, commit::commit, query::query}; +use crate::store::models::TransactionMode; +use crate::store::tests::helpers::read_recall_events; +use crate::store::tests::schema::helpers::{ + POSTGRES_STORE, SQLITE_STORE, create_unversioned_baseline, +}; +use crate::store::tests::store_helpers::{close_test_store, open_test_store, run}; +use crate::store_migrations::_helpers::migration::MIGRATIONS; +use crate::store_migrations::_helpers::migration_run::migrate_with; + +#[test] +fn given_a_store_with_partial_runs_and_sensors_when_upgraded_then_they_are_failed_runs_and_failed_watchers() + { + let test_cases = [ + PartialOutcomeUpgradeTestCase { + description: "SQLite", + dialect: &SQLITE_STORE, + mark_partial: "UPDATE sqb_runs SET status='partial' WHERE job_key='orders'; \ + UPDATE recall_events SET payload=json_set(payload,'$.change.change.outcome','partial') \ + WHERE event_type='run_terminated'; \ + UPDATE recall_events SET payload=json_set(payload,'$.platform.outcome','partial') \ + WHERE event_type='platform_run_failed'", + watched: &[ + ("orders_partial_sensor", &["partial"]), + ("orders_failed_or_partial_sensor", &["failed", "partial"]), + ("orders_success_sensor", &["success"]), + ], + expected_outcomes: ["failed"; 3], + expected_watched: &[ + ("orders_failed_or_partial_sensor", &[RunEventKind::Failed]), + ("orders_partial_sensor", &[RunEventKind::Failed]), + ("orders_success_sensor", &[RunEventKind::Success]), + ], + }, + PartialOutcomeUpgradeTestCase { + description: "PostgreSQL", + dialect: &POSTGRES_STORE, + mark_partial: "UPDATE sqb_runs SET status='partial' WHERE job_key='orders'; \ + UPDATE recall_events SET payload=jsonb_set(payload,'{change,change,outcome}','\"partial\"') \ + WHERE event_type='run_terminated'; \ + UPDATE recall_events SET payload=jsonb_set(payload,'{platform,outcome}','\"partial\"') \ + WHERE event_type='platform_run_failed'", + watched: &[ + ("orders_partial_sensor", &["partial"]), + ("orders_failed_or_partial_sensor", &["failed", "partial"]), + ("orders_success_sensor", &["success"]), + ], + expected_outcomes: ["failed"; 3], + expected_watched: &[ + ("orders_failed_or_partial_sensor", &[RunEventKind::Failed]), + ("orders_partial_sensor", &[RunEventKind::Failed]), + ("orders_success_sensor", &[RunEventKind::Success]), + ], + }, + ]; + for test_case in test_cases { + run(async { + let Some(fixture) = open_test_store(test_case.dialect.backend).await else { + return; + }; + let store = &fixture.store; + let before_0012 = MIGRATIONS + .iter() + .position(|migration| migration.name == "failed_run_outcome") + .expect("migration 0012"); + create_unversioned_baseline( + store, + test_case.dialect, + test_case.dialect.baseline_checksum, + ) + .await; + migrate_with(store, &MIGRATIONS[..before_0012]) + .await + .expect("a store from before 0012"); + let location = create_location(store, "partial_upgrade", "test-admin") + .await + .expect("location"); + let mut input = snapshot(location); + input.documents.insert( + "jobs".into(), + json!({"orders": {"description": "Refresh orders", "selection": ["customers", "orders"]}}), + ); + let sensors: serde_json::Map = test_case + .watched + .iter() + .map(|(name, _)| { + ((*name).to_owned(), json!({ + "description": "Watch orders", "function": "start_inventory", "code_hash": "v1", + "timeout_seconds": 60, "minimum_interval_seconds": 1, + "when": {"kind": "run_event", "job_key": "orders", "kinds": ["success"]} + })) + }) + .collect(); + input.documents.insert("triggers".into(), json!(sensors)); + let published = publish_snapshot(store, &input) + .await + .expect("publish sensors"); + watch_kinds(store, &published, test_case.watched).await; + let lease = acquire_lease(store, (Uuid::now_v7(), None)) + .await + .expect("elect") + .expect("leader"); + finish_run( + store, + &lease, + (location, "development"), + "orders", + RunOutcome::Failed, + [NodeOutcome::Success, NodeOutcome::Failed], + [true, true], + ) + .await; + let mut transaction = begin(store, TransactionMode::Write).await.expect("mark"); + for statement in test_case.mark_partial.split(';') { + (transaction, _) = query(transaction, statement, Vec::new()) + .await + .expect("store the run as partial"); + } + commit(transaction).await.expect("commit"); + + migrate_store(store).await.expect("upgrade"); + + let (transaction, runs) = query( + begin(store, TransactionMode::Read).await.expect("read"), + "SELECT status FROM sqb_runs WHERE job_key='orders'", + Vec::new(), + ) + .await + .expect("runs"); + let (transaction, rows) = query( + transaction, + "SELECT name, definition_json FROM sqb_triggers WHERE kind='sensor' ORDER BY name", + Vec::new(), + ) + .await + .expect("trigger rows"); + let (transaction, definitions) = frozen_definitions(transaction, published.snapshot_id) + .await + .expect("read the snapshot"); + commit(transaction).await.expect("commit"); + let events = read_recall_events(store, 0, 500).await.expect("facts"); + let outcome = |event_type: &str, pointer: &str| { + events + .iter() + .find(|event| event["event_type"] == event_type) + .and_then(|event| event["payload"].pointer(pointer)) + .and_then(serde_json::Value::as_str) + .map(str::to_owned) + }; + let in_rows: Vec<(String, Vec)> = rows + .iter() + .map(|row| { + let definition: SensorDefinition = + serde_json::from_value(json_column(&row["definition_json"])) + .expect("a trigger row decodes"); + ( + row["name"].as_str().unwrap_or_default().to_owned(), + watched_run_kinds(&definition), + ) + }) + .collect(); + let in_document: Vec<(String, Vec)> = definitions + .expect("the snapshot decodes") + .sensors + .iter() + .map(|(name, definition)| (name.clone(), watched_run_kinds(definition))) + .collect(); + let expected: Vec<(String, Vec)> = test_case + .expected_watched + .iter() + .map(|(name, kinds)| ((*name).to_owned(), kinds.to_vec())) + .collect(); + assert_eq!( + ( + [ + runs[0]["status"].as_str().map(str::to_owned), + outcome("run_terminated", "/change/change/outcome"), + outcome("platform_run_failed", "/platform/outcome"), + ], + in_document, + in_rows, + ), + ( + test_case + .expected_outcomes + .map(|outcome| Some(outcome.to_owned())), + expected.clone(), + expected, + ), + "{}: the run, its facts and its watchers say failed", + test_case.description + ); + close_test_store(fixture).await; + }); + } +} diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_person_state.rs b/crates/sqlbuild-orchestration/tests/sensors/test_person_state.rs index 2ebb32edf7..0950d76994 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_person_state.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_person_state.rs @@ -64,7 +64,7 @@ fn given_a_checked_sensor_when_people_read_its_state_then_listing_view_gates_it_ .await .expect("triggers") .remove(0); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_recovery.rs b/crates/sqlbuild-orchestration/tests/sensors/test_recovery.rs index 89ca60000e..b40b35024f 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_recovery.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_recovery.rs @@ -59,7 +59,7 @@ fn given_a_crashed_sensor_when_leadership_or_snapshot_changes_then_stale_results .expect("triggers") .remove(0); append_events(store, 0..1, chrono::Utc::now()).await; - let first = acquire_lease(store, Uuid::now_v7()) + let first = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -69,7 +69,7 @@ fn given_a_crashed_sensor_when_leadership_or_snapshot_changes_then_stale_results .expect("due"); expire_lease(store).await; let replica = second_store(store).await; - let successor = acquire_lease(&replica, Uuid::now_v7()) + let successor = acquire_lease(&replica, (Uuid::now_v7(), None)) .await .expect("takeover") .expect("new leader"); diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_run_keys.rs b/crates/sqlbuild-orchestration/tests/sensors/test_run_keys.rs index 32b6accb9e..5df0efdd2a 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_run_keys.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_run_keys.rs @@ -62,7 +62,7 @@ fn given_two_jobs_sharing_a_run_key_when_a_sensor_requests_them_twice_then_each_ .await .expect("triggers") .remove(0); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_runs.rs b/crates/sqlbuild-orchestration/tests/sensors/test_runs.rs index f0b638b686..a591483963 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_runs.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_runs.rs @@ -36,12 +36,12 @@ fn given_terminal_jobs_and_groups_when_selectors_retry_then_outcomes_scope_and_r SensorTestCase { description: "SQLite terminal outcome sensor recovery", backend: Backend::Sqlite, - expected_runs: 104, + expected_runs: 102, }, SensorTestCase { description: "PostgreSQL terminal outcome sensor recovery", backend: Backend::Postgres, - expected_runs: 104, + expected_runs: 102, }, ]; for test_case in test_cases { @@ -68,14 +68,7 @@ fn given_terminal_jobs_and_groups_when_selectors_retry_then_outcomes_scope_and_r input.documents.insert("groups".into(), json!({ "daily_orders": {"description": "Source group", "selection": ["orders", "customers"], "jobs": {"orders": []}} })); - let selectors = [ - "completed", - "success", - "warn", - "partial", - "failed", - "cancelled", - ]; + let selectors = ["completed", "success", "warn", "failed", "cancelled"]; let mut sensors = serde_json::Map::new(); for job_key in ["orders", "daily_orders"] { for selector in selectors { @@ -89,7 +82,7 @@ fn given_terminal_jobs_and_groups_when_selectors_retry_then_outcomes_scope_and_r ("both_completed", "completed", vec!["customers", "orders"]), ("customers_completed", "completed", vec!["customers"]), ("customers_success", "success", vec!["customers"]), - ("customers_partial", "partial", vec!["customers"]), + ("customers_failed", "failed", vec!["customers"]), ("orders_completed", "completed", vec!["orders"]), ] { sensors.insert(format!("{job_key}_executed_{name}"), json!({ @@ -103,7 +96,7 @@ fn given_terminal_jobs_and_groups_when_selectors_retry_then_outcomes_scope_and_r publish_snapshot(store, &input) .await .expect("publish sensors"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -120,11 +113,6 @@ fn given_terminal_jobs_and_groups_when_selectors_retry_then_outcomes_scope_and_r RunOutcome::Warn, [NodeOutcome::Warn, NodeOutcome::Success], ), - ( - "partial", - RunOutcome::Partial, - [NodeOutcome::Success, NodeOutcome::Failed], - ), ( "failed", RunOutcome::Failed, @@ -219,12 +207,12 @@ fn given_terminal_jobs_and_groups_when_selectors_retry_then_outcomes_scope_and_r ], }, SensorExecutionTestCase { - description: "partial outcome is independent of selected-node success", - outcome: RunOutcome::Partial, + description: "a failed run still counts a selected node that succeeded", + outcome: RunOutcome::Failed, nodes: [NodeOutcome::Success, NodeOutcome::Failed], started: [true; 2], - expected_selector: "partial", - expected_filters: &["customers_completed", "customers_partial"], + expected_selector: "failed", + expected_filters: &["customers_completed", "customers_failed"], }, SensorExecutionTestCase { description: "warning is not successful execution", @@ -244,18 +232,18 @@ fn given_terminal_jobs_and_groups_when_selectors_retry_then_outcomes_scope_and_r }, SensorExecutionTestCase { description: "skipped selected node is not successful", - outcome: RunOutcome::Partial, + outcome: RunOutcome::Failed, nodes: [NodeOutcome::Skipped, NodeOutcome::Success], started: [false, true], - expected_selector: "partial", + expected_selector: "failed", expected_filters: &["orders_completed"], }, SensorExecutionTestCase { - description: "a partial run's freshness-only node still does not qualify", - outcome: RunOutcome::Partial, + description: "a failed run's freshness-only node still does not qualify", + outcome: RunOutcome::Failed, nodes: [NodeOutcome::Success, NodeOutcome::Failed], started: [false, true], - expected_selector: "partial", + expected_selector: "failed", expected_filters: &[], }, SensorExecutionTestCase { @@ -318,7 +306,7 @@ fn given_terminal_jobs_and_groups_when_selectors_retry_then_outcomes_scope_and_r let retry = RerunRequest { run_id: Uuid::now_v7(), source_run_id: source_ids[&( - "partial outcome is independent of selected-node success", + "a failed run still counts a selected node that succeeded", "daily_orders", )], from_failure: true, diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_skip.rs b/crates/sqlbuild-orchestration/tests/sensors/test_skip.rs index 7550967380..9e355a059b 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_skip.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_skip.rs @@ -55,7 +55,7 @@ fn given_a_sensor_stuck_on_a_failing_event_when_an_operator_skips_it_then_the_ne .await .expect("triggers") .remove(0); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_skip_in_flight.rs b/crates/sqlbuild-orchestration/tests/sensors/test_skip_in_flight.rs index 2f2a4248fe..059debf285 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_skip_in_flight.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_skip_in_flight.rs @@ -60,7 +60,7 @@ fn given_a_tick_in_flight_on_the_stuck_event_when_an_operator_skips_it_then_the_ .await .expect("triggers") .remove(0); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_sources.rs b/crates/sqlbuild-orchestration/tests/sensors/test_sources.rs index 4d82000387..15ccf1044c 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_sources.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_sources.rs @@ -173,7 +173,7 @@ fn given_imported_source_versions_when_consuming_then_late_facts_queue_once_and_ .applied ); } - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -372,7 +372,7 @@ fn given_a_source_version_that_returns_after_a_complete_scan_prunes_history_when let data: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(path).expect("DuckShop case")) .expect("synthetic source versions"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); @@ -506,7 +506,7 @@ fn given_timestamp_observations_when_age_crosses_the_boundary_then_scoped_pages_ ) .await .expect("registered reader"); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_transitions.rs b/crates/sqlbuild-orchestration/tests/sensors/test_transitions.rs index 1d3d2fab66..56ff48a9b3 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_transitions.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_transitions.rs @@ -75,7 +75,7 @@ fn given_independent_check_failures_when_nondecisive_results_arrive_then_only_ex .await .expect("isolated snapshot"); } - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_types.rs b/crates/sqlbuild-orchestration/tests/sensors/test_types.rs index 8498170cbf..6309704dee 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_types.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_types.rs @@ -1,5 +1,5 @@ use crate::runs::models::{NodeOutcome, RunOutcome, RunStatus}; -use crate::sensors::models::SensorFunctionOutcome; +use crate::sensors::models::{RunEventKind, SensorFunctionOutcome}; use crate::store::tests::store_test_types::Backend; pub(crate) struct SensorTestCase { @@ -132,3 +132,16 @@ pub(crate) struct UnreadableTickTestCase { /// `None` when not failing, else the reason shown on the page and in the trigger list. pub(crate) expected_failing: Option>, } + +pub(crate) struct PartialOutcomeUpgradeTestCase { + pub(crate) description: &'static str, + pub(crate) dialect: &'static crate::store::tests::schema::test_types::StoreDialect, + /// Marks the finished run and its stored Recall facts `partial`, as a store before 0012 has them. + pub(crate) mark_partial: &'static str, + /// Each sensor's watched kinds before the upgrade, as stored. + pub(crate) watched: &'static [(&'static str, &'static [&'static str])], + /// The run's status, its terminal fact's and run_failed event's outcomes after the upgrade. + pub(crate) expected_outcomes: [&'static str; 3], + /// Each sensor's watched kinds after the upgrade, in its snapshot document and its trigger row. + pub(crate) expected_watched: &'static [(&'static str, &'static [RunEventKind])], +} diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_unreadable_ticks.rs b/crates/sqlbuild-orchestration/tests/sensors/test_unreadable_ticks.rs index 70484319bb..da954e61f2 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_unreadable_ticks.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_unreadable_ticks.rs @@ -123,7 +123,7 @@ fn given_a_tick_an_earlier_release_stored_unreadable_when_people_read_the_sensor .await .expect("triggers") .remove(0); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/sensors/test_upgrade.rs b/crates/sqlbuild-orchestration/tests/sensors/test_upgrade.rs index 535e25322b..788d364828 100644 --- a/crates/sqlbuild-orchestration/tests/sensors/test_upgrade.rs +++ b/crates/sqlbuild-orchestration/tests/sensors/test_upgrade.rs @@ -111,7 +111,7 @@ fn given_a_snapshot_with_an_old_form_sensor_when_the_store_upgrades_then_its_job test_case.description ); - let lease = acquire_lease(store, Uuid::now_v7()) + let lease = acquire_lease(store, (Uuid::now_v7(), None)) .await .expect("elect") .expect("leader"); diff --git a/crates/sqlbuild-orchestration/tests/store/schema/test_store_migrations.rs b/crates/sqlbuild-orchestration/tests/store/schema/test_store_migrations.rs index ed92b2cd73..29c5615889 100644 --- a/crates/sqlbuild-orchestration/tests/store/schema/test_store_migrations.rs +++ b/crates/sqlbuild-orchestration/tests/store/schema/test_store_migrations.rs @@ -76,6 +76,10 @@ const SQLITE_CHECKSUMS: &[(i64, &str)] = &[ 11, "690b5ac4f64f5d305a5bb7e3716e41ba2806c0e951b220b413c05b85c223c0a4", ), + ( + 12, + "34f24c9242dbaeca60ce2978c098825a8cba8479723f9662b6e1ee05a3b45d44", + ), ]; const POSTGRES_CHECKSUMS: &[(i64, &str)] = &[ ( @@ -123,6 +127,10 @@ const POSTGRES_CHECKSUMS: &[(i64, &str)] = &[ 11, "921b33c4e32ed5a89dc009f8ccadb62c6f6f4fa3da14a6f9a6b98183c15b6c53", ), + ( + 12, + "9e329995df701a2e34159edfa8a14ab264871756f152e48ccfdc2bd0295e6e15", + ), ]; /// A version 1 store mid-run: a child run holding a concurrency slot, a jobs document and an audit result. const VERSION_1_LIVE_WORK: &str = "ALTER TABLE sqb_schema_version ADD COLUMN version BIGINT; \ diff --git a/crates/sqlbuild-orchestration/tests/store/test_contracts.rs b/crates/sqlbuild-orchestration/tests/store/test_contracts.rs index 2133cbcebe..dc78181a16 100644 --- a/crates/sqlbuild-orchestration/tests/store/test_contracts.rs +++ b/crates/sqlbuild-orchestration/tests/store/test_contracts.rs @@ -15,7 +15,7 @@ pub(crate) mod logical_state; #[path = "replicas/helpers.rs"] pub(crate) mod replica_helpers; #[path = "schema/test_contracts.rs"] -mod schema; +pub(crate) mod schema; #[path = "helpers.rs"] pub(crate) mod store_helpers; #[path = "test_types.rs"] diff --git a/crates/sqlbuild-python-base/src/boundary/main/failure_reason.rs b/crates/sqlbuild-python-base/src/boundary/main/failure_reason.rs new file mode 100644 index 0000000000..b8a4064fc8 --- /dev/null +++ b/crates/sqlbuild-python-base/src/boundary/main/failure_reason.rs @@ -0,0 +1,13 @@ +//! `failure_reason`: a raised error's class and message on one line, redacted as warehouse error text. + +use pyo3::PyErr; +use sqlbuild_core::redaction::main::redact_error_text::redact_error_text; + +/// The driver's class and message on one line, redacted as warehouse error text. +#[must_use] +pub fn failure_reason(error: &PyErr) -> String { + redact_error_text(&error.to_string()) + .split_whitespace() + .collect::>() + .join(" ") +} diff --git a/crates/sqlbuild-python-base/src/boundary/main/mod.rs b/crates/sqlbuild-python-base/src/boundary/main/mod.rs index ff682f89d1..8534883129 100644 --- a/crates/sqlbuild-python-base/src/boundary/main/mod.rs +++ b/crates/sqlbuild-python-base/src/boundary/main/mod.rs @@ -5,6 +5,7 @@ pub mod compiler_guard; pub mod config_value_to_python; pub mod context_variable; pub mod error_text_fields; +pub mod failure_reason; pub mod imported; pub mod json_value_to_python; pub mod keywords; diff --git a/crates/sqlbuild-python-base/src/build_progress/models.rs b/crates/sqlbuild-python-base/src/build_progress/models.rs index 36b5e2b04c..d6b544eb0c 100644 --- a/crates/sqlbuild-python-base/src/build_progress/models.rs +++ b/crates/sqlbuild-python-base/src/build_progress/models.rs @@ -49,6 +49,7 @@ use sqlbuild_core::progress::models::ProgressProjection; use sqlbuild_core::progress::models::ProgressSettings; use sqlbuild_core::progress::models::StatementSummary; use sqlbuild_core::terminal_events::models::TerminalRequest; +use std::collections::HashMap; use std::sync::Mutex; use std::sync::MutexGuard; use std::sync::PoisonError; @@ -62,6 +63,15 @@ pub struct NativeProgressProjector { pub(crate) coordinator: Py, /// The lines held back instead of written, while something holds them. pub(crate) held: Mutex>>, + /// Each resource's lines held back until its result is known, while resources are held. + pub(crate) held_by_resource: Mutex>, +} + +/// Lines held back per resource, in the order resources first wrote one. +#[derive(Debug, Default)] +pub(crate) struct HeldResourceLines { + pub(crate) order: Vec, + pub(crate) lines: HashMap>, } impl NativeProgressProjector { @@ -69,6 +79,11 @@ impl NativeProgressProjector { self.held.lock().unwrap_or_else(PoisonError::into_inner) } + /// Whether lines are being held back instead of written. + pub fn is_holding(&self) -> bool { + self.held().is_some() + } + /// Hold back every line from now on instead of writing it. pub fn hold_lines(&self) { *self.held() = Some(Vec::new()); @@ -96,6 +111,53 @@ impl NativeProgressProjector { Ok(()) } + fn held_by_resource(&self) -> MutexGuard<'_, Option> { + self.held_by_resource + .lock() + .unwrap_or_else(PoisonError::into_inner) + } + + /// Hold back each resource's lines from now on until `release_resource` or `discard_resource`. + pub fn hold_resources(&self) { + *self.held_by_resource() = Some(HeldResourceLines::default()); + } + + /// Write the lines held back for `resource_id`, as they would have been written. + pub fn release_resource(&self, py: Python<'_>, resource_id: &str) -> PyResult<()> { + let lines: Vec = match self.held_by_resource().as_mut() { + Some(held) => held.lines.remove(resource_id).unwrap_or_default(), + None => Vec::new(), + }; + self.write_held(py, &lines) + } + + /// Drop the lines held back for `resource_id`, and never render that attempt's terminal. + pub fn discard_resource(&self, resource_id: &str) -> PyResult<()> { + if let Some(held) = self.held_by_resource().as_mut() { + held.lines.remove(resource_id); + } + self.locked()?.forget_resource_attempts(resource_id); + Ok(()) + } + + /// Never render the pending terminals of the resources reported under `resource_name`. + pub fn forget_resource_named(&self, resource_name: &str) -> PyResult<()> { + self.locked()?.forget_resource_named(resource_name); + Ok(()) + } + + /// Write lines as they come again, first writing every resource's lines still held back. + pub fn stop_holding_resources(&self, py: Python<'_>) -> PyResult<()> { + let Some(mut held) = self.held_by_resource().take() else { + return Ok(()); + }; + for resource_id in std::mem::take(&mut held.order) { + let lines: Vec = held.lines.remove(&resource_id).unwrap_or_default(); + self.write_held(py, &lines)?; + } + Ok(()) + } + pub(crate) fn locked(&self) -> PyResult> { self.state .lock() @@ -107,6 +169,16 @@ impl NativeProgressProjector { &self, py: Python<'_>, update: impl FnOnce(ProgressProjection) -> (ProgressProjection, Vec, T), + ) -> PyResult { + self.write_for(py, None, update) + } + + /// `write_with` for lines about `resource_id`, which wait while resources are held. + pub(crate) fn write_for( + &self, + py: Python<'_>, + resource_id: Option<&str>, + update: impl FnOnce(ProgressProjection) -> (ProgressProjection, Vec, T), ) -> PyResult { let coordinator: &Bound<'_, PyAny> = self.coordinator.bind(py); let lock: Bound<'_, PyAny> = native_field(coordinator, "lock")?; @@ -120,6 +192,18 @@ impl NativeProgressProjector { }; for line in lines { let text: String = format!("{line}\n"); + if let (Some(resource_id), Some(held)) = + (resource_id, self.held_by_resource().as_mut()) + { + if !held.lines.contains_key(resource_id) { + held.order.push(resource_id.to_owned()); + } + held.lines + .entry(resource_id.to_owned()) + .or_default() + .push(text); + continue; + } if let Some(held) = self.held().as_mut() { held.push(text); continue; @@ -158,6 +242,7 @@ impl NativeProgressProjector { stream: stream.unbind(), coordinator: coordinator.unbind(), held: Mutex::new(None), + held_by_resource: Mutex::new(None), }) } @@ -194,6 +279,13 @@ impl NativeProgressProjector { Ok(()) } + /// Declare that this resource never starts, so it shows only its terminal row. + #[pyo3(signature = (*, resource_name))] + pub(crate) fn expect_no_start(&self, resource_name: &str) -> PyResult<()> { + self.locked()?.expect_no_start(resource_name); + Ok(()) + } + /// Record how one audit attempt ended, so its terminal row shows the outcome. #[pyo3(signature = (*, resource_attempt_id, outcome))] pub(crate) fn record_audit_outcome( @@ -215,7 +307,7 @@ impl NativeProgressProjector { /// Consume one known lifecycle fact idempotently. pub(crate) fn consume(&self, py: Python<'_>, event: &Bound<'_, PyAny>) -> PyResult<()> { let event: ProgressEvent = progress_event(event)?; - self.write_with(py, |projection| { + self.write_for(py, event.resource_id.as_deref(), |projection| { let (projection, lines) = consume_progress_event(projection, &event); (projection, lines, ()) }) diff --git a/crates/sqlbuild-python-base/src/event_exporting/_helpers/closed_export.rs b/crates/sqlbuild-python-base/src/event_exporting/_helpers/closed_export.rs new file mode 100644 index 0000000000..f90b1b3bd9 --- /dev/null +++ b/crates/sqlbuild-python-base/src/event_exporting/_helpers/closed_export.rs @@ -0,0 +1,25 @@ +//! The newest command scope this thread closed, kept for the worker that reports the run. + +use std::cell::RefCell; + +use pyo3::prelude::{Bound, PyAny}; + +use crate::event_exporting::models::{ClosedExport, EventExportSummary}; + +thread_local! { + pub(crate) static CLOSED_EXPORT: RefCell> = const { RefCell::new(None) }; +} + +/// Keep `summary`'s per-sink counts and the `teardown_failures` for `take_closed_export`. +pub(crate) fn record_closed_export(summary: &Bound<'_, PyAny>, teardown_failures: Vec) { + let per_exporter = summary + .cast::() + .map(|summary| summary.get().snapshot.per_exporter.clone()) + .unwrap_or_default(); + CLOSED_EXPORT.with(|closed| { + *closed.borrow_mut() = Some(ClosedExport { + per_exporter, + teardown_failures, + }); + }); +} diff --git a/crates/sqlbuild-python-base/src/event_exporting/_helpers/mod.rs b/crates/sqlbuild-python-base/src/event_exporting/_helpers/mod.rs index b25725a0ef..0ce4c2febd 100644 --- a/crates/sqlbuild-python-base/src/event_exporting/_helpers/mod.rs +++ b/crates/sqlbuild-python-base/src/event_exporting/_helpers/mod.rs @@ -1,2 +1,3 @@ +pub(crate) mod closed_export; pub(crate) mod scope; pub(crate) mod values; diff --git a/crates/sqlbuild-python-base/src/event_exporting/main/mod.rs b/crates/sqlbuild-python-base/src/event_exporting/main/mod.rs index d9c23b7f2a..98930de846 100644 --- a/crates/sqlbuild-python-base/src/event_exporting/main/mod.rs +++ b/crates/sqlbuild-python-base/src/event_exporting/main/mod.rs @@ -8,3 +8,4 @@ pub mod register_scope; pub mod severity_from; pub mod severity_object; pub mod state_error; +pub mod take_closed_export; diff --git a/crates/sqlbuild-python-base/src/event_exporting/main/take_closed_export.rs b/crates/sqlbuild-python-base/src/event_exporting/main/take_closed_export.rs new file mode 100644 index 0000000000..712aa40cf0 --- /dev/null +++ b/crates/sqlbuild-python-base/src/event_exporting/main/take_closed_export.rs @@ -0,0 +1,10 @@ +//! `take_closed_export`: what the sinks of the command scope this thread closed last delivered. + +use crate::event_exporting::_helpers::closed_export::CLOSED_EXPORT; +use crate::event_exporting::models::ClosedExport; + +/// The newest closed scope's sink counts and teardown failures, once; `None` when no scope closed since. +#[must_use] +pub fn take_closed_export() -> Option { + CLOSED_EXPORT.with(|closed| closed.borrow_mut().take()) +} diff --git a/crates/sqlbuild-python-base/src/event_exporting/models.rs b/crates/sqlbuild-python-base/src/event_exporting/models.rs index 65be8bf398..b29aaa0673 100644 --- a/crates/sqlbuild-python-base/src/event_exporting/models.rs +++ b/crates/sqlbuild-python-base/src/event_exporting/models.rs @@ -3,6 +3,7 @@ use crate::boundary::main::call_with::call_with; use crate::boundary::main::context_variable::context_variable; use crate::boundary::models::KeywordArguments; +use crate::event_exporting::_helpers::closed_export::record_closed_export; use crate::event_exporting::_helpers::scope::CURRENT_SCOPE; use crate::event_exporting::_helpers::scope::ProviderSessionCloser; use crate::event_exporting::_helpers::scope::ScopeState; @@ -584,9 +585,16 @@ impl EventExporterCommandScope { .unbind()) } - /// Flush sink delivery before reverse-order provider teardown. + /// Flush sink delivery before reverse-order provider teardown, and keep what each sink delivered. pub(crate) fn close(&self, py: Python<'_>) -> PyResult> { let summary: Py = self.dispatcher.bind(py).call_method0("shutdown")?.unbind(); + self.finalize_providers(py)?; + record_closed_export(summary.bind(py), self.teardown_failures()?); + Ok(summary) + } + + /// Tear the sink providers down once delivery is idle, keeping each teardown that raised. + fn finalize_providers(&self, py: Python<'_>) -> PyResult<()> { let session: Py = { let mut state = self.locked()?; let Some(session) = state @@ -594,10 +602,10 @@ impl EventExporterCommandScope { .as_ref() .map(|session| session.clone_ref(py)) else { - return Ok(summary); + return Ok(()); }; if state.provider_close_registered { - return Ok(summary); + return Ok(()); } state.provider_close_registered = true; session @@ -610,7 +618,7 @@ impl EventExporterCommandScope { { self.locked()?.teardown_failures = teardown_failures(py, &error); } - Ok(summary) + Ok(()) } /// Each sink provider whose teardown raised when the scope closed, with its error type. @@ -658,3 +666,10 @@ impl EventExporterScopeContext { Ok(false) } } + +/// What a closed command scope's sinks did: each sink's counts, and each sink provider whose teardown raised. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ClosedExport { + pub per_exporter: Vec<(String, sqlbuild_core::event_export::models::ExporterCounts)>, + pub teardown_failures: Vec, +} diff --git a/crates/sqlbuild-python-base/src/invocation_phases/_helpers/held.rs b/crates/sqlbuild-python-base/src/invocation_phases/_helpers/held.rs new file mode 100644 index 0000000000..1df7cb7d66 --- /dev/null +++ b/crates/sqlbuild-python-base/src/invocation_phases/_helpers/held.rs @@ -0,0 +1,9 @@ +//! The planned phase this thread finished, until the command knows everything its plan runs. + +use std::cell::RefCell; + +use crate::invocation_phases::models::HeldPhase; + +thread_local! { + pub(crate) static HELD_PLANNED: RefCell> = const { RefCell::new(None) }; +} diff --git a/crates/sqlbuild-python-base/src/invocation_phases/_helpers/mod.rs b/crates/sqlbuild-python-base/src/invocation_phases/_helpers/mod.rs new file mode 100644 index 0000000000..7af26de363 --- /dev/null +++ b/crates/sqlbuild-python-base/src/invocation_phases/_helpers/mod.rs @@ -0,0 +1 @@ +pub(crate) mod held; diff --git a/crates/sqlbuild-python-base/src/invocation_phases/constants.rs b/crates/sqlbuild-python-base/src/invocation_phases/constants.rs index f94c266cfa..1084904622 100644 --- a/crates/sqlbuild-python-base/src/invocation_phases/constants.rs +++ b/crates/sqlbuild-python-base/src/invocation_phases/constants.rs @@ -17,3 +17,5 @@ pub const CONNECTED_PHASE: &str = "connected"; pub const INSPECTED_PHASE: &str = "inspected"; /// The plan was generated. pub const PLANNED_PHASE: &str = "planned"; +/// Execution began, before any of its work ran. +pub const STARTED_EXECUTION_PHASE: &str = "started_execution"; diff --git a/crates/sqlbuild-python-base/src/invocation_phases/main/hold_planned_phase.rs b/crates/sqlbuild-python-base/src/invocation_phases/main/hold_planned_phase.rs new file mode 100644 index 0000000000..4e43a1f642 --- /dev/null +++ b/crates/sqlbuild-python-base/src/invocation_phases/main/hold_planned_phase.rs @@ -0,0 +1,9 @@ +//! `hold_planned_phase`: keep the planned phase back until the plan's Python nodes are known. + +use crate::invocation_phases::_helpers::held::HELD_PLANNED; +use crate::invocation_phases::models::HeldPhase; + +/// Hold `phase` on this thread for `publish_planned_phase`, replacing any held before. +pub fn hold_planned_phase(phase: HeldPhase) { + HELD_PLANNED.with(|held| *held.borrow_mut() = Some(phase)); +} diff --git a/crates/sqlbuild-python-base/src/invocation_phases/main/mod.rs b/crates/sqlbuild-python-base/src/invocation_phases/main/mod.rs index cb988318cb..88aadebf19 100644 --- a/crates/sqlbuild-python-base/src/invocation_phases/main/mod.rs +++ b/crates/sqlbuild-python-base/src/invocation_phases/main/mod.rs @@ -1 +1,3 @@ +pub mod hold_planned_phase; pub mod phase_since; +pub mod publish_planned_phase; diff --git a/crates/sqlbuild-python-base/src/invocation_phases/main/publish_planned_phase.rs b/crates/sqlbuild-python-base/src/invocation_phases/main/publish_planned_phase.rs new file mode 100644 index 0000000000..e9dc8d90fb --- /dev/null +++ b/crates/sqlbuild-python-base/src/invocation_phases/main/publish_planned_phase.rs @@ -0,0 +1,25 @@ +//! `publish_planned_phase`: the held planned phase, with what the plan will run. + +use pyo3::prelude::{PyResult, Python}; + +use crate::invocation_phases::_helpers::held::HELD_PLANNED; +use crate::invocation_phases::constants::PLANNED_PHASE; +use crate::invocation_phases::models::{HeldPhase, InvocationPhase}; +use crate::native_host::main::publish_invocation_phase::publish_invocation_phase; + +/// Publish the planned phase this thread holds, named by `summary` such as `3 selected · 1 Python node`. +pub fn publish_planned_phase(py: Python<'_>, (summary, count): (String, usize)) -> PyResult<()> { + let held: HeldPhase = HELD_PLANNED + .with(|held| held.borrow_mut().take()) + .unwrap_or_default(); + publish_invocation_phase( + py, + &InvocationPhase { + phase: PLANNED_PHASE, + duration_ms: held.duration_ms, + count: Some(i64::try_from(count).unwrap_or(i64::MAX)), + name: Some(summary), + detail: held.detail, + }, + ) +} diff --git a/crates/sqlbuild-python-base/src/invocation_phases/mod.rs b/crates/sqlbuild-python-base/src/invocation_phases/mod.rs index d6f430ebab..9e210f7407 100644 --- a/crates/sqlbuild-python-base/src/invocation_phases/mod.rs +++ b/crates/sqlbuild-python-base/src/invocation_phases/mod.rs @@ -1,5 +1,6 @@ //! The finished phases of an invocation, published as `invocation_phase` lifecycle events. +pub(crate) mod _helpers; pub mod constants; pub mod main; pub mod models; diff --git a/crates/sqlbuild-python-base/src/invocation_phases/models.rs b/crates/sqlbuild-python-base/src/invocation_phases/models.rs index 996d3e36dd..fef7b7259b 100644 --- a/crates/sqlbuild-python-base/src/invocation_phases/models.rs +++ b/crates/sqlbuild-python-base/src/invocation_phases/models.rs @@ -13,3 +13,19 @@ pub struct InvocationPhase<'a> { /// The phase's sub-steps or facts, joined with ` · `. pub detail: Option, } + +/// A finished phase kept back until its summary is known: how long it took and its facts. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct HeldPhase { + pub duration_ms: Option, + pub detail: Option, +} + +impl From> for HeldPhase { + fn from(phase: InvocationPhase<'_>) -> Self { + Self { + duration_ms: phase.duration_ms, + detail: phase.detail, + } + } +} diff --git a/crates/sqlbuild-python-base/src/native_host/_helpers/results.rs b/crates/sqlbuild-python-base/src/native_host/_helpers/results.rs index 518d3d3203..7352c312f3 100644 --- a/crates/sqlbuild-python-base/src/native_host/_helpers/results.rs +++ b/crates/sqlbuild-python-base/src/native_host/_helpers/results.rs @@ -232,12 +232,12 @@ record!(ItemTimeoutReport { record!(SqlTestExecutionResult { test_name, outcome, source_path, block_index, parent_name, case_name, case_index, case_fingerprint, parameter_schema, parameter_values, step_results, error_code, error_help, - error_message, real_model_count, timeout, + error_message, real_model_count, timeout, local_refusal, }); record!(BuildExecutionResult { status, model_results, seed_results, function_results, load_results, test_results, source_audit_results, end_audit_results, success_count, failure_count, timeout_count, - skipped_count, warning_count, insufficient_count, ignored_audit_failure_count, + skipped_count, warning_count, insufficient_count, ignored_audit_failure_count, not_run_count, audit_result_projection_attempted_count, audit_result_projection_written_count, audit_result_projection_failed_count, timings, }); @@ -302,6 +302,7 @@ impl<'py> ReadResult<'py> for ScenarioRunResult> { error_help: ReadResult::read(&field(value, "error_help")?)?, error_message: ReadResult::read(&field(value, "error_message")?)?, duration_ms: ReadResult::read(&field(value, "duration_ms")?)?, + local_refusal: ReadResult::read(&field(value, "local_refusal")?)?, }) } } diff --git a/crates/sqlbuild-python-base/src/records/_helpers/contract_records/constants.rs b/crates/sqlbuild-python-base/src/records/_helpers/contract_records/constants.rs index ed1198e22e..f79da341dd 100644 --- a/crates/sqlbuild-python-base/src/records/_helpers/contract_records/constants.rs +++ b/crates/sqlbuild-python-base/src/records/_helpers/contract_records/constants.rs @@ -148,6 +148,8 @@ const R_TARGET_CONFIG: RecordSpec = RecordSpec { FieldDefault::NativeCall(RecordId::TargetWarehousesConfig), ), FieldSpec::new("concurrency", FieldDefault::None), + FieldSpec::new("test_run_on", FieldDefault::None), + FieldSpec::new("scenario_run_on", FieldDefault::None), FieldSpec::new("catalog_connection", FieldDefault::None), FieldSpec::new("ignore_audit_failures", FieldDefault::None), FieldSpec::new("plan_from", FieldDefault::None), @@ -210,6 +212,8 @@ const R_LOCAL_TARGET_CONFIG: RecordSpec = RecordSpec { FieldDefault::NativeCall(RecordId::TargetWarehousesConfig), ), FieldSpec::new("concurrency", FieldDefault::None), + FieldSpec::new("test_run_on", FieldDefault::None), + FieldSpec::new("scenario_run_on", FieldDefault::None), FieldSpec::new("catalog_connection", FieldDefault::None), FieldSpec::new("ignore_audit_failures", FieldDefault::None), FieldSpec::new("plan_from", FieldDefault::None), @@ -246,6 +250,8 @@ const R_SETTINGS_CONFIG: RecordSpec = RecordSpec { FieldSpec::new("allow_warehouse_round_trips", FieldDefault::False), FieldSpec::new("ignore_audit_failures", FieldDefault::False), FieldSpec::new("record_run_host", FieldDefault::True), + FieldSpec::new("test_run_on", FieldDefault::Text("auto")), + FieldSpec::new("scenario_run_on", FieldDefault::Text("auto")), ], }; const R_SCOPES_CONFIG: RecordSpec = RecordSpec { diff --git a/crates/sqlbuild-python-base/src/records/_helpers/planner_records/constants.rs b/crates/sqlbuild-python-base/src/records/_helpers/planner_records/constants.rs index bc42bb4dbd..02074e1cb1 100644 --- a/crates/sqlbuild-python-base/src/records/_helpers/planner_records/constants.rs +++ b/crates/sqlbuild-python-base/src/records/_helpers/planner_records/constants.rs @@ -53,6 +53,7 @@ const R_PLANNER_SCOPE: RecordSpec = RecordSpec { ), FieldSpec::new("load_sources", FieldDefault::True), FieldSpec::new("end_audit_source_keys", FieldDefault::EmptyFrozenset), + FieldSpec::new("selected_audit_names", FieldDefault::EmptyFrozenset), ], }; const R_SQL_TEST_ASSERTION_STEP: RecordSpec = RecordSpec { @@ -948,6 +949,8 @@ const R_PLAN_OUTPUT: RecordSpec = RecordSpec { FieldSpec::new("existing_model_names", FieldDefault::EmptyFrozenset), FieldSpec::new("end_audit_source_keys", FieldDefault::EmptyFrozenset), FieldSpec::new("ignore_audit_failures", FieldDefault::False), + FieldSpec::new("selected_audit_names", FieldDefault::EmptyTuple), + FieldSpec::new("audits_not_run", FieldDefault::EmptyDict), ], }; diff --git a/crates/sqlbuild-python-base/src/records/constants.rs b/crates/sqlbuild-python-base/src/records/constants.rs index 643e4877df..8e36a779b2 100644 --- a/crates/sqlbuild-python-base/src/records/constants.rs +++ b/crates/sqlbuild-python-base/src/records/constants.rs @@ -627,8 +627,8 @@ const SCENARIO_TEST_COMMAND_REQUEST: RecordSpec = RecordSpec { FieldSpec::new("selectors", FieldDefault::EmptyTuple), FieldSpec::new("exclude", FieldDefault::EmptyTuple), FieldSpec::new("retain", FieldDefault::False), - FieldSpec::new("local", FieldDefault::False), - FieldSpec::new("strict", FieldDefault::False), + FieldSpec::new("run_on", FieldDefault::None), + FieldSpec::new("verbose", FieldDefault::False), FieldSpec::new("concurrency", FieldDefault::None), FieldSpec::new("sync_snapshots", FieldDefault::False), FieldSpec::new("refresh", FieldDefault::False), @@ -705,6 +705,8 @@ const TEST_COMMAND_REQUEST: RecordSpec = RecordSpec { FieldSpec::new("case_name", FieldDefault::None), FieldSpec::new("inspect", FieldDefault::False), FieldSpec::new("test_timeout", FieldDefault::None), + FieldSpec::new("run_on", FieldDefault::None), + FieldSpec::new("verbose", FieldDefault::False), FieldSpec::new("since", FieldDefault::None), FieldSpec::new("explain", FieldDefault::False), FieldSpec::new("sql_only", FieldDefault::False), diff --git a/crates/sqlbuild-python-base/src/records/main/fields/attribute_text.rs b/crates/sqlbuild-python-base/src/records/main/fields/attribute_text.rs new file mode 100644 index 0000000000..09946f613e --- /dev/null +++ b/crates/sqlbuild-python-base/src/records/main/fields/attribute_text.rs @@ -0,0 +1,11 @@ +//! An object's attribute as text, when it has one that isn't `None`. + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; + +/// `name` of `value` as text, or `None` when it is absent or `None`. +pub fn attribute_text(value: &Bound<'_, PyAny>, name: &str) -> PyResult> { + match value.getattr_opt(name)? { + Some(item) if !item.is_none() => Ok(Some(item.str()?.extract()?)), + Some(_) | None => Ok(None), + } +} diff --git a/crates/sqlbuild-python-base/src/records/main/fields/mod.rs b/crates/sqlbuild-python-base/src/records/main/fields/mod.rs index aa98e4b666..affa1a399f 100644 --- a/crates/sqlbuild-python-base/src/records/main/fields/mod.rs +++ b/crates/sqlbuild-python-base/src/records/main/fields/mod.rs @@ -1,4 +1,5 @@ pub mod all_specs; +pub mod attribute_text; pub mod by_attribute; pub mod cached_value; pub mod enum_member_value; diff --git a/crates/sqlbuild-python-compile/src/analysis/_helpers/sql_test_comparisons.rs b/crates/sqlbuild-python-compile/src/analysis/_helpers/sql_test_comparisons.rs index a60b899a58..8ac829a989 100644 --- a/crates/sqlbuild-python-compile/src/analysis/_helpers/sql_test_comparisons.rs +++ b/crates/sqlbuild-python-compile/src/analysis/_helpers/sql_test_comparisons.rs @@ -9,7 +9,9 @@ use serde_json::{Value, json}; use sqlbuild_analysis::compiler::main::missing_expected_columns::missing_expected_columns; use sqlbuild_analysis::compiler::main::scenario_expected_comparison_sql::scenario_expected_comparison_sql; use sqlbuild_analysis::compiler::main::sql_test_difference_sampling::render_difference_sample_json; +use sqlbuild_analysis::compiler::main::sql_test_placed_rendering::render_placed_comparison; use sqlbuild_analysis::compiler::main::sql_test_rendering::render_json; +use sqlbuild_analysis::compiler::types::PlacedComparisonSql; use sqlbuild_python_base::boundary::main::value_error::value_error; use sqlbuild_python_base::boundary::models::Request; @@ -160,6 +162,25 @@ pub(crate) fn chain_step_request(step: &Bound<'_, PyAny>) -> PyResult { })) } +/// One planned test's comparison SQL and each CTE body's character range and origin in it. +#[pyfunction] +#[pyo3(signature = (test_entry, **options))] +pub(crate) fn render_sql_test_comparison_segments( + py: Python<'_>, + test_entry: Bound<'_, PyAny>, + options: Option<&Bound<'_, PyDict>>, +) -> PyResult { + let settings: RenderSettings = RenderSettings::read(options)?; + let request: String = serde_json::to_string(&comparison_request( + &test_entry, + &settings.set_difference_operator, + settings.sql_analysis_dialect.as_deref(), + )?) + .map_err(value_error)?; + py.compiler_detach(|| render_placed_comparison(&request)) + .map_err(value_error) +} + /// A bounded query for one direction of an expected-output difference of one chain step. #[pyfunction] #[pyo3(signature = (**options))] diff --git a/crates/sqlbuild-python-compile/src/analysis/main/register_sql_test_comparisons.rs b/crates/sqlbuild-python-compile/src/analysis/main/register_sql_test_comparisons.rs index f0af98d867..857faa425e 100644 --- a/crates/sqlbuild-python-compile/src/analysis/main/register_sql_test_comparisons.rs +++ b/crates/sqlbuild-python-compile/src/analysis/main/register_sql_test_comparisons.rs @@ -2,6 +2,7 @@ use crate::analysis::_helpers::sql_test_comparisons::build_scenario_expected_comparison_sql; use crate::analysis::_helpers::sql_test_comparisons::describe_missing_expected_columns; +use crate::analysis::_helpers::sql_test_comparisons::render_sql_test_comparison_segments; use crate::analysis::_helpers::sql_test_comparisons::render_sql_test_comparison_sql; use crate::analysis::_helpers::sql_test_comparisons::render_sql_test_difference_sample_sql; use pyo3::prelude::{Bound, PyModule, PyModuleMethods, PyResult}; @@ -10,6 +11,10 @@ use pyo3::wrap_pyfunction; /// Register the sql test comparisons functions and classes. pub fn register_sql_test_comparisons(module: &Bound<'_, PyModule>) -> PyResult<()> { module.add_function(wrap_pyfunction!(render_sql_test_comparison_sql, module)?)?; + module.add_function(wrap_pyfunction!( + render_sql_test_comparison_segments, + module + )?)?; module.add_function(wrap_pyfunction!( render_sql_test_difference_sample_sql, module diff --git a/crates/sqlbuild-python-compile/src/compile_driver/_helpers/setup/pipeline_entries.rs b/crates/sqlbuild-python-compile/src/compile_driver/_helpers/setup/pipeline_entries.rs index 4a544ce36a..9033d5a431 100644 --- a/crates/sqlbuild-python-compile/src/compile_driver/_helpers/setup/pipeline_entries.rs +++ b/crates/sqlbuild-python-compile/src/compile_driver/_helpers/setup/pipeline_entries.rs @@ -11,6 +11,17 @@ use sqlbuild_python_base::records::types::RecordId; /// Discovered Python node functions whose selectors need the Python graph. const PYTHON_NODE_FUNCTIONS: [&str; 3] = ["loader_functions", "asset_functions", "check_functions"]; +/// The plan entries the SQL phase runs; with none of them it opens no warehouse connection. +pub(crate) const SQL_PHASE_ENTRIES: [&str; 8] = [ + "execution_order", + "audit_entries", + "test_entries", + "migration_entries", + "column_migration_entries", + "retention_entries", + "old_name_view_entries", + "table_type_entries", +]; /// Plan entry lists that are runtime work. pub(crate) const PLAN_WORK_ENTRIES: [&str; 6] = [ "model_entries", diff --git a/crates/sqlbuild-python-compile/src/compile_driver/main/jobs/mod.rs b/crates/sqlbuild-python-compile/src/compile_driver/main/jobs/mod.rs index 97102c5ad6..1230c285cc 100644 --- a/crates/sqlbuild-python-compile/src/compile_driver/main/jobs/mod.rs +++ b/crates/sqlbuild-python-compile/src/compile_driver/main/jobs/mod.rs @@ -4,3 +4,4 @@ pub mod job_override_fields; pub mod job_plan_fields; pub mod job_run_context; pub mod planned_job_settings; +pub mod publish_execution_start; diff --git a/crates/sqlbuild-python-compile/src/compile_driver/main/jobs/publish_execution_start.rs b/crates/sqlbuild-python-compile/src/compile_driver/main/jobs/publish_execution_start.rs new file mode 100644 index 0000000000..2807dd39bf --- /dev/null +++ b/crates/sqlbuild-python-compile/src/compile_driver/main/jobs/publish_execution_start.rs @@ -0,0 +1,32 @@ +//! Announce that a build's execution started, before any of its work runs. + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; +use sqlbuild_python_base::invocation_phases::constants::STARTED_EXECUTION_PHASE; +use sqlbuild_python_base::invocation_phases::models::InvocationPhase; +use sqlbuild_python_base::native_host::main::publish_invocation_phase::publish_invocation_phase; +use sqlbuild_python_base::records::main::fields::field::field as native_field; + +use crate::compile_driver::_helpers::setup::pipeline_entries::SQL_PHASE_ENTRIES; + +/// Publish `started_execution` with the SQL phase's concurrency under `limit`, and its connections when it runs anything. +pub fn publish_execution_start(plan: &Bound<'_, PyAny>, limit: i64) -> PyResult<()> { + let mut width: i64 = + i64::try_from(native_field(plan, "execution_order")?.len()?).unwrap_or(i64::MAX); + for entry in native_field(plan, "model_entries")?.try_iter()? { + width = width.max(native_field(&entry?, "batch_concurrency")?.extract()?); + } + let concurrency: i64 = limit.max(1).min(width.max(1)); + let mut has_work: bool = false; + for name in SQL_PHASE_ENTRIES { + has_work |= native_field(plan, name)?.is_truthy()?; + } + publish_invocation_phase( + plan.py(), + &InvocationPhase { + phase: STARTED_EXECUTION_PHASE, + count: Some(concurrency), + detail: has_work.then(|| format!("{} connections", concurrency + 1)), + ..InvocationPhase::default() + }, + ) +} diff --git a/crates/sqlbuild-python-compile/src/compile_driver/main/setup/build_python_run_plan_outputs.rs b/crates/sqlbuild-python-compile/src/compile_driver/main/setup/build_python_run_plan_outputs.rs index 1ea0b41a35..1d17dbecc7 100644 --- a/crates/sqlbuild-python-compile/src/compile_driver/main/setup/build_python_run_plan_outputs.rs +++ b/crates/sqlbuild-python-compile/src/compile_driver/main/setup/build_python_run_plan_outputs.rs @@ -4,6 +4,7 @@ use crate::compile_driver::_helpers::setup::python_plan_entries::NodeKinds; use crate::compile_driver::_helpers::setup::python_plan_entries::node_graph; use crate::compile_driver::_helpers::setup::python_plan_entries::plan_entries; use crate::compile_driver::_helpers::setup::python_plan_entries::skipped_ingress_warnings; +use crate::compile_driver::main::setup::publish_plan_summary::publish_plan_summary; use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; use pyo3::pyfunction; use pyo3::types::{PyDict, PyTuple}; @@ -39,6 +40,7 @@ pub fn build_python_run_plan_outputs<'py>( let run_selection: Bound<'py, PyAny> = arguments.value("run_selection")?; let selected: Bound<'py, PyAny> = arguments.value("selected_python_node_names")?; if run_selection.is_none() { + publish_plan_summary(&plan_output, PyTuple::empty(py).as_any())?; return new_record_with( py, RecordId::PythonRunPlanOutputs, @@ -77,6 +79,7 @@ pub fn build_python_run_plan_outputs<'py>( (&graph, &kinds), &native_field(&plan_output, "python_identity_fingerprints")?, )?; + publish_plan_summary(&plan_output, entries.as_any())?; new_record_with( py, RecordId::PythonRunPlanOutputs, diff --git a/crates/sqlbuild-python-compile/src/compile_driver/main/setup/mod.rs b/crates/sqlbuild-python-compile/src/compile_driver/main/setup/mod.rs index 3dc72339e8..60794669aa 100644 --- a/crates/sqlbuild-python-compile/src/compile_driver/main/setup/mod.rs +++ b/crates/sqlbuild-python-compile/src/compile_driver/main/setup/mod.rs @@ -16,6 +16,7 @@ pub mod preserved_loader_schemas; pub mod progress; pub mod project_graph; pub mod project_target_settings; +pub mod publish_plan_summary; pub mod python_node_count; pub mod python_read_source_names_for; pub mod register_inputs; diff --git a/crates/sqlbuild-python-compile/src/compile_driver/main/setup/publish_plan_summary.rs b/crates/sqlbuild-python-compile/src/compile_driver/main/setup/publish_plan_summary.rs new file mode 100644 index 0000000000..856ecc863c --- /dev/null +++ b/crates/sqlbuild-python-compile/src/compile_driver/main/setup/publish_plan_summary.rs @@ -0,0 +1,35 @@ +//! Publish the planned phase with what the plan will run, in the parts of its `Plan ready` line. + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; +use sqlbuild_core::plan_display::main::plan_summary_parts::plan_summary_parts; +use sqlbuild_core::plan_display::models::PlanSummaryCounts; +use sqlbuild_python_base::invocation_phases::main::publish_planned_phase::publish_planned_phase; +use sqlbuild_python_base::records::main::fields::field::field as native_field; + +/// Publish the held planned phase for `plan_output` and its `python_entries`, such as `3 selected · 1 Python node`. +pub fn publish_plan_summary( + plan_output: &Bound<'_, PyAny>, + python_entries: &Bound<'_, PyAny>, +) -> PyResult<()> { + let count = |name: &str| -> PyResult { native_field(plan_output, name)?.len() }; + let mut reloads_sources: bool = false; + for load in native_field(plan_output, "source_load_entries")?.try_iter()? { + reloads_sources |= native_field(&load?, "is_reload")?.is_truthy()?; + } + let counts: PlanSummaryCounts = PlanSummaryCounts { + full_refresh: false, + selected: count("model_entries")? + count("seed_entries")? + count("function_entries")?, + sources: count("source_load_entries")?, + reloads_sources, + python: python_entries.len()?, + audits: count("selected_audit_names")?, + audits_not_run: count("audits_not_run")?, + }; + publish_planned_phase( + plan_output.py(), + ( + plan_summary_parts(&counts).join(" · "), + counts.selected + counts.sources + counts.python, + ), + ) +} diff --git a/crates/sqlbuild-python-front/src/command_runtime/main/mod.rs b/crates/sqlbuild-python-front/src/command_runtime/main/mod.rs index 8d8c59cb22..0584d59289 100644 --- a/crates/sqlbuild-python-front/src/command_runtime/main/mod.rs +++ b/crates/sqlbuild-python-front/src/command_runtime/main/mod.rs @@ -1,3 +1,5 @@ pub mod published_concurrency; pub mod resolve_concurrency; pub mod resolve_configured_concurrency; +pub mod resolve_run_on; +pub mod target_and_settings_value; diff --git a/crates/sqlbuild-python-front/src/command_runtime/main/resolve_run_on.rs b/crates/sqlbuild-python-front/src/command_runtime/main/resolve_run_on.rs new file mode 100644 index 0000000000..2e5bdfc424 --- /dev/null +++ b/crates/sqlbuild-python-front/src/command_runtime/main/resolve_run_on.rs @@ -0,0 +1,21 @@ +//! Where a command runs its unit tests or scenarios: the flag, the target, then `[settings]`. + +use crate::command_runtime::main::target_and_settings_value::target_and_settings_value; +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; +use sqlbuild_core::run_on::main::resolve_run_on::resolve_run_on as resolve_layers; +use sqlbuild_core::run_on::models::{RunOn, RunOnLayers}; + +/// The effective `key` (`test_run_on` or `scenario_run_on`) of a command on `selected_target`. +pub fn resolve_run_on( + flag: &Bound<'_, PyAny>, + discovered: &Bound<'_, PyAny>, + selected_target: &Bound<'_, PyAny>, + key: &str, +) -> PyResult { + let (target, settings) = target_and_settings_value(discovered, selected_target, key)?; + Ok(resolve_layers(&RunOnLayers { + flag: flag.extract()?, + target: target.map(|value| value.extract()).transpose()?.flatten(), + settings: settings.extract()?, + })) +} diff --git a/crates/sqlbuild-python-front/src/command_runtime/main/target_and_settings_value.rs b/crates/sqlbuild-python-front/src/command_runtime/main/target_and_settings_value.rs new file mode 100644 index 0000000000..5a26392dd7 --- /dev/null +++ b/crates/sqlbuild-python-front/src/command_runtime/main/target_and_settings_value.rs @@ -0,0 +1,31 @@ +//! One setting as the selected target sets it and as `[settings]` sets it. + +use crate::compile_attachment::main::build_effective_settings::build_effective_settings; +use crate::contracts::main::resolve_target_config::resolve_target_config; +use crate::contracts::main::resolve_target_name::resolve_target_name; +use pyo3::prelude::{Bound, PyAny, PyResult}; +use sqlbuild_python_base::records::main::fields::field::field as native_field; + +/// `key` on the selected target (`None` without one), and `key` in the effective `[settings]`. +pub fn target_and_settings_value<'py>( + discovered: &Bound<'py, PyAny>, + selected_target: &Bound<'py, PyAny>, + key: &str, +) -> PyResult<(Option>, Bound<'py, PyAny>)> { + let py = discovered.py(); + let project_config: Bound<'py, PyAny> = native_field(discovered, "project_config")?; + let local_config: Bound<'py, PyAny> = native_field(discovered, "local_config")?; + let target: Option> = + match resolve_target_name(py, &project_config, &local_config, selected_target)? { + Some(name) => Some(native_field( + &resolve_target_config(py, &project_config, &local_config, name.as_any())?, + key, + )?), + None => None, + }; + let settings: Bound<'py, PyAny> = native_field( + &build_effective_settings(&project_config, &local_config)?, + key, + )?; + Ok((target, settings)) +} diff --git a/crates/sqlbuild-python-output/src/build_progress/_helpers/nested_progress.rs b/crates/sqlbuild-python-output/src/build_progress/_helpers/nested_progress.rs index ef7bf8e6b2..7f647788a0 100644 --- a/crates/sqlbuild-python-output/src/build_progress/_helpers/nested_progress.rs +++ b/crates/sqlbuild-python-output/src/build_progress/_helpers/nested_progress.rs @@ -31,6 +31,8 @@ pub(crate) struct ReporterState { pub(crate) cursor_hidden: bool, pub(crate) stop_event: Option>, pub(crate) thread: Option>, + /// Whether item progress waits for each item's result, which may abandon the attempt. + pub(crate) holding: bool, } pub(crate) fn optional_argument( diff --git a/crates/sqlbuild-python-output/src/build_progress/main/local_attempt.rs b/crates/sqlbuild-python-output/src/build_progress/main/local_attempt.rs new file mode 100644 index 0000000000..2ae0d34de8 --- /dev/null +++ b/crates/sqlbuild-python-output/src/build_progress/main/local_attempt.rs @@ -0,0 +1,67 @@ +//! In `auto`, local attempts that fall back to the warehouse leave no progress behind. + +use crate::build_progress::main::test_label::test_label; +use crate::build_progress::models::{LocalAttemptStep, NestedCommandProgressCallbacks}; +use crate::result_output::main::events::sql_test_identity::sql_test_identity; +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; +use sqlbuild_python_base::build_progress::main::progress::current_projector::current_projector; +use sqlbuild_python_base::records::main::fields::field::field as native_field; + +/// Hold, release, abandon or settle local attempt progress; whether a settled replay fell back. +pub fn local_attempt(step: LocalAttemptStep<'_>) -> PyResult { + match step { + LocalAttemptStep::Hold(progress, hold) => { + if let (true, Ok(reporter)) = (hold, progress.cast::()) + { + reporter.get().hold_items(progress.py())?; + } + } + LocalAttemptStep::Release(progress) => { + if let Ok(reporter) = progress.cast::() { + reporter.get().release_items(progress.py())?; + } + } + LocalAttemptStep::Abandon(progress, result) => { + if let Ok(reporter) = progress.cast::() { + NestedCommandProgressCallbacks::on_item_abandoned( + reporter, + &test_label(result, "test_name")?, + &sql_test_identity(result, "test_name")?, + )?; + } + } + LocalAttemptStep::HoldReplays(py, hold) => { + if let (true, Some(projector)) = (hold, current_projector(py)?) { + projector.get().hold_lines(); + } + } + LocalAttemptStep::ReleaseReplays(py) => { + if let Some(projector) = current_projector(py)? { + let held: Vec = projector.get().release_lines(); + projector.get().write_held(py, &held)?; + } + } + LocalAttemptStep::SettleReplay(result) => return settle_replay(result), + } + Ok(false) +} + +/// Drop a held replay's lines and terminal when it falls back; else write them. Whether it fell back. +fn settle_replay(result: &Bound<'_, PyAny>) -> PyResult { + let py = result.py(); + let Some(projector) = current_projector(py)? else { + return Ok(false); + }; + let projector = projector.get(); + if !projector.is_holding() { + return Ok(false); + } + let held: Vec = projector.exchange_held_lines(Vec::new()); + if native_field(result, "local_refusal")?.is_none() { + projector.write_held(py, &held)?; + return Ok(false); + } + projector + .forget_resource_named(&native_field(result, "scenario_name")?.extract::()?)?; + Ok(true) +} diff --git a/crates/sqlbuild-python-output/src/build_progress/main/mod.rs b/crates/sqlbuild-python-output/src/build_progress/main/mod.rs index e571014c65..f20870c16b 100644 --- a/crates/sqlbuild-python-output/src/build_progress/main/mod.rs +++ b/crates/sqlbuild-python-output/src/build_progress/main/mod.rs @@ -5,6 +5,7 @@ pub mod format_build_footer_with; pub mod format_execution_header; pub mod format_expectation_detail; pub mod format_expectation_name; +pub mod local_attempt; pub mod register_audit_progress; pub mod register_build_callbacks; pub mod register_footer; diff --git a/crates/sqlbuild-python-output/src/build_progress/main/report_build_checks.rs b/crates/sqlbuild-python-output/src/build_progress/main/report_build_checks.rs index 1fa2f96b8b..18929b0c86 100644 --- a/crates/sqlbuild-python-output/src/build_progress/main/report_build_checks.rs +++ b/crates/sqlbuild-python-output/src/build_progress/main/report_build_checks.rs @@ -1,17 +1,16 @@ //! A worker build reports each audit and SQL test it ran as a check result, as `sqb audit` and `sqb test` do, without checking for a cancel: the build is already finishing. use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; -use sqlbuild_host::models::{AuditExecutionResult, AuditOutcome, SqlTestOutcome}; +use sqlbuild_host::models::SqlTestOutcome; use sqlbuild_host::types::ResultEnum; use sqlbuild_orchestration::runs::models::NodeOutcome; -use sqlbuild_python_base::native_host::types::ReadResult; use sqlbuild_python_base::records::main::fields::field::field; use sqlbuild_python_project::project_snapshot::models::WorkerBuild; use crate::result_output::main::events::sql_test_identity::sql_test_identity; -use crate::result_output::main::results::audit_check_id::audit_check_id; +use crate::result_output::main::results::audit_check::audit_check; -/// Record the outcome of every audit and SQL unit test in `executor_result`, the build's result, so check sensors and run events see them; a check the snapshot doesn't record is skipped. +/// Record the outcome of every audit and SQL unit test in `executor_result`, the build's result, so check sensors and run events see them; a singular audit reports under its own `audit:`, and a check the snapshot doesn't record is skipped. pub fn report_build_checks( py: Python<'_>, worker: &WorkerBuild, @@ -33,13 +32,8 @@ pub fn report_build_checks( ); } for audit in audits { - let outcome = match AuditExecutionResult::read(&audit)?.outcome { - AuditOutcome::Pass => NodeOutcome::Success, - AuditOutcome::Warn | AuditOutcome::Insufficient => NodeOutcome::Warn, - AuditOutcome::Skipped => NodeOutcome::Skipped, - AuditOutcome::Error => NodeOutcome::Failed, - }; - worker.report_attached(py, &audit_check_id(&audit)?, outcome)?; + let (key, outcome) = audit_check(worker, &audit)?; + worker.report_attached(py, &key, outcome)?; } for test in field(executor_result, "test_results")?.try_iter()? { let test = test?; diff --git a/crates/sqlbuild-python-output/src/build_progress/models.rs b/crates/sqlbuild-python-output/src/build_progress/models.rs index e8739769d3..16eb2d044b 100644 --- a/crates/sqlbuild-python-output/src/build_progress/models.rs +++ b/crates/sqlbuild-python-output/src/build_progress/models.rs @@ -942,6 +942,23 @@ impl BuildProgressCallbacks { } } +/// What happens to local test progress in `auto`, where a local attempt can fall back. +#[derive(Clone, Copy)] +pub enum LocalAttemptStep<'a> { + /// When true, hold each test's lines on this reporter until its result is known. + Hold(&'a Bound<'a, PyAny>, bool), + /// Write the reporter's lines as they come again, with those still held. + Release(&'a Bound<'a, PyAny>), + /// Drop the lines of this result's attempt on the reporter: it runs again on the warehouse. + Abandon(&'a Bound<'a, PyAny>, &'a Bound<'a, PyAny>), + /// When true, hold every progress line of a batch of local scenario replays. + HoldReplays(Python<'a>, bool), + /// Write the held replay lines, if any, and write lines as they come again. + ReleaseReplays(Python<'a>), + /// Settle a finished replay while held: drop its lines when it falls back, else write them. + SettleReplay(&'a Bound<'a, PyAny>), +} + /// Render one live spinner row for all running items and grouped completed rows. #[pyclass(module = "sqlbuild._native", frozen)] pub struct NestedCommandProgressCallbacks { @@ -1009,6 +1026,66 @@ impl NestedCommandProgressCallbacks { flush(stream) } + /// Hold each item's progress lines back until its result is known. + pub fn hold_items(&self, py: Python<'_>) -> PyResult<()> { + self.state().holding = true; + if let Some(projector) = self.native_projector(py)? { + projector.get().hold_resources(); + } + Ok(()) + } + + /// Write item progress as it comes again, after any lines still held back. + pub fn release_items(&self, py: Python<'_>) -> PyResult<()> { + self.state().holding = false; + match self.native_projector(py)? { + Some(projector) => self.locked(py, || projector.get().stop_holding_resources(py)), + None => Ok(()), + } + } + + /// Drop an abandoned attempt: its held lines, its terminal row and its place on the live row. + pub fn on_item_abandoned( + slf: &Bound<'_, Self>, + item_name: &str, + canonical_resource_id: &str, + ) -> PyResult<()> { + let py: Python<'_> = slf.py(); + let reporter: &Self = slf.get(); + if let Some(projector) = reporter.native_projector(py)? { + projector.get().discard_resource(canonical_resource_id)?; + } + let stopped: Option> = reporter.locked(py, || { + reporter + .state() + .running + .retain(|(name, _)| name != item_name); + Self::refresh_live_row(slf) + })?; + if let Some(thread) = stopped { + join_spinner(thread.bind(py))?; + } + Ok(()) + } + + /// The invocation's native projector, when progress has one. + pub(crate) fn native_projector<'py>( + &self, + py: Python<'py>, + ) -> PyResult>> { + let Some(projector) = &self.projector else { + return Ok(None); + }; + let Ok(native) = projector + .bind(py) + .clone() + .cast_into::() + else { + return Ok(None); + }; + Ok(Some(native)) + } + pub(crate) fn clear_live_row(&self, py: Python<'_>) -> PyResult<()> { if self.is_tty && self.state().line_active { write(self.stream.bind(py), CLEAR_LINE)?; @@ -1140,7 +1217,10 @@ impl NestedCommandProgressCallbacks { .call_method("expect_resource_enrichment", (), Some(&options))?; } reporter.locked(py, || { - if reporter.sequential && reporter.state().running.is_empty() { + if reporter.sequential + && reporter.state().running.is_empty() + && !reporter.state().holding + { reporter.clear_live_row(py)?; reporter.write_group_header(py, &group)?; } @@ -1183,6 +1263,20 @@ impl NestedCommandProgressCallbacks { let group: String = arguments.value("group_name")?.extract()?; let item_name: String = arguments.value("item_name")?.extract()?; let mut detail: String = optional_argument(&arguments, "detail")?.unwrap_or_default(); + let resource_id: Option = optional_argument(&arguments, "canonical_resource_id")?; + let held: Option> = match reporter.state().holding { + true => reporter.native_projector(py)?, + false => None, + }; + let release = |projector: &Option>| match ( + projector, + &resource_id, + ) { + (Some(projector), Some(resource_id)) => { + projector.get().release_resource(py, resource_id) + } + _ => Ok(()), + }; let duration_ms: Option = match &reporter.projector { Some(projector) => { let canonical: Option = @@ -1226,10 +1320,13 @@ impl NestedCommandProgressCallbacks { }; reporter.clear_live_row(py)?; reporter.write_group_header(py, &item_group)?; + release(&held)?; write( reporter.stream.bind(py), &render_nested_item(&item, &reporter.layout(py)?, reporter.style), )?; + } else { + release(&held)?; } let stopped: Option> = Self::refresh_live_row(slf)?; flush(reporter.stream.bind(py))?; diff --git a/crates/sqlbuild-python-output/src/event_exporting/main/mod.rs b/crates/sqlbuild-python-output/src/event_exporting/main/mod.rs index 72044fb874..c7d1276f22 100644 --- a/crates/sqlbuild-python-output/src/event_exporting/main/mod.rs +++ b/crates/sqlbuild-python-output/src/event_exporting/main/mod.rs @@ -1,2 +1,3 @@ pub mod register_policy; +pub mod sink_delivery_totals; pub mod stop_event_exporter_threads_function; diff --git a/crates/sqlbuild-python-output/src/event_exporting/main/sink_delivery_totals.rs b/crates/sqlbuild-python-output/src/event_exporting/main/sink_delivery_totals.rs new file mode 100644 index 0000000000..d9de5cb1eb --- /dev/null +++ b/crates/sqlbuild-python-output/src/event_exporting/main/sink_delivery_totals.rs @@ -0,0 +1,42 @@ +//! `sink_delivery_totals`: what each sink of the active exporter scope has delivered so far. + +use pyo3::prelude::{Bound, PyAny, PyResult, Python}; +use sqlbuild_orchestration::platform::models::SinkDeliveryTotals; +use sqlbuild_orchestration::runs::models::SinkDelivery; +use sqlbuild_python_base::event_exporting::main::current_scope::current_scope; +use sqlbuild_python_base::event_exporting::models::{ + EventExportSummary, EventExporterCommandScope, +}; + +use crate::event_exporting::models::EventExporterDispatcher; + +/// Each sink's totals since the active scope opened; none without a scope. +pub fn sink_delivery_totals(py: Python<'_>) -> PyResult { + let scope: Bound<'_, PyAny> = current_scope(py)?; + let Ok(scope) = scope.cast::() else { + return Ok(SinkDeliveryTotals::default()); + }; + let dispatcher = scope + .get() + .dispatcher(py) + .into_bound(py) + .cast_into::()?; + let summary = dispatcher.get().summary(py)?; + let mut sinks: Vec = Vec::new(); + for (name, counts) in &summary + .bind(py) + .cast::()? + .get() + .snapshot + .per_exporter + { + sinks.push(SinkDelivery { + name: name.clone(), + accepted: counts.accepted, + delivered: counts.delivered, + dropped: counts.dropped, + failed: counts.failed, + }); + } + Ok(SinkDeliveryTotals { sinks }) +} diff --git a/crates/sqlbuild-python-output/src/result_output/_helpers/results/aggregation.rs b/crates/sqlbuild-python-output/src/result_output/_helpers/results/aggregation.rs index f1a2b9583e..eeeed47861 100644 --- a/crates/sqlbuild-python-output/src/result_output/_helpers/results/aggregation.rs +++ b/crates/sqlbuild-python-output/src/result_output/_helpers/results/aggregation.rs @@ -192,6 +192,7 @@ pub(crate) fn aggregated_build_result<'py>( "ignored_audit_failure_count", counts.ignored_audit_failures.into_bound_py_any(py)?, ), + ("not_run_count", counts.not_run.into_bound_py_any(py)?), ]); call_with( &host_entry(py, ExecutorHost::BuildExecutionResult)?, diff --git a/crates/sqlbuild-python-output/src/result_output/_helpers/results/documents.rs b/crates/sqlbuild-python-output/src/result_output/_helpers/results/documents.rs index b210fde040..eadadc59a0 100644 --- a/crates/sqlbuild-python-output/src/result_output/_helpers/results/documents.rs +++ b/crates/sqlbuild-python-output/src/result_output/_helpers/results/documents.rs @@ -316,7 +316,7 @@ pub(crate) fn build_json<'py>( )?); assets.extend(load_assets(&projection, &retained.loads)?); assets.extend(python_node_assets(&projection, &nodes)?); - let counted: [usize; 5] = if partial { + let counted: [usize; 6] = if partial { let counts = retained.counts(); [ counts.success, @@ -324,6 +324,7 @@ pub(crate) fn build_json<'py>( counts.timeout, counts.skipped, counts.warning, + counts.not_run, ] } else { [ @@ -332,6 +333,7 @@ pub(crate) fn build_json<'py>( count(result.timeout_count)?, count(result.skipped_count)?, count(result.warning_count)?, + count(result.not_run_count)?, ] }; let summary: Bound<'py, PyDict> = summary( @@ -342,6 +344,7 @@ pub(crate) fn build_json<'py>( ("timeout_count", counted[2]), ("skipped_count", counted[3] + python_skipped), ("warning_count", counted[4] + check_warn + python_warnings), + ("not_run_count", counted[5]), ("python_check_pass_count", check_pass), ("python_check_warn_count", check_warn), ("python_check_fail_count", check_fail), diff --git a/crates/sqlbuild-python-output/src/result_output/_helpers/results/projection.rs b/crates/sqlbuild-python-output/src/result_output/_helpers/results/projection.rs index 7f5094ad9d..9b3f50c3a3 100644 --- a/crates/sqlbuild-python-output/src/result_output/_helpers/results/projection.rs +++ b/crates/sqlbuild-python-output/src/result_output/_helpers/results/projection.rs @@ -1,7 +1,7 @@ //! Executor results matched to the canonical terminals of the installed event index. +use crate::result_output::main::events::audit_identity::audit_identity; use crate::result_output::main::events::sql_test_identity::sql_test_identity; -use crate::result_output::main::results::audit_check_id::audit_check_id; use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyRef, PyResult, Python}; use pyo3::types::{PyFloat, PyInt}; use sqlbuild_core::nested_progress::main::audit_resource_id::audit_resource_id; @@ -100,7 +100,7 @@ pub(crate) fn resource_identity(result: &Bound<'_, PyAny>) -> PyResult (name("test_name")?, sql_test_check_id(result)?), - ResultKind::Audit => (name("audit_name")?, audit_check_id(result)?), + ResultKind::Audit => (name("audit_name")?, audit_identity(result, "audit_name")?), ResultKind::CloneItem | ResultKind::Other => return Ok(None), })) } diff --git a/crates/sqlbuild-python-output/src/result_output/main/results/audit_check.rs b/crates/sqlbuild-python-output/src/result_output/main/results/audit_check.rs new file mode 100644 index 0000000000..5cb95d1139 --- /dev/null +++ b/crates/sqlbuild-python-output/src/result_output/main/results/audit_check.rs @@ -0,0 +1,31 @@ +//! The check a worker reports an audit's result as, and the outcome it reports. + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; +use sqlbuild_host::models::{AuditExecutionResult, AuditOutcome}; +use sqlbuild_orchestration::runs::models::NodeOutcome; +use sqlbuild_python_base::native_host::types::ReadResult; +use sqlbuild_python_base::records::main::fields::field::field; +use sqlbuild_python_project::project_snapshot::models::WorkerBuild; + +use crate::result_output::main::events::audit_identity::audit_identity; + +/// `audit`'s published check and outcome: its attached check, else a singular audit's own `audit:`. +pub fn audit_check( + worker: &WorkerBuild, + audit: &Bound<'_, PyAny>, +) -> PyResult<(String, NodeOutcome)> { + let outcome = match AuditExecutionResult::read(audit)?.outcome { + AuditOutcome::Pass => NodeOutcome::Success, + AuditOutcome::Warn | AuditOutcome::Insufficient => NodeOutcome::Warn, + AuditOutcome::Skipped => NodeOutcome::Skipped, + AuditOutcome::NotRun => NodeOutcome::NotRun, + AuditOutcome::Error => NodeOutcome::Failed, + }; + let attached: String = audit_identity(audit, "audit_name")?; + let key: String = if worker.records_check(&attached) { + attached + } else { + format!("audit:{}", field(audit, "audit_name")?.str()?) + }; + Ok((key, outcome)) +} diff --git a/crates/sqlbuild-python-output/src/result_output/main/results/audit_check_id.rs b/crates/sqlbuild-python-output/src/result_output/main/results/audit_check_id.rs deleted file mode 100644 index 4cfb59f2ac..0000000000 --- a/crates/sqlbuild-python-output/src/result_output/main/results/audit_check_id.rs +++ /dev/null @@ -1,9 +0,0 @@ -//! `audit_resource_id` of one audit result. - -use crate::result_output::main::events::audit_identity::audit_identity; -use pyo3::prelude::{Bound, PyAny, PyResult}; - -/// `audit_resource_id` of one audit result. -pub fn audit_check_id(result: &Bound<'_, PyAny>) -> PyResult { - audit_identity(result, "audit_name") -} diff --git a/crates/sqlbuild-python-output/src/result_output/main/results/local_refusal.rs b/crates/sqlbuild-python-output/src/result_output/main/results/local_refusal.rs new file mode 100644 index 0000000000..6a0517adc8 --- /dev/null +++ b/crates/sqlbuild-python-output/src/result_output/main/results/local_refusal.rs @@ -0,0 +1,12 @@ +//! A local run's failure where the warehouse would not fail, as a result's `local_refusal` holds it. + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; +use sqlbuild_core::run_on::main::read_local_refusal::read_local_refusal; +use sqlbuild_core::run_on::models::LocalRefusal; +use std::collections::HashMap; + +/// The item named in a `local_refusal` value and its refusal; `None` when the value is `None`. +pub fn local_refusal(value: &Bound<'_, PyAny>) -> PyResult> { + let found: Option> = value.extract()?; + Ok(found.map(read_local_refusal)) +} diff --git a/crates/sqlbuild-python-output/src/result_output/main/results/mod.rs b/crates/sqlbuild-python-output/src/result_output/main/results/mod.rs index 5f6d034698..8b07f29ef6 100644 --- a/crates/sqlbuild-python-output/src/result_output/main/results/mod.rs +++ b/crates/sqlbuild-python-output/src/result_output/main/results/mod.rs @@ -1,4 +1,4 @@ -pub mod audit_check_id; +pub mod audit_check; pub mod audit_execution_json; pub mod audit_projection; pub mod discard_reports; @@ -9,7 +9,9 @@ pub mod format_load_execution_json; pub mod format_scenario_execution_json_with; pub mod format_scenario_snapshot_execution_json; pub mod format_seed_execution_json; +pub mod local_refusal; pub mod register_aggregation; pub mod register_documents; +pub mod split_scenario_fallbacks; pub mod test_execution_json; pub mod write_execution_json_output; diff --git a/crates/sqlbuild-python-output/src/result_output/main/results/split_scenario_fallbacks.rs b/crates/sqlbuild-python-output/src/result_output/main/results/split_scenario_fallbacks.rs new file mode 100644 index 0000000000..a9db5c2a99 --- /dev/null +++ b/crates/sqlbuild-python-output/src/result_output/main/results/split_scenario_fallbacks.rs @@ -0,0 +1,33 @@ +//! Local scenario replays that failed where the warehouse would not, placed as the run mode says. + +use crate::result_output::main::results::local_refusal::local_refusal; +use crate::result_output::types::ScenarioResults; +use pyo3::prelude::PyResult; +use sqlbuild_core::run_on::main::apply_local_refusals::apply_local_refusals; +use sqlbuild_core::run_on::models::{LocalRefusal, RunOn, RunOnDecision}; + +/// The results to report; in `auto` a scenario a guard or engine error refused is not one: it reruns. +pub fn split_scenario_fallbacks<'py>( + ran: ScenarioResults<'py>, + (decisions, mode): (&mut [RunOnDecision], RunOn), +) -> PyResult> { + let mut results: ScenarioResults<'py> = Vec::new(); + let mut refused: Vec<(String, LocalRefusal)> = Vec::new(); + for result in ran { + let found = result + .local_refusal + .as_ref() + .map(local_refusal) + .transpose()?; + let Some((name, refusal)) = found.flatten() else { + results.push(result); + continue; + }; + if mode != RunOn::Auto { + results.push(result); + } + refused.push((name, refusal)); + } + apply_local_refusals(decisions, refused, mode); + Ok(results) +} diff --git a/crates/sqlbuild-python-output/src/result_output/mod.rs b/crates/sqlbuild-python-output/src/result_output/mod.rs index 42aa4ebfba..998a7f5753 100644 --- a/crates/sqlbuild-python-output/src/result_output/mod.rs +++ b/crates/sqlbuild-python-output/src/result_output/mod.rs @@ -4,3 +4,4 @@ pub(crate) mod _helpers; pub mod constants; pub mod main; pub mod models; +pub mod types; diff --git a/crates/sqlbuild-python-output/src/result_output/types.rs b/crates/sqlbuild-python-output/src/result_output/types.rs new file mode 100644 index 0000000000..171bb061eb --- /dev/null +++ b/crates/sqlbuild-python-output/src/result_output/types.rs @@ -0,0 +1,7 @@ +//! Type aliases shared by result output. + +use pyo3::prelude::{Bound, PyAny}; +use sqlbuild_host::models::ScenarioRunResult; + +/// Scenario results as the executor returns them. +pub type ScenarioResults<'py> = Vec>>; diff --git a/crates/sqlbuild-python-planner/src/plan_output/_helpers/plan_json.rs b/crates/sqlbuild-python-planner/src/plan_output/_helpers/plan_json.rs index 55ef877fc6..6f17939fb5 100644 --- a/crates/sqlbuild-python-planner/src/plan_output/_helpers/plan_json.rs +++ b/crates/sqlbuild-python-planner/src/plan_output/_helpers/plan_json.rs @@ -10,6 +10,7 @@ use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; use pyo3::types::{PyDict, PyDictMethods, PyList, PyListMethods, PyString}; use crate::plan_output::_helpers::cursor_details::{CursorDetails, cursor_details, owner}; +use crate::plan_output::_helpers::plan_text::audits_not_run; use crate::plan_output::_helpers::plan_text::entry_wait_changes; use crate::plan_output::_helpers::plan_text::{model_config_diff, model_query_diff}; use crate::plan_output::_helpers::python_identity::{ @@ -775,3 +776,18 @@ pub(crate) fn table_type_json<'py>(plan: &Bound<'py, PyAny>) -> PyResult( + py: Python<'py>, + plan: &Bound<'py, PyAny>, +) -> PyResult> { + let items = PyList::empty(py); + for (name, missing) in audits_not_run(plan)? { + let item = PyDict::new(py); + item.set_item("name", name)?; + item.set_item("missing", missing)?; + items.append(item)?; + } + Ok(items.into_any()) +} diff --git a/crates/sqlbuild-python-planner/src/plan_output/_helpers/plan_text.rs b/crates/sqlbuild-python-planner/src/plan_output/_helpers/plan_text.rs index b25899025c..dc6c16de81 100644 --- a/crates/sqlbuild-python-planner/src/plan_output/_helpers/plan_text.rs +++ b/crates/sqlbuild-python-planner/src/plan_output/_helpers/plan_text.rs @@ -607,5 +607,17 @@ pub(crate) fn report(arguments: &KeywordArguments<'_>) -> PyResult) -> PyResult)>> { + let mut not_run: Vec<(String, Vec)> = native_field(plan, "audits_not_run")? + .extract::>>()? + .into_iter() + .collect(); + not_run.sort(); + Ok(not_run) +} diff --git a/crates/sqlbuild-python-planner/src/plan_output/main/format_plan_json.rs b/crates/sqlbuild-python-planner/src/plan_output/main/format_plan_json.rs index 38f688be75..0130cab3cb 100644 --- a/crates/sqlbuild-python-planner/src/plan_output/main/format_plan_json.rs +++ b/crates/sqlbuild-python-planner/src/plan_output/main/format_plan_json.rs @@ -1,6 +1,7 @@ //! The plan as one JSON document, `json.dumps(indent=2)`. use crate::plan_output::_helpers::plan_json::IGNORE_AUDIT_FAILURES_KEY; +use crate::plan_output::_helpers::plan_json::audits_not_run_json; use crate::plan_output::_helpers::plan_json::column_migrations_json; use crate::plan_output::_helpers::plan_json::function_json; use crate::plan_output::_helpers::plan_json::migrations_json; @@ -97,6 +98,15 @@ pub fn format_plan_json(py: Python<'_>, options: Option>) -> P mapped(&native_field(&plan, "function_entries")?, function_json)?, ), ("python_nodes", PyList::new(py, python_nodes)?.into_any()), + ( + "audits", + PyList::new( + py, + native_field(&plan, "selected_audit_names")?.extract::>()?, + )? + .into_any(), + ), + ("audits_not_run", audits_not_run_json(py, &plan)?), ("providers", providers_json(&plan, &python_entries)?), ( "warnings", diff --git a/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/relations.rs b/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/relations.rs index 238bd99f52..619acf3888 100644 --- a/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/relations.rs +++ b/crates/sqlbuild-python-planner/src/planner_entries/_helpers/entries/relations.rs @@ -43,12 +43,12 @@ use std::collections::HashSet; /// Relation keys needed to render selected audits without selecting those relations. fn selected_audit_relation_keys( project: &Bound<'_, PyAny>, - selected_keys: &HashSet, + selected: (&HashSet, &HashSet), ) -> PyResult> { let mut keys: HashSet = HashSet::new(); for audit in audits(project)?.try_iter()? { let audit = audit?; - if audit_is_selected(&audit, selected_keys)? { + if audit_is_selected(&audit, selected)? { for dependency in scope_deps(&audit)?.try_iter()? { keys.insert(native_key(&dependency?)?); } @@ -136,7 +136,8 @@ pub(crate) fn planner_relations_context<'py>( } let scope = scope_data(&scope)?; let load_keys = if relation_keys.is_none() { - let mut relevant = selected_audit_relation_keys(&project, &scope.selected)?; + let mut relevant = + selected_audit_relation_keys(&project, (&scope.selected, &scope.audits))?; relevant.extend(scope.selected.iter().cloned()); relevant.into_iter().collect() } else { diff --git a/crates/sqlbuild-python-planner/src/planner_entries/_helpers/plans/execution_plan.rs b/crates/sqlbuild-python-planner/src/planner_entries/_helpers/plans/execution_plan.rs index fb7e182690..0d5841f656 100644 --- a/crates/sqlbuild-python-planner/src/planner_entries/_helpers/plans/execution_plan.rs +++ b/crates/sqlbuild-python-planner/src/planner_entries/_helpers/plans/execution_plan.rs @@ -11,11 +11,10 @@ use crate::planner_phases::main::timing::timed::timed; use crate::planner_warehouse::models::PlannerReads; use sqlbuild_analysis::planner_scope::constants::MODEL; use sqlbuild_python_base::invocation_phases::constants::PLANNED_PHASE; +use sqlbuild_python_base::invocation_phases::main::hold_planned_phase::hold_planned_phase; use sqlbuild_python_base::invocation_phases::main::phase_since::phase_since; -use sqlbuild_python_base::invocation_phases::models::InvocationPhase; -use sqlbuild_python_base::native_host::main::publish_invocation_phase::publish_invocation_phase; +use sqlbuild_python_base::invocation_phases::models::HeldPhase; use sqlbuild_python_base::native_host::models::Dialect; -use sqlbuild_python_project::planner_scope::models::RetainedScope; use crate::planner_changes::main::detect_changes::detect_changes; use crate::planner_changes::main::resolve_model_actions::resolve_model_actions; @@ -170,7 +169,7 @@ pub(crate) fn planned_output<'py>( (scopes, &snapshot), native_field(&policies, "selection_diagnostics")?.extract()?, )?; - check_selected_scope_buildability(runtime, scopes, &warehouse, &deferral)?; + let audits_not_run = check_selected_scope_buildability(runtime, scopes, &warehouse, &deferral)?; let (changes, stale_warning_changes) = change_results( &project, (scopes, &snapshot, &identities), @@ -216,6 +215,7 @@ pub(crate) fn planned_output<'py>( warehouse: &warehouse, identities: &identities, overrides, + audits_not_run: &audits_not_run, }, PlannedModelEntries { execution_scope: &inspection_scope, @@ -248,24 +248,10 @@ pub(crate) fn planned_output<'py>( add_deferred_origin_notes(output, (&project, scopes), (&deferral, &origin_failures))?; let plan_output = add_plan_metadata(output, &source_freshness, &policies)?.build(py)?; record_step(ASSEMBLING, assembling_started.elapsed().as_secs_f64()); - publish_invocation_phase( - py, - &InvocationPhase { - count: Some( - i64::try_from( - class_field(scopes, |s: &PlannerScopeResolution| &s.selected_scope)? - .cast::()? - .get() - .data - .selected - .len(), - ) - .unwrap_or(i64::MAX), - ), - detail: Some(format!("source freshness {freshness_seconds:.2} s")), - ..phase_since(PLANNED_PHASE, started) - }, - )?; + hold_planned_phase(HeldPhase { + detail: Some(format!("source freshness {freshness_seconds:.2} s")), + ..HeldPhase::from(phase_since(PLANNED_PHASE, started)) + }); let on_progress = args.value("on_progress")?; if !on_progress.is_none() { on_progress.call1((format!( diff --git a/crates/sqlbuild-python-planner/src/planner_entries/_helpers/plans/plan_output.rs b/crates/sqlbuild-python-planner/src/planner_entries/_helpers/plans/plan_output.rs index 253d95cab2..0fee7956b2 100644 --- a/crates/sqlbuild-python-planner/src/planner_entries/_helpers/plans/plan_output.rs +++ b/crates/sqlbuild-python-planner/src/planner_entries/_helpers/plans/plan_output.rs @@ -28,6 +28,7 @@ use sqlbuild_python_project::compiled_views::main::project::sql_tests::sql_tests use sqlbuild_python_project::compiled_views::models::NativeProjectView; use sqlbuild_python_project::planner_phases::main::object::object; use sqlbuild_python_project::planner_scope::main::build_source_load_entries::build_source_load_entries; +use sqlbuild_python_project::planner_scope::main::scope_data::scope_data; use sqlbuild_python_project::planner_scope::main::upstream_loader_dependency_names::upstream_loader_dependency_names; use sqlbuild_python_project::planner_strategy::main::planning_context::planning_context; use sqlbuild_python_project::resource_views::main::function_reads::arguments::arguments; @@ -702,6 +703,7 @@ pub(crate) fn plan_output_fields<'py>( model_warnings, reload_sources, extras, + audits_not_run, } = inputs; let py = project.py(); let extras = if extras.is_none() { @@ -815,6 +817,11 @@ pub(crate) fn plan_output_fields<'py>( "end_audit_source_keys", native_field(&scope, "end_audit_source_keys")?, ), + ("selected_audit_names", selected_audit_names(&scope)?), + ( + "audits_not_run", + pyo3::IntoPyObject::into_pyobject(audits_not_run, py)?.into_any(), + ), ("upstream_deps", native_field(&scope, "upstream_deps")?), ("downstream_deps", native_field(&scope, "downstream_deps")?), ( @@ -858,6 +865,13 @@ pub(crate) fn plan_output_fields<'py>( ]) } +/// The audits the scope selects by name, sorted. +fn selected_audit_names<'py>(scope: &Bound<'py, PyAny>) -> PyResult> { + let mut names: Vec = scope_data(scope)?.audits.iter().cloned().collect(); + names.sort(); + Ok(PyTuple::new(scope.py(), names)?.into_any()) +} + /// Plan SQL tests selected by name or overlapping one selection into a reusable result. pub(crate) fn plan_selected_sql_tests<'py>( project: &Bound<'py, PyAny>, diff --git a/crates/sqlbuild-python-planner/src/planner_entries/models.rs b/crates/sqlbuild-python-planner/src/planner_entries/models.rs index 06dc1147ca..7bd05e212f 100644 --- a/crates/sqlbuild-python-planner/src/planner_entries/models.rs +++ b/crates/sqlbuild-python-planner/src/planner_entries/models.rs @@ -51,6 +51,8 @@ pub struct PlanOutputInputs<'py> { pub(crate) model_warnings: Vec>, pub(crate) reload_sources: Bound<'py, PyAny>, pub(crate) extras: Bound<'py, PyAny>, + /// End-of-build audits that won't run, by name with the reads that don't exist. + pub(crate) audits_not_run: std::collections::BTreeMap>, } /// Resolved relation and source inputs for plan entry construction. diff --git a/crates/sqlbuild-python-planner/src/planner_phases/_helpers/inputs/warehouse_state.rs b/crates/sqlbuild-python-planner/src/planner_phases/_helpers/inputs/warehouse_state.rs index c6c9837b8f..ebb0c04f5c 100644 --- a/crates/sqlbuild-python-planner/src/planner_phases/_helpers/inputs/warehouse_state.rs +++ b/crates/sqlbuild-python-planner/src/planner_phases/_helpers/inputs/warehouse_state.rs @@ -9,6 +9,7 @@ use crate::planner_migrations::models::ColumnMigrationInputs; use crate::planner_migrations::models::MigrationPhase; use crate::planner_phases::_helpers::inputs::contexts::class_field; use crate::planner_phases::_helpers::inputs::runtime::runtime_field; +use crate::planner_phases::_helpers::outputs::buildability::end_audits; use crate::planner_phases::main::inputs::runtime_dialect::runtime_dialect; use crate::planner_phases::main::inputs::runtime_reads::runtime_reads; use crate::planner_phases::main::rebuilds::effectively_full_refreshed_model_names::effectively_full_refreshed_model_names; @@ -91,12 +92,17 @@ pub(crate) fn gather_planner_warehouse_state<'py>( let stale_scope = scope_data(&class_field(scopes, |s: &PlannerScopeResolution| { &s.stale_warning_scope })?)?; + let audit_reads = end_audits(&project, &*scope_data(&selected_scope)?)? + .into_iter() + .flat_map(|audit| audit.reads) + .map(|read| (read.kind, read.name)); let stale_keys = compiled_graph_keys( py, stale_scope .names .iter() .map(|(_, key)| key.clone()) + .chain(audit_reads) .collect(), )? .into_any(); diff --git a/crates/sqlbuild-python-planner/src/planner_phases/_helpers/outputs/buildability.rs b/crates/sqlbuild-python-planner/src/planner_phases/_helpers/outputs/buildability.rs index e478f7f2c0..5d5e9aeeb9 100644 --- a/crates/sqlbuild-python-planner/src/planner_phases/_helpers/outputs/buildability.rs +++ b/crates/sqlbuild-python-planner/src/planner_phases/_helpers/outputs/buildability.rs @@ -3,9 +3,10 @@ use crate::planner_phases::_helpers::inputs::contexts::class_field; use crate::planner_phases::_helpers::inputs::runtime::runtime_field; use crate::planner_phases::_helpers::inputs::runtime::warehouse_field; -use crate::planner_phases::constants::MISSING_UPSTREAM_CODE; +use crate::planner_phases::constants::{AUDIT_KIND, MISSING_UPSTREAM_CODE}; use crate::planner_phases::main::inputs::runtime_dialect::runtime_dialect; use crate::planner_phases::main::inputs::runtime_reads::runtime_reads; +use crate::planner_strategy::main::audit_entries::audit_is_selected::audit_is_selected; use crate::planner_warehouse::main::sources::check_selected_source_tables_exist::check_selected_source_tables_exist; use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; use pyo3::types::{PyDict, PyDictMethods, PyString, PyTuple}; @@ -19,20 +20,28 @@ use sqlbuild_python_base::records::main::fields::field::field as native_field; use sqlbuild_python_base::records::types::ErrorId; use sqlbuild_python_front::contracts::main::resolve_target_config::resolve_target_config; use sqlbuild_python_front::contracts::main::resolve_target_name::resolve_target_name; +use sqlbuild_python_project::compiled_views::main::project::audits::audits; use sqlbuild_python_project::compiled_views::main::project::seeds::seeds; use sqlbuild_python_project::graph::main::nodes::native_key::native_key; use sqlbuild_python_project::planner_identity::main::execution_origins::execution_origins; use sqlbuild_python_project::planner_scope::main::scope_data::scope_data; use sqlbuild_python_project::planner_scope::models::PlannerScopeResolution; +use sqlbuild_python_project::planner_scope::models::ScopeData; +use sqlbuild_python_project::resource_views::main::audit_reads::attached_target_kind::attached_target_kind; +use sqlbuild_python_project::resource_views::main::audit_reads::attached_target_name::attached_target_name; +use sqlbuild_python_project::resource_views::main::audit_reads::name::name; +use sqlbuild_python_project::resource_views::main::audit_reads::scope_deps::scope_deps; use sqlbuild_python_project::resource_views::main::seed_reads::external::external; use sqlbuild_python_project::resource_views::main::seed_reads::key::key; +use std::collections::{BTreeMap, HashMap}; +/// Refuse a selected scope whose reads don't exist; the end-of-build audits whose reads don't exist and that aren't selected by name are returned as not run, by name with what they miss. pub(crate) fn check_selected_scope_buildability<'py>( runtime: &Bound<'py, PyAny>, scopes: &Bound<'py, PyAny>, warehouse: &Bound<'py, PyAny>, deferral: &Bound<'py, PyAny>, -) -> PyResult<()> { +) -> PyResult>> { let py = runtime.py(); let project = runtime_field(runtime, |runtime| &runtime.project)?; let selected_scope = class_field(scopes, |s: &PlannerScopeResolution| &s.selected_scope)?; @@ -64,13 +73,40 @@ pub(crate) fn check_selected_scope_buildability<'py>( ) }) .collect(); - let missing = missing_upstreams(&selected, &deps, &available); + let mut missing = missing_upstreams(&selected, &deps, &available); + let mut audit_origins: HashMap<(GraphKey, GraphKey), String> = HashMap::new(); + let mut not_run: BTreeMap> = BTreeMap::new(); + let mut built = available.clone(); + built.satisfied_keys.extend(selected.iter().cloned()); + for audit in end_audits(&project, &scope)? { + let reads = HashMap::from([(audit.key.clone(), audit.reads)]); + let misses = missing_upstreams(std::slice::from_ref(&audit.key), &reads, &built); + if misses.is_empty() { + continue; + } + if !audit.named { + let names: Vec = misses.iter().map(|miss| miss.key.name.clone()).collect(); + not_run.insert(audit.key.name.clone(), names); + continue; + } + for miss in &misses { + let label: String = match &audit.target { + Some(target) => format!( + "audit '{}' on '{target}' reads '{}'", + audit.key.name, miss.key.name + ), + None => format!("audit '{}' reads '{}'", audit.key.name, miss.key.name), + }; + audit_origins.insert((audit.key.clone(), miss.key.clone()), label); + } + missing.extend(misses); + } if !missing.is_empty() { - let origins: std::collections::HashMap<(GraphKey, GraphKey), String> = - execution_origins(&project)? - .into_iter() - .map(|((key, read), label)| ((GraphKey::from(&key), GraphKey::from(&read)), label)) - .collect(); + let mut origins: HashMap<(GraphKey, GraphKey), String> = execution_origins(&project)? + .into_iter() + .map(|((key, read), label)| ((GraphKey::from(&key), GraphKey::from(&read)), label)) + .collect(); + origins.extend(audit_origins); let message = missing_upstream_message( &missing, &origins, @@ -89,7 +125,56 @@ pub(crate) fn check_selected_scope_buildability<'py>( (&runtime_dialect(runtime)?, &runtime_reads(runtime)?), &selected_scope, &warehouse_field(warehouse, |warehouse| &warehouse.inspection_relations)?, - ) + )?; + Ok(not_run) +} + +/// An audit that runs after the build, with what it reads and whether it was selected by name. +pub(crate) struct EndAudit { + key: GraphKey, + target: Option, + pub(crate) reads: Vec, + named: bool, +} + +/// The selected audits that run after the build: singular audits, and named attached audits whose target isn't built; unnamed attached audits are skipped first. +pub(crate) fn end_audits(project: &Bound<'_, PyAny>, scope: &ScopeData) -> PyResult> { + let mut out: Vec = Vec::new(); + for audit in audits(project)?.try_iter()? { + let audit = audit?; + let audit_name: String = name(&audit)?.extract()?; + let named: bool = scope.audits.contains(&audit_name); + let target: Option = attached_target_name(&audit)?.extract()?; + if let Some(target) = &target { + if !named { + continue; + } + let kind = attached_target_kind(&audit)?; + let kind: String = match kind.getattr_opt("value")? { + Some(value) => value.extract()?, + None => kind.extract()?, + }; + if scope.selected.contains(&(kind, target.clone())) { + continue; + } + } else if !named && !audit_is_selected(&audit, (&scope.selected, &scope.audits))? { + continue; + } + let mut reads: Vec = Vec::new(); + for read in scope_deps(&audit)?.try_iter()? { + reads.push(GraphKey::from(&native_key(&read?)?)); + } + out.push(EndAudit { + key: GraphKey { + kind: AUDIT_KIND.to_owned(), + name: audit_name, + }, + target, + reads, + named, + }); + } + Ok(out) } /// The models and seeds whose deferred location, under an alias or a `migrate_from` origin, the deferred target lists. diff --git a/crates/sqlbuild-python-planner/src/planner_phases/_helpers/outputs/output_assembly.rs b/crates/sqlbuild-python-planner/src/planner_phases/_helpers/outputs/output_assembly.rs index cf337e003b..8b83560011 100644 --- a/crates/sqlbuild-python-planner/src/planner_phases/_helpers/outputs/output_assembly.rs +++ b/crates/sqlbuild-python-planner/src/planner_phases/_helpers/outputs/output_assembly.rs @@ -86,6 +86,7 @@ pub(crate) fn base_plan_output<'py>( warehouse, identities, overrides, + audits_not_run, }: PlanOutputContext<'_, 'py>, PlannedModelEntries { execution_scope, @@ -126,6 +127,7 @@ pub(crate) fn base_plan_output<'py>( model_warnings: entries.warnings, reload_sources: native_field(overrides, "reload_sources")?, extras, + audits_not_run: audits_not_run.clone(), })?, metadata: Vec::new(), }; diff --git a/crates/sqlbuild-python-planner/src/planner_phases/constants.rs b/crates/sqlbuild-python-planner/src/planner_phases/constants.rs index c1b2d1ca40..208b2f14de 100644 --- a/crates/sqlbuild-python-planner/src/planner_phases/constants.rs +++ b/crates/sqlbuild-python-planner/src/planner_phases/constants.rs @@ -32,6 +32,8 @@ pub(crate) const FULL_REFRESH_DISABLED_REBUILD_CODE: &str = "S203"; pub(crate) const UNBOUNDED_CURSOR_MARK: &str = "/* (unbounded) */"; pub(crate) const MISSING_UPSTREAM_CODE: &str = "S301"; +/// The graph kind of an audit, as a missing read's dependent. +pub(crate) const AUDIT_KIND: &str = "audit"; pub(crate) const RETENTION_DECREASE: &str = "decrease"; diff --git a/crates/sqlbuild-python-planner/src/planner_phases/main/outputs/base_plan_output.rs b/crates/sqlbuild-python-planner/src/planner_phases/main/outputs/base_plan_output.rs index bae81b84cf..a230c1b718 100644 --- a/crates/sqlbuild-python-planner/src/planner_phases/main/outputs/base_plan_output.rs +++ b/crates/sqlbuild-python-planner/src/planner_phases/main/outputs/base_plan_output.rs @@ -12,6 +12,7 @@ pub fn base_plan_output<'py>( warehouse, identities, overrides, + audits_not_run, }: PlanOutputContext<'_, 'py>, PlannedModelEntries { execution_scope, @@ -27,6 +28,7 @@ pub fn base_plan_output<'py>( warehouse, identities, overrides, + audits_not_run, }, PlannedModelEntries { execution_scope, diff --git a/crates/sqlbuild-python-planner/src/planner_phases/main/outputs/check_selected_scope_buildability.rs b/crates/sqlbuild-python-planner/src/planner_phases/main/outputs/check_selected_scope_buildability.rs index 8090e77bf5..4903fb8fb3 100644 --- a/crates/sqlbuild-python-planner/src/planner_phases/main/outputs/check_selected_scope_buildability.rs +++ b/crates/sqlbuild-python-planner/src/planner_phases/main/outputs/check_selected_scope_buildability.rs @@ -2,14 +2,15 @@ use crate::planner_phases::_helpers::outputs::buildability; use pyo3::prelude::{Bound, PyAny, PyResult}; +use std::collections::BTreeMap; -/// Check selected scope buildability. +/// Check selected scope buildability; returns the end-of-build audits that won't run, by name with the reads they miss. #[inline] pub fn check_selected_scope_buildability<'py>( runtime: &Bound<'py, PyAny>, scopes: &Bound<'py, PyAny>, warehouse: &Bound<'py, PyAny>, deferral: &Bound<'py, PyAny>, -) -> PyResult<()> { +) -> PyResult>> { buildability::check_selected_scope_buildability(runtime, scopes, warehouse, deferral) } diff --git a/crates/sqlbuild-python-planner/src/planner_phases/models.rs b/crates/sqlbuild-python-planner/src/planner_phases/models.rs index 7f3191446d..e6686bf82f 100644 --- a/crates/sqlbuild-python-planner/src/planner_phases/models.rs +++ b/crates/sqlbuild-python-planner/src/planner_phases/models.rs @@ -45,6 +45,8 @@ pub struct PlanOutputContext<'a, 'py> { pub warehouse: &'a Bound<'py, PyAny>, pub identities: &'a Bound<'py, PyAny>, pub overrides: &'a Bound<'py, PyAny>, + /// End-of-build audits that won't run, by name with the reads that don't exist. + pub audits_not_run: &'a BTreeMap>, } /// The execution scope, reconciled changes, planned entries and source freshness of a plan. diff --git a/crates/sqlbuild-python-planner/src/planner_strategy/_helpers/audit_entries.rs b/crates/sqlbuild-python-planner/src/planner_strategy/_helpers/audit_entries.rs index d7296f9142..c5c55251cb 100644 --- a/crates/sqlbuild-python-planner/src/planner_strategy/_helpers/audit_entries.rs +++ b/crates/sqlbuild-python-planner/src/planner_strategy/_helpers/audit_entries.rs @@ -42,6 +42,7 @@ use sqlbuild_python_base::records::main::fields::mapping_get::mapping_get; use sqlbuild_python_base::records::types::RecordId; use sqlbuild_python_project::planner_strategy::constants::AUDIT_TYPES_MODULE; use sqlbuild_python_project::planner_strategy::constants::COMPILE_TYPES_MODULE; +use sqlbuild_python_project::planner_strategy::constants::END_ATTACHMENT; use sqlbuild_python_project::planner_strategy::constants::MODEL_ATTACHMENT; use sqlbuild_python_project::planner_strategy::constants::SOURCE_ATTACHMENT; use sqlbuild_python_project::planner_strategy::models::AuditPlanning; @@ -161,6 +162,16 @@ pub(crate) fn plan_audit<'py>( }; let lineage = request.lineage.bind(py).borrow(); let (kind_text, target_name) = attachment(&audit, lineage.graph())?; + let (kind_text, target_name) = match &target_name { + Some(model) + if attached_target_kind(&audit)?.is_none() + && kind_text == MODEL_ATTACHMENT + && !request.model_materializations.contains(model)? => + { + (END_ATTACHMENT.to_owned(), None) + } + _ => (kind_text, target_name), + }; let kind = audit_enum( PyString::new(py, &kind_text).into_any(), "AuditAttachmentKind", diff --git a/crates/sqlbuild-python-planner/src/planner_strategy/main/audit_entries/audit_is_selected.rs b/crates/sqlbuild-python-planner/src/planner_strategy/main/audit_entries/audit_is_selected.rs index ab7a81e959..638c4ca7ad 100644 --- a/crates/sqlbuild-python-planner/src/planner_strategy/main/audit_entries/audit_is_selected.rs +++ b/crates/sqlbuild-python-planner/src/planner_strategy/main/audit_entries/audit_is_selected.rs @@ -1,4 +1,4 @@ -//! Select attached audits by their logical target and singular audits by dependency overlap. +//! Select audits by name, attached audits by their logical target and singular audits by dependency overlap. use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; use sqlbuild_analysis::assembly::project::types::ObjectKey; @@ -8,15 +8,19 @@ use sqlbuild_python_project::graph::main::nodes::native_key::native_key; use sqlbuild_python_project::planner_strategy::constants::COMPILE_TYPES_MODULE; use sqlbuild_python_project::resource_views::main::audit_reads::attached_target_kind::attached_target_kind; use sqlbuild_python_project::resource_views::main::audit_reads::attached_target_name::attached_target_name; +use sqlbuild_python_project::resource_views::main::audit_reads::name::name; use sqlbuild_python_project::resource_views::main::audit_reads::scope_deps::scope_deps; use std::collections::HashSet; -/// Select attached audits by their logical target and singular audits by dependency overlap. +/// Select audits named in `selected_names`, attached audits by their logical target and singular audits by dependency overlap. pub fn audit_is_selected( audit: &Bound<'_, PyAny>, - selected_keys: &HashSet, + (selected_keys, selected_names): (&HashSet, &HashSet), ) -> PyResult { let py = audit.py(); + if !selected_names.is_empty() && selected_names.contains(&name(audit)?.extract::()?) { + return Ok(true); + } let kind = attached_target_kind(audit)?; let name = attached_target_name(audit)?; if !kind.is_none() && !name.is_none() { diff --git a/crates/sqlbuild-python-planner/src/planner_strategy/main/audit_entries/build_selected_audit_entries.rs b/crates/sqlbuild-python-planner/src/planner_strategy/main/audit_entries/build_selected_audit_entries.rs index 06a2ffbafe..35ac724418 100644 --- a/crates/sqlbuild-python-planner/src/planner_strategy/main/audit_entries/build_selected_audit_entries.rs +++ b/crates/sqlbuild-python-planner/src/planner_strategy/main/audit_entries/build_selected_audit_entries.rs @@ -22,7 +22,7 @@ pub fn build_selected_audit_entries<'py>( let mut selected: Vec> = Vec::new(); for audit in audits(&project)?.try_iter()? { let audit = audit?; - if audit_is_selected(&audit, &scope.selected)? { + if audit_is_selected(&audit, (&scope.selected, &scope.audits))? { selected.push(audit); } } diff --git a/crates/sqlbuild-python-project/Cargo.toml b/crates/sqlbuild-python-project/Cargo.toml index c207f1cbe2..98d273da66 100644 --- a/crates/sqlbuild-python-project/Cargo.toml +++ b/crates/sqlbuild-python-project/Cargo.toml @@ -29,6 +29,7 @@ sqlbuild-project.workspace = true sqlbuild-pysource.workspace = true sqlbuild-python-base.workspace = true sqlbuild-python-front.workspace = true +sqlbuild-recall.workspace = true sqlbuild-rules.workspace = true sqlbuild-sqltext.workspace = true sqlbuild-state.workspace = true diff --git a/crates/sqlbuild-python-project/src/graph/_helpers/python_nodes/python_selection.rs b/crates/sqlbuild-python-project/src/graph/_helpers/python_nodes/python_selection.rs index 1a37690a10..e31e44d0c8 100644 --- a/crates/sqlbuild-python-project/src/graph/_helpers/python_nodes/python_selection.rs +++ b/crates/sqlbuild-python-project/src/graph/_helpers/python_nodes/python_selection.rs @@ -22,6 +22,8 @@ use sqlbuild_analysis::python_selection::models::{ use crate::graph::models::{CompiledProjectGraph, NativeProjectGraph, PythonAwareSelection}; use crate::job_settings::main::needed_jobs::needed_jobs; +use crate::planner_selection::main::graph_with_audits_and_runs::graph_with_audits_and_runs; +use sqlbuild_analysis::graph::constants::AUDIT_KIND; use sqlbuild_python_base::boundary::main::compiler_guard::compiler_guard; use sqlbuild_python_base::records::main::fields::field::field as native_field; use sqlbuild_python_base::records::main::fields::mapping_items::mapping_items; @@ -180,6 +182,12 @@ impl<'g> PythonAwareSelection<'g> { )), None => Cow::Borrowed(native), }; + let graph: Cow<'g, ProjectGraph> = + match graph_with_audits_and_runs(project_graph.get().project(py), &graph, selectors)? { + Ok(Cow::Owned(attached)) => Cow::Owned(attached), + Ok(Cow::Borrowed(_)) => graph, + Err(error) => return Err(planner_error(py, error)), + }; Ok(Self { graph, sources, @@ -218,7 +226,7 @@ impl<'g> PythonAwareSelection<'g> { Ok(keys) } - /// The SQL keys and Python node names `select` minus `exclude` resolve to. + /// The SQL keys and Python node names `select` minus `exclude` resolve to; audits are left to the planner, which reads them by name. pub fn resolve( &self, select: &[String], @@ -229,7 +237,9 @@ impl<'g> PythonAwareSelection<'g> { sources: &self.sources, allow_warehouse_round_trips: self.allow_warehouse_round_trips, }; - run_selection(sql, &self.nodes, select, exclude) + let mut selection = run_selection(sql, &self.nodes, select, exclude)?; + selection.sql_keys.retain(|key| key.0 != AUDIT_KIND); + Ok(selection) } } diff --git a/crates/sqlbuild-python-project/src/planner_scope/_helpers/retained.rs b/crates/sqlbuild-python-project/src/planner_scope/_helpers/retained.rs index 06ac1d20c1..ca86f70417 100644 --- a/crates/sqlbuild-python-project/src/planner_scope/_helpers/retained.rs +++ b/crates/sqlbuild-python-project/src/planner_scope/_helpers/retained.rs @@ -55,6 +55,7 @@ pub(crate) fn scope_data(value: &Bound<'_, PyAny>) -> PyResult> { end_audit_sources: keys(&field(value, "end_audit_source_keys")?)? .into_iter() .collect(), + audits: field(value, "selected_audit_names")?.extract()?, })) } @@ -79,6 +80,7 @@ pub(crate) fn project_scope<'py>(value: &Bound<'py, PyAny>) -> PyResult( py: Python<'py>, @@ -62,10 +63,16 @@ pub(crate) fn build_planner_scope<'py>( native_field(&project, "lineage_graph")?.cast_into()?; let lineage = lineage.borrow(); let selected = args.value("selected_keys")?; - let mut selected = if selected.is_none() { - resolve_graph_keys(lineage.graph(), (&select, &exclude))? + let (mut selected, audits) = if selected.is_none() { + resolve_planner_keys(&project, lineage.graph(), (&select, &exclude))? } else { - keys(&selected)? + let (select, exclude) = (audit_selectors(&select)?, audit_selectors(&exclude)?); + let audits = if select.is_truthy()? { + resolve_planner_keys(&project, lineage.graph(), (&select, &exclude))?.1 + } else { + BTreeSet::new() + }; + (keys(&selected)?, audits) }; let names = &lineage.graph().names; let texts = py_strings(&select)?; @@ -147,10 +154,27 @@ pub(crate) fn build_planner_scope<'py>( tests: tests.extract()?, load_sources: auto_load, end_audit_sources, + audits: audits.into_iter().collect(), } .object(py) } +/// The selectors in `texts` that can select an audit: `audit:` and the past-run selectors; the rest select only nodes. +fn audit_selectors<'py>(texts: &Bound<'py, PyAny>) -> PyResult> { + let picks = |part: &str| { + let part = part.trim_start_matches('+'); + part.split_once(':') + .is_some_and(|(kind, _)| kind == AUDIT_KIND || RUN_SELECTOR_KINDS.contains(&kind)) + }; + let mut kept: Vec> = Vec::new(); + for text in py_strings(texts)? { + if text.to_str()?.split(',').any(picks) { + kept.push(text); + } + } + Ok(PyTuple::new(texts.py(), kept)?.into_any()) +} + fn default_tuple<'py>(value: &Bound<'py, PyAny>) -> Bound<'py, PyAny> { if value.is_none() { PyTuple::empty(value.py()).into_any() diff --git a/crates/sqlbuild-python-project/src/planner_scope/models.rs b/crates/sqlbuild-python-project/src/planner_scope/models.rs index e807f3c8f9..e3d3c3ac96 100644 --- a/crates/sqlbuild-python-project/src/planner_scope/models.rs +++ b/crates/sqlbuild-python-project/src/planner_scope/models.rs @@ -38,6 +38,8 @@ pub struct ScopeData { pub tests: Py, pub load_sources: bool, pub end_audit_sources: HashSet, + /// Audits selected by name, with `audit:` or as a past run's failed audits, whatever their targets. + pub audits: HashSet, } /// Internal carrier, never returned in place of a supported public PlannerScope record. @@ -89,6 +91,7 @@ impl ScopeData { tests: self.tests.clone_ref(py), load_sources: self.load_sources, end_audit_sources: self.end_audit_sources.clone(), + audits: self.audits.clone(), } } @@ -107,6 +110,7 @@ impl ScopeData { "selected_keys" => key_set(&self.selected), "user_selected_keys" => key_set(&self.user_selected), "end_audit_source_keys" => key_set(&self.end_audit_sources), + "selected_audit_names" => Ok(PyFrozenSet::new(py, &self.audits)?.into_any()), "execution_order" => Ok(PyTuple::new(py, cache.keys(&self.order)?)?.into_any()), "all_keys" => { let values = PyDict::new(py); diff --git a/crates/sqlbuild-python-project/src/planner_selection/_helpers/mod.rs b/crates/sqlbuild-python-project/src/planner_selection/_helpers/mod.rs index f32364b5d9..fa85521145 100644 --- a/crates/sqlbuild-python-project/src/planner_selection/_helpers/mod.rs +++ b/crates/sqlbuild-python-project/src/planner_selection/_helpers/mod.rs @@ -1,4 +1,5 @@ pub(crate) mod carrier; pub(crate) mod model_selectors; +pub(crate) mod past_runs; pub(crate) mod selectors; pub(crate) mod unit_tests; diff --git a/crates/sqlbuild-python-project/src/planner_selection/_helpers/past_runs.rs b/crates/sqlbuild-python-project/src/planner_selection/_helpers/past_runs.rs new file mode 100644 index 0000000000..2a058430c5 --- /dev/null +++ b/crates/sqlbuild-python-project/src/planner_selection/_helpers/past_runs.rs @@ -0,0 +1,122 @@ +//! The project's audits and the past runs a command's selectors name, attached to its graph for planning. + +use std::borrow::Cow; +use std::cell::RefCell; +use std::collections::{BTreeMap, BTreeSet}; + +use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; +use sqlbuild_analysis::assembly::project::types::ObjectKey; +use sqlbuild_analysis::graph::constants::{AUDIT_KIND, PLANNER_DEFAULT_CODE}; +use sqlbuild_analysis::graph::errors::SelectorError; +use sqlbuild_analysis::graph::main::attach_audits_and_runs::attach_audits_and_runs; +use sqlbuild_analysis::graph::main::run_selector_ids::run_selector_ids; +use sqlbuild_analysis::graph::models::{ProjectGraph, RunResults}; +use sqlbuild_cli::run_selectors::main::read_past_run_keys::read_past_run_keys; +use sqlbuild_cli::run_selectors::models::{PastRunKeys, PastRunSource}; +use sqlbuild_cli::run_selectors::types::PastRunKeysById; + +use crate::compiled_views::main::project::audits::audits; +use crate::resource_views::main::audit_reads::name::name; +use sqlbuild_cli::run_selectors::main::names_audits_or_runs::names_audits_or_runs; + +thread_local! { + /// Where the running command's run selectors read past runs from, `None` for commands that select neither audits nor past runs; per thread, as the job scope is. + static PAST_RUN_SOURCE: RefCell> = const { RefCell::new(None) }; + /// The past runs the running command has read, so each is read once however many times its selectors resolve. + static READ_RUNS: RefCell = const { RefCell::new(PastRunKeysById::new()) }; +} + +/// Run `run` with `source` as where its run selectors read past runs, restoring the enclosing one after. +pub(crate) fn with_past_run_source(source: Option, run: impl FnOnce() -> T) -> T { + let previous = PAST_RUN_SOURCE.with(|current| current.replace(source)); + let read = READ_RUNS.with(|current| current.replace(PastRunKeysById::new())); + let result: T = run(); + PAST_RUN_SOURCE.with(|current| *current.borrow_mut() = previous); + READ_RUNS.with(|current| *current.borrow_mut() = read); + result +} + +/// The past runs `ids` name, read from `source` once per command. +fn read_runs(source: &PastRunSource, ids: &BTreeSet) -> Result { + let unread: BTreeSet = READ_RUNS.with(|read| { + ids.iter() + .filter(|id| !read.borrow().contains_key(*id)) + .cloned() + .collect() + }); + if !unread.is_empty() { + let fresh = read_past_run_keys(source, &unread)?; + READ_RUNS.with(|read| read.borrow_mut().extend(fresh)); + } + Ok(READ_RUNS.with(|read| { + let read = read.borrow(); + ids.iter() + .filter_map(|id| Some((id.clone(), read.get(id)?.clone()))) + .collect() + })) +} + +/// `graph` with `project`'s audits and the past runs attached when `selectors` name an audit or a run. +pub(crate) fn with_audits_and_runs<'g>( + project: &Bound<'_, PyAny>, + graph: &'g ProjectGraph, + selectors: &[String], +) -> PyResult, SelectorError>> { + let Some(source) = PAST_RUN_SOURCE.with(|source| source.borrow().clone()) else { + return Ok(Ok(Cow::Borrowed(graph))); + }; + if !names_audits_or_runs(selectors) { + return Ok(Ok(Cow::Borrowed(graph))); + } + let mut names: BTreeSet = BTreeSet::new(); + for audit in audits(project)?.try_iter()? { + names.insert(name(&audit?)?.extract()?); + } + let ids = run_selector_ids(selectors); + let past = if ids.is_empty() { + Ok(PastRunKeysById::new()) + } else { + read_runs(&source, &ids) + }; + let past = match past { + Ok(past) => past, + Err(message) => { + return Ok(Err(SelectorError { + code: PLANNER_DEFAULT_CODE, + message, + help: None, + })); + } + }; + let runs: BTreeMap = past + .iter() + .map(|(id, keys)| (id.clone(), graph_results(keys))) + .collect(); + Ok(Ok(Cow::Owned(attach_audits_and_runs( + graph.clone(), + (names, runs), + )))) +} + +fn graph_results(keys: &PastRunKeys) -> RunResults { + RunResults { + selected: graph_keys(&keys.selected), + failed: graph_keys(&keys.failed), + skipped: graph_keys(&keys.skipped), + } +} + +/// Run node keys as selector graph keys; an audit by its name. +fn graph_keys(nodes: &BTreeSet) -> BTreeSet { + nodes.iter().filter_map(|node| run_key(node)).collect() +} + +fn run_key(node: &str) -> Option { + let (kind, name) = node.split_once(':')?; + let name = if kind == AUDIT_KIND { + name.split_once(':').map_or(name, |(name, _)| name) + } else { + name + }; + Some((kind.to_owned(), name.to_owned())) +} diff --git a/crates/sqlbuild-python-project/src/planner_selection/_helpers/selectors.rs b/crates/sqlbuild-python-project/src/planner_selection/_helpers/selectors.rs index e464a53b32..6aa29dfa9e 100644 --- a/crates/sqlbuild-python-project/src/planner_selection/_helpers/selectors.rs +++ b/crates/sqlbuild-python-project/src/planner_selection/_helpers/selectors.rs @@ -1,10 +1,14 @@ //! Planner selector parsing and resolution over native project graphs, raising `PlannerInputError`. -use crate::planner_selection::main::resolve_graph_keys::resolve_graph_keys; +use crate::job_settings::main::graph_with_jobs::graph_with_jobs; +use crate::planner_selection::_helpers::past_runs::with_audits_and_runs; +use crate::planner_selection::main::py_strings::py_strings; use pyo3::prelude::{Bound, PyAny, PyResult, Python}; +use pyo3::types::PyString; use pyo3::types::{PyBool, PyFrozenSet}; use sqlbuild_analysis::assembly::project::types::ObjectKey; use sqlbuild_analysis::graph::errors::SelectorError; +use sqlbuild_analysis::graph::main::resolve_selectors::resolve_selectors; use sqlbuild_analysis::graph::models::{ParsedSelector, ProjectGraph}; use crate::graph::main::project::graph_from_view_mappings::graph_from_view_mappings; @@ -91,7 +95,10 @@ pub(crate) fn resolved<'py>( graph: &ProjectGraph, (select, exclude): (&Bound<'py, PyAny>, &Bound<'py, PyAny>), ) -> PyResult> { - compiled_keys(select.py(), &resolve_graph_keys(graph, (select, exclude))?) + compiled_keys( + select.py(), + &resolve_graph_keys(None, graph, (select, exclude))?, + ) } pub(crate) fn view_graph(mappings: GraphViewMappings<'_, '_>) -> PyResult { @@ -107,3 +114,26 @@ pub(crate) fn arguments_graph(arguments: &KeywordArguments<'_>) -> PyResult( + project: Option<&Bound<'py, PyAny>>, + graph: &ProjectGraph, + (select, exclude): (&Bound<'py, PyAny>, &Bound<'py, PyAny>), +) -> PyResult> { + let py: Python<'py> = select.py(); + let select: Vec> = py_strings(select)?; + let exclude: Vec> = py_strings(exclude)?; + let texts: Vec> = select.iter().chain(&exclude).cloned().collect(); + let carrier: Carrier<'py> = Carrier::new(py, &texts, || Ok(graph_names(graph)))?; + let (select, exclude) = (carrier.send_all(&select)?, carrier.send_all(&exclude)?); + let all: Vec = select.iter().chain(&exclude).cloned().collect(); + let graph = graph_with_jobs(py, graph, &all, &[])?; + let graph = match project { + Some(project) => { + with_audits_and_runs(project, &graph, &all)?.map_err(|error| carrier.error(error))? + } + None => graph, + }; + resolve_selectors(&graph, &select, &exclude).map_err(|error| carrier.error(error)) +} diff --git a/crates/sqlbuild-python-project/src/planner_selection/constants.rs b/crates/sqlbuild-python-project/src/planner_selection/constants.rs new file mode 100644 index 0000000000..f513e0928a --- /dev/null +++ b/crates/sqlbuild-python-project/src/planner_selection/constants.rs @@ -0,0 +1,4 @@ +//! The commands that select audits by name and read past runs. + +/// The commands whose selectors select audits by name and read past runs. +pub(crate) const RUN_SELECTOR_COMMANDS: [&str; 5] = ["plan", "build", "test", "audit", "check"]; diff --git a/crates/sqlbuild-python-project/src/planner_selection/main/graph_with_audits_and_runs.rs b/crates/sqlbuild-python-project/src/planner_selection/main/graph_with_audits_and_runs.rs new file mode 100644 index 0000000000..d2a78b54ab --- /dev/null +++ b/crates/sqlbuild-python-project/src/planner_selection/main/graph_with_audits_and_runs.rs @@ -0,0 +1,18 @@ +//! The graph a command's selectors resolve over, with the project's audits and the past runs they name. + +use std::borrow::Cow; + +use pyo3::prelude::{Bound, PyAny, PyResult}; +use sqlbuild_analysis::graph::errors::SelectorError; +use sqlbuild_analysis::graph::models::ProjectGraph; + +use crate::planner_selection::_helpers::past_runs::with_audits_and_runs; + +/// `graph` with `project`'s audits and the past runs attached when `selectors` name an audit or a run and the command reads them. +pub fn graph_with_audits_and_runs<'g>( + project: &Bound<'_, PyAny>, + graph: &'g ProjectGraph, + selectors: &[String], +) -> PyResult, SelectorError>> { + with_audits_and_runs(project, graph, selectors) +} diff --git a/crates/sqlbuild-python-project/src/planner_selection/main/mod.rs b/crates/sqlbuild-python-project/src/planner_selection/main/mod.rs index 5aada78366..71e3ea31c3 100644 --- a/crates/sqlbuild-python-project/src/planner_selection/main/mod.rs +++ b/crates/sqlbuild-python-project/src/planner_selection/main/mod.rs @@ -1,11 +1,12 @@ pub mod expand_project_upstream_keys; +pub mod graph_with_audits_and_runs; pub mod match_project_selector; pub mod parse_project_selector; pub mod py_strings; pub mod register_model_selectors; pub mod reject_unit_test_selectors; -pub mod resolve_graph_keys; pub mod resolve_graph_selection; +pub mod resolve_planner_keys; pub mod resolve_project_selector_tokens; pub mod resolve_project_selectors; pub mod resolve_sqlbuild_model_selector_names; @@ -13,3 +14,4 @@ pub mod select_project_graph; pub mod split_project_unit_test_selectors; pub mod split_selector_expansion; pub mod split_unit_test_selectors; +pub mod with_command_scope; diff --git a/crates/sqlbuild-python-project/src/planner_selection/main/resolve_graph_keys.rs b/crates/sqlbuild-python-project/src/planner_selection/main/resolve_graph_keys.rs deleted file mode 100644 index a0471e7c14..0000000000 --- a/crates/sqlbuild-python-project/src/planner_selection/main/resolve_graph_keys.rs +++ /dev/null @@ -1,27 +0,0 @@ -//! Resolve graph keys for native planning without building a public frozenset. - -use crate::job_settings::main::graph_with_jobs::graph_with_jobs; -use crate::planner_selection::_helpers::selectors::graph_names; -use crate::planner_selection::main::py_strings::py_strings; -use crate::planner_selection::models::Carrier; -use pyo3::prelude::{Bound, PyAny, PyResult, Python}; -use pyo3::types::PyString; -use sqlbuild_analysis::assembly::project::types::ObjectKey; -use sqlbuild_analysis::graph::main::resolve_selectors::resolve_selectors; -use sqlbuild_analysis::graph::models::ProjectGraph; - -/// Resolve graph keys for native planning without building a public frozenset. -pub fn resolve_graph_keys<'py>( - graph: &ProjectGraph, - (select, exclude): (&Bound<'py, PyAny>, &Bound<'py, PyAny>), -) -> PyResult> { - let py: Python<'py> = select.py(); - let select: Vec> = py_strings(select)?; - let exclude: Vec> = py_strings(exclude)?; - let texts: Vec> = select.iter().chain(&exclude).cloned().collect(); - let carrier: Carrier<'py> = Carrier::new(py, &texts, || Ok(graph_names(graph)))?; - let (select, exclude) = (carrier.send_all(&select)?, carrier.send_all(&exclude)?); - let all: Vec = select.iter().chain(&exclude).cloned().collect(); - let graph = graph_with_jobs(py, graph, &all, &[])?; - resolve_selectors(&graph, &select, &exclude).map_err(|error| carrier.error(error)) -} diff --git a/crates/sqlbuild-python-project/src/planner_selection/main/resolve_planner_keys.rs b/crates/sqlbuild-python-project/src/planner_selection/main/resolve_planner_keys.rs new file mode 100644 index 0000000000..0547e99fb8 --- /dev/null +++ b/crates/sqlbuild-python-project/src/planner_selection/main/resolve_planner_keys.rs @@ -0,0 +1,22 @@ +//! The keys and audits a command's selectors pick for planning, with the project's audits and the past runs they name. + +use std::collections::BTreeSet; + +use crate::planner_selection::_helpers::selectors::resolve_graph_keys; +use pyo3::prelude::{Bound, PyAny, PyResult}; +use sqlbuild_analysis::assembly::project::types::ObjectKey; +use sqlbuild_analysis::graph::constants::AUDIT_KIND; +use sqlbuild_analysis::graph::models::ProjectGraph; + +/// The graph keys `select` and `exclude` pick, and apart from them the names of the audits they pick. +pub fn resolve_planner_keys<'py>( + project: &Bound<'py, PyAny>, + graph: &ProjectGraph, + selectors: (&Bound<'py, PyAny>, &Bound<'py, PyAny>), +) -> PyResult<(Vec, BTreeSet)> { + let (audits, nodes): (Vec, Vec) = + resolve_graph_keys(Some(project), graph, selectors)? + .into_iter() + .partition(|key| key.0 == AUDIT_KIND); + Ok((nodes, audits.into_iter().map(|(_, name)| name).collect())) +} diff --git a/crates/sqlbuild-python-project/src/planner_selection/main/with_command_scope.rs b/crates/sqlbuild-python-project/src/planner_selection/main/with_command_scope.rs new file mode 100644 index 0000000000..5fc4a30481 --- /dev/null +++ b/crates/sqlbuild-python-project/src/planner_selection/main/with_command_scope.rs @@ -0,0 +1,51 @@ +//! Run one parsed command with its jobs selectable and, for commands that read them, where its run selectors read past runs. + +use std::path::PathBuf; + +use pyo3::prelude::{Bound, PyAny, PyResult}; +use sqlbuild_cli::run_selectors::main::past_run_source::past_run_source; +use sqlbuild_cli::run_selectors::models::PastRunSource; +use sqlbuild_recall::settings::models::{RecallSettings, StoreLocation}; + +use crate::job_settings::main::with_job_scope::with_job_scope; +use crate::planner_selection::_helpers::past_runs::with_past_run_source; +use crate::planner_selection::constants::RUN_SELECTOR_COMMANDS; +use sqlbuild_python_base::records::main::fields::attribute_text::attribute_text; + +/// Run `run` with jobs from `project_dir` on `args`' `--target`, and past runs from its `--server`, else the local SQLite Recall store `recall` names. +pub fn with_command_scope( + args: &Bound<'_, PyAny>, + (project_dir, recall): (PathBuf, &Option<(RecallSettings, PathBuf)>), + run: impl FnOnce() -> T, +) -> PyResult { + let selected_target: Option = attribute_text(args, "target")?; + let source = command_source(args, (&project_dir, selected_target.clone()), recall)?; + Ok(with_job_scope((project_dir, selected_target), || { + with_past_run_source(source, run) + })) +} + +/// Where `args`' command reads past runs; `None` for a command that selects neither audits nor past runs. +fn command_source( + args: &Bound<'_, PyAny>, + (project_dir, selected_target): (&std::path::Path, Option), + recall: &Option<(RecallSettings, PathBuf)>, +) -> PyResult> { + let text = |name: &str| attribute_text(args, name); + if !text("command")?.is_some_and(|command| RUN_SELECTOR_COMMANDS.contains(&command.as_str())) { + return Ok(None); + } + let store = match recall.as_ref().map(|(settings, _)| &settings.store) { + Some(StoreLocation::Sqlite { path }) => Some(path.clone()), + _ => None, + }; + Ok(Some(past_run_source( + ( + text("login_server")?, + text("login_ca")?.map(PathBuf::from), + text("person_location")?, + ), + (project_dir, selected_target), + store, + ))) +} diff --git a/crates/sqlbuild-python-project/src/planner_selection/mod.rs b/crates/sqlbuild-python-project/src/planner_selection/mod.rs index 4578773f1d..015677ebd0 100644 --- a/crates/sqlbuild-python-project/src/planner_selection/mod.rs +++ b/crates/sqlbuild-python-project/src/planner_selection/mod.rs @@ -1,5 +1,6 @@ //! Planner selection: selectors, model selectors, unit tests and their carrier. pub(crate) mod _helpers; +pub(crate) mod constants; pub mod main; pub mod models; diff --git a/crates/sqlbuild-python-project/src/planner_strategy/_helpers/fixtures/fixture_reads.rs b/crates/sqlbuild-python-project/src/planner_strategy/_helpers/fixtures/fixture_reads.rs index c21dc7ccb2..ffd93411e8 100644 --- a/crates/sqlbuild-python-project/src/planner_strategy/_helpers/fixtures/fixture_reads.rs +++ b/crates/sqlbuild-python-project/src/planner_strategy/_helpers/fixtures/fixture_reads.rs @@ -3,6 +3,7 @@ use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; use pyo3::pyfunction; use pyo3::types::PyFrozenSet; +use sqlbuild_analysis::planner_fixtures::main::prewarm_reads::prewarm_reads; use sqlbuild_analysis::planner_fixtures::main::required_columns::required_columns; use sqlbuild_analysis::planner_fixtures::main::star_keys::star_keys; use sqlbuild_analysis::planner_fixtures::models::{ @@ -52,11 +53,7 @@ pub(crate) fn required_fixture_columns( authoritative.insert(key.clone(), names.iter().cloned().collect()); } } - let analysis_dialect = dialect - .syntax("expression_inference_profile")? - .call0()? - .getattr("sql_analysis_dialect")? - .extract::>()?; + let analysis_dialect = analysis_dialect(dialect)?; let mut models: Vec = Vec::new(); for name in ordered_model_names { let Some(model) = context.models_by_name.get(name) else { @@ -66,26 +63,9 @@ pub(crate) fn required_fixture_columns( let Some(facts) = context.model_facts(py, name)? else { continue; }; - let mut references: Vec = Vec::new(); - for reference in - crate::compiled_views::main::compiled_models::references::references(&model)? - .try_iter()? - { - let reference = reference?; - references.push(FixtureReadReference { - kind: native_field(&reference, "ref_kind")?.extract()?, - name: native_field(&reference, "ref_name")?.extract()?, - package: native_field(&reference, "ref_package")?.extract()?, - argument_count: native_field(&reference, "call_argument_count")?.extract()?, - }); - } models.push(FixtureReadModel { name: name.clone(), - key: FixtureReadKey { - sql: query_sql(&model)?.extract()?, - references, - dialect: analysis_dialect.clone(), - }, + key: read_key(&model, analysis_dialect.clone())?, high_confidence: facts.reads.clone(), stars: model_stars(&model, &schema, dialect)?, }); @@ -109,6 +89,62 @@ pub(crate) fn required_fixture_columns( result.map_err(|error| value_error(format!("{error:?}"))) } +/// Resolve, in parallel, the reads of every listed model that per-test planning can look up. +pub(crate) fn prewarm_fixture_reads( + context: &RelationFixturePlanningContext, + model_names: &[String], + dialect: &Bound<'_, Dialect>, +) -> PyResult<()> { + let py = dialect.py(); + let analysis_dialect = analysis_dialect(dialect)?; + let mut keys: Vec = Vec::new(); + for name in model_names { + if let Some(model) = context.models_by_name.get(name) { + let model = model.bind(py); + let key = read_key(&model, analysis_dialect.clone())?; + if !key.references.is_empty() { + keys.push(key); + } + } + } + let owner = work_counts(py)?; + let mut owner = owner.borrow_mut(); + let cache = std::mem::take(&mut owner.cache); + owner.cache = py + .compiler_detach(|| Ok(prewarm_reads(cache, &keys))) + .unwrap_or_default(); + Ok(()) +} + +fn analysis_dialect(dialect: &Bound<'_, Dialect>) -> PyResult> { + dialect + .syntax("expression_inference_profile")? + .call0()? + .getattr("sql_analysis_dialect")? + .extract() +} + +/// The read cache key of one model: its SQL, complete references and analysis dialect. +fn read_key(model: &Bound<'_, PyAny>, dialect: Option) -> PyResult { + let mut references: Vec = Vec::new(); + for reference in + crate::compiled_views::main::compiled_models::references::references(model)?.try_iter()? + { + let reference = reference?; + references.push(FixtureReadReference { + kind: native_field(&reference, "ref_kind")?.extract()?, + name: native_field(&reference, "ref_name")?.extract()?, + package: native_field(&reference, "ref_package")?.extract()?, + argument_count: native_field(&reference, "call_argument_count")?.extract()?, + }); + } + Ok(FixtureReadKey { + sql: query_sql(model)?.extract()?, + references, + dialect, + }) +} + pub(crate) fn lineage_reads(model: &Bound<'_, PyAny>) -> PyResult> { let mut reads: Vec = Vec::new(); for LineageFactRow { diff --git a/crates/sqlbuild-python-project/src/planner_strategy/constants.rs b/crates/sqlbuild-python-project/src/planner_strategy/constants.rs index 420e5189c5..12fd7c3671 100644 --- a/crates/sqlbuild-python-project/src/planner_strategy/constants.rs +++ b/crates/sqlbuild-python-project/src/planner_strategy/constants.rs @@ -8,6 +8,9 @@ pub const MODEL_ATTACHMENT: &str = "model"; pub const SOURCE_ATTACHMENT: &str = "source"; +/// Where a singular audit runs when it gates no model this build builds: after everything else. +pub const END_ATTACHMENT: &str = "end"; + pub const INCREMENTAL_MATERIALIZATION: &str = "incremental"; pub const MICROBATCH_MODE: &str = "microbatch"; diff --git a/crates/sqlbuild-python-project/src/planner_strategy/main/mod.rs b/crates/sqlbuild-python-project/src/planner_strategy/main/mod.rs index 5cacd8332e..50ff737090 100644 --- a/crates/sqlbuild-python-project/src/planner_strategy/main/mod.rs +++ b/crates/sqlbuild-python-project/src/planner_strategy/main/mod.rs @@ -3,6 +3,7 @@ pub mod complete_fixtures; pub mod complete_typed_null_columns; pub mod count_chain_resolution; pub mod planning_context; +pub mod prewarm_fixture_reads; pub mod register_fixture_completion; pub mod register_fixture_context; pub mod register_fixture_reads; diff --git a/crates/sqlbuild-python-project/src/planner_strategy/main/prewarm_fixture_reads.rs b/crates/sqlbuild-python-project/src/planner_strategy/main/prewarm_fixture_reads.rs new file mode 100644 index 0000000000..6b082a80ac --- /dev/null +++ b/crates/sqlbuild-python-project/src/planner_strategy/main/prewarm_fixture_reads.rs @@ -0,0 +1,15 @@ +//! Resolve the fixture reads of a batch of tests' models ahead of per-test planning. + +use crate::planner_strategy::_helpers::fixtures::fixture_reads; +use crate::planner_strategy::models::RelationFixturePlanningContext; +use pyo3::prelude::{Bound, PyResult}; +use sqlbuild_python_base::native_host::models::Dialect; + +/// Resolve, in parallel, the reads of every listed model that per-test planning can look up. +pub fn prewarm_fixture_reads( + context: &RelationFixturePlanningContext, + model_names: &[String], + dialect: &Bound<'_, Dialect>, +) -> PyResult<()> { + fixture_reads::prewarm_fixture_reads(context, model_names, dialect) +} diff --git a/crates/sqlbuild-python-project/src/project_snapshot/_helpers/snapshot/snapshot_logs.rs b/crates/sqlbuild-python-project/src/project_snapshot/_helpers/snapshot/snapshot_logs.rs index f7bf86e776..a5b9f09fd7 100644 --- a/crates/sqlbuild-python-project/src/project_snapshot/_helpers/snapshot/snapshot_logs.rs +++ b/crates/sqlbuild-python-project/src/project_snapshot/_helpers/snapshot/snapshot_logs.rs @@ -1,11 +1,12 @@ -//! The `ctx.log` lines a finished node reports, and the note a worker leaves when run output was lost. +//! The `ctx.log` lines a finished node reports, the note a worker leaves when run output was lost, and its sinks' deliveries. use sqlbuild_host::models::{LifeCycleEvent, LifeCycleEventKind, LogLevel}; use sqlbuild_orchestration::run_output::constants::{ NODE_LOG_MESSAGE_BYTES, NODE_LOGS_PER_NODE, RUN_OUTPUT_NODE, }; use sqlbuild_orchestration::run_output::models::UploadSummary; -use sqlbuild_orchestration::runs::models::{NodeLogLevel, RunChange}; +use sqlbuild_orchestration::runs::models::{NodeLogLevel, RunChange, SinkDelivery}; +use sqlbuild_python_base::event_exporting::models::ClosedExport; const ELLIPSIS: char = '\u{2026}'; @@ -71,3 +72,23 @@ fn bounded(message: &str) -> String { .unwrap_or(0); format!("{}{ELLIPSIS}", &message[..end]) } + +/// What each lifecycle event sink of the worker's command delivered; `None` when it had no sinks. +pub(crate) fn sink_deliveries(closed: ClosedExport) -> Option { + (!closed.per_exporter.is_empty() || !closed.teardown_failures.is_empty()).then(|| { + RunChange::SinkDeliveries { + sinks: closed + .per_exporter + .into_iter() + .map(|(name, counts)| SinkDelivery { + name, + accepted: counts.accepted, + delivered: counts.delivered, + dropped: counts.dropped, + failed: counts.failed, + }) + .collect(), + teardown_failures: closed.teardown_failures, + } + }) +} diff --git a/crates/sqlbuild-python-project/src/project_snapshot/models.rs b/crates/sqlbuild-python-project/src/project_snapshot/models.rs index 6acd3adda3..572c269764 100644 --- a/crates/sqlbuild-python-project/src/project_snapshot/models.rs +++ b/crates/sqlbuild-python-project/src/project_snapshot/models.rs @@ -14,7 +14,9 @@ use crate::project_snapshot::_helpers::snapshot::snapshot_execution::is_function use crate::project_snapshot::_helpers::snapshot::snapshot_execution::planned_key; use crate::project_snapshot::_helpers::snapshot::snapshot_execution::poisoned; use crate::project_snapshot::_helpers::snapshot::snapshot_execution::severity; -use crate::project_snapshot::_helpers::snapshot::snapshot_logs::{node_log_changes, upload_loss}; +use crate::project_snapshot::_helpers::snapshot::snapshot_logs::{ + node_log_changes, sink_deliveries, upload_loss, +}; use crate::project_snapshot::_helpers::snapshot::snapshot_worker::WorkerOwner; use crate::project_snapshot::_helpers::snapshot::snapshot_worker::unavailable; use crate::project_snapshot::types::NodeKeys; @@ -54,6 +56,7 @@ use sqlbuild_orchestration::snapshots::models::SnapshotRecord; use sqlbuild_orchestration::worker::errors::WorkerError; use sqlbuild_orchestration::worker::main::connect_worker::connect_worker; use sqlbuild_orchestration::worker::main::start_worker::start_worker; +use sqlbuild_python_base::event_exporting::main::take_closed_export::take_closed_export; use sqlbuild_python_base::invocation_phases::constants::MATCHED_PHASE; use sqlbuild_python_base::invocation_phases::main::phase_since::phase_since; use sqlbuild_python_base::native_host::main::publish_invocation_phase::publish_invocation_phase; @@ -157,6 +160,8 @@ pub(crate) struct Completion { pub(crate) no_change_reason: Option, pub(crate) error_code: Option, pub(crate) error_message: Option, + /// Where a failed model failed, such as `staging` or `post_hook`. + pub(crate) phase: Option, /// The node skipped itself with a hard skip, so the nodes it blocks name it as their cause. pub(crate) skipped_itself: bool, } @@ -170,6 +175,7 @@ impl Completion { no_change_reason: None, error_code: None, error_message: None, + phase: None, skipped_itself: false, } } @@ -508,6 +514,7 @@ impl WorkerBuild { error_code: completion.error_code, skipped_because_of: skipped_because_of.clone(), error_message: completion.error_message.as_deref().map(redact_error_text), + phase: completion.phase.filter(|_| outcome == NodeOutcome::Failed), }, )?; let cause = match outcome { @@ -627,9 +634,17 @@ impl WorkerBuild { Ok(()) } + /// Whether the snapshot records `key` as a check, so its result is reported. + #[must_use] + pub fn records_check(&self, key: &str) -> bool { + self.attached.contains_key(key) + } + /// A test or audit finished; a check the snapshot does not record is not reported. pub fn finish_attached(&self, py: Python<'_>, key: &str, outcome: NodeOutcome) -> PyResult<()> { - if outcome != NodeOutcome::Skipped && self.attached.contains_key(key) { + if !matches!(outcome, NodeOutcome::Skipped | NodeOutcome::NotRun) + && self.attached.contains_key(key) + { self.check_cancelled(py)?; } self.report_attached(py, key, outcome) @@ -640,7 +655,7 @@ impl WorkerBuild { let Some(nodes) = self.attached.get(key) else { return Ok(()); }; - if outcome != NodeOutcome::Skipped { + if !matches!(outcome, NodeOutcome::Skipped | NodeOutcome::NotRun) { self.record_attached_start(py, key)?; } let outcome = if outcome == NodeOutcome::Failed @@ -655,7 +670,7 @@ impl WorkerBuild { } else { self.finish_check(py, key, outcome)?; } - if outcome == NodeOutcome::Skipped { + if matches!(outcome, NodeOutcome::Skipped | NodeOutcome::NotRun) { return Ok(()); } let mut checked = self.checked.lock().map_err(|_| poisoned())?; @@ -873,6 +888,13 @@ impl WorkerBuild { Some(value) => value.extract()?, None => None, }; + let phase: Option = match result.getattr_opt("failed_phase")? { + Some(value) if !value.is_none() => Some(match value.getattr_opt("value")? { + Some(inner) => inner.extract()?, + None => value.str()?.extract()?, + }), + _ => None, + }; let detail: Option = match result.getattr_opt("error_detail")? { Some(value) => value.extract()?, None => None, @@ -902,6 +924,7 @@ impl WorkerBuild { table_rows, error_code: error, error_message: message, + phase, skipped_itself: outcome == NodeOutcome::Skipped && skip_mode.as_deref() == Some(HARD_SKIP_MODE), ..Completion::of(outcome) @@ -1016,10 +1039,6 @@ impl WorkerBuild { let outcome = { let completed = self.completed.lock().map_err(|_| poisoned())?; let outcomes: Vec = completed.values().copied().collect(); - let good = completed.iter().any(|(key, value)| { - matches!(value, NodeOutcome::Success | NodeOutcome::Warn) - && !source_needs_no_run(key) - }); let bad = outcomes.iter().any(|value| { matches!( value, @@ -1031,8 +1050,6 @@ impl WorkerBuild { }); if cancelled { RunOutcome::Cancelled - } else if bad && good { - RunOutcome::Partial } else if bad || exit_code != 0 { RunOutcome::Failed } else if outcomes.contains(&NodeOutcome::Warn) { @@ -1082,6 +1099,14 @@ impl WorkerBuild { .change(py, "worker-output-loss", change), ); } + if let Some(change) = take_closed_export().and_then(sink_deliveries) { + drop( + self.worker + .bind(py) + .get() + .change(py, "worker-sink-deliveries", change), + ); + } let ignored: u32 = self.ignored_audit_failures.load(Ordering::SeqCst); if ignored > 0 { self.worker.bind(py).get().change( diff --git a/crates/sqlbuild-python-project/src/sql_test_glue/_helpers/plan/plan_fixtures.rs b/crates/sqlbuild-python-project/src/sql_test_glue/_helpers/plan/plan_fixtures.rs index 52631017fb..333bd4bb4d 100644 --- a/crates/sqlbuild-python-project/src/sql_test_glue/_helpers/plan/plan_fixtures.rs +++ b/crates/sqlbuild-python-project/src/sql_test_glue/_helpers/plan/plan_fixtures.rs @@ -3,10 +3,12 @@ use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult}; use pyo3::types::{PyDict, PyDictMethods, PyTuple}; +use crate::planner_strategy::main::prewarm_fixture_reads::prewarm_fixture_reads; use crate::planner_strategy::models::RelationFixturePlanningContext; use crate::sql_test_glue::_helpers::inputs::fixture_validation::validated_fixtures; use crate::sql_test_glue::_helpers::plan::plan_driver::resolve_sql_test_model_chains; use crate::sql_test_glue::_helpers::plan::plan_values::model_payload; +use sqlbuild_python_base::native_host::models::Dialect; use sqlbuild_python_base::records::main::fields::field::field as native_field; use sqlbuild_python_base::records::main::fields::mapping_get_or::mapping_get_or; use sqlbuild_python_base::records::main::fields::replaced_keywords::replaced_keywords; @@ -101,6 +103,13 @@ pub(crate) fn validate<'py>( "zip() argument lengths differ", )); } + let mut names: Vec = Vec::new(); + for chain in &chains { + names.extend(chain.extract::>()?); + } + names.sort_unstable(); + names.dedup(); + prewarm_fixture_reads(context, &names, &Dialect::of(inputs.1)?)?; let mut validated = tests.to_vec(); let mut diagnostics: std::collections::BTreeMap> = std::collections::BTreeMap::new(); diff --git a/crates/sqlbuild-python/src/bindings/_helpers/audit_command/command.rs b/crates/sqlbuild-python/src/bindings/_helpers/audit_command/command.rs index d10755d5a0..07fcd2005c 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/audit_command/command.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/audit_command/command.rs @@ -15,7 +15,6 @@ use sqlbuild_core::audit_command::models::AuditCounts; use sqlbuild_core::cli_text::models::CliStyle; use sqlbuild_host::entries::models::ExecutorHost; use sqlbuild_host::models::{AuditExecutionResult, AuditOutcome}; -use sqlbuild_orchestration::runs::models::NodeOutcome; use crate::bindings::_helpers::command_runtime::invocation::resolve_reported_command_invocation; use crate::bindings::_helpers::compile_driver::static_context::compile_static_command_context; @@ -37,7 +36,7 @@ use sqlbuild_python_output::build_progress::main::write_execution_header::write_ use sqlbuild_python_output::build_progress::models::AuditProgressReporter; use sqlbuild_python_output::build_progress::models::ConnectionProgressReporter; use sqlbuild_python_output::result_output::main::events::audit_identity::audit_identity; -use sqlbuild_python_output::result_output::main::results::audit_check_id::audit_check_id; +use sqlbuild_python_output::result_output::main::results::audit_check::audit_check; use sqlbuild_python_output::result_output::main::results::audit_execution_json::audit_execution_json; use sqlbuild_python_output::result_output::main::results::audit_projection::audit_projection; use sqlbuild_python_output::result_output::main::results::write_execution_json_output::write_execution_json_output; @@ -74,13 +73,8 @@ struct AuditCallbackRelay { impl AuditCallbackRelay { fn on_result(&self, py: Python<'_>, result: Bound<'_, PyAny>) -> PyResult<()> { if let Some(worker) = &self.worker { - let outcome = match AuditExecutionResult::read(&result)?.outcome { - AuditOutcome::Pass => NodeOutcome::Success, - AuditOutcome::Warn | AuditOutcome::Insufficient => NodeOutcome::Warn, - AuditOutcome::Skipped => NodeOutcome::Skipped, - AuditOutcome::Error => NodeOutcome::Failed, - }; - worker.finish_attached(py, &audit_check_id(&result)?, outcome)?; + let (key, outcome) = audit_check(worker, &result)?; + worker.finish_attached(py, &key, outcome)?; } call_with( &self.event_writer.bind(py).getattr("write_build_result")?, @@ -508,7 +502,7 @@ fn complete( AuditOutcome::Warn => counts.warned += 1, AuditOutcome::Error => counts.failed += 1, AuditOutcome::Insufficient => counts.insufficient += 1, - AuditOutcome::Skipped => {} + AuditOutcome::Skipped | AuditOutcome::NotRun => {} } } let stream: Bound<'_, PyAny> = native_field(invocation, "progress_stream")?; diff --git a/crates/sqlbuild-python/src/bindings/_helpers/build_command/execution.rs b/crates/sqlbuild-python/src/bindings/_helpers/build_command/execution.rs index 187b50a6c3..91b534ac93 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/build_command/execution.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/build_command/execution.rs @@ -46,6 +46,7 @@ use sqlbuild_python_base::records::types::RecordId; use sqlbuild_python_compile::compile_driver::main::jobs::build_concurrency::build_concurrency; use sqlbuild_python_compile::compile_driver::main::jobs::connection_limit::connection_limit; use sqlbuild_python_compile::compile_driver::main::jobs::job_run_context::job_run_context; +use sqlbuild_python_compile::compile_driver::main::jobs::publish_execution_start::publish_execution_start; use sqlbuild_python_compile::compile_driver::main::setup::build_project_relation_targets::build_project_relation_targets; use sqlbuild_python_compile::compile_driver::main::setup::project_target_settings::project_target_settings; use sqlbuild_python_compile::compile_driver::models::TargetSettingsValues; @@ -304,6 +305,7 @@ pub(crate) fn prepare_build_execution<'py>( on_node_complete: native_field(&callbacks, "on_node_complete")?, providers: providers.clone(), }; + publish_execution_start(&plan, concurrency)?; let lifecycle: Bound<'py, DirectPythonLifecycle> = prepare_direct_python_lifecycle(context, pipeline, &inputs)?; Ok(Preparation { @@ -504,6 +506,7 @@ pub(crate) fn execute_build_plan<'py>( ("callbacks", build_callbacks), ("customizations", customizations), ("initial_state", initial_state), + ("execution_announced", boolean(py, true)), ], )?; for warning in recorder.get().finish(py, &result)? { diff --git a/crates/sqlbuild-python/src/bindings/_helpers/change_selection/definition_snapshot.rs b/crates/sqlbuild-python/src/bindings/_helpers/change_selection/definition_snapshot.rs index d636f24a33..7c86854c8b 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/change_selection/definition_snapshot.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/change_selection/definition_snapshot.rs @@ -64,7 +64,7 @@ const PROJECT_CONFIG_ELSEWHERE: [&str; 12] = [ ]; const LOCAL_CONFIG_ELSEWHERE: [&str; 4] = ["settings", "setting_overrides", "vars", "scenario"]; /// Settings that tune how a run executes or validates, not what a node computes. -const RUNTIME_SETTINGS: [&str; 12] = [ +const RUNTIME_SETTINGS: [&str; 14] = [ "sql_analysis", "require_sql_analysis", "allow_warehouse_round_trips", @@ -77,6 +77,8 @@ const RUNTIME_SETTINGS: [&str; 12] = [ "delta_compile", "ignore_audit_failures", "record_run_host", + "test_run_on", + "scenario_run_on", ]; const PYTHON_SUFFIX: &str = ".py"; /// Discovered Python node collections, in `PYTHON_NODE_KINDS` order. diff --git a/crates/sqlbuild-python/src/bindings/_helpers/cli/dispatch.rs b/crates/sqlbuild-python/src/bindings/_helpers/cli/dispatch.rs index fc7e7362ae..3104469e3a 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/cli/dispatch.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/cli/dispatch.rs @@ -1,7 +1,7 @@ //! `sqb` command dispatch: the native route table applied to a parsed namespace. -use crate::bindings::_helpers::review_command::support::attribute; use sqlbuild_python_base::records::main::construct::new_error::new_error; +use sqlbuild_python_base::records::main::fields::attribute_text::attribute_text as attribute; use std::path::PathBuf; use crate::bindings::_helpers::audit_command::command::run_audit_command; @@ -58,7 +58,7 @@ use sqlbuild_python_base::records::main::construct::record_class::record_class; use sqlbuild_python_compile::compile_command::main::invocation::run_compile::run_compile; use sqlbuild_python_front::discovery::models::MissingSecretsScope; use sqlbuild_python_output::recall::models::InvocationRecall; -use sqlbuild_python_project::job_settings::main::with_job_scope::with_job_scope; +use sqlbuild_python_project::planner_selection::main::with_command_scope::with_command_scope; use sqlbuild_python_base::boundary::main::imported::imported; use sqlbuild_python_base::boundary::main::within::within; @@ -536,13 +536,9 @@ fn routed_command<'py>( return Err(user_error(py, failure)); } let project_dir: PathBuf = invocation.value(Source::EffectiveProjectDir)?.extract()?; - let selected_target: Option = match invocation.value(Source::Attr("target")) { - Ok(target) => optional_text(&target)?, - Err(_) => None, - }; - with_job_scope((project_dir, selected_target), || { + with_command_scope(args, (project_dir, &recall.settings), || { call_route(&invocation, route, handler, recall) - }) + })? } } } @@ -612,9 +608,6 @@ pub(crate) fn command_facts(args: &Bound<'_, PyAny>) -> PyResult { format_diff: flag("format_diff")?, format_fix: flag("format_fix")?, format_fixtures_only: flag("format_fixtures_only")?, - scenario_local: flag("scenario_local")?, - scenario_retain: flag("scenario_retain")?, - scenario_snapshot_sync: flag("scenario_sync_snapshots")? || flag("scenario_refresh")?, raw_query_diff, ignores_failures_of_no_audits: attr("ignore_audit_failures")?.is_truthy()? && !flag("run_audits")?, diff --git a/crates/sqlbuild-python/src/bindings/_helpers/command_runtime/audit_failures.rs b/crates/sqlbuild-python/src/bindings/_helpers/command_runtime/audit_failures.rs index 0a97a9a39e..cba30458c7 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/command_runtime/audit_failures.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/command_runtime/audit_failures.rs @@ -5,9 +5,7 @@ use sqlbuild_config::effective::main::effective_ignore_audit_failures::effective use sqlbuild_config::effective::models::AuditFailureLayers; use sqlbuild_python_base::records::main::fields::field::field as native_field; -use sqlbuild_python_front::compile_attachment::main::build_effective_settings::build_effective_settings; -use sqlbuild_python_front::contracts::main::resolve_target_config::resolve_target_config; -use sqlbuild_python_front::contracts::main::resolve_target_name::resolve_target_name; +use sqlbuild_python_front::command_runtime::main::target_and_settings_value::target_and_settings_value; const IGNORE_AUDIT_FAILURES: &str = "ignore_audit_failures"; @@ -17,23 +15,10 @@ pub(crate) fn resolve_ignore_audit_failures( discovered: &Bound<'_, PyAny>, selected_target: &Bound<'_, PyAny>, ) -> PyResult { - let py = request.py(); - let project_config: Bound<'_, PyAny> = native_field(discovered, "project_config")?; - let local_config: Bound<'_, PyAny> = native_field(discovered, "local_config")?; - let target: Option = - match resolve_target_name(py, &project_config, &local_config, selected_target)? { - Some(name) => native_field( - &resolve_target_config(py, &project_config, &local_config, name.as_any())?, - IGNORE_AUDIT_FAILURES, - )? - .extract()?, - None => None, - }; - let settings: bool = native_field( - &build_effective_settings(&project_config, &local_config)?, - IGNORE_AUDIT_FAILURES, - )? - .extract()?; + let (target, settings) = + target_and_settings_value(discovered, selected_target, IGNORE_AUDIT_FAILURES)?; + let target: Option = target.map(|value| value.extract()).transpose()?.flatten(); + let settings: bool = settings.extract()?; Ok(effective_ignore_audit_failures(&AuditFailureLayers { requested: native_field(request, IGNORE_AUDIT_FAILURES)?.extract()?, target, diff --git a/crates/sqlbuild-python/src/bindings/_helpers/dbt_interop/plan_output.rs b/crates/sqlbuild-python/src/bindings/_helpers/dbt_interop/plan_output.rs index 284894aded..66b16afd3a 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/dbt_interop/plan_output.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/dbt_interop/plan_output.rs @@ -5,6 +5,7 @@ use pyo3::types::{PyDict, PyDictMethods}; use pyo3::{pyfunction, wrap_pyfunction}; use sqlbuild_host::entries::models::ExecutorHost; use sqlbuild_python_base::native_host::models::Dialect; +use sqlbuild_python_compile::compile_driver::main::setup::publish_plan_summary::publish_plan_summary; use sqlbuild_python_planner::live_reads::models::LiveReads; use crate::bindings::_helpers::command_runtime::connection::anchor_local_database_path; @@ -247,7 +248,9 @@ pub(crate) fn build_sqlbuild_plan_output<'py>( } })(); native_field(&environment, "adapter")?.call_method1("close", (connection,))?; - planned + let planned: Bound<'py, PyAny> = planned?; + publish_plan_summary(&planned, pyo3::types::PyTuple::empty(planned.py()).as_any())?; + Ok(planned) } /// Attach live SQLBuild planning when the selection contains SQLBuild models. diff --git a/crates/sqlbuild-python/src/bindings/_helpers/location_command/runtime.rs b/crates/sqlbuild-python/src/bindings/_helpers/location_command/runtime.rs index cd68b57b91..f18bd8e66c 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/location_command/runtime.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/location_command/runtime.rs @@ -2,7 +2,6 @@ use std::io::{self, Write}; -use pyo3::PyErr; use pyo3::exceptions::{PyMemoryError, PyValueError}; use pyo3::prelude::{Bound, PyAnyMethods, PyResult, Python}; use pyo3::types::{PyDict, PyDictMethods}; @@ -33,13 +32,16 @@ use sqlbuild_orchestration::discovered_sets::constants::{CHECK_DISCOVERED_KEY, G use sqlbuild_orchestration::discovered_sets::models::{ DiscoveredSetCheck, DiscoveryPublishRequest, }; +use sqlbuild_orchestration::platform::constants::SINK_DELIVERIES_REQUEST; use sqlbuild_python_base::boundary::main::error_text_fields::error_text_fields; +use sqlbuild_python_base::boundary::main::failure_reason::failure_reason; use sqlbuild_python_base::boundary::main::within::within; use sqlbuild_python_base::native_host::main::redirect_stdout_to_stderr::redirect_stdout_to_stderr; use sqlbuild_python_front::discovered_sets::main::checked_set::checked_set; use sqlbuild_python_front::discovered_sets::main::discover_for_publication::discover_for_publication; use sqlbuild_python_front::discovered_sets::main::published_sets::published_sets; use sqlbuild_python_front::discovered_sets::main::with_set_retries::with_set_retries; +use sqlbuild_python_output::event_exporting::main::sink_delivery_totals::sink_delivery_totals; use sqlbuild_python_output::recall::main::write_stderr::write_stderr; pub(super) fn run_runtime(py: Python<'_>, options: Bound<'_, PyDict>) -> PyResult { @@ -109,6 +111,8 @@ pub(super) fn run_runtime(py: Python<'_>, options: Bound<'_, PyDict>) -> PyResul "discover_files": discover_files, "error": error_text, })) + } else if request.get(SINK_DELIVERIES_REQUEST).is_some() { + serde_json::to_string(&sink_delivery_totals(py)?) } else if request.get(CHECK_DISCOVERED_KEY).is_some() { let check: DiscoveredSetCheck = serde_json::from_value(request.clone()) .map_err(|_| { @@ -150,6 +154,7 @@ pub(super) fn run_runtime(py: Python<'_>, options: Bound<'_, PyDict>) -> PyResul Err(error) => { busy = error.to_string().contains(DUCKDB_LOCK_CONFLICT); if !busy { + unconnected.connection = true; unconnected.reason = failure_reason(&error); write_stderr( py, @@ -177,6 +182,7 @@ pub(super) fn run_runtime(py: Python<'_>, options: Bound<'_, PyDict>) -> PyResul .map_err(|error| WarehouseHistoryFailure { reason: failure_reason(&error), page_size: error.is_instance_of::(py), + connection: false, }), None => Err(unconnected), }; @@ -286,11 +292,3 @@ pub(super) fn run_runtime(py: Python<'_>, options: Bound<'_, PyDict>) -> PyResul result }) } - -/// The driver's class and message on one line, redacted as warehouse error text. -fn failure_reason(error: &PyErr) -> String { - redact_error_text(&error.to_string()) - .split_whitespace() - .collect::>() - .join(" ") -} diff --git a/crates/sqlbuild-python/src/bindings/_helpers/location_command/runtime_plan.rs b/crates/sqlbuild-python/src/bindings/_helpers/location_command/runtime_plan.rs index 6844b551b9..891e413593 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/location_command/runtime_plan.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/location_command/runtime_plan.rs @@ -18,7 +18,7 @@ use crate::bindings::_helpers::location_command::constants::PLAN_FAILED_CODE; use crate::bindings::_helpers::location_command::types::HeldProject; use crate::bindings::_helpers::plan_command::plan::PlanProject; use crate::bindings::_helpers::plan_command::plan::location_plan; -use crate::bindings::_helpers::review_command::support::attribute; +use sqlbuild_python_base::records::main::fields::attribute_text::attribute_text as attribute; use sqlbuild_python_base::records::main::fields::field::field; use sqlbuild_python_output::recall::main::write_stderr::write_stderr; use sqlbuild_python_project::job_settings::main::pinned_plan::pinned_plan; diff --git a/crates/sqlbuild-python/src/bindings/_helpers/native_host/statement_report.rs b/crates/sqlbuild-python/src/bindings/_helpers/native_host/statement_report.rs index eeb9cc5d32..1f303fbdee 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/native_host/statement_report.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/native_host/statement_report.rs @@ -45,8 +45,9 @@ impl StatementReport { pub(crate) fn of_invocation( invocation: &Bound<'_, PyAny>, started: Instant, + local: &StatementSummary, ) -> PyResult> { - Self::read( + Self::read_excluding( invocation.py(), &StatementSource { adapter_name: &invocation.getattr("adapter_name")?.extract::()?, @@ -54,15 +55,29 @@ impl StatementReport { connection_config: &invocation.getattr("connection_config")?, started, }, + local, ) } - /// The report of the installed projector, or nothing when no projector is installed. - pub(crate) fn read(py: Python<'_>, source: &StatementSource<'_, '_>) -> PyResult> { + /// The report of the installed projector without the statements of a local DuckDB batch. + pub(crate) fn read_excluding( + py: Python<'_>, + source: &StatementSource<'_, '_>, + local: &StatementSummary, + ) -> PyResult> { let Some(projector) = current_projector(py)? else { return Ok(None); }; - let summary: StatementSummary = projector.get().statement_summary()?; + let mut summary: StatementSummary = projector.get().statement_summary()?; + for (kind, count) in &local.by_kind { + if let Some(total) = summary.by_kind.get_mut(kind) { + *total = total.saturating_sub(*count); + } + } + summary.by_kind.retain(|_, count| *count > 0); + summary + .query_ids + .retain(|query_id| !local.query_ids.contains(query_id)); let timing: StatementTiming = statement_timing(py, source, &summary.query_ids)?; Ok(Some(Self { summary, timing })) } diff --git a/crates/sqlbuild-python/src/bindings/_helpers/review_command/support.rs b/crates/sqlbuild-python/src/bindings/_helpers/review_command/support.rs index 5424091e4f..37910b2511 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/review_command/support.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/review_command/support.rs @@ -16,6 +16,7 @@ use sqlbuild_python_base::boundary::main::call_with::call_with; use sqlbuild_python_base::boundary::main::imported::imported; use sqlbuild_python_base::boundary::main::within::within; use sqlbuild_python_base::native_host::main::host_entry::host_entry; +use sqlbuild_python_base::records::main::fields::attribute_text::attribute_text as attribute; use sqlbuild_python_base::records::main::fields::field::field as native_field; use sqlbuild_python_base::records::types::ErrorId; use sqlbuild_python_front::execution_history::main::nullable_text::nullable_text; @@ -52,14 +53,6 @@ pub(crate) fn plan_error(py: Python<'_>, error: &ReviewPlanError) -> PyErr { review_error(py, &error.code, &error.message, error.help.as_deref()) } -/// `name` of `value` as text, or `None` when it is absent or `None`. -pub(crate) fn attribute(value: &Bound<'_, PyAny>, name: &str) -> PyResult> { - match value.getattr_opt(name)? { - Some(item) if !item.is_none() => Ok(Some(item.str()?.extract()?)), - Some(_) | None => Ok(None), - } -} - /// The code, message and help of `error`, as the report records it. pub(crate) fn error_parts(py: Python<'_>, error: &PyErr) -> PyResult { let value: Bound<'_, PyAny> = error.value(py).clone().into_any(); diff --git a/crates/sqlbuild-python/src/bindings/_helpers/scenario_command/capture_command.rs b/crates/sqlbuild-python/src/bindings/_helpers/scenario_command/capture_command.rs index d9d900a18f..fdee26ea41 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/scenario_command/capture_command.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/scenario_command/capture_command.rs @@ -27,13 +27,6 @@ use sqlbuild_python_base::records::main::fields::field::field as native_field; const EXECUTION_COMMAND: &str = "sqb scenario capture"; -fn count(label: &str, value: usize) -> SummaryCount { - SummaryCount { - label: label.to_owned(), - value: i64::try_from(value).unwrap_or(i64::MAX), - } -} - /// Run one `sqb scenario capture` request. #[pyfunction] #[pyo3(signature = (*, request))] @@ -152,9 +145,9 @@ pub(crate) fn run_scenario_capture_command( format_summary_footer( style, &[ - count("PASS", passed), - count("FAIL", failed), - count("TOTAL", results.len()) + SummaryCount::of("PASS", passed), + SummaryCount::of("FAIL", failed), + SummaryCount::of("TOTAL", results.len()) ], None ) diff --git a/crates/sqlbuild-python/src/bindings/_helpers/scenario_command/presentation.rs b/crates/sqlbuild-python/src/bindings/_helpers/scenario_command/presentation.rs index 1e0d9c4c48..809e2c1fdd 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/scenario_command/presentation.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/scenario_command/presentation.rs @@ -13,6 +13,8 @@ use sqlbuild_core::scenario_command::main::scenario_activity_message::scenario_a use sqlbuild_core::scenario_command::models::ScenarioNamespace; use sqlbuild_host::entries::models::ExecutorHost; use sqlbuild_host::models::ScenarioRunResult; +use sqlbuild_python_output::build_progress::main::local_attempt::local_attempt; +use sqlbuild_python_output::build_progress::models::LocalAttemptStep; use crate::bindings::_helpers::scenario_command::conversions::{ capture_row, scenario_result_row, write_local_runtime_target, write_warehouse_runtime_target, @@ -76,6 +78,9 @@ impl ScenarioProgressRelay { let style: CliStyle = CliStyle { use_color: self.use_color, }; + if local_attempt(LocalAttemptStep::SettleReplay(&result))? { + return Ok(()); + } let plan: Option<&Bound<'_, PyAny>> = (!scenario_plan.is_none()).then_some(&scenario_plan); let project_dir: &Bound<'_, PyAny> = self.project_dir.bind(py); let rendered: String = match &self.kind { diff --git a/crates/sqlbuild-python/src/bindings/_helpers/scenario_command/snapshot_sync.rs b/crates/sqlbuild-python/src/bindings/_helpers/scenario_command/snapshot_sync.rs index 5e35577dc3..bd271600f7 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/scenario_command/snapshot_sync.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/scenario_command/snapshot_sync.rs @@ -1,4 +1,4 @@ -//! `sqb scenario test --local --sync-snapshots` and `--refresh`: capture stale snapshots first. +//! `sqb scenario test --sync-snapshots` and `--refresh`: capture stale snapshots before local runs. use pyo3::prelude::{Bound, PyAny, PyAnyMethods, PyResult, Python}; use pyo3::types::{PyString, PyTuple, PyTupleMethods}; diff --git a/crates/sqlbuild-python/src/bindings/_helpers/scenario_command/test_command.rs b/crates/sqlbuild-python/src/bindings/_helpers/scenario_command/test_command.rs index 74ddc70cbd..c299f2495c 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/scenario_command/test_command.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/scenario_command/test_command.rs @@ -9,6 +9,14 @@ use pyo3::{pyfunction, wrap_pyfunction}; use sqlbuild_analysis::definition_changes::models::{ExecutedItem, SelectedItem}; use sqlbuild_core::cli_text::main::format_summary_footer::format_summary_footer; use sqlbuild_core::cli_text::models::{CliStyle, SummaryCount}; +use sqlbuild_core::progress::main::statement_summary_delta::statement_summary_delta; +use sqlbuild_core::progress::models::StatementSummary; +use sqlbuild_core::run_on::main::read_run_on_decisions::read_run_on_decisions; +use sqlbuild_core::run_on::main::render_local_refusals::render_local_refusals; +use sqlbuild_core::run_on::main::render_warehouse_census::render_warehouse_census; +use sqlbuild_core::run_on::main::run_on_split::run_on_split; +use sqlbuild_core::run_on::main::with_run_on_json::with_run_on_json; +use sqlbuild_core::run_on::models::{RunOn, RunOnDecision}; use sqlbuild_core::scenario_command::main::render_scenario_failures::render_scenario_failures; use sqlbuild_core::scenario_command::main::validate_scenario_test_flags::validate_scenario_test_flags; use sqlbuild_core::scenario_command::models::{ @@ -17,6 +25,9 @@ use sqlbuild_core::scenario_command::models::{ use sqlbuild_host::entries::models::ExecutorHost; use sqlbuild_host::models::{ExecutionStatus, ScenarioRunResult}; use sqlbuild_host::types::ResultEnum; +use sqlbuild_python_output::build_progress::main::local_attempt::local_attempt; +use sqlbuild_python_output::build_progress::models::LocalAttemptStep; +use sqlbuild_python_output::result_output::main::results::split_scenario_fallbacks::split_scenario_fallbacks; use crate::bindings::_helpers::change_selection::base_snapshot::{ BaseComparison, base_comparison, base_variant, @@ -40,16 +51,22 @@ use crate::bindings::_helpers::sql_test_command::test_command::timeout_record; use crate::bindings::_helpers::sql_test_command::timeouts::{TimeoutKind, resolve_run_timeout}; use sqlbuild_python_base::boundary::main::call_with::call_with; use sqlbuild_python_base::boundary::main::keywords::keywords; +use sqlbuild_python_base::boundary::main::value_error::value_error; +use sqlbuild_python_base::build_progress::main::progress::current_projector::current_projector; use sqlbuild_python_base::native_host::main::host_entry::host_entry; use sqlbuild_python_base::native_host::types::ReadResult; use sqlbuild_python_base::records::main::fields::field::field as native_field; use sqlbuild_python_front::command_runtime::main::resolve_concurrency::resolve_concurrency; +use sqlbuild_python_front::command_runtime::main::resolve_run_on::resolve_run_on; use sqlbuild_python_output::result_output::main::results::format_scenario_execution_json_with::format_scenario_execution_json_with; use sqlbuild_python_output::result_output::main::results::write_execution_json_output::write_execution_json_output; const LOCAL_ADAPTER: &str = "duckdb"; -const LOCAL_STATUSES: [&str; 4] = ["PASS", "FAIL", "ERROR", "SKIP"]; +const STATUSES: [&str; 3] = ["PASS", "FAIL", "ERROR"]; const TARGET_DIR: &str = "target"; +const RUN_ON_SETTING: &str = "scenario_run_on"; +const SCENARIO_NOUNS: (&str, &str) = ("scenario", "scenarios"); +const JSON_SCENARIO_NAME_KEYS: [&str; 2] = ["scenario_name", "name"]; /// The resolved adapters, connection and output settings of one scenario test run. pub(crate) struct TestRun<'py> { @@ -72,16 +89,12 @@ fn flag(request: &Bound<'_, PyAny>, name: &str) -> PyResult { native_field(request, name)?.is_truthy() } -fn prepare<'py>(py: Python<'py>, request: &Bound<'py, PyAny>) -> PyResult> { - let local: bool = flag(request, "local")?; - validate_scenario_test_flags(ScenarioTestFlags { - local, - retain: flag(request, "retain")?, - sync_snapshots: flag(request, "sync_snapshots")?, - refresh: flag(request, "refresh")?, - }) - .map_err(|error| cli_user_error(py, error))?; - let project: ScenarioProject<'py> = discover_project(py, request)?; +fn prepare<'py>( + request: &Bound<'py, PyAny>, + project: ScenarioProject<'py>, + local: bool, +) -> PyResult> { + let py: Python<'py> = request.py(); if local { require_sql_analysis( &project, @@ -140,7 +153,15 @@ fn prepare<'py>(py: Python<'py>, request: &Bound<'py, PyAny>) -> PyResult, + local_statements: StatementSummary, + verbose: bool, +} + +/// The run's elapsed summary, refusals, completion line and JSON document. fn finish( request: &Bound<'_, PyAny>, run: &TestRun<'_>, @@ -149,16 +170,47 @@ fn finish( Instant, &[ScenarioRunResult>], ), - (counts, succeeded): (Vec, bool), -) -> PyResult<()> { + report: &RunOnReport, +) -> PyResult { let py: Python<'_> = request.py(); section.status.call_method0("close")?; let elapsed_seconds: f64 = started.elapsed().as_secs_f64(); + let mut tallies: [usize; 3] = [0; 3]; + for result in results { + let status: String = match result.local_status { + Some(status) => status.value().to_owned(), + None if result.status == ExecutionStatus::Success => STATUSES[0].to_owned(), + None => STATUSES[1].to_owned(), + }; + if let Some(index) = STATUSES.iter().position(|label| *label == status) { + tallies[index] += 1; + } + } + let mut counts: Vec = STATUSES + .iter() + .zip(tallies) + .filter(|(label, value)| **label != STATUSES[2] || *value > 0) + .map(|(label, value)| SummaryCount::of(label, value)) + .collect(); + counts.push(SummaryCount::of("TOTAL", results.len())); + let succeeded: bool = tallies[1] == 0 && tallies[2] == 0; + let local: usize = results + .iter() + .filter(|result| result.local_status.is_some()) + .count(); + let split: (usize, usize) = (local, results.len() - local); write( &run.stream, &format!( "\n{}\n", - format_summary_footer(run.style, &counts, Some(&format!("{elapsed_seconds:.2}s"))) + format_summary_footer( + run.style, + &counts, + Some(&format!( + "{}, {elapsed_seconds:.2}s", + run_on_split(split.0, split.1) + )) + ) ), )?; let rows: Vec = results @@ -169,7 +221,7 @@ fn finish( if !failures.is_empty() { write(&run.stream, &format!("{failures}\n"))?; } - let report: Option = StatementReport::read( + let statements: Option = StatementReport::read_excluding( py, &StatementSource { adapter_name: &run.adapter_name, @@ -177,76 +229,78 @@ fn finish( connection_config: &run.connection_config, started, }, + &report.local_statements, )?; - if let Some(line) = report.as_ref().and_then(StatementReport::line) { + if let Some(line) = statements.as_ref().and_then(StatementReport::line) { write(&run.stream, &format!("{line}\n"))?; } + let refusals: String = match report.mode { + RunOn::Warehouse => String::new(), + RunOn::Local => render_local_refusals(&report.decisions, true, SCENARIO_NOUNS, run.style), + RunOn::Auto if report.verbose => { + render_local_refusals(&report.decisions, false, SCENARIO_NOUNS, run.style) + } + RunOn::Auto => render_warehouse_census(&report.decisions, SCENARIO_NOUNS, run.style), + }; + if !refusals.is_empty() { + write(&run.stream, &refusals)?; + } flush(&run.stream)?; write_completion(&run.stream, (&run.project.namespace, succeeded))?; let namespace: &ScenarioNamespace = &run.project.namespace; - let payload: Bound<'_, PyAny> = PyString::new( - py, - &with_since_section( - format_scenario_execution_json_with( + let payload: String = with_since_section( + format_scenario_execution_json_with( + py, + results, + Some(keywords( py, - results, - Some(keywords( - py, - &[ - ("local", boolean(py, run.local)), - ( - "run_namespace", - optional_text(py, namespace.value.as_deref()), - ), - ("namespace_source", text(py, &namespace.source)), - ( - "duration_ms", - pyo3::types::PyFloat::new(py, elapsed_seconds * 1000.0).into_any(), - ), - ], - )?), - )?, - run.since_json.as_deref(), - ) - .and_then(|payload| match &report { - Some(report) => report.with_section(&payload), - None => Ok(payload), - })?, + &[ + ("local", boolean(py, report.mode == RunOn::Local)), + ( + "run_namespace", + optional_text(py, namespace.value.as_deref()), + ), + ("namespace_source", text(py, &namespace.source)), + ( + "duration_ms", + pyo3::types::PyFloat::new(py, elapsed_seconds * 1000.0).into_any(), + ), + ], + )?), + )?, + run.since_json.as_deref(), + )?; + let payload: String = with_run_on_json( + &payload, + ("scenarios", &JSON_SCENARIO_NAME_KEYS), + &report.decisions, + split, ) - .into_any(); + .map_err(value_error)?; + let payload: String = match &statements { + Some(statements) => statements.with_section(&payload)?, + None => payload, + }; write_execution_json_output( py, - payload, + PyString::new(py, &payload).into_any(), request.getattr("json_output")?.extract()?, request.getattr("json_output_path")?, )?; - Ok(()) + Ok(succeeded) } -fn count(label: &str, value: usize) -> SummaryCount { - SummaryCount { - label: label.to_owned(), - value: i64::try_from(value).unwrap_or(i64::MAX), +/// Run `scenarios` locally on run-scoped DuckDB or on the warehouse, as `run` is set up. +fn execute_batch<'py>( + request: &Bound<'py, PyAny>, + run: &TestRun<'py>, + (pipeline, scenarios): (&Bound<'py, PyAny>, &Bound<'py, PyTuple>), + (section, fallback): (&SectionStatus<'py>, bool), +) -> PyResult>>> { + let py: Python<'py> = request.py(); + if scenarios.is_empty() { + return Ok(Vec::new()); } -} - -/// Run the selected scenarios warehouse-direct, or replay them on run-scoped DuckDB. -fn run_scenarios( - request: &Bound<'_, PyAny>, - run: &TestRun<'_>, - (pipeline, scenarios): (&Bound<'_, PyAny>, &Bound<'_, PyTuple>), -) -> PyResult { - let py: Python<'_> = request.py(); - let section: SectionStatus<'_> = begin_section( - &run.stream, - ( - &format!("Scenario ({} selected)", scenarios.len()), - "", - activity("Running scenarios...", &run.project.namespace), - ), - run.style, - )?; - let started: Instant = Instant::now(); let target_dir: PathBuf = run .project .project_dir @@ -254,7 +308,7 @@ fn run_scenarios( .join(TARGET_DIR); let relay = progress_relay( &run.stream, - §ion, + section, RelayContext { project_dir: &run.project.project_dir, adapter: &run.adapter, @@ -278,21 +332,9 @@ fn run_scenarios( ), ]; let runner: ExecutorHost = if run.local { - let replay_source: Bound<'_, PyAny> = call_with( - &host_entry(py, ExecutorHost::ScenarioLocalReplaySource)?, - &[ - ( - "lexical_syntax", - run.project_adapter.getattr("sql_lexical_syntax")?, - ), - ("capture_adapter", text(py, &run.project_adapter_name)), - ("capture_dialect", text(py, &run.capture_dialect)), - ], - )?; arguments.extend([ ("project_dir", run.project.project_dir.clone()), - ("strict", request.getattr("strict")?), - ("replay_source", replay_source), + ("replay_source", replay_source(run)?), ]); ExecutorHost::RunScenarioLocalTestPipeline } else { @@ -326,45 +368,61 @@ fn run_scenarios( ]); ExecutorHost::RunScenarioTestPipeline }; - let results = - Vec::>::read(&call_with(&host_entry(py, runner)?, &arguments)?)?; - let total: usize = results.len(); - let (counts, ok): (Vec, bool) = if run.local { - let mut tallies: [usize; 4] = [0; 4]; - for result in results.iter() { - let Some(status) = result.local_status else { - continue; - }; - let value = status.value(); - if let Some(index) = LOCAL_STATUSES.iter().position(|label| *label == value) { - tallies[index] += 1; - } - } - let mut counts: Vec = LOCAL_STATUSES - .iter() - .zip(tallies) - .map(|(label, value)| count(label, value)) - .collect(); - counts.push(count("TOTAL", total)); - (counts, tallies[1] == 0 && tallies[2] == 0) - } else { - let mut passed: usize = 0; - for result in results.iter() { - if result.status == ExecutionStatus::Success { - passed += 1; - } - } - ( - vec![ - count("PASS", passed), - count("FAIL", total - passed), - count("TOTAL", total), - ], - passed == total, - ) - }; - finish(request, run, (§ion, started, &results), (counts, ok))?; - Ok(if ok { 0 } else { 1 }) + local_attempt(LocalAttemptStep::HoldReplays(py, fallback))?; + let ran: PyResult> = call_with(&host_entry(py, runner)?, &arguments); + local_attempt(LocalAttemptStep::ReleaseReplays(py))?; + Vec::>::read(&ran?) +} + +/// The project adapter whose dialect locally replayed SQL is authored in. +fn replay_source<'py>(run: &TestRun<'py>) -> PyResult> { + let py: Python<'py> = run.stream.py(); + call_with( + &host_entry(py, ExecutorHost::ScenarioLocalReplaySource)?, + &[ + ( + "lexical_syntax", + run.project_adapter.getattr("sql_lexical_syntax")?, + ), + ("capture_adapter", text(py, &run.project_adapter_name)), + ("capture_dialect", text(py, &run.capture_dialect)), + ], + ) +} + +/// Each selected scenario's run-on decision, from the local runner. +fn decide<'py>( + run: &TestRun<'py>, + (pipeline, scenarios): (&Bound<'py, PyAny>, &Bound<'py, PyTuple>), + mode: RunOn, +) -> PyResult> { + let py: Python<'py> = run.stream.py(); + let project_name: Bound<'_, PyAny> = native_field( + &native_field(&run.project.discovered, "project_config")?, + "name", + )?; + let json: String = call_with( + &host_entry(py, ExecutorHost::DecideScenarioRunOn)?, + &[ + ("project_dir", run.project.project_dir.clone()), + ("pipeline_result", pipeline.clone()), + ("scenarios", scenarios.clone().into_any()), + ("adapter", run.adapter.clone()), + ("project_name", project_name), + ("replay_source", replay_source(run)?), + ("run_on", text(py, mode.as_str())), + ], + )? + .extract()?; + read_run_on_decisions(&json).map_err(value_error) +} + +/// The statements the installed projector has counted so far. +fn statement_summary(py: Python<'_>) -> PyResult { + match current_projector(py)? { + Some(projector) => projector.get().statement_summary(), + None => Ok(StatementSummary::default()), + } } /// Keep only the scenarios that execute something changed since the base revision. @@ -407,36 +465,14 @@ fn select_changed<'py>( )) } -/// Run one `sqb scenario test` request. -#[pyfunction] -#[pyo3(signature = (*, request))] -pub(crate) fn run_scenario_test_command( - py: Python<'_>, - request: &Bound<'_, PyAny>, -) -> PyResult { - let mut run: TestRun<'_> = prepare(py, request)?; - let planning: Bound<'_, PyAny> = write_headers( - &run.stream, - &run.project, - ( - if run.local { - "sqb scenario test --local" - } else { - "sqb scenario test" - }, - if run.local { 1 } else { run.concurrency }, - run.style, - ), - )?; - let since: Option = native_field(request, "since")?.extract()?; - let base: Option = match since.as_deref() { - Some(since) => Some(base_comparison( - (&run.stream, &run.project.project_dir), - since, - &base_variant(None, &py.None().into_bound(py))?, - )?), - None => None, - }; +/// A compiled, selected and `--since`-narrowed set of scenarios, and the `--since` JSON. +fn compiled<'py>( + request: &Bound<'py, PyAny>, + run: &TestRun<'py>, + planning: &Bound<'py, PyAny>, + base: Option, +) -> PyResult<(Bound<'py, PyAny>, Bound<'py, PyTuple>, Option)> { + let py: Python<'py> = request.py(); let no_sql_validation: bool = run.local || flag(request, "no_sql_validation")?; let compiled: PyResult> = compile( &run.project, @@ -451,7 +487,7 @@ pub(crate) fn run_scenario_test_command( native_field(&run.project_adapter, "sql_lexical_syntax")?, ), ], - planning: &planning, + planning, }, ); let finished: PyResult> = planning.call_method0("finish"); @@ -461,23 +497,184 @@ pub(crate) fn run_scenario_test_command( let exclude: Vec = run.project.exclude.extract()?; let mut scenarios: Bound<'_, PyTuple> = selected_scenarios(&pipeline, (&selectors, &exclude, &run.project.project_dir))?; + let mut since_json: Option = None; if let Some(base) = base { - let since_json: String; - (scenarios, since_json) = select_changed( - &run, - (&pipeline, scenarios), - base, - flag(request, "explain")?, - )?; - run.since_json = Some(since_json); + let changed_json: String; + (scenarios, changed_json) = + select_changed(run, (&pipeline, scenarios), base, flag(request, "explain")?)?; + since_json = Some(changed_json); } + Ok((pipeline, scenarios, since_json)) +} + +/// The `--since` base of a run, when the request names one. +fn since_base(request: &Bound<'_, PyAny>, run: &TestRun<'_>) -> PyResult> { + let py: Python<'_> = request.py(); + let since: Option = native_field(request, "since")?.extract()?; + since + .as_deref() + .map(|since| { + base_comparison( + (&run.stream, &run.project.project_dir), + since, + &base_variant(None, &py.None().into_bound(py))?, + ) + }) + .transpose() +} + +/// The scenarios of `scenarios` whose name is in `names`, in order. +fn named<'py>(scenarios: &Bound<'py, PyTuple>, names: &[&str]) -> PyResult> { + let mut kept: Vec> = Vec::new(); + for scenario in scenarios.iter() { + let name: String = native_field(&scenario, "name")?.extract()?; + if names.contains(&name.as_str()) { + kept.push(scenario); + } + } + PyTuple::new(scenarios.py(), kept) +} + +/// Run one `sqb scenario test` request. +#[pyfunction] +#[pyo3(signature = (*, request))] +pub(crate) fn run_scenario_test_command( + py: Python<'_>, + request: &Bound<'_, PyAny>, +) -> PyResult { + let project: ScenarioProject<'_> = discover_project(py, request)?; + let mode: RunOn = resolve_run_on( + &request.getattr("run_on")?, + &project.discovered, + &py.None().into_bound(py), + RUN_ON_SETTING, + )?; + validate_scenario_test_flags(ScenarioTestFlags { + local: mode == RunOn::Local, + warehouse: mode == RunOn::Warehouse, + retain: flag(request, "retain")?, + sync_snapshots: flag(request, "sync_snapshots")?, + refresh: flag(request, "refresh")?, + }) + .map_err(|error| cli_user_error(py, error))?; + let mut run: TestRun<'_> = prepare(request, project, mode != RunOn::Warehouse)?; + let planning: Bound<'_, PyAny> = write_headers( + &run.stream, + &run.project, + ( + "sqb scenario test", + if mode == RunOn::Local { + 1 + } else { + run.concurrency + }, + run.style, + ), + )?; + let base: Option = since_base(request, &run)?; + let (pipeline, scenarios, since_json) = compiled(request, &run, &planning, base)?; + run.since_json = since_json; if run.local && (flag(request, "sync_snapshots")? || flag(request, "refresh")?) { let synced: LocalSync<'_> = sync_local_snapshots(request, &run, (&pipeline, &scenarios))?; if synced.exit_code != 0 { return synced.write_failure_json(request, &run.project.namespace); } } - run_scenarios(request, &run, (&pipeline, &scenarios)) + let mut decisions: Vec = if run.local { + decide(&run, (&pipeline, &scenarios), mode)? + } else { + scenarios + .iter() + .map(|scenario| { + Ok(RunOnDecision { + name: native_field(&scenario, "name")?.extract()?, + run_on: "warehouse".to_owned(), + refusals: Vec::new(), + }) + }) + .collect::>()? + }; + let local_names: Vec<&str> = decisions + .iter() + .filter(|decision| mode == RunOn::Local || decision.local()) + .map(|decision| decision.name.as_str()) + .collect(); + let section: SectionStatus<'_> = begin_section( + &run.stream, + ( + &format!("Scenario ({} selected)", scenarios.len()), + "", + activity("Running scenarios...", &run.project.namespace), + ), + run.style, + )?; + let started: Instant = Instant::now(); + let mut results: Vec>> = Vec::new(); + let mut local_statements: StatementSummary = StatementSummary::default(); + if run.local { + let before: StatementSummary = statement_summary(py)?; + let ran = execute_batch( + request, + &run, + (&pipeline, &named(&scenarios, &local_names)?), + (§ion, mode == RunOn::Auto), + )?; + results.extend(split_scenario_fallbacks(ran, (&mut decisions, mode))?); + local_statements = statement_summary_delta(&before, &statement_summary(py)?); + } + let warehouse_names: Vec<&str> = decisions + .iter() + .filter(|decision| mode != RunOn::Local && !decision.local()) + .map(|decision| decision.name.as_str()) + .collect(); + let reporting: TestRun<'_> = if warehouse_names.is_empty() || !run.local { + if !run.local { + results.extend(execute_batch( + request, + &run, + (&pipeline, &named(&scenarios, &warehouse_names)?), + (§ion, false), + )?); + } + run + } else { + let mut remote: TestRun<'_> = prepare(request, discover_project(py, request)?, false)?; + let quiet: Bound<'_, PyAny> = Bound::new( + py, + sqlbuild_python_output::build_progress::models::PlanningProgressReporter::new( + py, + &remote.stream, + remote.style.use_color, + )?, + )? + .into_any(); + let remote_base: Option = since_base(request, &remote)?; + let (remote_pipeline, remote_scenarios, _remote_since_json) = + compiled(request, &remote, &quiet, remote_base)?; + remote.since_json = run.since_json.clone(); + results.extend(execute_batch( + request, + &remote, + ( + &remote_pipeline, + &named(&remote_scenarios, &warehouse_names)?, + ), + (§ion, false), + )?); + remote + }; + let succeeded: bool = finish( + request, + &reporting, + (§ion, started, &results), + &RunOnReport { + mode, + decisions, + local_statements, + verbose: flag(request, "verbose")?, + }, + )?; + Ok(if succeeded { 0 } else { 1 }) } pub(crate) fn register(module: &Bound<'_, PyModule>) -> PyResult<()> { diff --git a/crates/sqlbuild-python/src/bindings/_helpers/sql_test_command/test_command.rs b/crates/sqlbuild-python/src/bindings/_helpers/sql_test_command/test_command.rs index 6d91e5f9bc..05b4ee29e9 100644 --- a/crates/sqlbuild-python/src/bindings/_helpers/sql_test_command/test_command.rs +++ b/crates/sqlbuild-python/src/bindings/_helpers/sql_test_command/test_command.rs @@ -3,7 +3,7 @@ use sqlbuild_python_base::native_host::models::Dialect; use std::collections::{BTreeSet, HashMap}; use std::path::PathBuf; -use std::sync::Arc; +use std::sync::{Arc, Mutex, PoisonError}; use std::time::Instant; use pyo3::prelude::{ @@ -13,6 +13,15 @@ use pyo3::types::{PyBool, PyDict, PyDictMethods, PyInt, PyString, PyTuple}; use pyo3::{pyclass, pyfunction, pymethods, wrap_pyfunction}; use sqlbuild_analysis::definition_changes::models::{ExecutedItem, SelectedItem}; use sqlbuild_core::cli_text::models::CliStyle; +use sqlbuild_core::progress::main::statement_summary_delta::statement_summary_delta; +use sqlbuild_core::progress::models::StatementSummary; +use sqlbuild_core::run_on::main::apply_local_refusals::apply_local_refusals; +use sqlbuild_core::run_on::main::read_run_on_decisions::read_run_on_decisions; +use sqlbuild_core::run_on::main::render_local_refusals::render_local_refusals; +use sqlbuild_core::run_on::main::render_warehouse_census::render_warehouse_census; +use sqlbuild_core::run_on::main::run_on_column::run_on_column; +use sqlbuild_core::run_on::main::with_run_on_json::with_run_on_json; +use sqlbuild_core::run_on::models::{LocalRefusal, RunOn, RunOnDecision}; use sqlbuild_core::test_command::main::render_test_completion::render_test_completion; use sqlbuild_core::test_command::main::render_test_inspection::render_test_inspection; use sqlbuild_core::test_command::main::render_test_ready::render_test_ready; @@ -49,9 +58,11 @@ use crate::bindings::_helpers::sql_test_command::timeouts::TimeoutKind; use crate::bindings::_helpers::sql_test_command::timeouts::resolve_run_timeout; use sqlbuild_python_base::boundary::main::call_with::call_with; use sqlbuild_python_base::boundary::main::keywords::keywords; +use sqlbuild_python_base::boundary::main::value_error::value_error; use sqlbuild_python_base::boundary::models::KeywordArguments; use sqlbuild_python_base::build_command::main::emit::emit; use sqlbuild_python_base::build_progress::main::progress::current_native_progress_projector::current_native_progress_projector; +use sqlbuild_python_base::build_progress::main::progress::current_projector::current_projector; use sqlbuild_python_base::build_progress::main::transient_status::status_reporter::status_reporter; use sqlbuild_python_base::native_host::main::host_entry::host_entry; use sqlbuild_python_base::native_host::types::ReadResult; @@ -63,16 +74,21 @@ use sqlbuild_python_base::records::main::fields::replaced::replaced; use sqlbuild_python_base::records::types::ErrorId; use sqlbuild_python_base::records::types::RecordId; use sqlbuild_python_compile::compile_driver::main::setup::build_static_pipeline_result::build_static_pipeline_result; +use sqlbuild_python_compile::compile_outputs::main::planned_sql_test_path::planned_sql_test_path; use sqlbuild_python_compile::compile_outputs::main::write_test_runtime_target::write_test_runtime_target; use sqlbuild_python_front::command_runtime::main::resolve_concurrency::resolve_concurrency; +use sqlbuild_python_front::command_runtime::main::resolve_run_on::resolve_run_on; use sqlbuild_python_output::build_progress::main::format_expectation_detail::format_expectation_detail; use sqlbuild_python_output::build_progress::main::format_expectation_name::format_expectation_name; +use sqlbuild_python_output::build_progress::main::local_attempt::local_attempt; use sqlbuild_python_output::build_progress::main::test_label::test_label; use sqlbuild_python_output::build_progress::main::test_result_label::test_result_label; use sqlbuild_python_output::build_progress::main::write_execution_header::write_execution_header; use sqlbuild_python_output::build_progress::models::ConnectionProgressReporter; +use sqlbuild_python_output::build_progress::models::LocalAttemptStep; use sqlbuild_python_output::build_progress::models::NestedCommandProgressCallbacks; use sqlbuild_python_output::result_output::main::events::sql_test_identity::sql_test_identity; +use sqlbuild_python_output::result_output::main::results::local_refusal::local_refusal; use sqlbuild_python_output::result_output::main::results::test_execution_json::test_execution_json; use sqlbuild_python_output::result_output::main::results::write_execution_json_output::write_execution_json_output; use sqlbuild_python_output::result_output::models::ExecutionEventWriter; @@ -88,6 +104,16 @@ const EXPECT_LABEL: &str = "expect"; const UNKNOWN_GROUP: &str = "(unknown)"; const EXECUTION_COMMAND: &str = "sqb test"; const UNKNOWN_CASE_CODE: &str = "S008"; +const RUN_ON_SETTING: &str = "test_run_on"; +const TEST_NOUNS: (&str, &str) = ("test", "tests"); +const LOCAL_RUN_ON: &str = "local"; +const WAREHOUSE_RUN_ON: &str = "warehouse"; +const CANNOT_RUN_LOCALLY_CODE: &str = "T007"; +const CANNOT_RUN_LOCALLY_MESSAGE: &str = "can't run locally"; +const NEEDS_WAREHOUSE_CODE: &str = "T008"; +const NEEDS_WAREHOUSE_MESSAGE: &str = "needs the warehouse (no connection)"; +const COMPILED_TESTS_DIR: &str = "target/run/tests"; +const JSON_CHECK_NAME_KEYS: [&str; 3] = ["test_name", "name", "resource_name"]; fn text<'py>(py: Python<'py>, value: &str) -> Bound<'py, PyAny> { PyString::new(py, value).into_any() @@ -192,6 +218,10 @@ fn entry_group(entry: &Bound<'_, PyAny>) -> PyResult { #[pyclass(module = "sqlbuild._native", frozen)] struct TestCallbackRelay { worker: Option>, + /// Where each test runs, by test name; a local test that falls back becomes `warehouse`. + run_on: Mutex>, + /// In `auto`, a local test DuckDB can't run as the warehouse would runs there instead, unreported. + fallback: bool, progress: Py, event_writer: Py, plan_output: Py, @@ -216,6 +246,14 @@ impl TestCallbackRelay { } fn on_test_complete(&self, py: Python<'_>, result: &Bound<'_, PyAny>) -> PyResult<()> { + if let (true, Some((name, refusal))) = (self.fallback, refused(result)?) { + let mut run_on = self.run_on.lock().unwrap_or_else(PoisonError::into_inner); + if run_on.get(&name).map(String::as_str) == Some(LOCAL_RUN_ON) { + run_on.insert(name, format!("{WAREHOUSE_RUN_ON} ({})", refusal.title())); + let step = LocalAttemptStep::Abandon(self.progress.bind(py), result); + return local_attempt(step).map(drop); + } + } let mut group: String = String::new(); if let Some(step) = result.getattr("step_results")?.try_iter()?.next() { group = step?.getattr("model_name")?.extract()?; @@ -242,7 +280,7 @@ impl TestCallbackRelay { ("item_name", text(py, &test_label(result, "test_name")?)), ("status_text", text(py, status)), ("child_rows", expectation_rows(result)?.into_any()), - ("detail", text(py, &real_model_detail(result)?)), + ("detail", text(py, &self.detail(result)?)), ("error_code", result.getattr("error_code")?), ("error_help", result.getattr("error_help")?), ("error_message", result.getattr("error_message")?), @@ -289,6 +327,19 @@ impl TestCallbackRelay { } impl TestCallbackRelay { + /// The run-on column, then `N real models`. + fn detail(&self, result: &Bound<'_, PyAny>) -> PyResult { + let name: String = result.getattr("test_name")?.extract()?; + let real: String = real_model_detail(result)?; + let run_on = self.run_on.lock().unwrap_or_else(PoisonError::into_inner); + Ok(match run_on.get(&name) { + Some(run_on) => format!(" {}{real}", run_on_column(run_on)) + .trim_end() + .to_owned(), + None => real, + }) + } + fn connection_call( &self, py: Python<'_>, @@ -305,6 +356,11 @@ impl TestCallbackRelay { } } +/// The test that ran locally and failed where the warehouse would not, and why, when it did. +fn refused(result: &Bound<'_, PyAny>) -> PyResult> { + local_refusal(&native_field(result, "local_refusal")?) +} + fn unknown_case(py: Python<'_>, message: String) -> PyErr { new_error( py, @@ -442,6 +498,7 @@ fn inspection_entry(entry: &Bound<'_, PyAny>) -> PyResult { real_models, expected_models, selection_reasons: Vec::new(), + run_on: None, }) } @@ -449,13 +506,20 @@ fn inspection_entry(entry: &Bound<'_, PyAny>) -> PyResult { fn inspect( stream: &Bound<'_, PyAny>, plan_output: &Bound<'_, PyAny>, - reasons: &HashMap>, + (reasons, decisions): (&HashMap>, &[RunOnDecision]), ) -> PyResult { + let by_name: HashMap<&str, &RunOnDecision> = decisions + .iter() + .map(|decision| (decision.name.as_str(), decision)) + .collect(); let entries: Vec = native_field(plan_output, "test_entries")? .try_iter()? .map(|entry| { - let mut entry: TestInspectionEntry = inspection_entry(&entry?)?; + let entry: Bound<'_, PyAny> = entry?; + let name: String = entry.getattr("name")?.extract()?; + let mut entry: TestInspectionEntry = inspection_entry(&entry)?; entry.selection_reasons = reasons.get(&entry.label).cloned().unwrap_or_default(); + entry.run_on = by_name.get(name.as_str()).copied().cloned(); Ok(entry) }) .collect::>()?; @@ -519,12 +583,34 @@ fn select_changed<'py>( )) } -/// Write the ready header and run the tests with nested progress; returns the results. +/// Where each selected test goes: an error row, the local DuckDB batch, or the warehouse batch. +pub(crate) struct TestPlacement<'py> { + /// Tests that do not run, with the code and message of their error row. + unplaced: Vec<(Bound<'py, PyAny>, &'static str, &'static str)>, + local: Vec>, + /// The local tests' names, in the same order. + local_names: Vec, + warehouse: Vec>, + /// Where each test runs, by name, for its row. + run_on: HashMap, + /// In `auto`, warehouse tests without a connection become error rows instead of failing the run. + warehouse_optional: bool, +} + +/// Results in plan order, local statements, and each local test failing where the warehouse wouldn't. +type RanTests<'py> = ( + Vec>>, + StatementSummary, + Vec<(String, LocalRefusal)>, +); + +/// Run the tests with nested progress, local ones first; in `auto`, those that fall back after. fn run_tests<'py>( invocation: &Bound<'py, PyAny>, pipeline: &Bound<'py, PyAny>, (concurrency, timeout, worker): (i64, &RunTimeout, Option>), -) -> PyResult>>> { + placement: TestPlacement<'py>, +) -> PyResult> { let py: Python<'py> = invocation.py(); let stream: Bound<'py, PyAny> = invocation.getattr("progress_stream")?; let use_color: Bound<'py, PyAny> = invocation.getattr("use_color")?; @@ -594,60 +680,212 @@ fn run_tests<'py>( let preflight: Bound<'py, PyAny> = status_reporter(&stream, use_color.is_truthy()?)?; let event_writer: Bound<'py, PyAny> = Bound::new(py, ExecutionEventWriter::new(py, None)?)?.into_any(); + let TestPlacement { + unplaced, + local, + local_names, + mut warehouse, + run_on, + warehouse_optional, + } = placement; + let mut refused_locally: Vec<(String, LocalRefusal)> = Vec::new(); let relay: Bound<'py, TestCallbackRelay> = Bound::new( py, TestCallbackRelay { worker, + run_on: Mutex::new(run_on), + fallback: warehouse_optional, progress: progress.unbind(), event_writer: event_writer.clone().unbind(), plan_output: plan_output.clone().unbind(), connection: connection.clone().unbind(), }, )?; - let executed: PyResult>>> = (|| { - let callbacks: Bound<'py, PyAny> = call_with( - &host_entry(py, ExecutorHost::TestPipelineCallbacks)?, - &[ - ( - "on_connection_start", - connection.getattr("on_connection_start")?, - ), - ( - "on_connection_complete", - relay.getattr("on_connection_complete")?, - ), - ("on_connection_error", relay.getattr("on_connection_error")?), + let mut local_statements: StatementSummary = StatementSummary::default(); + let executed: PyResult>> = (|| { + let mut results: Vec> = Vec::new(); + for (code, message) in [ + (CANNOT_RUN_LOCALLY_CODE, CANNOT_RUN_LOCALLY_MESSAGE), + (NEEDS_WAREHOUSE_CODE, NEEDS_WAREHOUSE_MESSAGE), + ] { + let entries: Vec> = unplaced + .iter() + .filter(|(_, unplaced_code, _)| *unplaced_code == code) + .map(|(entry, _, _)| entry.clone()) + .collect(); + results.extend(report_unplaced( + &relay, + pipeline, + &entries, + (code, message), + )?); + } + let callbacks = |reporting_connection: bool| -> PyResult> { + let mut hooks: Vec<(&str, Bound<'py, PyAny>)> = vec![ ( "on_progress", preflight.getattr("report_preflight_progress")?, ), ("on_test_start", relay.getattr("on_test_start")?), ("on_test_complete", relay.getattr("on_test_complete")?), - ], - )?; - call_with( - &host_entry(py, ExecutorHost::RunTestPipeline)?, - &[ - ("plan", plan_output), + ]; + if reporting_connection { + hooks.extend([ + ( + "on_connection_start", + connection.getattr("on_connection_start")?, + ), + ( + "on_connection_complete", + relay.getattr("on_connection_complete")?, + ), + ("on_connection_error", relay.getattr("on_connection_error")?), + ]); + } + call_with( + &host_entry(py, ExecutorHost::TestPipelineCallbacks)?, + &hooks, + ) + }; + let run = |batch: &[Bound<'py, PyAny>], + (adapter, connection_config): (Bound<'py, PyAny>, Bound<'py, PyAny>), + reporting_connection: bool| + -> PyResult>> { + call_with( + &host_entry(py, ExecutorHost::RunTestPipeline)?, + &[ + ( + "plan", + replaced( + &plan_output, + &[("test_entries", PyTuple::new(py, batch)?.into_any())], + )?, + ), + ("connection_config", connection_config), + ("adapter", adapter), + ("max_concurrency", PyInt::new(py, concurrency).into_any()), + ("callbacks", callbacks(reporting_connection)?), + ("run_id", pipeline.getattr("project")?.getattr("run_id")?), + ("timeouts", timeout_record(py, timeout)?), + ], + )? + .try_iter()? + .collect() + }; + if !local.is_empty() { + let before: StatementSummary = statement_summary(py)?; + let adapter: Bound<'py, PyAny> = call_with( + &host_entry(py, ExecutorHost::LocalTestAdapter)?, + &[ + ("project", native_field(pipeline, "project")?), + ("adapter", invocation.getattr("adapter")?), + ], + )?; + let memory: Bound<'py, PyDict> = PyDict::new(py); + memory.set_item("database", ":memory:")?; + let progress: &Bound<'py, PyAny> = relay.get().progress.bind(py); + local_attempt(LocalAttemptStep::Hold(progress, warehouse_optional))?; + let ran: PyResult>> = + run(&local, (adapter, memory.into_any()), false); + local_attempt(LocalAttemptStep::Release(progress))?; + for result in ran? { + let Some((name, refusal)) = refused(&result)? else { + results.push(result); + continue; + }; + let entry = local_names + .iter() + .position(|test| *test == name) + .map(|at| &local[at]); + refused_locally.push((name, refusal)); + match (warehouse_optional, entry) { + (true, Some(entry)) => warehouse.push(entry.clone()), + _ => results.push(result), + } + } + local_statements = statement_summary_delta(&before, &statement_summary(py)?); + } + if !warehouse.is_empty() { + match run( + &warehouse, ( - "connection_config", + invocation.getattr("adapter")?, invocation.getattr("connection_config")?, ), - ("adapter", invocation.getattr("adapter")?), - ("max_concurrency", PyInt::new(py, concurrency).into_any()), - ("callbacks", callbacks), - ("run_id", pipeline.getattr("project")?.getattr("run_id")?), - ("timeouts", timeout_record(py, timeout)?), - ], - )? - .try_iter()? - .map(|result| SqlTestExecutionResult::read(&result?)) - .collect() + true, + ) { + Ok(ran) => results.extend(ran), + Err(error) + if warehouse_optional + && error.is_instance( + py, + &host_entry(py, ExecutorHost::WarehouseConnectionError)?, + ) => + { + results.extend(report_unplaced( + &relay, + pipeline, + &warehouse, + (NEEDS_WAREHOUSE_CODE, NEEDS_WAREHOUSE_MESSAGE), + )?); + } + Err(error) => return Err(error), + } + } + Ok(results) })(); let closed: PyResult> = event_writer.call_method0("close"); - let results: Vec>> = executed?; + let ran: Vec> = executed?; closed?; - Ok(results) + let mut by_name: HashMap> = HashMap::new(); + for result in ran { + by_name.insert(result.getattr("test_name")?.extract()?, result); + } + let mut results: Vec>> = Vec::new(); + for entry in entries.try_iter()? { + let name: String = entry?.getattr("name")?.extract()?; + if let Some(result) = by_name.remove(&name) { + results.push(SqlTestExecutionResult::read(&result)?); + } + } + for result in by_name.into_values() { + results.push(SqlTestExecutionResult::read(&result)?); + } + Ok((results, local_statements, refused_locally)) +} + +/// Error rows for tests that do not run, reported as the run reports every other test. +fn report_unplaced<'py>( + relay: &Bound<'py, TestCallbackRelay>, + pipeline: &Bound<'py, PyAny>, + entries: &[Bound<'py, PyAny>], + (code, message): (&str, &str), +) -> PyResult>> { + let py: Python<'py> = relay.py(); + if entries.is_empty() { + return Ok(Vec::new()); + } + call_with( + &host_entry(py, ExecutorHost::ReportUnplacedSqlTests)?, + &[ + ("test_entries", PyTuple::new(py, entries)?.into_any()), + ("code", text(py, code)), + ("message", text(py, message)), + ("run_id", pipeline.getattr("project")?.getattr("run_id")?), + ("on_test_start", relay.getattr("on_test_start")?), + ("on_test_complete", relay.getattr("on_test_complete")?), + ], + )? + .try_iter()? + .collect() +} + +/// The statements the installed projector has counted so far. +fn statement_summary(py: Python<'_>) -> PyResult { + match current_projector(py)? { + Some(projector) => projector.get().statement_summary(), + None => Ok(StatementSummary::default()), + } } /// The executor's `RunItemTimeouts` for a resolved run limit. @@ -658,18 +896,35 @@ pub(crate) fn timeout_record<'py>( host_entry(py, ExecutorHost::RunItemTimeouts)?.call((), Some(&timeout.keywords(py)?)) } -/// Write the summary and failures; returns the exit code and the `--json` document. +/// Where the run sent its tests, for the summary, the refusal report and `--json`. +struct RunOnReport { + mode: RunOn, + decisions: Vec, + local_statements: StatementSummary, + verbose: bool, +} + +/// Write the summary, failures, statements and refusals; returns the exit code and the `--json` document. fn complete( invocation: &Bound<'_, PyAny>, (results, since_json): (&[SqlTestExecutionResult>], Option<&str>), started: Instant, + report: &RunOnReport, ) -> PyResult<(i32, String)> { let py: Python<'_> = invocation.py(); let mut failures: Vec = Vec::new(); + let mut failed: usize = 0; for result in results { if result.outcome == SqlTestOutcome::Pass { continue; } + failed += 1; + if matches!( + result.error_code.as_deref(), + Some(CANNOT_RUN_LOCALLY_CODE | NEEDS_WAREHOUSE_CODE) + ) { + continue; + } failures.push(TestFailure { label: test_result_label(result)?, error_message: result.error_message.clone(), @@ -677,27 +932,57 @@ fn complete( error_help: result.error_help.clone(), }); } - let passed: usize = results.len() - failures.len(); + let passed: usize = results.len() - failed; + let local: usize = report + .decisions + .iter() + .filter(|decision| decision.run_on == LOCAL_RUN_ON) + .count(); + let split: (usize, usize) = (local, report.decisions.len() - local); let stream: Bound<'_, PyAny> = invocation.getattr("progress_stream")?; let style: CliStyle = CliStyle { use_color: invocation.getattr("use_color")?.is_truthy()?, }; - let completion: String = render_test_completion((passed, results.len()), &failures, style); + let completion: String = + render_test_completion((passed, results.len()), &failures, Some(split), style); emit(&stream, &completion)?; - let report: Option = StatementReport::of_invocation(invocation, started)?; - if let Some(line) = report.as_ref().and_then(StatementReport::line) { + let statements: Option = + StatementReport::of_invocation(invocation, started, &report.local_statements)?; + if let Some(line) = statements.as_ref().and_then(StatementReport::line) { emit(&stream, &format!("\n{line}\n"))?; } - let payload: String = with_since_section(test_execution_json(py, results)?, since_json)?; + let refusals: String = refusal_report(report, style); + if !refusals.is_empty() { + emit(&stream, &refusals)?; + } + let payload: String = with_run_on_json( + &with_since_section(test_execution_json(py, results)?, since_json)?, + ("checks", &JSON_CHECK_NAME_KEYS), + &report.decisions, + split, + ) + .map_err(value_error)?; Ok(( test_exit_code(passed, results.len()), - match report { - Some(report) => report.with_section(&payload)?, + match statements { + Some(statements) => statements.with_section(&payload)?, None => payload, }, )) } +/// `local`: every refusal as a diagnostic; `auto`: a census, or the diagnostics with `--verbose`. +fn refusal_report(report: &RunOnReport, style: CliStyle) -> String { + match report.mode { + RunOn::Warehouse => String::new(), + RunOn::Local => render_local_refusals(&report.decisions, true, TEST_NOUNS, style), + RunOn::Auto if report.verbose => { + render_local_refusals(&report.decisions, false, TEST_NOUNS, style) + } + RunOn::Auto => render_warehouse_census(&report.decisions, TEST_NOUNS, style), + } +} + /// Run one `sqb test` request. #[pyfunction] #[pyo3(signature = (*, request))] @@ -741,11 +1026,30 @@ pub(crate) fn run_test<'py>( ), )); } - let invocation: Bound<'_, PyAny> = resolve_reported_command_invocation( - request, - &record_class(py, RecordId::TestInvocation)?, - (!inspect_only, discovered), - )?; + let wants_connection: bool = !inspect_only + && native_field(request, "run_on")? + .extract::>()? + .as_deref() + != Some(LOCAL_RUN_ON); + let invocation_class: Bound<'_, PyAny> = record_class(py, RecordId::TestInvocation)?; + let (invocation, connection_error): (Bound<'_, PyAny>, Option) = + match resolve_reported_command_invocation( + request, + &invocation_class, + (wants_connection, discovered), + ) { + Ok(invocation) => (invocation, None), + Err(error) if wants_connection => ( + resolve_reported_command_invocation( + request, + &invocation_class, + (false, discovered), + ) + .map_err(|_| error.clone_ref(py))?, + Some(error), + ), + Err(error) => return Err(error), + }; let python: bool = worker.is_none() && !inspect_only && !native_field(request, "sql_only")?.is_truthy()? @@ -771,7 +1075,12 @@ pub(crate) fn run_test<'py>( Some(test_execution_json(py, &[])?), ) } - modules => run_sql_tests(request, &invocation, worker, (modules, resolve))?, + modules => run_sql_tests( + request, + (&invocation, connection_error), + worker, + (modules, resolve), + )?, }; if python_tests.is_empty() { write_json(request, payload)?; @@ -805,7 +1114,7 @@ fn write_json(request: &Bound<'_, PyAny>, payload: Option) -> PyResult<( /// Compile, inspect or run the selected SQL tests and pick the Python test `modules` to run after. fn run_sql_tests<'py>( request: &Bound<'py, PyAny>, - invocation: &Bound<'py, PyAny>, + (invocation, connection_error): (&Bound<'py, PyAny>, Option), worker: Option>, (modules, resolve): (Option>, bool), ) -> PyResult<(i32, Vec, Option)> { @@ -850,12 +1159,35 @@ fn run_sql_tests<'py>( )?; since_json = Some(json); } + let mode: RunOn = resolve_run_on( + &request.getattr("run_on")?, + &native_field(invocation, "discovered_inputs")?, + &request.getattr("selected_target")?, + RUN_ON_SETTING, + )?; + if mode == RunOn::Warehouse + && !inspect_only + && let Some(error) = connection_error.as_ref() + { + return Err(error.clone_ref(py)); + } + let decisions: Vec = decide(invocation, &pipeline, mode)?; if inspect_only { - return Ok(( - inspect(&stream, &pipeline.getattr("plan_output")?, &reasons)?, - python_tests, - None, - )); + let style: CliStyle = CliStyle { + use_color: invocation.getattr("use_color")?.is_truthy()?, + }; + let code: i32 = inspect( + &stream, + &pipeline.getattr("plan_output")?, + (&reasons, &decisions), + )?; + if mode != RunOn::Warehouse { + emit( + &stream, + &render_local_refusals(&decisions, mode == RunOn::Local, TEST_NOUNS, style), + )?; + } + return Ok((code, python_tests, None)); } if !python_tests.is_empty() && !pipeline @@ -894,8 +1226,18 @@ fn run_sql_tests<'py>( request.getattr("test_timeout")?.extract()?, TimeoutKind::Test, )?; - let results: Vec>> = - run_tests(invocation, &pipeline, (concurrency, &timeout, worker))?; + let (placement, mut decisions): (TestPlacement<'_>, Vec) = place_tests( + &pipeline.getattr("plan_output")?.getattr("test_entries")?, + (mode, decisions), + connection_error.is_some(), + )?; + let (results, local_statements, refused_locally): RanTests<'_> = run_tests( + invocation, + &pipeline, + (concurrency, &timeout, worker), + placement, + )?; + apply_local_refusals(&mut decisions, refused_locally, mode); write_test_runtime_target( ( &native_field(invocation, "effective_project_dir")? @@ -905,11 +1247,112 @@ fn run_sql_tests<'py>( &pipeline.getattr("plan_output")?, &results, )?; - let (code, payload): (i32, String) = - complete(invocation, (&results, since_json.as_deref()), started)?; + let (code, payload): (i32, String) = complete( + invocation, + (&results, since_json.as_deref()), + started, + &RunOnReport { + mode, + decisions, + local_statements, + verbose: native_field(request, "verbose")?.is_truthy()?, + }, + )?; Ok((code, python_tests, Some(payload))) } +/// Each selected test's run-on decision, from the local runner. +fn decide( + invocation: &Bound<'_, PyAny>, + pipeline: &Bound<'_, PyAny>, + mode: RunOn, +) -> PyResult> { + let py: Python<'_> = invocation.py(); + let entries: Bound<'_, PyAny> = pipeline.getattr("plan_output")?.getattr("test_entries")?; + let paths: Bound<'_, PyDict> = PyDict::new(py); + for entry in entries.try_iter()? { + let entry: Bound<'_, PyAny> = entry?; + let path: String = planned_sql_test_path(&entry)?.str()?.extract()?; + paths.set_item( + entry.getattr("name")?, + format!("{COMPILED_TESTS_DIR}/{}", path.replace('\\', "/")), + )?; + } + let json: String = call_with( + &host_entry(py, ExecutorHost::DecideSqlTestRunOn)?, + &[ + ("project", native_field(pipeline, "project")?), + ("test_entries", entries), + ("adapter", invocation.getattr("adapter")?), + ( + "project_dir", + native_field(invocation, "effective_project_dir")?, + ), + ("compiled_paths", paths.into_any()), + ("run_on", text(py, mode.as_str())), + ], + )? + .extract()?; + read_run_on_decisions(&json).map_err(value_error) +} + +/// Split the tests by `mode` and their decisions, and say where each one ran. +fn place_tests<'py>( + entries: &Bound<'py, PyAny>, + (mode, decisions): (RunOn, Vec), + no_connection: bool, +) -> PyResult<(TestPlacement<'py>, Vec)> { + let mut placement: TestPlacement<'py> = TestPlacement { + unplaced: Vec::new(), + local: Vec::new(), + local_names: Vec::new(), + warehouse: Vec::new(), + run_on: HashMap::new(), + warehouse_optional: mode == RunOn::Auto, + }; + let mut placed: Vec = Vec::with_capacity(decisions.len()); + for entry in entries.try_iter()? { + let entry: Bound<'py, PyAny> = entry?; + let name: String = entry.getattr("name")?.extract()?; + let mut decision: RunOnDecision = decisions + .iter() + .find(|decision| decision.name == name) + .cloned() + .unwrap_or_else(|| RunOnDecision { + name: name.clone(), + run_on: WAREHOUSE_RUN_ON.to_owned(), + refusals: Vec::new(), + }); + match mode { + RunOn::Warehouse => { + decision.run_on = WAREHOUSE_RUN_ON.to_owned(); + placement.warehouse.push(entry); + } + _ if decision.local() => { + placement.local_names.push(name.clone()); + placement.local.push(entry); + } + RunOn::Local => { + decision.run_on = LOCAL_RUN_ON.to_owned(); + placement.unplaced.push(( + entry, + CANNOT_RUN_LOCALLY_CODE, + CANNOT_RUN_LOCALLY_MESSAGE, + )); + } + RunOn::Auto if no_connection => { + placement + .unplaced + .push((entry, NEEDS_WAREHOUSE_CODE, NEEDS_WAREHOUSE_MESSAGE)) + } + RunOn::Auto => placement.warehouse.push(entry), + } + placement.run_on.insert(name, decision.run_on.clone()); + placed.push(decision); + } + Ok((placement, placed)) +} + /// Add source and safe typed values only for parameterized test rows. #[pyfunction] #[pyo3(signature = (**options))] diff --git a/crates/sqlbuild-recall/src/store/constants.rs b/crates/sqlbuild-recall/src/store/constants.rs index 80bd1d4e04..46ae018a67 100644 --- a/crates/sqlbuild-recall/src/store/constants.rs +++ b/crates/sqlbuild-recall/src/store/constants.rs @@ -34,3 +34,7 @@ pub const DECIMAL_UNITS: [&str; 4] = ["kB", "MB", "GB", "TB"]; pub const BINARY_UNITS: [&str; 4] = ["KiB", "MiB", "GiB", "TiB"]; /// The `sqlite_schema.type` of a view. pub(crate) const SQLITE_VIEW_TYPE: &str = "view"; +/// The fewest characters of a run ID run selectors take, like a short git hash. +pub const MIN_RUN_ID_PREFIX: usize = 8; +/// How many runs an ambiguous run ID prefix lists. +pub const LISTED_RUN_CANDIDATES: usize = 5; diff --git a/crates/sqlbuild-recall/src/store/main/mod.rs b/crates/sqlbuild-recall/src/store/main/mod.rs index 040662b9ad..1d6ce2ece8 100644 --- a/crates/sqlbuild-recall/src/store/main/mod.rs +++ b/crates/sqlbuild-recall/src/store/main/mod.rs @@ -11,8 +11,10 @@ pub mod open_sqlite_store; pub mod quarantine_store; pub mod query_store; pub mod read_output_transcript; +pub mod read_run_results; pub mod relational_insert; pub mod relational_lookup; pub mod relational_row; pub mod resolve_invocation; +pub mod resolve_run; pub mod store_location_problem; diff --git a/crates/sqlbuild-recall/src/store/main/read_run_results.rs b/crates/sqlbuild-recall/src/store/main/read_run_results.rs new file mode 100644 index 0000000000..b74442b19c --- /dev/null +++ b/crates/sqlbuild-recall/src/store/main/read_run_results.rs @@ -0,0 +1,41 @@ +//! `read_run_results`: what one recorded run attempted, didn't finish and skipped, and the audits that failed it. + +use std::collections::BTreeSet; + +use crate::store::_helpers::sqlite::checked; +use crate::store::errors::StoreError; +use crate::store::models::{RecallRunResults, SqliteStore}; + +/// The resources `run_id` attempted or skipped by outcome, with its unignored error-severity audit failures as `audit:`; an audit it didn't run, for a read the target lacked, is none of them. +pub fn read_run_results(store: &SqliteStore, run_id: &str) -> Result { + let keys = |sql: &str| -> Result, StoreError> { + let mut statement = checked(store.connection.prepare(sql), "read the run")?; + checked( + statement + .query_map([run_id], |row| row.get(0)) + .and_then(Iterator::collect), + "read the run", + ) + }; + Ok(RecallRunResults { + run_id: run_id.to_owned(), + selected: keys( + "SELECT DISTINCT resource_id FROM recall_events WHERE run_id = ?1 \ + AND resource_id IS NOT NULL AND event_type LIKE 'resource_attempt_%' \ + AND NOT (resource_kind = 'audit' AND resource_name IN \ + (SELECT audit_name FROM audit_results WHERE run_id = ?1 AND outcome = 'not_run'))", + )?, + failed: keys( + "SELECT DISTINCT resource_id FROM recall_events WHERE run_id = ?1 \ + AND event_type = 'resource_attempt_failed' AND resource_id NOT IN \ + (SELECT resource_id FROM recall_events WHERE run_id = ?1 \ + AND event_type = 'resource_attempt_completed' AND resource_id IS NOT NULL) \ + UNION SELECT DISTINCT 'audit:' || audit_name FROM audit_results \ + WHERE run_id = ?1 AND outcome = 'error' AND ignored = 0", + )?, + skipped: keys( + "SELECT DISTINCT resource_id FROM recall_events WHERE run_id = ?1 \ + AND event_type = 'resource_attempt_skipped' AND resource_id IS NOT NULL", + )?, + }) +} diff --git a/crates/sqlbuild-recall/src/store/main/resolve_run.rs b/crates/sqlbuild-recall/src/store/main/resolve_run.rs new file mode 100644 index 0000000000..ce698d6f78 --- /dev/null +++ b/crates/sqlbuild-recall/src/store/main/resolve_run.rs @@ -0,0 +1,60 @@ +//! `resolve_run`: the recorded run a full ID or unique prefix of at least 8 characters names. + +use crate::store::_helpers::sqlite::checked; +use crate::store::constants::{LISTED_RUN_CANDIDATES, MIN_RUN_ID_PREFIX}; +use crate::store::errors::{StoreError, StoreErrorKind}; +use crate::store::models::SqliteStore; + +/// The full run ID `selector` names: itself, or the one recorded run it prefixes. +pub fn resolve_run(store: &SqliteStore, selector: &str) -> Result { + if selector.chars().count() < MIN_RUN_ID_PREFIX { + return Err(StoreError::new( + StoreErrorKind::Query, + format!( + "run ID '{selector}' is too short: give the full ID or at least {MIN_RUN_ID_PREFIX} characters of it" + ), + )); + } + let mut statement = checked( + store.connection.prepare( + "SELECT DISTINCT run_id FROM recall_events \ + WHERE run_id IS NOT NULL AND substr(run_id, 1, length(?1)) = ?1 \ + ORDER BY run_id LIMIT ?2", + ), + "find the run", + )?; + let candidates: Vec = checked( + statement + .query_map( + rusqlite::params![selector, LISTED_RUN_CANDIDATES + 1], + |row| row.get(0), + ) + .and_then(Iterator::collect), + "find the run", + )?; + if let Some(exact) = candidates.iter().find(|candidate| *candidate == selector) { + return Ok(exact.clone()); + } + match candidates.as_slice() { + [only] => Ok(only.clone()), + [] => Err(StoreError::new( + StoreErrorKind::NotFound, + format!("no run '{selector}' in the local Recall history"), + )), + several => { + let listed: &[String] = &several[..several.len().min(LISTED_RUN_CANDIDATES)]; + Err(StoreError::new( + StoreErrorKind::Ambiguous, + format!( + "run ID '{selector}' is ambiguous: it starts {}{}; give more of the ID", + listed.join(", "), + if several.len() > listed.len() { + ", and more" + } else { + "" + } + ), + )) + } + } +} diff --git a/crates/sqlbuild-recall/src/store/models.rs b/crates/sqlbuild-recall/src/store/models.rs index fd53a8b5c7..3e1157dcbc 100644 --- a/crates/sqlbuild-recall/src/store/models.rs +++ b/crates/sqlbuild-recall/src/store/models.rs @@ -96,6 +96,18 @@ pub struct MaintenanceOutcome { pub complete: bool, } +/// One recorded run's resources and audits as node keys, for `run:`, `failed:` and `skipped:`; failed audits are `audit:`. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RecallRunResults { + pub run_id: String, + /// Every resource the run attempted or skipped. + pub selected: std::collections::BTreeSet, + /// Resources whose attempts all failed, and error-severity audit failures it didn't let through. + pub failed: std::collections::BTreeSet, + /// Resources it skipped. + pub skipped: std::collections::BTreeSet, +} + /// The rows of a read-only query. #[derive(Clone, Debug, Default, PartialEq)] pub struct QueryResult { diff --git a/crates/sqlbuild-state/src/runs/constants.rs b/crates/sqlbuild-state/src/runs/constants.rs index 5b5246edb5..7c321b4927 100644 --- a/crates/sqlbuild-state/src/runs/constants.rs +++ b/crates/sqlbuild-state/src/runs/constants.rs @@ -49,12 +49,10 @@ pub const STARTED_PHASE: &str = "started"; pub const FINISHED_PHASE: &str = "finished"; /// A finished run whose nodes all succeeded, warnings included. pub const SUCCEEDED_STATUS: &str = "succeeded"; -/// A finished run in which nothing succeeded and something failed or was skipped. +/// A finished run in which a node failed, was skipped or never started. pub const FAILED_STATUS: &str = "failed"; /// A finished run stopped by an interrupt or a cancel. pub const CANCELLED_STATUS: &str = "cancelled"; -/// A finished run in which some nodes succeeded and others failed or were skipped. -pub const PARTIAL_STATUS: &str = "partial"; /// `sqlbuild_user` of a run the scheduler started. pub const SYSTEM_SCHEDULE_USER: &str = "system:schedule"; /// `sqlbuild_user` of a run a sensor started. diff --git a/crates/sqlbuild-state/src/runs/main/run_status.rs b/crates/sqlbuild-state/src/runs/main/run_status.rs index 92f2c9b2dc..a92dffc23e 100644 --- a/crates/sqlbuild-state/src/runs/main/run_status.rs +++ b/crates/sqlbuild-state/src/runs/main/run_status.rs @@ -1,17 +1,15 @@ //! A finished run's status from how it ended and its node counts, by the server's rule for its own runs. -use crate::runs::constants::{CANCELLED_STATUS, FAILED_STATUS, PARTIAL_STATUS, SUCCEEDED_STATUS}; +use crate::runs::constants::{CANCELLED_STATUS, FAILED_STATUS, SUCCEEDED_STATUS}; use crate::runs::models::{RunEnding, RunNodeCounts}; -/// `cancelled` if interrupted, `failed` on an error, else partial, failed or succeeded by node counts. +/// `cancelled` if interrupted, else `failed` on an error or a node that failed, was skipped or never started, else `succeeded`. #[must_use] pub fn run_status(counts: &RunNodeCounts, ending: RunEnding) -> &'static str { - let good: bool = counts.succeeded > 0; let bad: bool = counts.failed + counts.skipped + counts.not_started > 0; - match (ending, bad, good) { - (RunEnding::Interrupted, _, _) => CANCELLED_STATUS, - (RunEnding::Raised, _, _) | (RunEnding::Completed, true, false) => FAILED_STATUS, - (RunEnding::Completed, true, true) => PARTIAL_STATUS, - (RunEnding::Completed, false, _) => SUCCEEDED_STATUS, + match (ending, bad) { + (RunEnding::Interrupted, _) => CANCELLED_STATUS, + (RunEnding::Raised, _) | (RunEnding::Completed, true) => FAILED_STATUS, + (RunEnding::Completed, false) => SUCCEEDED_STATUS, } } diff --git a/crates/sqlbuild-state/src/runs/tests/test_run_status.rs b/crates/sqlbuild-state/src/runs/tests/test_run_status.rs index e8a2edcc9a..e6b9441202 100644 --- a/crates/sqlbuild-state/src/runs/tests/test_run_status.rs +++ b/crates/sqlbuild-state/src/runs/tests/test_run_status.rs @@ -16,14 +16,14 @@ fn given_node_counts_when_finishing_a_run_then_the_status_follows_the_server_rul expected_status: "succeeded", }, RunStatusTestCase { - description: "a failure beside successes is partial", + description: "a failure beside successes fails the run", counts: RunNodeCounts { succeeded: 2, failed: 1, ..RunNodeCounts::default() }, ending: RunEnding::Completed, - expected_status: "partial", + expected_status: "failed", }, RunStatusTestCase { description: "nodes skipped after the only node failed is a failure", @@ -43,7 +43,7 @@ fn given_node_counts_when_finishing_a_run_then_the_status_follows_the_server_rul ..RunNodeCounts::default() }, ending: RunEnding::Completed, - expected_status: "partial", + expected_status: "failed", }, RunStatusTestCase { description: "an interrupt cancels, whatever ran", diff --git a/fensu.toml b/fensu.toml index 8fd49c7291..66a0e8deb3 100644 --- a/fensu.toml +++ b/fensu.toml @@ -499,7 +499,22 @@ reason = "Native code resolves these through the sqlbuild._native_host name tabl [[targets.python.dead_code.roots]] modules = ["sqlbuild.executor.pipeline._helpers.scenario"] -symbols = ["run_scenario_capture_pipeline", "run_scenario_local_test_pipeline", "run_scenario_test_pipeline", "select_scenario_snapshot_capture_candidates"] +symbols = ["decide_scenario_run_on", "run_scenario_capture_pipeline", "run_scenario_local_test_pipeline", "run_scenario_test_pipeline", "select_scenario_snapshot_capture_candidates"] +reason = "Native code resolves these through the sqlbuild._native_host name table." + +[[targets.python.dead_code.roots]] +modules = ["sqlbuild.executor.local.main._decide_sql_test_run_on"] +symbols = ["decide_sql_test_run_on"] +reason = "Native code resolves these through the sqlbuild._native_host name table." + +[[targets.python.dead_code.roots]] +modules = ["sqlbuild.executor.local.main._local_test_adapter"] +symbols = ["local_test_adapter"] +reason = "Native code resolves these through the sqlbuild._native_host name table." + +[[targets.python.dead_code.roots]] +modules = ["sqlbuild.executor.local.main._report_unplaced_sql_tests"] +symbols = ["report_unplaced_sql_tests"] reason = "Native code resolves these through the sqlbuild._native_host name table." [[targets.python.dead_code.roots]] @@ -1376,6 +1391,10 @@ rule = "FFR601" path = "src/sqlbuild/adapters/sqlserver/classes/sqlserver_adapter.py" reason = "The SQL Server adapter intentionally keeps overrideable backend behavior on one class." +[[dupes.allowlist]] +paths = ["crates/sqlbuild-python-compile/src/analysis/main/register_sql_test_comparisons.rs", "crates/sqlbuild-python-compile/src/rules/main/checking/register_project_tree_queries.rs", "crates/sqlbuild-python-compile/src/rules/main/custom/register_custom_rule_evidence.rs", "crates/sqlbuild-python-front/src/contracts/main/register_effective_config.rs", "crates/sqlbuild-python-front/src/discovery/main/failures/register_guidance.rs", "crates/sqlbuild-python-front/src/model_config/main/config/register_config_values.rs", "crates/sqlbuild-python-front/src/state_rows/main/migrations/register_migration_io.rs", "crates/sqlbuild-python-output/src/cost_telemetry/main/register_snowflake.rs", "crates/sqlbuild-python-planner/src/plan_output/main/register_display.rs", "crates/sqlbuild-python-planner/src/planner_resolution/main/references/register_refs.rs", "crates/sqlbuild-python-project/src/fingerprints/main/register_storage_io.rs"] +reason = "Each registers its own module's Python functions; only the add-function calls are alike." + [[dupes.allowlist]] paths = ["crates/sqlbuild-orchestration/src/declarations/main/published_job.rs", "crates/sqlbuild-orchestration/src/scheduler/main/active_job_run.rs"] reason = "Each reads one row by location, target and job key: the published job, decoded with its snapshot named when it no longer decodes, and the run a skip overlap yields to. Only the keyed one-row query shape is alike." @@ -1384,6 +1403,10 @@ reason = "Each reads one row by location, target and job key: the published job, paths = ["crates/sqlbuild-orchestration/src/platform/models.rs", "crates/sqlbuild-orchestration/src/runs/models.rs"] reason = "PlatformEvent::event_type and RunChange::event_type each name their own enum's stored event types, one arm per variant; 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." + [[dupes.allowlist]] paths = ["scripts/native_layering/_helpers/layering.py", "src/sqlbuild/executor/dynamic_pauses/_helpers/scope.py"] reason = "A ten-line depth-first walk in two packages that must not import each other: the dependency-layering tool walks Cargo.lock packages, the build's dynamic-model hold walks plan edges between models." @@ -1734,8 +1757,8 @@ select = [ [[targets.rust.threshold_overrides]] paths = ["crates/sqlbuild-python/Cargo.toml"] -thresholds = { max_crate_code_lines = 51319 } -reason = "The Python bindings crate is above the code-line limit; this caps it near its current size until it is split into crates by area. The location and plan bindings of the large-project server work and #1560 grew it to 51,122; moving them out would need new cross-crate imports or a policy exception. The dbt event stream moved to sqlbuild-python-output, and the location sync's dynamic-model resume came in (50,945). The CHI-1589 stop handling and dev error fields plus the CHI-1595/CHI-1593 env-file merge took it to 51,210 when combined. The CHI-1443 project layout's exported path constants and its event_sinks and extra_paths keys took it to 51,305, CHI-1650's older-table read of the two cost price columns to 51,311, and CHI-1666's build refusal of models that can't be planned to 51,319. The cap stays near its current size; lower it as code moves out." +thresholds = { max_crate_code_lines = 51911 } +reason = "The Python bindings crate is above the code-line limit; this caps it near its current size until it is split into crates by area. The location and plan bindings of the large-project server work and #1560 grew it to 51,122; moving them out would need new cross-crate imports or a policy exception. The dbt event stream moved to sqlbuild-python-output, and the location sync's dynamic-model resume came in (50,945). The CHI-1589 stop handling and dev error fields plus the CHI-1595/CHI-1593 env-file merge took it to 51,210 when combined. The CHI-1443 project layout's exported path constants and its event_sinks and extra_paths keys took it to 51,305, and CHI-1650's older-table read of the two cost price columns to 51,311. CHI-1666's build refusal of models that can't be planned added 8 lines, and CHI-1663's local test placement (local, warehouse and unplaced batches, run-on rows, census and JSON) took it to 51,911. The cap stays near its current size; lower it as code moves out." [[targets.rust.threshold_overrides]] paths = ["crates/sqlbuild-python/src/bindings/_helpers"] @@ -2024,6 +2047,12 @@ path = "crates/sqlbuild-orchestration/src/api/_helpers/resources/plain_http.rs" symbols = ["warn_plain_http"] reason = "Locations, workers and remote publication share this client; it warns once per process on stderr, before any request, when a bearer token would travel over plain HTTP to a non-loopback host." +[[targets.rust.rule_exceptions]] +rule = "FPRSH011" +path = "crates/sqlbuild-orchestration/src/health/main/log_cause.rs" +symbols = ["log_cause"] +reason = "The server log is where operators find a control database failure: the request it failed, the sentence the API returned, and each cause's own message, never a password or stack trace. Requests and the health probe that meet the failure have no caller to return it to beyond the response." + [[targets.rust.rule_exceptions]] rule = "FPRSS130" path = "crates/sqlbuild-orchestration/src/warehouse_history/_helpers/audit_repeats.rs" @@ -2950,7 +2979,7 @@ pending_budgets = [ "crates/sqlbuild-python/src/bindings/_helpers/scenario_command/test_command.rs=13", "crates/sqlbuild-python/src/bindings/_helpers/scopes/scope_command.rs=8", "crates/sqlbuild-python/src/bindings/_helpers/seed_command/command.rs=14", - "crates/sqlbuild-python/src/bindings/_helpers/sql_test_command/test_command.rs=96", + "crates/sqlbuild-python/src/bindings/_helpers/sql_test_command/test_command.rs=115", "crates/sqlbuild-python/src/bindings/_helpers/workspace_commands/commands.rs=5", ] @@ -3208,7 +3237,7 @@ pending_budgets = [ "crates/sqlbuild-python/src/bindings/_helpers/scenario_command/snapshot_sync.rs=1", "crates/sqlbuild-python/src/bindings/_helpers/scenario_command/test_command.rs=4", "crates/sqlbuild-python/src/bindings/_helpers/seed_command/command.rs=5", - "crates/sqlbuild-python/src/bindings/_helpers/sql_test_command/test_command.rs=4", + "crates/sqlbuild-python/src/bindings/_helpers/sql_test_command/test_command.rs=7", ] [targets.rust.rule_options.XSB075] diff --git a/pyproject.toml b/pyproject.toml index d3ca598102..107fd7ac55 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,10 +15,10 @@ dependencies = [ "duckdb>=2.0.0", "filelock>=3.20.3", "orjson>=3.11.7", - "polyglot-sql-chio==0.13.10", "pydantic-settings>=2,<3", "PyYAML>=6.0.2", "sqlbuild-cli==0.261.0", # x-release-please-version + "sqlquack==0.24.1", ] [project.optional-dependencies] diff --git a/python-boundary.toml b/python-boundary.toml index 96f82acf80..d18806aff8 100644 --- a/python-boundary.toml +++ b/python-boundary.toml @@ -572,16 +572,6 @@ path = "compiler/auditing/main/get_audit_factory_definition.py" rule = 3 note = "Reads the declaration attached to a project audit factory." -[[stays]] -path = "compiler/sql_analysis/main/import_polyglot_sql.py" -rule = 4 -note = "Imports the Polyglot SQL Python package for the Python API." - -[[stays]] -path = "compiler/sql_analysis/_helpers/polyglot.py" -rule = 4 -note = "Wraps the Polyglot Python package with complexity guards." - [[stays]] path = "_native_host.py" rule = 1 @@ -802,11 +792,6 @@ path = "compiler/compile/exceptions.py" rule = 2 note = "Shape rule: data exceptions only (MacroDeclarationLookupError, a CompileInputError that is also a KeyError, which a native error class with one parent cannot express), no logic; consumed by compiler/compile/_helpers/render/user_macros.py." -[[stays]] -path = "compiler/sql_analysis/constants.py" -rule = 4 -note = "Rule 4: polyglot_sql glue only; the entry point, call-shape and option names (POLYGLOT_ANALYZE_QUERY_ENTRY_POINT, POLYGLOT_COMPLEXITY_GUARD_OPTION, POLYGLOT_MAX_FUNCTION_CALL_DEPTH, ...) that compiler/sql_analysis/_helpers/polyglot.py uses to wrap the polyglot_sql Python package." - [[stays]] path = "compiler/compile/models.py" rule = 3 diff --git a/scripts/compiler_differential/constants.py b/scripts/compiler_differential/constants.py index 0881a3c23f..1b28c2f522 100644 --- a/scripts/compiler_differential/constants.py +++ b/scripts/compiler_differential/constants.py @@ -695,10 +695,7 @@ def short_model_names(*, model: Model, ctx: RuleContext) -> list[Finding]: "the capture does not record the write-schema check itself" ), } -ANALYSIS_CODE_SCAN_ROOTS: tuple[str, ...] = ( - "compile/_helpers/diagnostics", - "sql_analysis", -) +ANALYSIS_CODE_SCAN_ROOTS: tuple[str, ...] = ("compile/_helpers/diagnostics",) ANALYSIS_NATIVE_CODE_SCAN_ROOTS: tuple[str, ...] = ( "crates/sqlbuild-analysis/src/semantic_checks/constants.rs", "crates/sqlbuild-analysis/src/semantic_checks/_helpers/resource_sql/diagnostics.rs", diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/CONTENTS.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/CONTENTS.md index 5c8ee5e766..973c1a1817 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/CONTENTS.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/CONTENTS.md @@ -142,7 +142,7 @@ Bundled copies of every page on the SQLBuild documentation site, matching the in - [sqb compile](cli/compile.md) (`cli/compile`) - Compile models into resolved SQL, validate contracts, and write target artifacts - fully offline. - [sqb format](cli/format.md) (`cli/format`) - Apply canonical SQLBuild SQL formatting. - [sqb test](cli/test.md) (`cli/test`) - Run SQL unit tests, multi-model tests and the project's Python tests in isolation. -- [sqb scenario](cli/scenario.md) (`cli/scenario`) - Run end-to-end scenario tests against the warehouse or locally with DuckDB. +- [sqb scenario](cli/scenario.md) (`cli/scenario`) - Run end-to-end scenario tests locally with DuckDB or against the warehouse. - [sqb lineage](cli/lineage.md) (`cli/lineage`) - Explore model and column-level dependency graphs from the command line. - [sqb scope](cli/scope.md) (`cli/scope`) - Inspect declaration visibility, usage, placement, and move impact offline. - [sqb rename and sqb mv](cli/rename.md) (`cli/rename`) - Rename or move a model, or rename a column, and update every reference in one verified step. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/audit.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/audit.md index 4192716058..225a79146b 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/audit.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/audit.md @@ -26,6 +26,7 @@ Positional `SELECTOR` arguments work like `--select`, and both forms can be comb | `--select`, `-s` | Select audits attached to specific models | | `--select-file` | Read selectors from a file | | `--exclude` | Exclude audits attached to specific models | +| `--server`, `--location-id`, `--ca-cert` | Read the runs that [`run:`, `failed:` and `skipped:`](../concepts/selectors.md#selecting-from-a-past-run) name from this server's runs of the location, with your [`sqb login`](login.md) session, instead of the local Recall history | | `--concurrency` | Maximum number of audits to run concurrently (default: `1`) | | `--json` | Print structured audit results | | `--json-output` | Write structured audit results to a file | diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/build.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/build.md index cc8cb52570..0a3ffa9421 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/build.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/build.md @@ -86,6 +86,7 @@ own option. `--version` works only directly after `sqb`, as in `sqb --version`: | `SELECTOR ...` | Positional selectors, the same as `--select` | | `--select`, `-s` | Select specific models, or unit tests by name (`test:`); selecting only unit tests runs them without building models | | `--exclude` | Exclude specific models | +| `--server`, `--location-id`, `--ca-cert` | Read the runs that [`run:`, `failed:` and `skipped:`](../concepts/selectors.md#selecting-from-a-past-run) name from this server's runs of the location, with your [`sqb login`](login.md) session, instead of the local Recall history | | `--warehouse ` | Snowflake warehouse for this invocation; overrides the target's `build` [warehouse group](../concepts/adapters/snowflake.md#command-group-warehouses) and the connection warehouse | ## Fast iteration @@ -302,6 +303,12 @@ skipped as for any other failure. Its row shows `TIMEOUT`. In the summary line, failures were timeouts. A timeout is a failure for the exit code: the build exits non-zero and its JSON `status` is `failed`. +A singular audit whose references don't all exist in the target is not run. Its row shows +`NOT RUN`, the summary line counts it under `NOT_RUN=` (shown only when there is one) and in no +other count, and a `Not run` section names what each one reads that is missing. In `--json` +output, `summary.not_run_count` counts them. The build still succeeds; see +[Singular audits](../concepts/audits.md#singular-audits). + ## Limits A target's [`execution_limits`](../concepts/project-configuration.md#execution-limits) cap a whole diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/check.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/check.md index 84a983548d..4c27301062 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/check.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/check.md @@ -23,6 +23,7 @@ Positional `SELECTOR` arguments work like `--select`, and both forms can be comb | `SELECTOR ...` | Positional selectors, the same as `--select` | | `--select`, `-s` | Select checks to run (by name, `check:`, `tag:`, or graph expansion) | | `--exclude` | Exclude checks from the selection | +| `--server`, `--location-id`, `--ca-cert` | Read the runs that [`run:`, `failed:` and `skipped:`](../concepts/selectors.md#selecting-from-a-past-run) name from this server's runs of the location, with your [`sqb login`](login.md) session, instead of the local Recall history | | `--no-sql-analysis` | Disable compile-time SQL analysis (`--no-sql-validation` is an alias) | | `--json` | Print check results as JSON | | `--json-output` | Write check results JSON to a file path | diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/plan.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/plan.md index 430f95aa37..f5aa0e1839 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/plan.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/plan.md @@ -55,6 +55,7 @@ Positional `SELECTOR` arguments work like `--select`, and both forms can be comb | `SELECTOR ...` | Positional selectors, the same as `--select` | | `--select`, `-s` | Select specific models | | `--exclude` | Exclude specific models | +| `--server`, `--location-id`, `--ca-cert` | Read the runs that [`run:`, `failed:` and `skipped:`](../concepts/selectors.md#selecting-from-a-past-run) name from this server's runs of the location, with your [`sqb login`](login.md) session, instead of the local Recall history | | `--warehouse ` | Snowflake warehouse for this invocation; overrides the target's `build` [warehouse group](../concepts/adapters/snowflake.md#command-group-warehouses) and the connection warehouse | ## Output @@ -246,6 +247,27 @@ error[S301]: cannot build selected scope: audit 'relationships' on 'stg_orders' Load or build the resource first (for a seed, `sqb seed`), or add it to the selection. When both kinds are missing, the error lists the missing upstream resources and then the audit reads. +The same applies to a singular audit selected by name, with `audit:` or a past run's failed audits: + +``` +error[S301]: cannot build selected scope: audit 'orders_have_payments' reads 'payments', which is not selected and does not exist in the warehouse; select it or build it first +``` + +A singular audit the plan selects only because the build builds something it references is not +refused. When something it references doesn't exist in the target, the plan lists it as not run, +and the build succeeds without running it; see [Singular audits](../concepts/audits.md#singular-audits): + +``` +Plan ready 1 selected, 1 audit not run +Models (1) +└── orders table +Audits not run (1) +└── orders_have_payments reads payments, which doesn't exist in the target +``` + +`sqb plan --json` lists these audits under `audits_not_run`, each with its `name` and the +`missing` resources it reads. + ## Missing source tables When a selected model reads an external source whose table does not exist in the warehouse, diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/scenario.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/scenario.md index 1818c13c2b..eb1b7bb31e 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/scenario.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/scenario.md @@ -2,7 +2,7 @@ # sqb scenario -> Run end-to-end scenario tests against the warehouse or locally with DuckDB. +> Run end-to-end scenario tests locally with DuckDB or against the warehouse. Online: https://sqlbuild.com/docs/cli/scenario/ @@ -16,7 +16,7 @@ Run end-to-end scenario tests. Scenarios materialize fixture inputs as physical ## sqb scenario test -Run scenario tests against the warehouse. +Run scenario tests locally in DuckDB from captured snapshots, or against the warehouse. ```bash sqb scenario test [flags] @@ -30,12 +30,12 @@ sqb scenario test [flags] | `--exclude` | Exclude scenarios from the selection | | `--retain` | Keep scenario-owned warehouse artifacts for inspection | | `--scenario-namespace NAMESPACE` | Isolate warehouse artifacts for this run; overrides environment and config | -| `--local` | Run locally against DuckDB using captured JSONL snapshots | -| `--strict` | Treat missing/stale local snapshots as errors instead of skips | +| `--run-on auto\|local\|warehouse` | Where scenarios run; overrides the target's and `[settings]` `scenario_run_on` (see [Where scenarios run](#where-scenarios-run)) | +| `--verbose` | Print every reason that keeps a scenario off DuckDB in full, instead of the census | | `--concurrency N` | Run up to `N` scenarios at once (default: the project `concurrency` setting) | -| `--scenario-timeout ` | Time limit for each scenario in this warehouse run, such as `10m`, or `disabled`; overrides `SCENARIO(timeout ...)`, the target and `[settings] scenario_timeout`. Not applied with `--local` | -| `--sync-snapshots` | Capture missing/stale snapshots before local run (requires `--local`) | -| `--refresh` | Recapture all selected snapshots before local run (requires `--local`) | +| `--scenario-timeout ` | Time limit for each scenario run on the warehouse, such as `10m`, or `disabled`; overrides `SCENARIO(timeout ...)`, the target and `[settings] scenario_timeout`. Not applied to local runs | +| `--sync-snapshots` | Capture missing or stale snapshots before the run, so those scenarios can run locally; not with `--run-on warehouse` | +| `--refresh` | Recapture all selected snapshots before the run; not with `--run-on warehouse` | | `--force` | Bypass snapshot capture safety limits | | `--max-snapshot-rows` | Override per-relation row limit for capture | | `--max-snapshot-total-rows` | Override total row limit for capture | @@ -99,45 +99,63 @@ sqb scenario test --select daily_revenue_minimal --retain sqb scenario test --select revenue ``` -### Local examples +### Where scenarios run + +| `--run-on` | Where each scenario runs | +|------|-------------| +| `auto` (default) | Locally when its snapshot is fresh and SQLQuack converts all its SQL; otherwise on the warehouse | +| `local` | Locally. A missing or stale snapshot, or SQL SQLQuack refuses, is an `ERROR`; nothing goes to the warehouse | +| `warehouse` | On the warehouse | + +The setting comes from, in order: `--run-on`, the default target's `scenario_run_on`, +`[settings] scenario_run_on` in `sqlbuild_local.toml`, then in `sqlbuild_project.toml`, then +`auto`. `--retain` keeps warehouse artifacts only, so it is rejected with `--run-on local`. ```bash # Run locally (requires prior capture) -sqb scenario test --local +sqb scenario test --run-on local -# Run locally, capture missing/stale snapshots first -sqb scenario test --local --sync-snapshots +# Capture missing/stale snapshots first, then run locally +sqb scenario test --run-on local --sync-snapshots -# Run locally, recapture everything first -sqb scenario test --local --refresh - -# Fail on missing/stale snapshots instead of skipping -sqb scenario test --local --strict +# Recapture everything first +sqb scenario test --run-on local --refresh ``` ### Output -Remote scenarios report per-scenario PASS/FAIL with nested check rows: +Scenarios report per-scenario PASS/FAIL, where each ran, and nested check rows: ``` -daily_revenue_minimal PASS 0.84s +daily_revenue_minimal PASS warehouse 0.84s expect expected daily_revenue PASS expect assertion no_negative_revenue PASS -PASS=1 FAIL=0 TOTAL=1 (0.91s) -Statements: 9 (CREATE 3, SELECT 3, DROP 2, ALTER 1); compile time not reported by duckdb +PASS=1 FAIL=0 TOTAL=1 (0 local, 1 warehouse, 0.91s) +Statements: 9 on the warehouse (CREATE 3, SELECT 3, DROP 2, ALTER 1); compile time not reported by duckdb ``` Each scenario row shows its wall time and the summary shows the total. `--json` reports the same values as `scenarios[].duration_ms` and `summary.duration_ms`. The `Statements:` line and the JSON `statements` section are described in [Statement summary](test.md#statement-summary). -Local scenarios add ERROR and SKIP statuses: +A scenario that cannot run, such as one without a fresh snapshot under `--run-on local`, is +`ERROR`, and the summary adds an `ERROR=` count: ``` -PASS=2 FAIL=0 ERROR=0 SKIP=1 TOTAL=3 (1.20s) +PASS=2 FAIL=0 ERROR=1 TOTAL=3 (3 local, 0 warehouse, 1.20s) ``` +After the summary, `--run-on local` lists why scenarios could not run locally (`Can't run locally`), +and `auto` counts what sent scenarios to the warehouse (`On the warehouse`), as +[`sqb test`](test.md#local-and-warehouse-runs) does. A snapshot reason reads +`snapshot stale: scenario:` or `snapshot missing: scenario:`. A scenario whose +converted SQL hits a SQLQuack guard or a DuckDB internal error while it replays runs again on the +warehouse in `auto`, with the reason `SQLQuack guard: ` or `DuckDB internal error: `, +and its local attempt prints nothing; with `--run-on local` it is an `ERROR` (`T007`). With `--json`, each +scenario has `run_on` and `run_on_reason`, `summary` has `local_count` and `warehouse_count`, and +the document has `refusals`, as for `sqb test`. + Failed scenarios suggest rerunning with `--retain` for inspection. Local runs always keep the DuckDB file at `target/run/scenarios//local.duckdb`. ## sqb scenario capture diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md index b64c6cde37..60c99ad916 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/server.md @@ -10,12 +10,14 @@ Online: https://sqlbuild.com/docs/cli/server/ - Configure the server - Stop the server +- Check the server's health - Serve over HTTPS - Add people who sign in with passwords - Administer the server with sqb admin - Call the server from scripts with service accounts - Sign in through a reverse proxy - Receive platform events +- See lost lifecycle events - Acknowledge attention items - Back up the control database - Upgrade @@ -104,6 +106,55 @@ process group, so Ctrl+C in the server's terminal reaches only the server. A sec SIGTERM while the workers stop kills their process groups at once; the server still records the runs and releases their claims before it exits. +## Check the server's health + +Each server keeps its own health in memory, so it can answer while its control database can't be +reached: + +| Path | Sign-in | Answers | +| --- | --- | --- | +| `/livez` | None | `200 ok` while the process runs; it checks nothing else | +| `/api/health` | None | Each part's state, since when and a short reason; `200` when every part is healthy, `503` otherwise | +| `/api/health/details` | People who may manage people | Where the control database is, each cause's own message and the IDs of requests that failed | + +The parts are the server (version and uptime), the control database (checked every 10 seconds), +the scheduler on servers that run one, each location, which is degraded once it hasn't +reported for 90 seconds, and each event webhook the server forwards to (see +[Receive platform events](#receive-platform-events)). The report's `status` is `unavailable` while the control database is, +`degraded` while any other part isn't healthy, and `healthy` otherwise. Point a load balancer's +liveness check at `/livez`, and monitoring at `/api/health`. + +When a request fails because of the control database, the error says why instead of a generic +"busy": + +| `cause.case` | Message | +| --- | --- | +| `name_lookup` | Can't reach the control database: `` doesn't resolve (DNS) | +| `unreachable` | Can't reach the control database at `:` | +| `login_rejected` | The control database rejected the login for `` | +| `no_free_connections` | The control database has no free connections | +| `restarting` | The control database is restarting | +| `pool_exhausted` | All 10 control database connections were busy for 30 s | +| `locked` | The control database is locked by another process | +| `other` | Control database error: `` | + +The response body carries `error` (the message), `cause` with `case` and `since`, and +`request_id`, which every response also sends as `x-request-id`. The server log has each failure +with its request ID and every cause's own message, never the password. Any other unknown path +under `/api/` is a JSON `404`, never the UI's page. + +`sqb server` listens before it opens its control database. While the database can't be reached, +for example because its host doesn't resolve, the server answers `/livez`, `/api/health` and the +UI, refuses other API requests with `503` and the cause, and tries again with a wait that doubles +up to 30 seconds. It then starts the full API on the same address without a restart. A failure that +retrying can't fix, such as a rejected login or a schema it can't migrate, stops the server. + +The UI reads the same health. The top bar says **Live**, **Degraded** or **Unavailable**, and +links to **Status**, which shows every part without signing in. While the control database is +unavailable, every page keeps its address and says it isn't available, with the reason, since +when and the parts, and loads by itself when the database is back. While a part is degraded, pages +work and a banner names it. + ## Serve over HTTPS Code locations and workers send their bearer token with every request to the `--server` URL. @@ -338,16 +389,30 @@ receive the URL. "job_key": "daily_orders", "location_id": "01a1d38b-e214-7151-8c8e-8606917c3ee6", "target": "production", - "outcome": "partial", + "outcome": "failed", + "url": "https://sqlbuild.example.com/runs/01a1d3b9-2c4e-7f10-8a3b-1d2e3f4a5b6c", + "trigger": { "kind": "schedule", "name": "daily_orders", "person": null }, + "started_at": "2026-11-13T06:52:51.204Z", + "ended_at": "2026-11-13T07:12:04.112Z", + "duration_ms": 1152908, + "error": null, "failed_nodes": [ { "node_key": "model:fct_orders", "error_code": "E100", "message": "Conversion Error: Could not convert string 'n/a' to INT32", - "path": "sql/models/marts/fct_orders.sql" + "path": "sql/models/marts/fct_orders.sql", + "phase": "post_hook", + "url": "https://sqlbuild.example.com/runs/01a1d3b9-2c4e-7f10-8a3b-1d2e3f4a5b6c?node=model%3Afct_orders", + "logs_url": "https://sqlbuild.example.com/runs/01a1d3b9-2c4e-7f10-8a3b-1d2e3f4a5b6c/output/model%3Afct_orders" } ], - "failed_node_count": 1 + "failed_node_count": 1, + "failed_audits": [], + "failed_audit_count": 0, + "succeeded_node_count": 194, + "skipped_nodes": ["model:fct_order_margin", "model:order_summary"], + "skipped_node_count": 2 } } } @@ -357,6 +422,13 @@ Delivery is at least once and in order. A response other than `2xx`, or no respo seconds, stops delivery and retries the same event. Deduplicate by `event_id`, which the `Idempotency-Key` header repeats. +While the webhook fails, **Platform event forwarding** is degraded in the server's health, with +since when and why, such as `the webhook answered HTTP 503` or `can't connect to the webhook`, and +it is an item on every Overview's attention list. Events are kept and retried every 5 seconds, and +the item clears with the first delivery. The security audit webhook +(`SQLBUILD_SECURITY_AUDIT_WEBHOOK_URL`) is reported the same way, as **Security audit event +forwarding**. + | `kind` | Sent when | Fields | | --- | --- | --- | | `heartbeat` | Each server replica is alive, periodically | `replica_id`, `store_bytes` (the control database size on disk) | @@ -366,7 +438,7 @@ seconds, stops delivery and retries the same event. Deduplicate by `event_id`, w | `location_broken` | Every instance of a location and target has stopped reporting for over 90 seconds | `location_id`, `target`, `last_seen_at` | | `location_failing` | A location and target that checks in failed its latest load (`falling_back`), its plan of what changed (`change_plan_failed`), a discover function (`discovery_failed`) or the connection check after its last load (`degraded`) | `location_id`, `target`, `state`, `failed_at`, `error`, `serving_generation` (the generation runs use instead) | | `launch_failed` | Starting a worker failed; it may still start | `run_id`, `claim_id`, `code` | -| `run_failed` | A job, group or ad-hoc run ends `failed` or `partial` | `run_id`, `run_kind`, `job_key`, `location_id`, `target`, `outcome`, `failed_nodes`, `failed_node_count` | +| `run_failed` | A job, group or ad-hoc run ends `failed` | See [Fields of `run_failed`](#fields-of-run_failed) | | `trigger_skipped` | The scheduler skips a trigger whose stored job or snapshot can't be read, or a sensor whose check failed; the sensor is checked again a minute later | `trigger_id`, `snapshot_id`, `reason` | | `sensor_rechecked` | A sensor's last check can't be read, so it is checked again from scratch | `trigger_id`, `snapshot_id`, `evaluation_id` | | `calendar_times_dropped` | A publish drops a calendar schedule's due times | `trigger_id`, `snapshot_id`, `times` | @@ -380,12 +452,51 @@ completed check in that snapshot: a later attempt that fails differently sends n doesn't replace it. Everyone who can view the target sees the reason, and it can quote stored values. -`run_failed` lists at most 20 failed nodes, ordered by node key; `failed_node_count` is the full -number. A `partial` run is included because some of its nodes failed. `job_key` is `null` for -ad-hoc runs. Each `message` is the node's error text with credentials redacted, cut to 2,000 -characters, and `null` when the worker reported none. It can quote warehouse data, so treat the -webhook like other run evidence. `run_failed` events appear only in the webhook, not in the -server's platform history. +### Fields of `run_failed` + +`run_failed` carries what an alert needs to say what failed, where, and to link to it: + +| Field | Meaning | +| --- | --- | +| `run_id`, `run_kind`, `job_key`, `location_id`, `target` | The run, its kind (`job`, `group`, `adhoc`), its job (`null` for ad-hoc runs), and where it ran | +| `outcome` | `failed` | +| `url` | The run's page in the UI | +| `trigger` | What started the run: `kind` is `schedule`, `sensor`, `manual` (a person) or `api` (a service account); `name` is the schedule's or sensor's name; `person` is who asked for a manual or API run | +| `started_at`, `ended_at`, `duration_ms` | When the run's worker started and the run ended; `null` for a run that never started | +| `error` | Why the run failed when no node or audit says, such as a project that can't load: `phase` (`launch`, `worker_start`, `load`, `planning` or `build`), `code` (the error's type) and `message`; `null` when `failed_nodes` or `failed_audits` say why | +| `failed_nodes` | The first 20 failed nodes, ordered by key, each with `node_key`, `error_code`, `message`, `path` (the node's file), `phase` (where a model failed: `pre_hook`, `staging`, `contract`, `audit`, `post_hook` and so on; `null` for other nodes), `url` (the node on the run's page) and `logs_url` (its output) | +| `failed_node_count` | Every failed node | +| `failed_audits` | The first 20 error-severity audit failures the run didn't let through, ordered by name, each with `name`, `node_key` (`null` for an end-of-build singular audit), `sqlstate` and `message` (the warehouse's error when the audit's query couldn't run) and `failing_rows` (when it ran) | +| `failed_audit_count` | Every such audit failure | +| `succeeded_node_count`, `skipped_node_count` | How many nodes built and how many were skipped | +| `skipped_nodes` | The first 20 skipped nodes, ordered by key | + +The links (`url`, and each failed node's `url` and `logs_url`) are `null` when the server has no +sign-in origin, such as `[server] password_origin`. `job_key` is `null` for ad-hoc runs. Each +`message` is the error text with credentials redacted, cut to 2,000 characters, and `null` when the +worker reported none. It can quote warehouse data, so treat the webhook like other run evidence. +`run_failed` events appear in the webhook and to +[`platform_event` sensors](../concepts/orchestration.md#react-with-a-sensor), not in the server's +platform history. + +## See lost lifecycle events + +A worker counts what each of the project's lifecycle event sinks delivered when its run's command +closes, and reports it with the run. A location's own interpreters, which compile, read run history +and evaluate sensors, run the same sinks: once a minute, each idle one says what its sinks +delivered, and the location reports what changed since the last report. + +A sink that dropped or failed events in the newest run or location report of a location and target +is an item on that target's attention list, such as `event sink kafka losing events since 17:42: +116 of 116 events not delivered (116 failed)`, from its first lossy run or report in a row. A sink +provider whose teardown raised at the end of a run is listed as `sink providers`, because events it +still held may not have been delivered. The item clears once a run, or a minute in which the sink +took events, delivers every event. Reports from the last 7 days count. + +SQLBuild counts what a sink function does: an event it raised on is failed, and one it never got +is dropped. A sink that hands events to a client which sends them later, such as a Kafka producer, +reports a send that fails afterwards only if it raises, from a later call or when its provider +closes. ## Acknowledge attention items @@ -816,11 +927,17 @@ Details: - On Snowflake, a sync skips state tables that haven't changed since the last sync, the pause table included, so a sync with nothing new doesn't resume the warehouse. - When a read fails, the Connections page shows the warehouse error. A read that ran out of memory - or time retries a smaller page. Any other error, such as a missing permission or table, retries - after 30 seconds, then waits twice as long after each failure in a row. After 5 failures in a row - the sync stops until a run ends, you request one, the location publishes again, or the next safety - sync is due (`sync_at_least_every`). It then starts again from the first kind of history, and - failed reads back off again before they stop it. + or time retries a smaller page. A read that never reached the warehouse, such as a host that + doesn't resolve, a refused connection or Snowflake's `250001 Could not connect`, spent no + compute: it retries after 30 seconds, then every 60 seconds, and never stops the sync. Any other + error, such as a missing permission or table, retries after 30 seconds, then every 60 seconds. + After 5 such failures in a row the sync stops until a run ends, you request one (**Resume** on + the Overview's attention item), the location publishes again, or the next safety sync is due + (`sync_at_least_every`). It then starts again from the first kind of history. +- A request to the server that fails, for example while its control database is unreachable, + keeps the page and retries it every 30 seconds; it never stops the sync. After a failing streak, + the location logs `Run history sync recovered after N min; M pages caught up.` once the sync + completes. - `[control]` holds no secrets. The session stays in the login `sqb login` saved for that server. - When a state table holds two rows with the same ID, such as one check result written twice, the server keeps the row with the earlier time. Estimated query costs are the exception: when two @@ -862,13 +979,15 @@ Warehouse history synchronization completed: 14 kinds, 31,204 rows in 12.8 s. A page holds up to 2,000 rows and ends early at 8 MiB, so wide rows make smaller pages. A failed read prints which kind failed, the page size and why, then what the location does next. A read that -ran out of time or memory retries a smaller page; any other failure retries the same page after a -wait that doubles each time, and the fifth in a row stops the sync: +ran out of time or memory retries a smaller page; any other failure retries the same page after 30 +seconds, then every 60 seconds. One that never reached the warehouse never stops the sync; the +fifth other failure in a row does: ```text Warehouse history read failed for statistics (100-relation page): no reply within 130 s. Sync incomplete; retaining mirror and retrying a smaller page in 30 s. Warehouse history read failed for catalog (2000-row page): permission denied for table _sqlbuild_catalog. Sync incomplete; retaining mirror and retrying in 60 s. Warehouse history read failed for catalog (2000-row page): permission denied for table _sqlbuild_catalog. Synchronization stopped after 5 failed reads in a row; it resumes after the next run, on request or after a publish. +Warehouse history read failed for catalog (2000-row page): 250001 Could not connect to Snowflake backend after 2 attempt(s). Run history can't reach the warehouse; no compute ran. Retrying in 60 s; this never stops the sync. ``` | Cause | Printed as | @@ -889,6 +1008,12 @@ The location's page shows a failing sync as **failing** with when it last synced each failing kind with the cause, the page size and the warehouse's message, shortened and with secrets removed. The Connections page shows a stopped sync as **stopped after failed reads**. +While the sync fails, the top bar says what stands, since when, how it retries and why, for example +`Run history can't reach the warehouse since 17:42 · retrying every 60 s · 250001 Could not +connect…`, and links to the location's page; its tooltip has the last success and the next +attempt. The Overview lists it as needing attention with the same reason, and drops it once a sync +report succeeds. A sync that failed reads stopped has a **Resume** action there. + ## Skip overlapping runs and retry failures Declare who owns a job, whether scheduled requests wait for a running copy, and how often a failed @@ -912,7 +1037,7 @@ delay_seconds = 600 | --- | --- | --- | --- | | `owner` | Any non-blank text | None | Shown on the job's page and in the job list | | `overlap` | `queue` or `skip` | `queue` | With `skip`, a schedule tick or sensor request that arrives while a run of the job is queued or running starts no run | -| `retry` | `attempts` from 2 to 11, `delay_seconds` from 0 to 86400 | None | A failed or partial run nobody cancelled reruns its failed, cancelled and skipped nodes, and those it never reached, after the delay, until it succeeds or has run `attempts` times in all | +| `retry` | `attempts` from 2 to 11, `delay_seconds` from 0 to 86400 | None | A failed run nobody cancelled reruns its failed, cancelled and skipped nodes, and those it never reached, after the delay, until it succeeds or has run `attempts` times in all | A skipped tick shows as **skipped** in the trigger's tick log, with the run it yielded to, and creates no run. A sensor tick lists the requests it skipped the same way. @@ -933,7 +1058,7 @@ Details: - A member job's `[retry]` also applies inside a group run. When the member fails, the group runs it again after `delay_seconds`, inside the same group run, and the jobs that depend on it wait instead of skipping. The group keeps its pool slots meanwhile. -- A group's own `[retry]` is a final sweep: after the group run ends `failed` or `partial`, it +- A group's own `[retry]` is a final sweep: after the group run ends `failed`, it queues one new linked rerun of the group's failed, cancelled and skipped nodes, and those it never reached. - So a retry of a whole run, a job's or a group's, is a new linked run, and a retry of a member stays inside its group run. @@ -1069,8 +1194,19 @@ runs. A `build` loads the managed sources its models read, as `sqb build` does, alone; `--no-load` turns that off. A `test` or `audit` run reports each selected node with the worst result of its tests or audits. -Selectors use the CLI grammar: names, `seed:`, `source:`, `tag:`, `path:`, `test:` and `job:`, -with `+` for upstream or downstream nodes. Positional selectors work as on the command line. +Selectors use the CLI grammar: names, `seed:`, `source:`, `tag:`, `path:`, `test:`, `job:` and +`audit:`, with `+` for upstream or downstream nodes. Positional selectors work as on the command line. +[`run:`, `failed:` and `skipped:`](../concepts/selectors.md#selecting-from-a-past-run) select from +a run of the same location and target, by full ID or a unique prefix of at least 8 characters. The +server resolves them when the run is requested and freezes the nodes and audits they select with +it, so later runs don't change what it runs. + +In the web UI, Rerun on a run opens the rerun plan on `failed:+`; rerunning the whole run opens +on `run:`, and one node or audit on its own name or `audit:`. The box holds the whole +selection: its suggestions only rewrite the text, and Run starts the ad-hoc run +`sqb build -s ` shown beside it, against the current publication. The run it starts shows +`from run ` for each past run its selection names. Reruns of several runs at once, and retries, +still repeat each run's own frozen version and settings. A `build` whose selection names a job takes the job's settings, exactly as `sqb build` and the job's own runs do; see diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/test.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/test.md index 0bcf57ad9d..6651f6202f 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/test.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/cli/test.md @@ -10,6 +10,7 @@ Online: https://sqlbuild.com/docs/cli/test/ - Usage - Flags +- Local and warehouse runs - Statement summary - Python tests - Run only affected tests @@ -35,8 +36,11 @@ Positional `SELECTOR` arguments work like `--select`, and both forms can be comb | `SELECTOR ...` | Positional selectors, the same as `--select` | | `--select`, `-s` | Select tests by name (`order_status_rules` or `test:order_status_rules`), or the tests targeting specific models | | `--exclude` | Exclude tests by name, or the tests targeting specific models | +| `--server`, `--location-id`, `--ca-cert` | Read the runs that [`run:`, `failed:` and `skipped:`](../concepts/selectors.md#selecting-from-a-past-run) name from this server's runs of the location, with your [`sqb login`](login.md) session, instead of the local Recall history | | `--warehouse ` | Snowflake warehouse for this invocation; overrides the target's `query` [warehouse group](../concepts/adapters/snowflake.md#command-group-warehouses) and the connection warehouse | | `--test-timeout ` | Time limit for each test in this run, such as `30s` or `2m`, or `disabled`; overrides `TEST(timeout ...)`, the target and `[settings] test_timeout` | +| `--run-on auto\|local\|warehouse` | Where unit tests run; overrides the target's and `[settings]` `test_run_on`. See [Local and warehouse runs](#local-and-warehouse-runs) | +| `--verbose` | Print every refusal that keeps a test off DuckDB in full, instead of the census | | `--since ` | Run only the tests affected by changes since the merge base of `` and `HEAD` (see [Run only affected tests](#run-only-affected-tests)); `@base` reads `[git] base_ref` | | `--explain` | With `--since`, print why each selected test was selected | | `--sql` | Run only SQL tests | @@ -65,13 +69,59 @@ counted under `TIMEOUT=` and excluded from `FAIL=` in the summary line output, `summary.fail_count` still includes timed-out tests, and `summary.timeout_count` reports how many of them timed out. A timeout still fails the run: `sqb test` exits non-zero. +## Local and warehouse runs + +Each SQL test runs locally in DuckDB or on the warehouse, decided per test at compile time; see +[Running tests locally](../concepts/testing-reference.md#running-tests-locally). Each row names +where its test ran, and the summary splits the total: + +``` +fact_orders + test test_fact_orders PASS warehouse 1 real model 0.84s +PASS=4 FAIL=0 TOTAL=4 (3 local, 1 warehouse) +Statements: 5 on the warehouse (CREATE 2, DROP 2, WITH 1); compile 0.4s, execution 0.1s +``` + +A test that does not run is an `ERROR` row with a short reason: `can't run locally` (`T007`, with +`--run-on local`) or `needs the warehouse (no connection)` (`T008`, in `auto`). A local test whose +converted SQL hits a SQLQuack guard or a DuckDB internal error while it runs is also `T007` with +`--run-on local`; in `auto` it runs again on the warehouse. + +After the summary: + +- With `--run-on local`, `Can't run locally (N tests)` lists SQLQuack's diagnostics: code, + message, the model or test file position, the source line with a caret and label, notes and + help, and `= tests:` with every test the refusal blocks. A refusal in a model's SQL points at + the model file; one in a fixture or expected rows at the test file; one inside a macro expansion + at the call site, with the generated SQL as the source line; one in SQL SQLBuild generates at the + compiled test under `target/run/tests/`. +- In `auto`, `On the warehouse (N tests)` counts the tests each refusal sends to the warehouse, + most tests first: + +``` +On the warehouse (4 tests) + a known difference that isn't allowed: fn:HASH 3 tests + missing rule: node:method_call 1 test +``` + +`--verbose` and `--inspect` print the full diagnostics instead, as notes (`note[SQ0003]`), since these +tests still run; under `--run-on local` they are errors. + +With `--json`, each check has `run_on` (`local` or `warehouse`) and `run_on_reason` (the first +refusal's `: `, or `null`), `summary` has `local_count` and +`warehouse_count`, and the document has `refusals`: each refusal once per construct and place, +with SQLQuack's `code`, `category`, `construct`, `reason`, `message`, `label`, `notes` and +`help`, its `path`, `line` and `column`, its `title` (`: `), and `tests`, +the tests it blocks. + ## Statement summary After the pass/fail summary, `sqb test` and `sqb scenario test` print how many warehouse statements -the SQL tests or scenarios sent, by leading keyword, and how long the warehouse spent compiling and executing them: +the SQL tests or scenarios sent, by leading keyword, and how long the warehouse spent compiling and executing them. +Statements of tests and scenarios that ran locally are not counted: ``` -Statements: 12 (SELECT 7, CREATE 2, DROP 2, ALTER 1); compile 1.5s, execution 0.3s +Statements: 12 on the warehouse (SELECT 7, CREATE 2, DROP 2, ALTER 1); compile 1.5s, execution 0.3s ``` With `--json`, the document gains a `statements` section with `total`, `by_kind` and diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/adapters/sqlite.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/adapters/sqlite.md index 4747f831bb..dc3d28f143 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/adapters/sqlite.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/adapters/sqlite.md @@ -108,7 +108,7 @@ SQLite stores values by type affinity, so SQLBuild keeps column types explicitly | Snapshots (timestamp, check, historical) | Supported | | Schema changes | Add, drop and rename columns in place; type changes rebuild the table and its indexes in one transaction | | `sqb diff`, `sqb clone` | Supported; clones are physical copies | -| Scenarios, `sqb scenario capture`, `--local` replay | Supported; see below | +| Scenarios, `sqb scenario capture` | Supported on SQLite; see below | | Statement time limits | Connection interrupt | | `sqb load`: Python loaders | Supported | @@ -118,9 +118,9 @@ Scenario fixtures and models are tables in the same file, named `____sqb_____`, and are dropped when the scenario finishes unless you pass `--retain`. Concurrent scenarios queue for the file's single writer. -`sqb scenario test --local` transpiles SQLite SQL to DuckDB. Date functions with modifiers, such -as `datetime(ordered_at, 'start of day')`, have no DuckDB translation and fail locally; use -`date(...)` or `strftime(...)` in models you want to replay locally. +Scenarios run on the SQLite file. Local replay converts Snowflake SQL only, so with +`--run-on auto` SQLite scenarios run on SQLite (reason `dialect: sqlite`), and `--run-on local` +refuses them. ## Limits diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/audits.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/audits.md index 6f09161236..59ba42ecd8 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/audits.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/audits.md @@ -369,9 +369,27 @@ singular audit must live under the nearest folder containing everything it refer directly under `sql/audits/` or in any other `sql/audits/` child are compile errors. SQLBuild infers where a singular audit runs from its references. When one referenced model is -downstream of every other referenced model, the audit attaches to that model. Otherwise it runs at -the end of the build, after the resources it references are published. Only singular audits run at -the end of the build; attached audits always gate their target. +downstream of every other referenced model and the build builds it, the audit attaches to that +model. Otherwise it runs at the end of the build, after the resources it references are published. +Only singular audits run at the end of the build; attached audits always gate their target. + +A build selects a singular audit when it builds anything the audit references. The audit runs when +everything it references exists: built in this run, or already in the target. When something it +references doesn't exist in the target, the audit is not run. That is neither a pass nor a failure, +and the build still succeeds. The plan lists the audit under `Audits not run` with what is +missing, the build shows it as `NOT RUN` and counts it under `NOT_RUN=`, and the run page shows it +as not run with the same reason: + +``` +✓ Completed successfully PASS=1 WARN=0 FAIL=0 INSUFFICIENT=0 SKIP=0 NOT_RUN=1 TOTAL=2 (0.35s) + +Not run (1): + orders_have_payments (audit) reads payments, which doesn't exist in the target +``` + +Selecting the audit itself, with `audit:orders_have_payments` or a past run's failed audits, fails +planning with `S301` instead, naming what it reads that doesn't exist; see +[Missing upstream dependencies](../cli/plan.md#missing-upstream-dependencies). ## Source audits diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/orchestration.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/orchestration.md index 93416dde7b..6bda6c2d77 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/orchestration.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/orchestration.md @@ -294,7 +294,7 @@ Pass `name="..."` to choose another name, which must also end in `_sensor`. | Not set | Every `minimum_interval_seconds`: a polling sensor | `kinds` take the enums `RunEventKind`, `NodeEventKind`, `CheckEventKind` and `PlatformEventKind` -from `sqlbuild.orchestration`. `RunEventKind` has `SUCCESS`, `WARN`, `PARTIAL`, `FAILED`, +from `sqlbuild.orchestration`. `RunEventKind` has `SUCCESS`, `WARN`, `FAILED` (a node failed, was skipped or never ran), `CANCELLED`, `SKIPPED` (a member its group did not run) and `COMPLETED` for any of them. `CheckEventKind` has `FAILED` and `WARN`. `check_event` covers checks inside job runs and manual builds, such as one started from the Plan page, where the event's `job` is `None`. It doesn't @@ -314,6 +314,41 @@ cover standalone `sqb test` or `sqb audit` runs, or `sqb scenario test`. | `platform_event` | `PlatformEvent` | `id`, `occurred_at`, `event`, `details` | | Not set | `None` | None; keep your place between polls in `ctx.cursor` | +A `platform_event` sensor for `PlatformEventKind.RUN_FAILED` gets every field of the server's +[`run_failed` event](../cli/server.md#fields-of-run_failed) in `ctx.event.details`, enough to build +an alert for any failed run. SQLBuild ships no chat integration; this sensor builds a message for a +`team_chat` provider the project defines: + +```python +# orchestration/sensors/platform/failed_run_alert_sensor.py +from sqlbuild.orchestration import PlatformEvent, PlatformEventKind, SensorContext, platform_event, sensor + +@sensor( + description="Post every failed run to the team channel", + when=platform_event(kinds=[PlatformEventKind.RUN_FAILED]), +) +def failed_run_alert_sensor(ctx: SensorContext[PlatformEvent], team_chat): + run = ctx.event.details + minutes, seconds = divmod((run["duration_ms"] or 0) // 1000, 60) + lines = [ + f"{run['job_key'] or 'Ad-hoc run'} failed in {run['target']}", + f"{run['succeeded_node_count']} built, {run['failed_node_count']} failed, " + f"{run['skipped_node_count']} skipped · {minutes}m {seconds}s", + ] + for node in run["failed_nodes"][:3]: + where = f" in {node['phase']}" if node["phase"] else "" + lines.append(f"• {node['node_key']} failed{where}: {node['message'] or node['error_code']}") + for audit in run["failed_audits"][:3]: + lines.append(f"• audit {audit['name']} failed: {audit['message'] or audit['failing_rows']}") + if run["error"]: + lines.append(f"• failed in {run['error']['phase']}: {run['error']['message']}") + if run["skipped_nodes"]: + lines.append("Skipped: " + ", ".join(run["skipped_nodes"][:5])) + if run["url"]: + lines.append(run["url"]) + team_chat.post("\n".join(lines)) +``` + `ctx.cursor` is for polling sensors only. A sensor with a `when` condition always sees `None`, and a value it assigns is ignored: the server keeps its place in the events. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/project-configuration.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/project-configuration.md index b1c5c7cf2d..c4f4be58fe 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/project-configuration.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/project-configuration.md @@ -134,8 +134,8 @@ schema = "dev" # uses connections.local, the only named connection A command that needs the warehouse, such as `build`, `plan`, `query`, `diff`, or `debug`, fails with `D001` before connecting when no connection is configured. Commands and modes that don't -connect, such as `compile`, `format`, `lineage`, `scope`, `rename`, `mv`, `test --inspect`, and -`scenario test --local`, keep working without one. +connect, such as `compile`, `format`, `lineage`, `scope`, `rename`, `mv`, `test --inspect`, +`test --run-on local` and `scenario test --run-on local`, keep working without one. SQLBuild never falls back to an implicit in-memory DuckDB database; to use one, set it explicitly: @@ -190,6 +190,8 @@ A target is a named build context - the database and schema you build into, plus | `missing_migration_origin` | What a build does when a declared `migrate_from` origin does not exist in this target: `allow` (default), `require_confirmation`, or `deny`. See [Missing migration origins](models/migrations.md#missing-migration-origins) | | `warehouses` | Snowflake warehouse per command group: `build`, `query` and `sync` (a location's warehouse syncs). See [Command-group warehouses](adapters/snowflake.md#command-group-warehouses) | | `concurrency` | Worker limit for commands run against this target, replacing `[settings] concurrency` (see below) | +| `test_run_on` | Where `sqb test` runs unit tests on this target: `auto`, `local` or `warehouse`; replaces `[settings] test_run_on` | +| `scenario_run_on` | Where `sqb scenario test` runs scenarios on this target: `auto`, `local` or `warehouse`; replaces `[settings] scenario_run_on` | | `ignore_audit_failures` | Whether builds on this target let audit failures through, replacing `[settings] ignore_audit_failures`; see [Ignoring audit failures](audits.md#ignoring-audit-failures) | | `plan_from` | Where `sqb plan` and `sqb build` read warehouse state: `live` (default) or `synced_state`; see [Planning from synced state](#planning-from-synced-state) | | `pause_dynamic` | `true` keeps this target's [dynamic models](models/dynamic.md) suspended between builds; each build refreshes the ones it selects. Default `false` | @@ -619,6 +621,8 @@ default_audit_run_scope = "delta_and_final" unit_test_max_real_models = 10 test_timeout = "30s" scenario_timeout = "15m" +test_run_on = "auto" +scenario_run_on = "auto" delta_compile = true ``` @@ -637,6 +641,8 @@ delta_compile = true | `unit_test_max_real_models` | `10` | Most real (unmocked) models one SQL unit test may execute; a larger test fails compilation. See [Unit test and scenario limits](#unit-test-and-scenario-limits). | | `test_timeout` | `30s` | Time limit for each SQL unit test, or `"disabled"` | | `scenario_timeout` | none | Time limit for each scenario, or `"disabled"` | +| `test_run_on` | `auto` | Where `sqb test` runs unit tests: `auto` (locally in DuckDB when SQLQuack converts a test, otherwise on the warehouse), `local` or `warehouse`. See [Running tests locally](testing-reference.md#running-tests-locally) | +| `scenario_run_on` | `auto` | Where `sqb scenario test` runs scenarios: `auto` (locally with a fresh snapshot whose SQL converts, otherwise on the warehouse), `local` or `warehouse`. See [Local scenario testing](scenarios.md#local-scenario-testing) | | `delta_compile` | `true` | After an edit to model SQL or SQL test files only, compile just the changed files against the previous compile. See [Compiling after an edit](../cli/compile.md#compiling-after-an-edit). | | `allow_missing_secrets` | `false` | Let `compile`, `rules run`, `format`, `dag`, `lineage` and `scope` run without any provider's secrets on this machine. `sqlbuild_local.toml` only; a target lists the providers it expects to miss in [`[targets.] allow_missing_secrets`](#allowed-missing-secrets). See [Secrets](python-nodes/providers.md#allowing-missing-secrets). | | `allow_warehouse_round_trips` | `false` | Allow a loader to depend on an asset that reads SQL, so data can leave the warehouse and come back through a source. Project file only. See [The SQL boundary](python-nodes/overview.md#warehouse-round-trips). | diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/scenarios.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/scenarios.md index 720a178609..d651f7886a 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/scenarios.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/scenarios.md @@ -215,7 +215,7 @@ fixtures still isolate every scenario. On Ctrl-C, SQLBuild prints one notice, cancels scenarios that have not started, cancels the statements running scenarios have in flight, drops their relations (unless `--retain`), and only then exits. A second Ctrl-C skips that cleanup and exits immediately; the next run of the same -scenarios drops whatever they left behind. `--local` replay and `sqb scenario capture` run one +scenarios drops whatever they left behind. Local replay and `sqb scenario capture` run one scenario at a time. ### Parallel CI runs @@ -326,15 +326,20 @@ When a limit is exceeded, capture fails with a clear error and suggests narrowin Run scenarios locally against DuckDB: ```bash -sqb scenario test --local +sqb scenario test --run-on local ``` -This: +By default (`auto`), a scenario replays locally when its snapshot is fresh and SQLQuack converts +all of its SQL, and runs on the warehouse otherwise. With `--run-on local`, every scenario replays +locally, and one that cannot is an `ERROR`. Set the default with `[settings] scenario_run_on` or +a target's `scenario_run_on`; see [`sqb scenario test`](../cli/scenario.md#where-scenarios-run). + +Local replay: -1. Checks snapshot freshness via the input fingerprint (missing/stale snapshots are skipped by default) +1. Checks snapshot freshness via the input fingerprint; a missing or stale snapshot keeps the scenario off DuckDB 2. Creates a temporary DuckDB database at `target/run/scenarios//local.duckdb` 3. Loads JSONL snapshots into typed DuckDB tables using column metadata from `scenario.json` -4. Transpiles model and check SQL from the project adapter dialect to DuckDB; SQL captured from a DuckDB project runs as authored +4. Converts function, model and check SQL from Snowflake to DuckDB with [SQLQuack](https://github.com/sqlstack-io/sqlquack), in a UTC session, reading the snapshot columns' captured types and models' declared column types; SQL captured from a DuckDB project runs as authored, and other adapters' scenarios run on the warehouse 5. Builds functions, models, and runs expected/assertion checks in DuckDB 6. Keeps the local DuckDB file for inspection (it lives under `target/`, so it's always retained) @@ -344,22 +349,14 @@ Instead of running capture and test separately, sync snapshots in one command: ```bash # Capture missing/stale snapshots, then run locally -sqb scenario test --local --sync-snapshots +sqb scenario test --sync-snapshots # Recapture all snapshots, then run locally -sqb scenario test --local --refresh +sqb scenario test --refresh ``` With `--sync-snapshots`, fresh snapshots are reused. With `--refresh`, all selected snapshots are recaptured even if fresh. -### Strict mode - -By default, missing or stale snapshots are skipped with a warning. Use `--strict` to treat them as errors: - -```bash -sqb scenario test --local --strict -``` - ### Local type overrides When the automatic warehouse-to-DuckDB type conversion produces an incompatible type, you can override it in `sqlbuild_project.toml`: @@ -397,5 +394,5 @@ See the [CLI reference](../cli/scenario.md) for full command documentation. order, whitespace and number spelling do not matter, so a Snowflake capture's pretty-printed JSON equals an expected `PARSE_JSON(...)`. Values of non-JSON types with the same JSON text also compare equal, for example `DATE '2024-01-01'::VARIANT` and `'2024-01-01'::VARIANT`. -- Local replay transpiles SQL from the project adapter dialect to DuckDB. Adapter-specific SQL that cannot be translated will produce a clear error with the failing resource name and reason. -- Outside local replay, scenario fixture, expected and assertion SQL runs as authored: SQLBuild replaces `__ref`, `__source`, `__seed` and `__dbt_ref` calls with relation names and may wrap a partial fixture to add its missing columns, but never regenerates the query. Calls inside comments and quoted text are left unchanged. Quoted text and comments follow the project adapter's rules, including with `--local`: backslash escapes on Snowflake, BigQuery and Databricks, `E'...'` strings on DuckDB and Postgres, nested block comments on DuckDB, Postgres, Databricks and SQL Server, `#` line comments on BigQuery, and `//` line comments on Snowflake. A call naming a relation the scenario does not provide, or SQL with an unclosed string or comment, fails planning with `S511` naming the scenario file. +- Local replay runs only SQL SQLQuack converts. A model read by another model needs fully typed declared columns, or SQLQuack refuses the reading SQL (`unresolved name`) and the scenario runs on the warehouse. +- Outside local replay, scenario fixture, expected and assertion SQL runs as authored: SQLBuild replaces `__ref`, `__source`, `__seed` and `__dbt_ref` calls with relation names and may wrap a partial fixture to add its missing columns, but never regenerates the query. Calls inside comments and quoted text are left unchanged. Quoted text and comments follow the project adapter's rules, including in local replay: backslash escapes on Snowflake, BigQuery and Databricks, `E'...'` strings on DuckDB and Postgres, nested block comments on DuckDB, Postgres, Databricks and SQL Server, `#` line comments on BigQuery, and `//` line comments on Snowflake. A call naming a relation the scenario does not provide, or SQL with an unclosed string or comment, fails planning with `S511` naming the scenario file. diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/selectors.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/selectors.md index efee250736..66507d7d5d 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/selectors.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/selectors.md @@ -14,6 +14,7 @@ Online: https://sqlbuild.com/docs/concepts/selectors/ - Path-between selectors - Intersection - Combining select and exclude +- Selecting from a past run - Error handling Selectors let you scope commands to specific subsets of your project. They work with `plan`, `build`, `test`, `audit`, `seed`, `clone`, and `diff`. @@ -130,6 +131,25 @@ sqb test "test:orders_*" stg_customers Test selectors are unioned with other selectors and cannot use `+` or `,`. Other commands reject them with `S013`. +### Audit + +`audit:` selects an audit by name, the end-of-build singular audits included, and accepts glob +patterns: + +```bash +sqb build audit:orders_match_payments +sqb audit "audit:not_null_*" +sqb build daily_revenue audit:revenue_reconciles +``` + +An audit has no upstream or downstream nodes, so `+` adds nothing to it, and it composes with `,` +and `--exclude` like any other selector. An audit selected by name runs whether or not its target +is in the selection: when the build doesn't build the target, the audit runs after everything else, +against the target as it is. `sqb plan` lists audits selected by name under `Audits`, and its +`--json` output under `audits`. + +`plan`, `build`, `test`, `audit` and `check` accept `audit:`; other commands reject it with `S010`. + ## Graph expansion ### Upstream @@ -207,6 +227,49 @@ sqb build --select path:sql/models/marts --exclude daily_revenue sqb build --select +fact_orders --exclude tag:staging ``` +## Selecting from a past run + +Three selectors select from a run that already happened: + +| Selector | Selects | +| --- | --- | +| `run:` | Every node the run selected | +| `failed:` | The nodes that failed, were cancelled or never ran, and the audits that failed, not counting ignored audit failures | +| `skipped:` | The nodes the run skipped | + +They compose like any other selector, so `failed:+` reruns what didn't succeed and everything +downstream of it, and `run: --exclude skipped:` repeats what the run didn't skip: + +```bash +sqb plan failed:20261125T142600Z_1732548e8aea+ +sqb build failed:20261125T1426+ +sqb build model_a model_b failed:20261125T1426+ +``` + +The last command builds `model_a` and `model_b` too, for example when a failed audit read them +and they don't exist in the target yet. + +`` is the run's full ID or a prefix of at least 8 characters that only one run starts with; +wildcards are not accepted. A prefix that more runs start with is an error that lists them. + +Without `--server`, the run comes from the project's local [Recall](../cli/recall.md) history, +which needs the default SQLite store. To list the latest local runs: + +```bash +sqb recall query "SELECT run_id, MIN(occurred_at) AS started FROM events + WHERE run_id IS NOT NULL GROUP BY run_id ORDER BY started DESC LIMIT 5" +``` + +With `--server`, `--location-id` and an [`sqb login`](../cli/login.md) session, the run comes from +the server's runs of that location on the command's target, as the web UI shows them: + +```bash +sqb plan failed:0192c1a4+ --server https://control.example.com --location-id +``` + +`plan`, `build`, `test`, `audit` and `check` read past runs; other commands reject run selectors with +`S010`. + ## Error handling Unknown resource names, name patterns with no matches, empty paths, and malformed selectors produce @@ -220,6 +283,17 @@ error[S000]: no SQL resources or Python nodes found with tag 'nonexistent_tag' error[S007]: unknown node kind 'modle' error[S003]: path selector 'fact_orders~' requires names on both sides of '~' error[S013]: selector 'order_status_rules' selects a unit test; only `sqb test` and `sqb build` accept unit-test selectors +error[S007]: unknown audit name 'orders_match_payment' +error[S010]: selector 'failed:20261125T1426' selects from a past run; only plan, build, test, audit and check read past runs +``` + +A run ID that is too short, names no run, or starts more than one is refused before anything is +planned: + +``` +error[S000]: run ID '2026112' is too short: give the full ID or at least 8 characters of it +error[S000]: no run '20261124' in the local Recall history +error[S000]: run ID '20261125' is ambiguous: it starts 20261125T142600Z_1732548e8aea, 20261125T153329Z_746e30e62302; give more of the ID ``` Unknown names suggest the closest selectable names, including unit tests: diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/testing-reference.md b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/testing-reference.md index 604c440d4f..c4ca75c088 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/testing-reference.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/docs/concepts/testing-reference.md @@ -13,6 +13,7 @@ Online: https://sqlbuild.com/docs/concepts/testing-reference/ - Cursor windows in tests - Empty-input tests - Cost guards +- Running tests locally - Skipping SQL analysis - Details @@ -429,6 +430,71 @@ to change it, without the scenario advice. Scenarios have their own limit, `scenario_timeout`; see [Scenario timeouts](project-configuration.md#unit-test-and-scenario-limits). +## Running tests locally + +`sqb test` runs each SQL unit test either locally, in a run-scoped in-memory DuckDB database, or on +the warehouse. Unit test fixtures are inline, so a local test needs no captured data and no +credentials. + +| Setting | Where each test runs | +| --- | --- | +| `auto` (default) | Locally when [SQLQuack](https://github.com/sqlstack-io/sqlquack) converts its comparison SQL to DuckDB, otherwise on the warehouse | +| `local` | Locally. A test SQLQuack refuses is an `ERROR` (`T007`, `can't run locally`); it is never skipped or sent to the warehouse | +| `warehouse` | On the warehouse, as every test ran before | + +The setting comes from, in order: `--run-on`, the selected target's `test_run_on` (a target in +`sqlbuild_local.toml` replaces the project file's), `[settings] test_run_on` in +`sqlbuild_local.toml`, then in `sqlbuild_project.toml`, then `auto`. + +```toml +[settings] +test_run_on = "auto" + +[targets.ci] +test_run_on = "local" +``` + +How SQLBuild decides, at compile time, before anything runs: + +- **Snowflake projects.** SQLQuack converts the test's comparison SQL: every real model in its + chain, its fixtures, expected rows and assertions. SQLQuack converts only constructs whose rules + were verified against recorded Snowflake results, and refuses anything else. SQLBuild gives + SQLQuack the declared columns of the project's sources, seeds and models. +- **DuckDB projects.** The SQL is already DuckDB SQL, so tests run locally as written. +- **Project functions.** A local run makes temporary copies of the functions a test calls. A + function whose body reads a table or view, or any function in a project that isn't DuckDB, needs + the warehouse (reason `project function: `). +- **Unmocked relations.** A test whose SQL still reads a relation the local database doesn't have, + rather than one of its fixtures, needs the warehouse (reason `warehouse relation: `). In a + Snowflake project SQLQuack refuses names the project doesn't declare, and a declared relation the + converted SQL reads by name, such as a table a model names directly, is one only the warehouse has. +- **Work per run.** Each distinct test statement is converted once, in worker processes, and the + test run reuses those conversions. Conversions are kept in `target/sqlquack-cache/`, keyed by the + SQL, the declared relations it reads, the session and the SQLQuack version, so a later run + converts only the statements that changed. At the end of a run, SQLBuild deletes the conversions + no run has used for 7 days. Deleting the folder is always safe. +- **Other adapters.** SQLQuack converts Snowflake SQL only, so tests run on the warehouse (reason + `dialect: `). +- **Time zone.** Local runs use a UTC session. When the target's connection sets another + `TIMEZONE` in `session_parameters`, SQLQuack refuses SQL whose result depends on the time zone, + and those tests go to the warehouse. + +`sqb test --inspect` adds one line per test: `runs on: local`, or +`runs on: warehouse ()`, where the reason is SQLQuack's refusal label +`: `, such as `missing rule: node:method_call` or +`a known difference that isn't allowed: fn:HASH`. The full diagnostics follow the plan. + +In `auto`, when the warehouse connection cannot be made, the local tests still run and each +warehouse test is an `ERROR` (`T008`, `needs the warehouse (no connection)`). + +Some problems only show when a test runs. SQLQuack's converted SQL raises, instead of returning a +different value, for inputs DuckDB would read differently from Snowflake, and DuckDB can fail with +an internal error on SQL it accepted. In `auto` such a test runs again on the warehouse, with the +reason `SQLQuack guard: `, such as `SQLQuack guard: array_agg_order`, or +`DuckDB internal error: `. The local attempt prints nothing; the test's row shows +`warehouse ()`. With `--run-on local` it is an `ERROR` (`T007`) that names the guard. An error Snowflake would raise too, such as a value that isn't a number, is the test's +own result wherever it runs. + ## Skipping SQL analysis Compile checks test fixtures and assertions like model SQL. For SQL the parser can't read, add diff --git a/src/sqlbuild/.agents/skills/sqlbuild/references/investigating-runs.md b/src/sqlbuild/.agents/skills/sqlbuild/references/investigating-runs.md index 1f509c9bd3..f909cfa776 100644 --- a/src/sqlbuild/.agents/skills/sqlbuild/references/investigating-runs.md +++ b/src/sqlbuild/.agents/skills/sqlbuild/references/investigating-runs.md @@ -39,6 +39,9 @@ what they printed. `sqb recall query` runs one read-only `SELECT` over a set of `invocation_id` and `artifacts.digest = 'sha256:' || statements.sql_digest` for the SQL text (`artifacts.text`), also for failed and cancelled statements. `statements.sql_available = 0` means the text is missing, and `sql_unavailable_reason` says why. +- **Local test statements keep no SQL text.** Statements of tests run in the local DuckDB have + `run_on = 'local'` in their event payload (`json_extract(payload, '$.run_on')`) and no stored + text; the converted test SQL is in the compiled tests under `target/run/tests/`. - **Audit evidence is an artifact.** A warning or failing audit's flagged rows (up to `evidence_limit`) are in `artifacts` with `digest = 'sha256:' || audit_results.sample_digest` in the same invocation; `sample_digest` is diff --git a/src/sqlbuild/_native.pyi b/src/sqlbuild/_native.pyi index ff6c1298b1..3fe89d44b4 100644 --- a/src/sqlbuild/_native.pyi +++ b/src/sqlbuild/_native.pyi @@ -2744,6 +2744,7 @@ class NativeProgressProjector: def restore(self, token: Token[NativeProgressProjector | None]) -> None: ... def configure_resources(self, *, ordinals: Mapping[str, int], total: int) -> None: ... def expect_resource_enrichment(self, *, resource_name: str) -> None: ... + def expect_no_start(self, *, resource_name: str) -> None: ... def record_audit_outcome(self, *, resource_attempt_id: str, outcome: str) -> None: ... def is_operation_active(self, *, operation_name: str) -> bool: ... def consume(self, event: LifecycleEvent) -> None: ... @@ -4483,6 +4484,12 @@ def render_sql_test_comparison_sql( output_step_index: int | None = None, actual_relations: Mapping[int, str] | None = None, ) -> list[str]: ... +def render_sql_test_comparison_segments( + test_entry: SqlTestPlanEntry, + *, + set_difference_operator: str = "EXCEPT", + sql_analysis_dialect: str | None = None, +) -> tuple[str, list[tuple[int, int, str]]]: ... def render_sql_test_difference_sample_sql( *, test_entry: SqlTestPlanEntry, @@ -7114,8 +7121,8 @@ class ScenarioTestCommandRequest(NativeRecord): selectors: tuple[str, ...] exclude: tuple[str, ...] retain: bool - local: bool - strict: bool + run_on: str | None + verbose: bool concurrency: int | None sync_snapshots: bool refresh: bool @@ -7134,8 +7141,8 @@ class ScenarioTestCommandRequest(NativeRecord): selectors: tuple[str, ...] = (), exclude: tuple[str, ...] = (), retain: bool = False, - local: bool = False, - strict: bool = False, + run_on: str | None = None, + verbose: bool = False, concurrency: int | None = None, sync_snapshots: bool = False, refresh: bool = False, @@ -7186,6 +7193,8 @@ class TestCommandRequest(NativeRecord): case_name: str | None inspect: bool test_timeout: str | None + run_on: str | None + verbose: bool since: str | None explain: bool sql_only: bool @@ -7205,6 +7214,8 @@ class TestCommandRequest(NativeRecord): case_name: str | None = None, inspect: bool = False, test_timeout: str | None = None, + run_on: str | None = None, + verbose: bool = False, since: str | None = None, explain: bool = False, sql_only: bool = False, @@ -10471,6 +10482,7 @@ class PlannerScope(NativeRecord): sql_test_selection: SqlTestSelection load_sources: bool end_audit_source_keys: frozenset[CompiledObjectKey] + selected_audit_names: frozenset[str] def __init__( self, upstream_deps: dict[CompiledObjectKey, tuple[CompiledObjectKey, ...]], @@ -10484,6 +10496,7 @@ class PlannerScope(NativeRecord): sql_test_selection: SqlTestSelection = ..., load_sources: bool = ..., end_audit_source_keys: frozenset[CompiledObjectKey] = ..., + selected_audit_names: frozenset[str] = ..., ) -> None: ... class PlannerRelationsContext: @@ -12057,6 +12070,8 @@ class TargetConfig(NativeRecord): diff: TargetDiffConfig warehouses: TargetWarehousesConfig concurrency: int | None + test_run_on: str | None + scenario_run_on: str | None catalog_connection: str | None ignore_audit_failures: bool | None plan_from: str | None @@ -12086,6 +12101,8 @@ class TargetConfig(NativeRecord): diff: TargetDiffConfig = ..., warehouses: TargetWarehousesConfig = ..., concurrency: int | None = ..., + test_run_on: str | None = ..., + scenario_run_on: str | None = ..., catalog_connection: str | None = ..., ignore_audit_failures: bool | None = ..., plan_from: str | None = ..., @@ -12118,6 +12135,8 @@ class LocalTargetConfig(NativeRecord): diff: TargetDiffConfig warehouses: TargetWarehousesConfig concurrency: int | None + test_run_on: str | None + scenario_run_on: str | None catalog_connection: str | None ignore_audit_failures: bool | None plan_from: str | None @@ -12148,6 +12167,8 @@ class LocalTargetConfig(NativeRecord): diff: TargetDiffConfig = ..., warehouses: TargetWarehousesConfig = ..., concurrency: int | None = ..., + test_run_on: str | None = ..., + scenario_run_on: str | None = ..., catalog_connection: str | None = ..., ignore_audit_failures: bool | None = ..., plan_from: str | None = ..., @@ -12180,6 +12201,8 @@ class SettingsConfig(NativeRecord): allow_warehouse_round_trips: bool ignore_audit_failures: bool record_run_host: bool + test_run_on: str + scenario_run_on: str def __init__( self, sql_analysis: bool = ..., @@ -12203,6 +12226,8 @@ class SettingsConfig(NativeRecord): allow_warehouse_round_trips: bool = ..., ignore_audit_failures: bool = ..., record_run_host: bool = ..., + test_run_on: str = ..., + scenario_run_on: str = ..., ) -> None: ... @property def sql_validation(self) -> bool: ... @@ -14681,6 +14706,8 @@ class PlanOutput(NativeRecord): existing_model_names: frozenset[str] end_audit_source_keys: frozenset[CompiledObjectKey] ignore_audit_failures: bool + selected_audit_names: tuple[str, ...] + audits_not_run: dict[str, tuple[str, ...]] def __init__( self, execution_order: tuple[CompiledObjectKey, ...] = ..., @@ -14718,6 +14745,8 @@ class PlanOutput(NativeRecord): existing_model_names: frozenset[str] = ..., end_audit_source_keys: frozenset[CompiledObjectKey] = ..., ignore_audit_failures: bool = ..., + selected_audit_names: tuple[str, ...] = ..., + audits_not_run: dict[str, tuple[str, ...]] = ..., ) -> None: ... @property def python_source_entries(self) -> dict[str, SourceEntry]: ... diff --git a/src/sqlbuild/_native_host.py b/src/sqlbuild/_native_host.py index 8a53a8c20b..f9b9c240fa 100644 --- a/src/sqlbuild/_native_host.py +++ b/src/sqlbuild/_native_host.py @@ -473,6 +473,19 @@ ), "run_seed_pipeline": ("sqlbuild.executor.pipeline.main.run", "run_seed_pipeline"), "run_test_pipeline": ("sqlbuild.executor.pipeline.main.run", "run_test_pipeline"), + "decide_sql_test_run_on": ( + "sqlbuild.executor.local.main._decide_sql_test_run_on", + "decide_sql_test_run_on", + ), + "local_test_adapter": ( + "sqlbuild.executor.local.main._local_test_adapter", + "local_test_adapter", + ), + "report_unplaced_sql_tests": ( + "sqlbuild.executor.local.main._report_unplaced_sql_tests", + "report_unplaced_sql_tests", + ), + "decide_scenario_run_on": ("sqlbuild.executor.pipeline.main.run", "decide_scenario_run_on"), "select_scenario_snapshot_capture_candidates": ( "sqlbuild.executor.pipeline.main.run", "select_scenario_snapshot_capture_candidates", diff --git a/src/sqlbuild/compiler/auditing/types.py b/src/sqlbuild/compiler/auditing/types.py index 16eced37fc..df76a8350b 100644 --- a/src/sqlbuild/compiler/auditing/types.py +++ b/src/sqlbuild/compiler/auditing/types.py @@ -39,3 +39,4 @@ class AuditOutcome(StrEnum): ERROR = "error" INSUFFICIENT = "insufficient" SKIPPED = "skipped" + NOT_RUN = "not_run" diff --git a/src/sqlbuild/compiler/sql_analysis/_helpers/polyglot.py b/src/sqlbuild/compiler/sql_analysis/_helpers/polyglot.py deleted file mode 100644 index 15badf7b70..0000000000 --- a/src/sqlbuild/compiler/sql_analysis/_helpers/polyglot.py +++ /dev/null @@ -1,82 +0,0 @@ -"""Required Polyglot import helpers.""" - -from __future__ import annotations - -from typing import Any - -import polyglot_sql - -from sqlbuild.compiler.sql_analysis.constants import ( - POLYGLOT_ANALYZE_QUERY_ENTRY_POINT, - POLYGLOT_ANALYZE_QUERY_OPTIONS_ARGUMENT_COUNT, - POLYGLOT_ANALYZE_QUERY_OPTIONS_ARGUMENT_INDEX, - POLYGLOT_COMPLEXITY_GUARD_OPTION, - POLYGLOT_COMPLEXITY_GUARD_PARAMETER, - POLYGLOT_MAX_FUNCTION_CALL_DEPTH, - POLYGLOT_MAX_FUNCTION_CALL_DEPTH_OPTION, -) - -_COMPLEXITY_GUARD: dict[str, int] = { - POLYGLOT_MAX_FUNCTION_CALL_DEPTH_OPTION: POLYGLOT_MAX_FUNCTION_CALL_DEPTH, -} -_GUARDED_ENTRY_POINTS: frozenset[str] = frozenset( - { - POLYGLOT_ANALYZE_QUERY_ENTRY_POINT, - "parse", - "parse_data_type", - "parse_one", - "transpile", - "validate", - "validate_with_schema", - } -) - - -class _GuardedEntryPoint: - """One Polyglot entry point with SQLBuild's bounded trusted-SQL budget.""" - - def __init__(self, *, name: str, function: Any) -> None: - self._name: str = name - self._function: Any = function - - def __call__(self, *args: Any, **kwargs: Any) -> Any: - if self._has_explicit_options_guard(args=args, kwargs=kwargs): - return self._function(*args, **kwargs) - guarded_kwargs: dict[str, Any] = { - POLYGLOT_COMPLEXITY_GUARD_PARAMETER: dict(_COMPLEXITY_GUARD), - **kwargs, - } - return self._function(*args, **guarded_kwargs) - - def _has_explicit_options_guard(self, *, args: tuple[Any, ...], kwargs: dict[str, Any]) -> bool: - if self._name != POLYGLOT_ANALYZE_QUERY_ENTRY_POINT: - return False - options: object = kwargs.get("options") - if len(args) >= POLYGLOT_ANALYZE_QUERY_OPTIONS_ARGUMENT_COUNT: - options = args[POLYGLOT_ANALYZE_QUERY_OPTIONS_ARGUMENT_INDEX] - return isinstance(options, dict) and POLYGLOT_COMPLEXITY_GUARD_OPTION in options - - -class _PolyglotSqlModule: - """Proxy Polyglot parsing through SQLBuild's trusted-SQL policy.""" - - def __getattr__(self, name: str) -> Any: - attribute: Any = getattr(polyglot_sql, name) - if name in _GUARDED_ENTRY_POINTS: - return _GuardedEntryPoint(name=name, function=attribute) - return attribute - - -_POLYGLOT_SQL_MODULE: _PolyglotSqlModule = _PolyglotSqlModule() - - -def import_polyglot() -> Any: - """Return SQLBuild's required Polyglot SQL module.""" - - return _POLYGLOT_SQL_MODULE - - -def import_polyglot_sql() -> Any: - """Return SQLBuild's required Polyglot SQL module.""" - - return import_polyglot() diff --git a/src/sqlbuild/compiler/sql_analysis/constants.py b/src/sqlbuild/compiler/sql_analysis/constants.py deleted file mode 100644 index 6f78551182..0000000000 --- a/src/sqlbuild/compiler/sql_analysis/constants.py +++ /dev/null @@ -1,13 +0,0 @@ -"""Polyglot SQL analysis vocabulary.""" - -from __future__ import annotations - -from sqlbuild._native import MAX_FUNCTION_CALL_DEPTH - -POLYGLOT_ANALYZE_QUERY_ENTRY_POINT: str = "analyze_query" -POLYGLOT_ANALYZE_QUERY_OPTIONS_ARGUMENT_COUNT: int = 2 -POLYGLOT_ANALYZE_QUERY_OPTIONS_ARGUMENT_INDEX: int = 1 -POLYGLOT_COMPLEXITY_GUARD_PARAMETER: str = "complexity_guard" -POLYGLOT_COMPLEXITY_GUARD_OPTION: str = "complexityGuard" -POLYGLOT_MAX_FUNCTION_CALL_DEPTH_OPTION: str = "maxFunctionCallDepth" -POLYGLOT_MAX_FUNCTION_CALL_DEPTH: int = MAX_FUNCTION_CALL_DEPTH diff --git a/src/sqlbuild/compiler/sql_analysis/main/__init__.py b/src/sqlbuild/compiler/sql_analysis/main/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/src/sqlbuild/compiler/sql_analysis/main/import_polyglot_sql.py b/src/sqlbuild/compiler/sql_analysis/main/import_polyglot_sql.py deleted file mode 100644 index f4bc7eee77..0000000000 --- a/src/sqlbuild/compiler/sql_analysis/main/import_polyglot_sql.py +++ /dev/null @@ -1,13 +0,0 @@ -"""Public required Polyglot SQL import entry.""" - -from typing import Any - -from sqlbuild.compiler.sql_analysis._helpers.polyglot import ( - import_polyglot_sql as _import_polyglot_sql, -) - - -def import_polyglot_sql() -> Any: - """Return SQLBuild's required Polyglot SQL module.""" - - return _import_polyglot_sql() diff --git a/src/sqlbuild/errors/contracts/exceptions.py b/src/sqlbuild/errors/contracts/exceptions.py index a09baa678c..37e22479d5 100644 --- a/src/sqlbuild/errors/contracts/exceptions.py +++ b/src/sqlbuild/errors/contracts/exceptions.py @@ -25,3 +25,16 @@ def __init__(self, message: str, *, code: str | None = None, help: str | None = self.message = message self.code = code if code is not None else self.code self.help = help + + +class LocalRunRefusedError(ExecutorInputError): + """Raised when SQL running in the local DuckDB fails in a way the warehouse would not.""" + + code: str = "T007" + + def __init__( + self, message: str, *, category: str, construct: str, help: str | None = None + ) -> None: + super().__init__(message, help=help) + self.category: str = category + self.construct: str = construct diff --git a/src/sqlbuild/executor/auditing/_helpers/result_projection.py b/src/sqlbuild/executor/auditing/_helpers/result_projection.py index c48889f2a5..84b0431292 100644 --- a/src/sqlbuild/executor/auditing/_helpers/result_projection.py +++ b/src/sqlbuild/executor/auditing/_helpers/result_projection.py @@ -11,6 +11,7 @@ from contextlib import contextmanager from contextvars import Context, ContextVar, Token, copy_context from datetime import UTC, datetime +from functools import partial from typing import Any from sqlbuild._native import ( @@ -22,7 +23,7 @@ build_audit_gate_identity, ) from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter -from sqlbuild.compiler.auditing.types import AuditEvaluationMode, ThresholdOperator +from sqlbuild.compiler.auditing.types import AuditEvaluationMode, AuditOutcome, ThresholdOperator from sqlbuild.executor.audit_results.constants import ( AUDIT_RESULT_SCHEMA_VERSION, IGNORED_FAILURE_METADATA_JSON, @@ -90,7 +91,12 @@ def publish(self, results: tuple[AuditExecutionResult, ...]) -> None: record: AuditResultRecord | None = self._build(result) self._records[id(result)] = (result, record) if record is not None: - self._context.run(_publish_safely, record) + not_run_reason: str | None = ( + result.skip_reason if result.outcome == AuditOutcome.NOT_RUN else None + ) + self._context.run( + partial(_publish_safely, record=record, not_run_reason=not_run_reason) + ) def records_for( self, results: tuple[AuditExecutionResult, ...] @@ -371,9 +377,9 @@ def _build_record( # noqa: PLR0913 ) -def _publish_safely(record: AuditResultRecord) -> None: +def _publish_safely(*, record: AuditResultRecord, not_run_reason: str | None) -> None: try: - _publish_audit_completed(record) + _publish_audit_completed(record=record, not_run_reason=not_run_reason) except Exception as error: _LOGGER.warning( "Audit result lifecycle publication degraded for '%s' (%s)", @@ -382,7 +388,7 @@ def _publish_safely(record: AuditResultRecord) -> None: ) -def _publish_audit_completed(record: AuditResultRecord) -> None: +def _publish_audit_completed(*, record: AuditResultRecord, not_run_reason: str | None) -> None: payload: dict[str, JSONValue] = { "audit_name": record.audit_name, "audit_definition_name": record.audit_definition_name, @@ -403,6 +409,8 @@ def _publish_audit_completed(record: AuditResultRecord) -> None: } if record.metadata_json == IGNORED_FAILURE_METADATA_JSON: payload["ignored"] = True + if not_run_reason: + payload["not_run_reason"] = not_run_reason optional: dict[str, JSONValue | None] = { "attached_target_kind": record.attached_target_kind, "attached_target_name": record.attached_target_name, diff --git a/src/sqlbuild/executor/build/_helpers/indexes.py b/src/sqlbuild/executor/build/_helpers/indexes.py index 04df581d06..2da584eeee 100644 --- a/src/sqlbuild/executor/build/_helpers/indexes.py +++ b/src/sqlbuild/executor/build/_helpers/indexes.py @@ -8,24 +8,30 @@ def build_execution_indexes(plan: PlanOutput) -> BuildIndexes: - """Build all lookup indexes from a plan output.""" + """Build lookup indexes from a plan; a named audit on an unbuilt target runs at the end.""" source_audits: dict[str, list[AuditPlanEntry]] = {} seed_audits: dict[str, list[AuditPlanEntry]] = {} model_audits: dict[str, list[AuditPlanEntry]] = {} end_audits: list[AuditPlanEntry] = [] + by_name: frozenset[str] = frozenset(plan.selected_audit_names) + built_models: frozenset[str] = frozenset(entry.name for entry in plan.model_entries) + built_seeds: frozenset[str] = frozenset(entry.name for entry in plan.seed_entries) audit: AuditPlanEntry for audit in plan.audit_entries: + target: str = audit.attached_target_name or "" if audit.attachment_kind == AuditAttachmentKind.SOURCE: - source_name: str = audit.attached_target_name or "" - source_audits.setdefault(source_name, []).append(audit) - elif audit.attachment_kind == AuditAttachmentKind.SEED: - seed_audits.setdefault(audit.attached_target_name or "", []).append(audit) - elif audit.attachment_kind == AuditAttachmentKind.MODEL: - model_name: str = audit.attached_target_name or "" - model_audits.setdefault(model_name, []).append(audit) - elif audit.attachment_kind == AuditAttachmentKind.END: + source_audits.setdefault(target, []).append(audit) + elif audit.attachment_kind == AuditAttachmentKind.SEED and ( + target in built_seeds or audit.name not in by_name + ): + seed_audits.setdefault(target, []).append(audit) + elif audit.attachment_kind == AuditAttachmentKind.MODEL and ( + target in built_models or audit.name not in by_name + ): + model_audits.setdefault(target, []).append(audit) + else: end_audits.append(audit) return BuildIndexes( diff --git a/src/sqlbuild/executor/build/classes/build_scheduler.py b/src/sqlbuild/executor/build/classes/build_scheduler.py index e3ec5443af..c675f0a8e8 100644 --- a/src/sqlbuild/executor/build/classes/build_scheduler.py +++ b/src/sqlbuild/executor/build/classes/build_scheduler.py @@ -25,6 +25,7 @@ IncrementalMode, IncrementalStrategy, ModelPlanEntry, + NativeProgressProjector, PlanAction, PlanOutput, SeedPlanEntry, @@ -33,6 +34,7 @@ SqlTestPlanEntry, TableTypePlanEntry, audit_resource_id, + current_native_progress_projector, output_node_scope, sql_test_resource_id, ) @@ -348,16 +350,14 @@ def run( end_audit_results: tuple[AuditExecutionResult, ...] = () runnable_end_audits: tuple[AuditPlanEntry, ...] = tuple( - audit - for audit in self._indexes.end_audits - if self._unbuilt_keys.isdisjoint(audit.scope_deps) + audit for audit in self._indexes.end_audits if self._can_run_end_audit(audit=audit) ) skipped_end_audits: tuple[AuditExecutionResult, ...] = () if self._run_audits: skipped_end_audits = tuple( self._skipped_end_audit(audit=audit) for audit in self._indexes.end_audits - if not self._unbuilt_keys.isdisjoint(audit.scope_deps) + if not self._can_run_end_audit(audit=audit) ) if self._run_audits and runnable_end_audits: end_audit_results = run_end_audits( @@ -924,27 +924,47 @@ def _mark_unbuilt(self, *, key: CompiledObjectKey) -> None: return self._unbuilt_keys.add(key) - def _skipped_end_audit(self, *, audit: AuditPlanEntry) -> AuditExecutionResult: - """The SKIPPED result of an end-of-build audit that reads a resource not built this run.""" + def _can_run_end_audit(self, *, audit: AuditPlanEntry) -> bool: + """Whether every read of an end-of-build audit exists: built this run or in the target.""" + + return audit.name not in self._plan.audits_not_run and self._unbuilt_keys.isdisjoint( + audit.scope_deps + ) + + def _skip_reason(self, *, audit: AuditPlanEntry) -> str: + """Why an end-of-build audit doesn't run: a read the target lacks, or one not built.""" + missing: tuple[str, ...] = self._plan.audits_not_run.get(audit.name, ()) + if missing: + verb: str = "which doesn't" if len(missing) == 1 else "which don't" + return f"reads {', '.join(missing)}, {verb} exist in the target" unbuilt: CompiledObjectKey = next( key for key in audit.scope_deps if key in self._unbuilt_keys ) + return f"reads {unbuilt.name}, which was not built" + + def _skipped_end_audit(self, *, audit: AuditPlanEntry) -> AuditExecutionResult: + """NOT_RUN when the target lacks a read of an end-of-build audit; SKIPPED when unbuilt.""" + + not_run: bool = audit.name in self._plan.audits_not_run result: AuditExecutionResult = AuditExecutionResult( audit_name=audit.name, audit_definition_name=audit.definition_name, attachment_kind=audit.attachment_kind, severity=audit.severity, - outcome=AuditOutcome.SKIPPED, + outcome=AuditOutcome.NOT_RUN if not_run else AuditOutcome.SKIPPED, row_count=0, - executed_sql="", + executed_sql=audit.resolved_sql if not_run else "", attached_target_kind=audit.attached_target_kind, attached_target_name=audit.attached_target_name, attached_column_name=audit.attached_column_name, audit_description=audit.description, audit_meta=audit.meta, - skip_reason=f"reads {unbuilt.name}, which was not built", + skip_reason=self._skip_reason(audit=audit), ) + projector: NativeProgressProjector | None = current_native_progress_projector() + if not_run and projector is not None: + projector.expect_no_start(resource_name=audit.name) with ResourceAttemptLifecycle( resource_id=audit_resource_id( audit_name=audit.name, @@ -960,7 +980,8 @@ def _skipped_end_audit(self, *, audit: AuditPlanEntry) -> AuditExecutionResult: record_audit_progress_outcome( resource_attempt_id=lifecycle.resource_attempt_id, result=result ) - lifecycle.skipped(skip_code="scheduler") + if not not_run: + lifecycle.skipped(skip_code="scheduler") return result def _unloaded_selected_sources(self) -> tuple[CompiledObjectKey, ...]: diff --git a/src/sqlbuild/executor/build/models.py b/src/sqlbuild/executor/build/models.py index 562f493977..4398121f1a 100644 --- a/src/sqlbuild/executor/build/models.py +++ b/src/sqlbuild/executor/build/models.py @@ -246,6 +246,7 @@ class BuildExecutionResult: warning_count: int = 0 insufficient_count: int = 0 ignored_audit_failure_count: int = 0 + not_run_count: int = 0 audit_result_projection_attempted_count: int = 0 audit_result_projection_written_count: int = 0 audit_result_projection_failed_count: int = 0 diff --git a/src/sqlbuild/executor/local/__init__.py b/src/sqlbuild/executor/local/__init__.py new file mode 100644 index 0000000000..6e0b2f45c2 --- /dev/null +++ b/src/sqlbuild/executor/local/__init__.py @@ -0,0 +1 @@ +"""Local DuckDB runs of unit tests and scenarios, converted by SQLQuack.""" diff --git a/src/sqlbuild/executor/local/_helpers/__init__.py b/src/sqlbuild/executor/local/_helpers/__init__.py new file mode 100644 index 0000000000..6121cd2b62 --- /dev/null +++ b/src/sqlbuild/executor/local/_helpers/__init__.py @@ -0,0 +1 @@ +"""Local run _helpers package.""" diff --git a/src/sqlbuild/executor/local/_helpers/conversion.py b/src/sqlbuild/executor/local/_helpers/conversion.py new file mode 100644 index 0000000000..a58ebb46c9 --- /dev/null +++ b/src/sqlbuild/executor/local/_helpers/conversion.py @@ -0,0 +1,443 @@ +"""Once per unique SQL: SQLQuack's conversion and the relation an empty DuckDB lacks.""" + +from __future__ import annotations + +import hashlib +import json +import multiprocessing +import os +import re +import threading +from collections.abc import Mapping, Sequence +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path +from typing import Any + +import sqlquack +from sqlquack import ConvertOptions +from sqlquack.api.constants import DEFAULT_PATH + +from sqlbuild.errors.contracts.exceptions import ExecutorInputError +from sqlbuild.executor.local.classes.empty_duckdb import EmptyDuckDb +from sqlbuild.executor.local.constants import ( + CONVERSION_CACHE_INDEX, + CONVERSION_CACHE_LIFETIME_SECONDS, + TIMEZONE_PARAMETER, + UTC_TIME_ZONE, +) +from sqlbuild.executor.local.models import ConvertedSql, LocalSqlCheck, LocalWorkCounts + +_PARALLEL_MINIMUM: int = 8 +_MAX_WORKERS: int = 4 +_CHUNKS_PER_WORKER: int = 4 +_IDENTIFIER: re.Pattern[str] = re.compile(r"[A-Za-z_][A-Za-z0-9_$]*") + +_CACHE_FORMAT: str = "sqlbuild-local-conversion/1" + +type _CheckKey = tuple[str, str, str, bool] +type _CheckJob = tuple[str, dict[str, Any] | None, dict[str, str], bool] + + +class _LocalWork: + """Checks shared by every thread of the process, and how much work they took.""" + + def __init__(self) -> None: + self._lock: threading.Lock = threading.Lock() + self._checks: dict[_CheckKey, LocalSqlCheck] = {} + self._schema_keys: dict[int, tuple[Mapping[str, Any], str]] = {} + self._relation_names: dict[int, tuple[Mapping[str, Any], dict[str, list[str]]]] = {} + self._slices: dict[int, dict[str, dict[str, Any]]] = {} + self._counts: dict[str, int] = { + "conversions": 0, + "bindings": 0, + "schema_keys": 0, + "cached": 0, + } + self._empty: EmptyDuckDb | None = None + self._cache_dir: Path | None = None + self._used: set[str] = set() + + def use_cache_dir(self, directory: Path | None) -> None: + with self._lock: + self._cache_dir = directory + + def cache_dir(self) -> Path | None: + with self._lock: + return self._cache_dir + + def mark_used(self, path: Path) -> None: + with self._lock: + self._used.add(path.stem) + + def take_used(self) -> set[str]: + """The cache entries this process read or wrote since the last call.""" + + with self._lock: + used: set[str] = self._used + self._used = set() + return used + + def schema_key(self, schema: Mapping[str, Any] | None) -> str: + """The schema's JSON, serialised once per schema object.""" + + if not schema: + return "" + with self._lock: + known: tuple[Mapping[str, Any], str] | None = self._schema_keys.get(id(schema)) + if known is not None and known[0] is schema: + return known[1] + key: str = json.dumps(schema, sort_keys=True) + with self._lock: + self._schema_keys[id(schema)] = (schema, key) + self._counts["schema_keys"] += 1 + return key + + def statement_schema( + self, *, schema: Mapping[str, Any] | None, sql: str + ) -> dict[str, Any] | None: + """Only the relations whose names `sql` mentions, so each call reads a small schema.""" + + if not schema: + return None + with self._lock: + known: tuple[Mapping[str, Any], dict[str, list[str]]] | None = self._relation_names.get( + id(schema) + ) + if known is None or known[0] is not schema: + by_name: dict[str, list[str]] = {} + for relation in schema.get("relations", {}): + by_name.setdefault(relation.rsplit(".", 1)[-1].upper(), []).append(relation) + known = (schema, by_name) + with self._lock: + self._relation_names[id(schema)] = known + self._slices[id(schema)] = {} + with self._lock: + sliced: dict[str, Any] | None = self._slices.get(id(schema), {}).get(sql) + if sliced is not None: + return sliced + relations: Mapping[str, Any] = schema.get("relations", {}) + mentioned: set[str] = {token.upper() for token in _IDENTIFIER.findall(sql)} + read: dict[str, Any] = {} + for name in mentioned & known[1].keys(): + for relation in known[1][name]: + read[relation] = relations[relation] + sliced = {**schema, "relations": read} + with self._lock: + self._slices.setdefault(id(schema), {})[sql] = sliced + return sliced + + def get(self, key: _CheckKey) -> LocalSqlCheck | None: + with self._lock: + return self._checks.get(key) + + def missing(self, keys: Sequence[_CheckKey]) -> list[_CheckKey]: + with self._lock: + return list(dict.fromkeys(key for key in keys if key not in self._checks)) + + def store( + self, *, checks: Mapping[_CheckKey, LocalSqlCheck], counts: Mapping[str, int] + ) -> None: + with self._lock: + self._checks.update(checks) + for name, count in counts.items(): + self._counts[name] += count + + def counts(self) -> LocalWorkCounts: + with self._lock: + return LocalWorkCounts(**self._counts) + + def empty(self) -> EmptyDuckDb: + """This process's empty DuckDB, opened on first use.""" + + with self._lock: + if self._empty is None: + self._empty = EmptyDuckDb() + return self._empty + + +_WORK: _LocalWork = _LocalWork() + + +def use_conversion_cache(directory: Path | None) -> None: + """Keep conversions in `directory` across runs, keyed by SQL, schema and SQLQuack version.""" + + _WORK.use_cache_dir(directory) + + +def converted( + *, sql: str, schema: Mapping[str, Any] | None, time_zone: str | None, path: str +) -> ConvertedSql: + """SQLQuack's conversion of `sql`: DuckDB SQL and its macros, or the refusals.""" + + conversion: ConvertedSql | None = local_check( + sql=sql, schema=schema, time_zone=time_zone, path=path + ).conversion + if conversion is None: + raise ExecutorInputError(f"SQL checked for conversion was not converted: {path}") + return conversion + + +def local_check( + *, + sql: str, + schema: Mapping[str, Any] | None, + time_zone: str | None, + path: str, + convert: bool = True, +) -> LocalSqlCheck: + """`sql` converted when `convert`, else the first relation an empty DuckDB lacks for it.""" + + key: _CheckKey = _key(sql=sql, schema=schema, time_zone=time_zone, convert=convert) + cached: LocalSqlCheck | None = _WORK.get(key) + if cached is not None: + return cached + job: _CheckJob = ( + sql, + _WORK.statement_schema(schema=schema, sql=sql), + _session(time_zone=time_zone), + convert, + ) + stored: LocalSqlCheck | None = _stored(job) + if stored is not None: + _WORK.store(checks={key: stored}, counts={"cached": 1}) + return stored + check: LocalSqlCheck = _check(job=job, empty=_WORK.empty(), path=path) + _keep(job=job, check=check) + _WORK.store(checks={key: check}, counts=_check_counts(check)) + return check + + +def check_all( + *, + sqls: Sequence[str], + schema: Mapping[str, Any] | None, + time_zone: str | None, + convert: bool, +) -> int: + """Check in worker processes every statement not checked yet; how many they checked.""" + + missing: list[_CheckKey] = _WORK.missing( + [_key(sql=sql, schema=schema, time_zone=time_zone, convert=convert) for sql in sqls] + ) + jobs_by_key: dict[_CheckKey, _CheckJob] = { + key: ( + key[0], + _WORK.statement_schema(schema=schema, sql=key[0]), + _session(time_zone=time_zone), + convert, + ) + for key in missing + } + stored: dict[_CheckKey, LocalSqlCheck] = { + key: check for key, job in jobs_by_key.items() if (check := _stored(job)) is not None + } + _WORK.store(checks=stored, counts={"cached": len(stored)}) + missing = [key for key in missing if key not in stored] + workers: int = min(_MAX_WORKERS, os.cpu_count() or 1) + if len(missing) < _PARALLEL_MINIMUM or workers <= 1: + return 0 + jobs: list[_CheckJob] = [jobs_by_key[key] for key in missing] + with ProcessPoolExecutor( + max_workers=workers, mp_context=multiprocessing.get_context("spawn") + ) as pool: + results: list[LocalSqlCheck] = list( + pool.map( + _worker_check, + jobs, + chunksize=max(1, len(jobs) // (workers * _CHUNKS_PER_WORKER)), + ) + ) + totals: dict[str, int] = {"conversions": 0, "bindings": 0} + for job, check in zip(jobs, results, strict=True): + _keep(job=job, check=check) + for name, count in _check_counts(check).items(): + totals[name] += count + _WORK.store(checks=dict(zip(missing, results, strict=True)), counts=totals) + return len(results) + + +def warehouse_relations( + *, sql: str, schema: Mapping[str, Any] | None, conversion: ConvertedSql +) -> tuple[str, ...]: + """Declared relations the converted SQL names in full, not via a fixture CTE: warehouse-only.""" + + relations: Mapping[str, Any] = (_WORK.statement_schema(schema=schema, sql=sql) or {}).get( + "relations", {} + ) + return tuple( + relation for relation in sorted(relations) if _quoted_name(relation) in conversion.sql + ) + + +def _quoted_name(relation: str) -> str: + """`DB.SCHEMA.TABLE` as converted SQL names it: `"DB"."SCHEMA"."TABLE"`.""" + + parts: list[str] = ['"' + part.replace('"', '""') + '"' for part in relation.split(".")] + return ".".join(parts) + + +def _key( + *, sql: str, schema: Mapping[str, Any] | None, time_zone: str | None, convert: bool +) -> _CheckKey: + return (sql, _WORK.schema_key(schema), time_zone or UTC_TIME_ZONE, convert) + + +def _session(*, time_zone: str | None) -> dict[str, str]: + zone: str = time_zone or UTC_TIME_ZONE + return {} if zone == UTC_TIME_ZONE else {TIMEZONE_PARAMETER: zone} + + +def _check(*, job: _CheckJob, empty: EmptyDuckDb, path: str) -> LocalSqlCheck: + """Convert Snowflake SQL, whose unknown names SQLQuack refuses; bind DuckDB SQL as authored.""" + + sql, schema, session, convert = job + if not convert: + return LocalSqlCheck(conversion=None, missing=empty.missing_relation(sql=sql, macros=())) + conversion: Any = sqlquack.convert( + sql=sql, + options=ConvertOptions( + no_config=True, schema=schema, session=session, compact=True, bind_check=False + ), + path=path, + ) + return LocalSqlCheck( + conversion=ConvertedSql( + converted=conversion.converted, + sql=conversion.sql, + macros=tuple(conversion.macros), + refusals=tuple(conversion.report["refusals"]), + rendered=conversion.rendered, + ), + missing=None, + bound=False, + ) + + +def _cache_file(job: _CheckJob) -> Path | None: + """Where a conversion of `job` is kept: a file named by the hash of everything it reads.""" + + directory: Path | None = _WORK.cache_dir() + sql, schema, session, convert = job + if directory is None or not convert: + return None + digest: str = hashlib.sha256( + json.dumps( + [_CACHE_FORMAT, sqlquack.__version__, sql, schema, session], sort_keys=True + ).encode() + ).hexdigest() + return directory / digest[:2] / f"{digest}.json" + + +def _stored(job: _CheckJob) -> LocalSqlCheck | None: + """The kept conversion of `job`, if a readable one is there.""" + + path: Path | None = _cache_file(job) + if path is None: + return None + try: + kept: dict[str, Any] = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + _WORK.mark_used(path) + return LocalSqlCheck( + conversion=ConvertedSql( + converted=bool(kept["converted"]), + sql=str(kept["sql"]), + macros=tuple(kept["macros"]), + refusals=tuple(kept["refusals"]), + rendered=str(kept["rendered"]), + ), + missing=None, + bound=False, + ) + + +def _keep(*, job: _CheckJob, check: LocalSqlCheck) -> None: + """Write `check`'s conversion for later runs; a write that fails only loses the shortcut.""" + + path: Path | None = _cache_file(job) + if path is None or check.conversion is None: + return + conversion: ConvertedSql = check.conversion + partial: Path = path.with_suffix(f".{os.getpid()}.{threading.get_ident()}.tmp") + try: + path.parent.mkdir(parents=True, exist_ok=True) + partial.write_text( + json.dumps( + { + "converted": conversion.converted, + "sql": conversion.sql, + "macros": list(conversion.macros), + "refusals": list(conversion.refusals), + "rendered": conversion.rendered, + } + ), + encoding="utf-8", + ) + os.replace(partial, path) + except OSError: + partial.unlink(missing_ok=True) + return + _WORK.mark_used(path) + + +def prune_conversion_cache(*, now: float) -> int: + """Record this run's use of kept conversions, then delete those unused for a week; how many.""" + + directory: Path | None = _WORK.cache_dir() + used: set[str] = _WORK.take_used() + if directory is None or not directory.is_dir(): + return 0 + index: Path = directory / CONVERSION_CACHE_INDEX + last_used: dict[str, float] = {**_last_used(index), **dict.fromkeys(used, now)} + kept: dict[str, float] = {} + pruned: int = 0 + for entry in directory.glob("*/*.json"): + stamp: float = last_used.get(entry.stem, now) + if now - stamp <= CONVERSION_CACHE_LIFETIME_SECONDS: + kept[entry.stem] = stamp + continue + try: + entry.unlink() + except OSError: + kept[entry.stem] = stamp + continue + pruned += 1 + _write_last_used(index=index, last_used=kept) + return pruned + + +def _last_used(index: Path) -> dict[str, float]: + """When each kept conversion was last used, by entry name; empty when unreadable.""" + + try: + loaded: Any = json.loads(index.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + if not isinstance(loaded, dict): + return {} + return { + str(name): float(stamp) + for name, stamp in loaded.items() + if isinstance(stamp, int | float) and not isinstance(stamp, bool) + } + + +def _write_last_used(*, index: Path, last_used: Mapping[str, float]) -> None: + partial: Path = index.with_suffix(f".{os.getpid()}.{threading.get_ident()}.tmp") + try: + partial.write_text(json.dumps(last_used, sort_keys=True), encoding="utf-8") + os.replace(partial, index) + except OSError: + partial.unlink(missing_ok=True) + + +def _check_counts(check: LocalSqlCheck) -> dict[str, int]: + return { + "conversions": int(check.conversion is not None), + "bindings": int(check.bound), + } + + +def _worker_check(job: _CheckJob) -> LocalSqlCheck: + return _check(job=job, empty=_WORK.empty(), path=DEFAULT_PATH) diff --git a/src/sqlbuild/executor/local/_helpers/decisions.py b/src/sqlbuild/executor/local/_helpers/decisions.py new file mode 100644 index 0000000000..71705eb8fa --- /dev/null +++ b/src/sqlbuild/executor/local/_helpers/decisions.py @@ -0,0 +1,268 @@ +"""Each unit test's decision: local when DuckDB can run it, else the warehouse and why.""" + +from __future__ import annotations + +import json +from collections.abc import Mapping, Sequence +from dataclasses import asdict, replace +from pathlib import Path +from typing import Any + +from sqlbuild._native import SqlTestPlanEntry, render_sql_test_comparison_segments +from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter +from sqlbuild.executor.local._helpers.conversion import ( + check_all, + local_check, + use_conversion_cache, + warehouse_relations, +) +from sqlbuild.executor.local._helpers.positions import placed_refusal +from sqlbuild.executor.local._helpers.schema import project_schema +from sqlbuild.executor.local._helpers.session import session_time_zone +from sqlbuild.executor.local.constants import ( + CONVERSION_CACHE_DIR, + CONVERTED_DIALECT, + DIALECT_REASON_CATEGORY, + FUNCTION_REASON_CATEGORY, + LOCAL_DIALECT, + RELATION_REASON_CATEGORY, + RUN_ON_LOCAL, + RUN_ON_WAREHOUSE, +) +from sqlbuild.executor.local.models import ( + ConvertedSql, + DecisionContext, + LocalRefusal, + LocalSqlCheck, + RunOnDecision, + Segment, + TestSources, +) + + +def decision_context( + *, + project: Any, + test_entries: Sequence[SqlTestPlanEntry], + adapter: BaseAdapter, + run_on: str, + location: tuple[Path, Mapping[str, str]], +) -> DecisionContext: + """The project's functions and schema, and every convertible test's SQL, converted up front.""" + + dialect: str | None = adapter.sql_analysis_dialect() + context: DecisionContext = DecisionContext( + project=project, + dialect=dialect, + run_on=run_on, + set_difference_operator=adapter.render_set_difference_operator(), + functions={function.name: function for function in getattr(project, "functions", ())}, + schema={}, + time_zone=session_time_zone(project), + rendered={}, + project_dir=location[0], + compiled_paths=location[1], + ) + if run_on == RUN_ON_WAREHOUSE or dialect not in (CONVERTED_DIALECT, LOCAL_DIALECT): + return context + use_conversion_cache(location[0] / CONVERSION_CACHE_DIR) + rendered: dict[str, tuple[str, list[tuple[int, int, str]]]] = { + entry.name: _rendered(entry=entry, context=context) + for entry in test_entries + if not _blocking_functions(entry=entry, context=context) + } + schema: dict[str, Any] = project_schema(project) if dialect == CONVERTED_DIALECT else {} + _ = check_all( + sqls=[sql for sql, _segments in rendered.values()], + schema=schema, + time_zone=context.time_zone, + convert=dialect == CONVERTED_DIALECT, + ) + return replace(context, schema=schema, rendered=rendered) + + +def decide_each( + *, context: DecisionContext, test_entries: Sequence[SqlTestPlanEntry] +) -> tuple[RunOnDecision, ...]: + """Every test's decision from its checked SQL: converted, and bound in an empty DuckDB.""" + + return tuple(_decision(entry=entry, context=context) for entry in test_entries) + + +def decisions_json(decisions: Sequence[RunOnDecision]) -> str: + """The decisions as the JSON the test command reads.""" + + return json.dumps({"decisions": [_decision_payload(decision) for decision in decisions]}) + + +def _decision(*, entry: SqlTestPlanEntry, context: DecisionContext) -> RunOnDecision: + blocking: list[str] = _blocking_functions(entry=entry, context=context) + if context.run_on == RUN_ON_WAREHOUSE: + return RunOnDecision(name=entry.name, run_on=RUN_ON_WAREHOUSE) + if blocking: + return _function_decision(name=entry.name, blocking=blocking) + if context.dialect == LOCAL_DIALECT: + sql: str = context.rendered[entry.name][0] + missing: str | None = local_check( + sql=sql, schema=None, time_zone=context.time_zone, path="", convert=False + ).missing + return _bound_decision(name=entry.name, missing=missing) + if context.dialect != CONVERTED_DIALECT: + return _dialect_decision(name=entry.name, dialect=context.dialect) + return _converted_decision(entry=entry, context=context) + + +def _blocking_functions(*, entry: SqlTestPlanEntry, context: DecisionContext) -> list[str]: + """Functions the test calls whose temporary copy cannot be made in an empty DuckDB.""" + + return [ + key.name + for key in entry.function_deps + if context.dialect != LOCAL_DIALECT + or key.name not in context.functions + or context.functions[key.name].references + ] + + +def _rendered( + *, entry: SqlTestPlanEntry, context: DecisionContext +) -> tuple[str, list[tuple[int, int, str]]]: + return render_sql_test_comparison_segments( + entry, + set_difference_operator=context.set_difference_operator, + sql_analysis_dialect=context.dialect, + ) + + +def _function_decision(*, name: str, blocking: Sequence[str]) -> RunOnDecision: + return RunOnDecision( + name=name, + run_on=RUN_ON_WAREHOUSE, + refusals=tuple( + LocalRefusal( + category=FUNCTION_REASON_CATEGORY, + construct=function, + reason=( + f"the test calls project function {function}, whose temporary copy " + "needs the warehouse" + ), + ) + for function in blocking + ), + ) + + +def _dialect_decision(*, name: str, dialect: str | None) -> RunOnDecision: + return RunOnDecision( + name=name, + run_on=RUN_ON_WAREHOUSE, + refusals=( + LocalRefusal( + category=DIALECT_REASON_CATEGORY, + construct=str(dialect), + reason=f"SQLQuack converts Snowflake SQL only, not {dialect}", + ), + ), + ) + + +def _converted_decision(*, entry: SqlTestPlanEntry, context: DecisionContext) -> RunOnDecision: + sql: str = context.rendered[entry.name][0] + check: LocalSqlCheck = local_check( + sql=sql, + schema=context.schema, + time_zone=context.time_zone, + path=context.compiled_paths.get(entry.name, ""), + ) + conversion: ConvertedSql | None = check.conversion + if conversion is None: + return _bound_decision(name=entry.name, missing=check.missing) + if conversion.converted: + return _relations_decision( + name=entry.name, + relations=warehouse_relations(sql=sql, schema=context.schema, conversion=conversion), + ) + sources: TestSources = _test_sources(entry=entry, context=context) + return RunOnDecision( + name=entry.name, + run_on=RUN_ON_WAREHOUSE, + refusals=tuple( + placed_refusal(refusal=refusal, sources=sources) for refusal in conversion.refusals + ), + ) + + +def _test_sources(*, entry: SqlTestPlanEntry, context: DecisionContext) -> TestSources: + """What the test's comparison SQL was built from, to place refusals back in those files.""" + + sql, segments = context.rendered[entry.name] + test_path, test_text = _test_file(entry=entry, project_dir=context.project_dir) + return TestSources( + sql=sql, + segments=tuple( + Segment(start=start, end=end, origin=origin) for start, end, origin in segments + ), + test_path=test_path, + test_text=test_text, + compiled_path=context.compiled_paths.get(entry.name, ""), + mocked_models=frozenset(entry.mock_ref_names), + models={model.name: model for model in getattr(context.project, "models", ())}, + chain_sql={step.model_name: step.resolved_sql for step in entry.chain}, + dialect=CONVERTED_DIALECT, + ) + + +def _test_file(*, entry: SqlTestPlanEntry, project_dir: Path) -> tuple[str | None, str | None]: + """The test file's project-relative path and text, when it can be read.""" + + if entry.source_path is None: + return None, None + source: Path = Path(entry.source_path) + absolute: Path = source if source.is_absolute() else project_dir / source + relative: str = ( + absolute.relative_to(project_dir).as_posix() + if absolute.is_relative_to(project_dir) + else absolute.as_posix() + ) + try: + return relative, absolute.read_text(encoding="utf-8") + except OSError: + return relative, None + + +def _bound_decision(*, name: str, missing: str | None) -> RunOnDecision: + """Local, unless the test reads a relation only the warehouse has.""" + + return _relations_decision(name=name, relations=() if missing is None else (missing,)) + + +def _relations_decision(*, name: str, relations: Sequence[str]) -> RunOnDecision: + """Local, unless the test reads relations only the warehouse has: one refusal for each.""" + + if not relations: + return RunOnDecision(name=name, run_on=RUN_ON_LOCAL) + return RunOnDecision( + name=name, + run_on=RUN_ON_WAREHOUSE, + refusals=tuple( + LocalRefusal( + category=RELATION_REASON_CATEGORY, + construct=relation, + reason=f"the test reads {relation}, which only the warehouse has", + ) + for relation in relations + ), + ) + + +def _decision_payload(decision: RunOnDecision) -> dict[str, Any]: + return { + "name": decision.name, + "run_on": decision.run_on, + "reason": decision.reason, + "refusals": [_refusal_payload(refusal) for refusal in decision.refusals], + } + + +def _refusal_payload(refusal: LocalRefusal) -> dict[str, Any]: + return {**asdict(refusal), "title": refusal.title} diff --git a/src/sqlbuild/executor/local/_helpers/positions.py b/src/sqlbuild/executor/local/_helpers/positions.py new file mode 100644 index 0000000000..2d57b14dae --- /dev/null +++ b/src/sqlbuild/executor/local/_helpers/positions.py @@ -0,0 +1,269 @@ +"""Place a refusal in a unit test's comparison SQL back in the model or test file that holds it.""" + +from __future__ import annotations + +import difflib +import re +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +from sqlbuild._native import SqlDocument +from sqlbuild.executor.local.constants import ( + SQLBUILD_SOURCES_HELP, + SQLQUACK_SOURCES_HELP, + STATEMENT_CONSTRUCT, +) +from sqlbuild.executor.local.models import LocalRefusal, Segment, TestSources + +_MODEL_ORIGIN: re.Pattern[str] = re.compile(r"^model '(?P.+)'$") +_SIMILAR_LINE_RATIO: float = 0.6 +_EQUAL_OPCODE: str = "equal" +_MACRO_CALL: re.Pattern[str] = re.compile(r"@(?:py|sql)\.[A-Za-z_][A-Za-z0-9_.]*") + + +@dataclass(frozen=True) +class _Place: + path: str + line: int + column: int + snippet: str + expanded: bool = False + snippet_column: int | None = None + expanded_from: str | None = None + + +def placed_refusal(*, refusal: Mapping[str, Any], sources: TestSources) -> LocalRefusal: + """One SQLQuack refusal as a diagnostic in the model or test file, or the compiled test file.""" + + span: Mapping[str, int] | None = refusal.get("span") + place: _Place | None = None + width: int = 1 + if span is not None: + start: int = int(span["start"]) + end: int = max(int(span["end"]), start + 1) + refused: str = sources.sql[start:end] + width = max(1, len(refused.split("\n", 1)[0])) + place = _place(start=start, refused=refused, sources=sources) + help_text: str | None = refusal.get("help") + if help_text is not None: + help_text = help_text.replace(SQLQUACK_SOURCES_HELP, SQLBUILD_SOURCES_HELP) + return LocalRefusal( + category=str(refusal.get("category", "")), + construct=str(refusal.get("construct") or STATEMENT_CONSTRUCT), + reason=str(refusal.get("reason", "")), + code=refusal.get("code"), + message=refusal.get("message"), + label=refusal.get("label"), + notes=tuple(refusal.get("notes") or ()), + help=help_text, + path=None if place is None else place.path, + line=None if place is None else place.line, + column=None if place is None else place.column, + width=width, + snippet=None if place is None else place.snippet, + snippet_column=None if place is None else place.snippet_column, + expanded_from=None if place is None else place.expanded_from, + ) + + +def file_placed_refusal( + *, refusal: Mapping[str, Any], sql: str, file: tuple[str, str] | None +) -> dict[str, Any]: + """A refusal of converted `sql` placed in `file` (path, text) where its text appears there.""" + + placed: dict[str, Any] = dict(refusal) + help_text: str | None = refusal.get("help") + if help_text is not None: + placed["help"] = help_text.replace(SQLQUACK_SOURCES_HELP, SQLBUILD_SOURCES_HELP) + span: Mapping[str, int] | None = refusal.get("span") + if span is None or file is None: + return placed + start: int = int(span["start"]) + end: int = max(int(span["end"]), start + 1) + refused: str = sql[start:end].split("\n", 1)[0] + line, column = _line_column(text=sql, offset=start) + path, text = file + place: _Place | None = _token_place( + path=path, text=text, token=refused, near=line + ) or _similar_line_place( + path=path, text=text, line_text=_line_text(text=sql, line=line), column=column + ) + if place is None: + return placed + placed.update( + path=place.path, + line=place.line, + column=place.column, + width=max(1, len(refused)), + snippet=place.snippet, + ) + return placed + + +def _place(*, start: int, refused: str, sources: TestSources) -> _Place: + segment: Segment | None = next( + (item for item in sources.segments if item.start <= start < item.end), None + ) + if segment is not None: + body: str = sources.sql[segment.start : segment.end] + offset: int = start - segment.start + match: re.Match[str] | None = _MODEL_ORIGIN.match(segment.origin) + if match is not None and match["name"] not in sources.mocked_models: + placed: _Place | None = _model_place( + name=match["name"], body=body, offset=offset, refused=refused, sources=sources + ) + if placed is not None: + return placed + elif sources.test_text is not None and sources.test_path is not None: + placed = _text_place( + path=sources.test_path, text=sources.test_text, body=body, offset=offset + ) or _similar_line_place( + path=sources.test_path, + text=sources.test_text, + line_text=_line_text(text=body, line=_line_column(text=body, offset=offset)[0]), + column=_line_column(text=body, offset=offset)[1], + ) + if placed is not None: + return placed + line, column = _line_column(text=sources.sql, offset=start) + return _Place( + path=sources.compiled_path, + line=line, + column=column, + snippet=_line_text(text=sources.sql, line=line), + ) + + +def _model_place( + *, name: str, body: str, offset: int, refused: str, sources: TestSources +) -> _Place | None: + """The model file position of `offset` in a body lifted from the model's resolved SQL.""" + + model: Any = sources.models.get(name) + if model is None: + return None + body_line, column = _line_column(text=body, offset=offset) + line_text: str = _line_text(text=body, line=body_line) + resolved: str = sources.chain_sql.get(name) or "" + at: int = resolved.find(body) + line: int = _line_column(text=resolved, offset=at + offset)[0] if at >= 0 else body_line + authored: str = model.authored_sql + path: str = Path(model.relative_path).as_posix() + token: str = refused.split("\n", 1)[0] + found: _Place | None = _token_place(path=path, text=authored, token=token, near=line) + if found is not None: + return found + expanded: _Place | None = _expanded_place( + model=model, path=path, line_text=line_text, token=token, sources=sources + ) + if expanded is not None and expanded.expanded_from is not None: + return expanded + return ( + _similar_line_place(path=path, text=authored, line_text=line_text, column=column) + or expanded + ) + + +def _expanded_place( + *, model: Any, path: str, line_text: str, token: str, sources: TestSources +) -> _Place | None: + """The macro call that generated `line_text`, showing the generated SQL as the snippet.""" + + query: str = model.query_sql + query_lines: list[str] = query.split("\n") + wanted: str = line_text.strip() + query_line: int | None = next( + (index for index, text in enumerate(query_lines, start=1) if text.strip() == wanted), + None, + ) + if query_line is None: + return None + generated: str = query_lines[query_line - 1] + found: int = generated.find(token) if token else -1 + snippet_column: int = found + 1 if found >= 0 else len(generated) - len(generated.lstrip()) + 1 + document: SqlDocument = SqlDocument( + source=query, dialect=sources.dialect, place=model.query_place, file=model.authored_sql + ) + mapped: tuple[int, int] | None = document.file_position( + node=SimpleNamespace(line=query_line, column=snippet_column) + ) + if mapped is None: + return None + call_line, call_column = int(mapped[0]), int(mapped[1]) + call: re.Match[str] | None = _MACRO_CALL.match( + _line_text(text=model.authored_sql, line=call_line)[call_column - 1 :] + ) + return _Place( + path=path, + line=call_line, + column=call_column, + snippet=generated, + expanded=True, + snippet_column=snippet_column, + expanded_from=None + if call is None + else f"{call.group(0)} at {path}:{call_line}:{call_column}", + ) + + +def _token_place(*, path: str, text: str, token: str, near: int) -> _Place | None: + """The occurrence of `token` in `text` nearest line `near`; `None` when it does not appear.""" + + if not token.strip(): + return None + starts: list[int] = [match.start() for match in re.finditer(re.escape(token), text)] + if not starts: + return None + placed: list[tuple[int, int]] = [_line_column(text=text, offset=start) for start in starts] + line, column = min(placed, key=lambda position: abs(position[0] - near)) + return _Place(path=path, line=line, column=column, snippet=_line_text(text=text, line=line)) + + +def _similar_line_place(*, path: str, text: str, line_text: str, column: int) -> _Place | None: + """The line of `text` most like `line_text`, with `column` carried across the differences.""" + + wanted: str = line_text.strip() + if not wanted: + return None + best: tuple[float, int] = (0.0, 0) + for index, candidate in enumerate(text.split("\n"), start=1): + ratio: float = difflib.SequenceMatcher(None, wanted, candidate.strip()).ratio() + if ratio > best[0]: + best = (ratio, index) + if best[0] < _SIMILAR_LINE_RATIO: + return None + target: str = _line_text(text=text, line=best[1]) + matcher: difflib.SequenceMatcher[str] = difflib.SequenceMatcher(None, line_text, target) + mapped: int = column - 1 + for tag, start, end, target_start, target_end in matcher.get_opcodes(): + if start <= column - 1 < end or (start == end == column - 1): + mapped = target_start + (column - 1 - start) if tag == _EQUAL_OPCODE else target_start + mapped = min(mapped, max(target_end - 1, target_start)) + break + return _Place(path=path, line=best[1], column=mapped + 1, snippet=target) + + +def _text_place(*, path: str, text: str, body: str, offset: int) -> _Place | None: + """The position of `offset` in `body` where `body` appears verbatim in `text`.""" + + at: int = text.find(body.strip()) + if at < 0: + return None + at += offset - (len(body) - len(body.lstrip())) + line, column = _line_column(text=text, offset=max(at, 0)) + return _Place(path=path, line=line, column=column, snippet=_line_text(text=text, line=line)) + + +def _line_column(*, text: str, offset: int) -> tuple[int, int]: + before: str = text[:offset] + line: int = before.count("\n") + 1 + column: int = offset - (before.rfind("\n") + 1) + 1 + return line, column + + +def _line_text(*, text: str, line: int) -> str: + lines: list[str] = text.split("\n") + return lines[line - 1] if 0 < line <= len(lines) else "" diff --git a/src/sqlbuild/executor/local/_helpers/runtime.py b/src/sqlbuild/executor/local/_helpers/runtime.py new file mode 100644 index 0000000000..a364f22c07 --- /dev/null +++ b/src/sqlbuild/executor/local/_helpers/runtime.py @@ -0,0 +1,63 @@ +"""Failures of converted SQL in DuckDB that the warehouse would not have: guards and engine bugs.""" + +from __future__ import annotations + +import re + +from sqlbuild.errors.contracts.exceptions import LocalRunRefusedError +from sqlbuild.executor.local.constants import ( + CANNOT_RUN_LOCALLY_HELP, + DUCKDB_ERROR_CATEGORY, + GUARD_CATEGORY, +) + +_GUARD_RAISE: re.Pattern[str] = re.compile(r"'([a-z][a-z0-9_]*)#(?:[0-9a-f]{12}|\?): ([^']*)") +_INTERNAL_PREFIX: re.Pattern[str] = re.compile(r"^\s*INTERNAL Error:\s*") +_INTERNAL_MARKER: re.Pattern[str] = re.compile(r"INTERNAL Error:\s*") +_CONSTRUCT_WIDTH: int = 80 +_INTERNAL_EXCEPTION: str = "InternalException" + + +def local_run_refusal(*, error: Exception, fatal: bool) -> LocalRunRefusedError | None: + """Why a SQLQuack guard's raise or DuckDB internal error keeps a test off DuckDB, or None.""" + + message: str = str(error) + guarded: LocalRunRefusedError | None = _guard_refusal(message) + if guarded is not None: + return guarded + if not fatal or type(error).__name__ != _INTERNAL_EXCEPTION: + return None + return _internal_refusal(_INTERNAL_PREFIX.sub("", message)) + + +def local_failure_refusal(message: str) -> LocalRunRefusedError | None: + """`local_run_refusal` for a failure known only by its text, as a scenario step reports it.""" + + guarded: LocalRunRefusedError | None = _guard_refusal(message) + if guarded is not None: + return guarded + internal: re.Match[str] | None = _INTERNAL_MARKER.search(message) + return None if internal is None else _internal_refusal(message[internal.end() :]) + + +def _guard_refusal(message: str) -> LocalRunRefusedError | None: + raised: re.Match[str] | None = _GUARD_RAISE.search(message) + if raised is None: + return None + guard: str = raised.group(1) + return LocalRunRefusedError( + f"SQLQuack's guard {guard} raised in DuckDB: {raised.group(2)}", + category=GUARD_CATEGORY, + construct=guard, + help=CANNOT_RUN_LOCALLY_HELP, + ) + + +def _internal_refusal(message: str) -> LocalRunRefusedError: + first: str = message.splitlines()[0].strip() if message else "" + return LocalRunRefusedError( + f"DuckDB failed on the converted SQL: {first}", + category=DUCKDB_ERROR_CATEGORY, + construct=first[:_CONSTRUCT_WIDTH] or "internal error", + help=CANNOT_RUN_LOCALLY_HELP, + ) diff --git a/src/sqlbuild/executor/local/_helpers/schema.py b/src/sqlbuild/executor/local/_helpers/schema.py new file mode 100644 index 0000000000..73fad1c5ad --- /dev/null +++ b/src/sqlbuild/executor/local/_helpers/schema.py @@ -0,0 +1,63 @@ +"""The project's declared relations and column types, as SQLQuack's schema option takes them.""" + +from __future__ import annotations + +from collections.abc import Iterable +from typing import Any + + +def project_schema(project: Any) -> dict[str, Any]: + """Sources, seeds and models with typed columns, keyed by their Snowflake-resolved names.""" + + relations: dict[str, list[list[str]]] = {} + for source in getattr(project, "sources", ()): + entry: Any = source.source_entry + relations.update( + _typed_relation( + parts=(entry.database, entry.schema, entry.table or entry.name), + columns=((column.name, getattr(column, "type", None)) for column in entry.columns), + ) + ) + for seed in getattr(project, "seeds", ()): + destination: Any = seed.destination + relations.update( + _typed_relation( + parts=(destination.database, destination.schema, destination.name), + columns=((column.name, column.type) for column in seed.schema_entry.columns), + ) + ) + for model in getattr(project, "models", ()): + schema_entry: Any = model.schema_entry + if schema_entry is None: + continue + destination = model.destination + relations.update( + _typed_relation( + parts=(destination.database, destination.schema, destination.name), + columns=((column.name, column.type) for column in schema_entry.columns), + ) + ) + return {"relations": relations} + + +def _typed_relation( + *, parts: tuple[str | None, ...], columns: Iterable[tuple[str, str | None]] +) -> dict[str, list[list[str]]]: + """One relation keyed by its resolved name when every column has a declared type, else none.""" + + typed: list[list[str]] = [] + for name, column_type in columns: + if not column_type: + return {} + typed.append([_resolved(name), column_type]) + if not typed: + return {} + return {".".join(_resolved(part) for part in parts if part): typed} + + +def _resolved(name: str) -> str: + """An identifier as Snowflake resolves it: quoted keeps its case, unquoted is upper case.""" + + if len(name) > 1 and name.startswith('"') and name.endswith('"'): + return name[1:-1] + return name.upper() diff --git a/src/sqlbuild/executor/local/_helpers/session.py b/src/sqlbuild/executor/local/_helpers/session.py new file mode 100644 index 0000000000..fbbc95add4 --- /dev/null +++ b/src/sqlbuild/executor/local/_helpers/session.py @@ -0,0 +1,21 @@ +"""The session time zone a target's warehouse connection sets.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from sqlbuild.executor.local.constants import SESSION_PARAMETERS_KEY, TIMEZONE_PARAMETER + + +def session_time_zone(project: Any) -> str | None: + """The `TIMEZONE` session parameter the target's connection sets; `None` when unset.""" + + connection: Mapping[str, Any] = getattr(project, "effective_connection", None) or {} + parameters: Any = connection.get(SESSION_PARAMETERS_KEY) or {} + if not isinstance(parameters, Mapping): + return None + for key, value in parameters.items(): + if str(key).upper() == TIMEZONE_PARAMETER and value: + return str(value) + return None diff --git a/src/sqlbuild/executor/local/classes/__init__.py b/src/sqlbuild/executor/local/classes/__init__.py new file mode 100644 index 0000000000..b828822408 --- /dev/null +++ b/src/sqlbuild/executor/local/classes/__init__.py @@ -0,0 +1 @@ +"""Local run classes package.""" diff --git a/src/sqlbuild/executor/local/classes/empty_duckdb.py b/src/sqlbuild/executor/local/classes/empty_duckdb.py new file mode 100644 index 0000000000..3e7b89ce7f --- /dev/null +++ b/src/sqlbuild/executor/local/classes/empty_duckdb.py @@ -0,0 +1,52 @@ +"""An empty in-memory DuckDB that finds the first relation a test's SQL reads and lacks.""" + +from __future__ import annotations + +import re +import threading +from collections.abc import Sequence +from typing import Any + +_PROBE: str = "__sqb_local_probe" +_MISSING_TABLE: re.Pattern[str] = re.compile(r"Table with name (\S+) does not exist") + + +class EmptyDuckDb: + """An in-memory DuckDB with nothing in it, to bind test SQL before deciding where it runs.""" + + def __init__(self) -> None: + import duckdb + + self._connection: Any = duckdb.connect(database=":memory:") + self._macros: set[str] = set() + self._lock: threading.Lock = threading.Lock() + + def missing_relation(self, *, sql: str, macros: Sequence[str]) -> str | None: + """The first relation `sql` reads that an empty database lacks; `None` when it binds.""" + + with self._lock: + return self._missing_relation(sql=sql, macros=macros) + + def _missing_relation(self, *, sql: str, macros: Sequence[str]) -> str | None: + import duckdb + + for macro in macros: + if macro in self._macros: + continue + self._macros.add(macro) + try: + _ = self._connection.execute(macro) + except duckdb.Error: + return None + try: + _ = self._connection.execute(f"PREPARE {_PROBE} AS {sql}") + _ = self._connection.execute(f"DEALLOCATE {_PROBE}") + except duckdb.CatalogException as error: + match: re.Match[str] | None = _MISSING_TABLE.search(str(error)) + return None if match is None else match.group(1) + except duckdb.Error: + return None + return None + + def close(self) -> None: + self._connection.close() diff --git a/src/sqlbuild/executor/local/classes/local_test_adapter.py b/src/sqlbuild/executor/local/classes/local_test_adapter.py new file mode 100644 index 0000000000..70ed2e9330 --- /dev/null +++ b/src/sqlbuild/executor/local/classes/local_test_adapter.py @@ -0,0 +1,120 @@ +"""A run-scoped in-memory DuckDB that runs a project's unit test SQL, converted by SQLQuack.""" + +from __future__ import annotations + +import threading +from collections.abc import Mapping +from typing import Any + +from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter +from sqlbuild.adapters.duckdb.classes.duckdb_adapter import DuckDbAdapter +from sqlbuild.errors.contracts.exceptions import ExecutorInputError, LocalRunRefusedError +from sqlbuild.executor.local._helpers.conversion import converted +from sqlbuild.executor.local._helpers.runtime import local_run_refusal +from sqlbuild.executor.local.constants import ( + CANNOT_RUN_LOCALLY_CODE, + CANNOT_RUN_LOCALLY_HELP, + CONVERTED_DIALECT, + UTC_TIME_ZONE, +) +from sqlbuild.executor.local.models import ConvertedSql +from sqlbuild.runtime.observability.classes.statement_lifecycle import StatementLifecycle +from sqlbuild.runtime.observability.constants import LOCAL_RUN_ON + +_UTC_SESSION_SQL: str = f"SET TimeZone = '{UTC_TIME_ZONE}'" +_INVALIDATED_MARKER: str = "database has been invalidated" +_FATAL_ERRORS: frozenset[str] = frozenset({"FatalException", "InternalException"}) + + +class LocalTestAdapter(DuckDbAdapter): + """Renders test SQL as the project's adapter does and runs it in DuckDB after conversion.""" + + def __init__( + self, + *, + project_adapter: BaseAdapter, + schema: Mapping[str, Any] | None, + time_zone: str | None, + ) -> None: + super().__init__() + self._project_adapter: BaseAdapter = project_adapter + self._dialect: str | None = project_adapter.sql_analysis_dialect() + self._schema: Mapping[str, Any] | None = schema + self._time_zone: str | None = time_zone + self._macros_lock: threading.Lock = threading.Lock() + self._macros: dict[int, set[str]] = {} + + def sql_analysis_dialect(self) -> str | None: + return self._dialect + + def render_set_difference_operator(self) -> str: + return self._project_adapter.render_set_difference_operator() + + def create_sql_test_output(self, *, connection: Any, sql: str, name: str) -> str | None: + """Compare inline: each comparison converts as one statement.""" + + del connection, sql, name + return None + + def connect(self, config: dict[str, Any]) -> Any: + connection: Any = super().connect(config) + with StatementLifecycle.run_on_scope(LOCAL_RUN_ON): + _ = super().execute(connection=connection, sql=_UTC_SESSION_SQL) + return connection + + def execute(self, *, connection: Any, sql: str) -> Any: + try: + with StatementLifecycle.run_on_scope(LOCAL_RUN_ON): + return self._converted_execute(connection=connection, sql=sql) + except Exception as error: + fatal: bool = _INVALIDATED_MARKER in str(error) or type(error).__name__ in _FATAL_ERRORS + if fatal: + self._reopen(connection) + refused: LocalRunRefusedError | None = ( + local_run_refusal(error=error, fatal=fatal) + if self._dialect == CONVERTED_DIALECT + else None + ) + if refused is not None: + raise refused from error + raise + + def _reopen(self, connection: Any) -> None: + """Replace a run-scoped database DuckDB invalidated, so later tests get a working one.""" + + import duckdb + + object.__setattr__(connection, "raw_connection", duckdb.connect(database=":memory:")) + with self._macros_lock: + self._macros.pop(id(connection), None) + with StatementLifecycle.run_on_scope(LOCAL_RUN_ON): + _ = super().execute(connection=connection, sql=_UTC_SESSION_SQL) + + def _converted_execute(self, *, connection: Any, sql: str) -> Any: + if self._dialect != CONVERTED_DIALECT or sql == _UTC_SESSION_SQL: + return super().execute(connection=connection, sql=sql) + conversion: ConvertedSql = converted( + sql=sql, schema=self._schema, time_zone=self._time_zone, path="test.sql" + ) + if not conversion.converted: + raise ExecutorInputError( + "SQLQuack refused SQL the local test run needed: " + + "; ".join( + f"{refusal.get('code')}: {refusal.get('label')}" + for refusal in conversion.refusals + ), + code=CANNOT_RUN_LOCALLY_CODE, + help=CANNOT_RUN_LOCALLY_HELP, + ) + self._install_macros(connection=connection, macros=conversion.macros) + return super().execute(connection=connection, sql=conversion.sql) + + def _install_macros(self, *, connection: Any, macros: tuple[str, ...]) -> None: + """Run the helper macros converted SQL calls, once per connection.""" + + with self._macros_lock: + installed: set[str] = self._macros.setdefault(id(connection), set()) + missing: list[str] = [macro for macro in macros if macro not in installed] + installed.update(missing) + for macro in missing: + _ = super().execute(connection=connection, sql=macro) diff --git a/src/sqlbuild/executor/local/constants.py b/src/sqlbuild/executor/local/constants.py new file mode 100644 index 0000000000..7dea221721 --- /dev/null +++ b/src/sqlbuild/executor/local/constants.py @@ -0,0 +1,34 @@ +"""Where tests and scenarios run, SQLBuild's own reasons, and the SQLQuack vocabulary they read.""" + +from __future__ import annotations + +RUN_ON_LOCAL: str = "local" +RUN_ON_WAREHOUSE: str = "warehouse" + +LOCAL_DIALECT: str = "duckdb" +CONVERTED_DIALECT: str = "snowflake" + +DIALECT_REASON_CATEGORY: str = "dialect" +FUNCTION_REASON_CATEGORY: str = "project function" +RELATION_REASON_CATEGORY: str = "warehouse relation" +SNAPSHOT_MISSING_CATEGORY: str = "snapshot missing" +SNAPSHOT_STALE_CATEGORY: str = "snapshot stale" +SNAPSHOT_INVALID_CATEGORY: str = "snapshot invalid" + +SQLQUACK_SOURCES_HELP: str = "a source file of the project (`sources/*.yml`)" +SQLBUILD_SOURCES_HELP: str = "a source file of the project (`sql/sources/`)" + +TIMEZONE_PARAMETER: str = "TIMEZONE" +SESSION_PARAMETERS_KEY: str = "session_parameters" +UTC_TIME_ZONE: str = "UTC" + +STATEMENT_CONSTRUCT: str = "statement" + +CONVERSION_CACHE_DIR: str = "target/sqlquack-cache" +CONVERSION_CACHE_INDEX: str = "used.json" +CONVERSION_CACHE_LIFETIME_SECONDS: float = 7 * 24 * 60 * 60 + +CANNOT_RUN_LOCALLY_CODE: str = "T007" +CANNOT_RUN_LOCALLY_HELP: str = "Run this test on the warehouse with --run-on warehouse." +GUARD_CATEGORY: str = "SQLQuack guard" +DUCKDB_ERROR_CATEGORY: str = "DuckDB internal error" diff --git a/src/sqlbuild/executor/local/main/__init__.py b/src/sqlbuild/executor/local/main/__init__.py new file mode 100644 index 0000000000..81087946db --- /dev/null +++ b/src/sqlbuild/executor/local/main/__init__.py @@ -0,0 +1 @@ +"""Local run main package.""" diff --git a/src/sqlbuild/executor/local/main/_convert_local_sql.py b/src/sqlbuild/executor/local/main/_convert_local_sql.py new file mode 100644 index 0000000000..64fdb8c736 --- /dev/null +++ b/src/sqlbuild/executor/local/main/_convert_local_sql.py @@ -0,0 +1,21 @@ +"""SQLQuack's DuckDB conversion of Snowflake SQL, for scenarios replayed locally.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from sqlbuild.executor.local._helpers.conversion import converted +from sqlbuild.executor.local._helpers.positions import ( + file_placed_refusal as file_placed_refusal, +) +from sqlbuild.executor.local._helpers.session import session_time_zone as session_time_zone +from sqlbuild.executor.local.models import ConvertedSql + + +def convert_local_sql( + *, sql: str, schema: Mapping[str, Any] | None, time_zone: str | None, path: str +) -> ConvertedSql: + """SQLQuack's conversion of `sql` in the target's time zone: DuckDB SQL, or its refusals.""" + + return converted(sql=sql, schema=schema, time_zone=time_zone, path=path) diff --git a/src/sqlbuild/executor/local/main/_decide_sql_test_run_on.py b/src/sqlbuild/executor/local/main/_decide_sql_test_run_on.py new file mode 100644 index 0000000000..38750589cc --- /dev/null +++ b/src/sqlbuild/executor/local/main/_decide_sql_test_run_on.py @@ -0,0 +1,34 @@ +"""Where each unit test runs: locally in DuckDB when its SQL converts, else on the warehouse.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from pathlib import Path +from typing import Any + +from sqlbuild._native import SqlTestPlanEntry +from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter +from sqlbuild.executor.local._helpers.decisions import decide_each, decision_context, decisions_json +from sqlbuild.executor.local.models import DecisionContext, RunOnDecision + + +def decide_sql_test_run_on( + *, + project: Any, + test_entries: Sequence[SqlTestPlanEntry], + adapter: BaseAdapter, + project_dir: Path, + compiled_paths: Mapping[str, str], + run_on: str, +) -> str: + """Each test's decision as JSON: `run_on`, `reason` and the refusals behind it.""" + + context: DecisionContext = decision_context( + project=project, + test_entries=test_entries, + adapter=adapter, + run_on=run_on, + location=(project_dir, compiled_paths), + ) + decisions: tuple[RunOnDecision, ...] = decide_each(context=context, test_entries=test_entries) + return decisions_json(decisions) diff --git a/src/sqlbuild/executor/local/main/_local_failure_refusal.py b/src/sqlbuild/executor/local/main/_local_failure_refusal.py new file mode 100644 index 0000000000..d02c0a0e94 --- /dev/null +++ b/src/sqlbuild/executor/local/main/_local_failure_refusal.py @@ -0,0 +1,12 @@ +"""Why a failure of converted SQL, known only by its text, keeps a run off DuckDB.""" + +from __future__ import annotations + +from sqlbuild.errors.contracts.exceptions import LocalRunRefusedError +from sqlbuild.executor.local._helpers.runtime import local_failure_refusal as _refusal + + +def local_failure_refusal(message: str) -> LocalRunRefusedError | None: + """A SQLQuack guard's raise or DuckDB internal error in `message`, or None.""" + + return _refusal(message) diff --git a/src/sqlbuild/executor/local/main/_local_test_adapter.py b/src/sqlbuild/executor/local/main/_local_test_adapter.py new file mode 100644 index 0000000000..553c6fd3b7 --- /dev/null +++ b/src/sqlbuild/executor/local/main/_local_test_adapter.py @@ -0,0 +1,22 @@ +"""The in-memory DuckDB adapter that runs a project's local unit tests.""" + +from __future__ import annotations + +from typing import Any + +from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter +from sqlbuild.executor.local._helpers.schema import project_schema +from sqlbuild.executor.local._helpers.session import session_time_zone +from sqlbuild.executor.local.classes.local_test_adapter import LocalTestAdapter +from sqlbuild.executor.local.constants import CONVERTED_DIALECT + + +def local_test_adapter(*, project: Any, adapter: BaseAdapter) -> LocalTestAdapter: + """The in-memory DuckDB adapter that runs the project's local unit tests.""" + + dialect: str | None = adapter.sql_analysis_dialect() + return LocalTestAdapter( + project_adapter=adapter, + schema=project_schema(project) if dialect == CONVERTED_DIALECT else None, + time_zone=session_time_zone(project), + ) diff --git a/src/sqlbuild/executor/local/main/_prune_local_conversion_cache.py b/src/sqlbuild/executor/local/main/_prune_local_conversion_cache.py new file mode 100644 index 0000000000..21633a28b9 --- /dev/null +++ b/src/sqlbuild/executor/local/main/_prune_local_conversion_cache.py @@ -0,0 +1,13 @@ +"""Drop the project's kept conversions that no run has used for a week.""" + +from __future__ import annotations + +import time + +from sqlbuild.executor.local._helpers.conversion import prune_conversion_cache + + +def prune_local_conversion_cache() -> int: + """At the end of a local run: record which conversions it used and prune stale ones.""" + + return prune_conversion_cache(now=time.time()) diff --git a/src/sqlbuild/executor/local/main/_report_unplaced_sql_tests.py b/src/sqlbuild/executor/local/main/_report_unplaced_sql_tests.py new file mode 100644 index 0000000000..72e63c8e9d --- /dev/null +++ b/src/sqlbuild/executor/local/main/_report_unplaced_sql_tests.py @@ -0,0 +1,68 @@ +"""Unit tests the run could not place, refused locally or with no warehouse, reported as errors.""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence + +from sqlbuild._native import SqlTestPlanEntry, sql_test_resource_id +from sqlbuild.executor.testing.models import SqlTestExecutionResult +from sqlbuild.executor.testing.types import SqlTestOutcome +from sqlbuild.runtime.observability.classes.resource_attempt_lifecycle import ( + ResourceAttemptLifecycle, +) + + +def report_unplaced_sql_tests( + *, + test_entries: Sequence[SqlTestPlanEntry], + code: str, + message: str, + run_id: str, + on_test_start: Callable[[SqlTestPlanEntry], None], + on_test_complete: Callable[[SqlTestExecutionResult], None], +) -> tuple[SqlTestExecutionResult, ...]: + """One ERROR result per test, each reported through its own resource attempt.""" + + results: list[SqlTestExecutionResult] = [] + for entry in test_entries: + with ResourceAttemptLifecycle( + resource_id=sql_test_resource_id( + test_name=entry.name, + source_path=entry.source_path, + block_index=entry.block_index, + case_name=entry.case_name, + ), + resource_kind="test", + resource_name=entry.name, + run_id=run_id, + ) as lifecycle: + on_test_start(entry) + result: SqlTestExecutionResult = _unplaced_result( + test_entry=entry, code=code, message=message + ) + lifecycle.failed(error_code=code) + on_test_complete(result) + results.append(result) + return tuple(results) + + +def _unplaced_result( + *, test_entry: SqlTestPlanEntry, code: str, message: str +) -> SqlTestExecutionResult: + """An ERROR result that names why the test did not run, with no warehouse or DuckDB work.""" + + return SqlTestExecutionResult( + test_name=test_entry.name, + outcome=SqlTestOutcome.ERROR, + source_path=test_entry.source_path, + block_index=test_entry.block_index, + parent_name=test_entry.parent_name, + case_name=test_entry.case_name, + case_index=test_entry.case_index, + case_fingerprint=test_entry.case_fingerprint, + parameter_schema=test_entry.parameter_schema, + parameter_values=test_entry.parameter_values, + error_code=code, + error_message=message, + real_model_count=test_entry.real_model_count, + ) diff --git a/src/sqlbuild/executor/local/main/_use_local_conversion_cache.py b/src/sqlbuild/executor/local/main/_use_local_conversion_cache.py new file mode 100644 index 0000000000..e97270e414 --- /dev/null +++ b/src/sqlbuild/executor/local/main/_use_local_conversion_cache.py @@ -0,0 +1,14 @@ +"""Where a project's local conversions are kept between runs.""" + +from __future__ import annotations + +from pathlib import Path + +from sqlbuild.executor.local._helpers.conversion import use_conversion_cache +from sqlbuild.executor.local.constants import CONVERSION_CACHE_DIR + + +def use_local_conversion_cache(project_dir: Path) -> None: + """Keep the project's conversions under its target directory across runs.""" + + _ = use_conversion_cache(project_dir / CONVERSION_CACHE_DIR) diff --git a/src/sqlbuild/executor/local/models.py b/src/sqlbuild/executor/local/models.py new file mode 100644 index 0000000000..ae9293876c --- /dev/null +++ b/src/sqlbuild/executor/local/models.py @@ -0,0 +1,120 @@ +"""Where one test or scenario runs, and why it cannot run locally.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + + +@dataclass(frozen=True) +class LocalRefusal: + """One SQLQuack refusal, or one of SQLBuild's own reasons, placed in the file that holds it.""" + + category: str + construct: str + reason: str + code: str | None = None + message: str | None = None + label: str | None = None + notes: tuple[str, ...] = field(default_factory=tuple) + help: str | None = None + path: str | None = None + line: int | None = None + column: int | None = None + width: int = 1 + snippet: str | None = None + snippet_column: int | None = None + expanded_from: str | None = None + + @property + def title(self) -> str: + """`: `, as SQLQuack's census labels a refusal.""" + + return f"{self.category}: {self.construct}" + + +@dataclass(frozen=True) +class RunOnDecision: + """Where one test or scenario runs: `local` or `warehouse`, and why not locally.""" + + name: str + run_on: str + refusals: tuple[LocalRefusal, ...] = field(default_factory=tuple) + + @property + def reason(self) -> str | None: + """The first refusal's label; `None` for a test that runs locally.""" + + return self.refusals[0].title if self.refusals else None + + +@dataclass(frozen=True) +class Segment: + """Where one CTE body sits in the comparison SQL, and what it stands for.""" + + start: int + end: int + origin: str + + +@dataclass(frozen=True) +class TestSources: + """What a unit test's comparison SQL was built from: its test file, models and compiled file.""" + + sql: str + segments: Sequence[Segment] + test_path: str | None + test_text: str | None + compiled_path: str + mocked_models: frozenset[str] + models: Mapping[str, Any] + chain_sql: Mapping[str, str] + dialect: str + + +@dataclass(frozen=True) +class DecisionContext: + """What deciding where each unit test runs reads: the project, its dialect and converted SQL.""" + + project: Any + dialect: str | None + run_on: str + set_difference_operator: str + functions: Mapping[str, Any] + schema: Mapping[str, Any] + time_zone: str | None + rendered: Mapping[str, tuple[str, list[tuple[int, int, str]]]] + project_dir: Path + compiled_paths: Mapping[str, str] + + +@dataclass(frozen=True) +class ConvertedSql: + """What SQLBuild keeps of a SQLQuack conversion: its DuckDB SQL and macros, or its refusals.""" + + converted: bool + sql: str + macros: tuple[str, ...] + refusals: tuple[Mapping[str, Any], ...] + rendered: str + + +@dataclass(frozen=True) +class LocalSqlCheck: + """One statement's SQLQuack conversion, when asked for, and the relation DuckDB lacks for it.""" + + conversion: ConvertedSql | None + missing: str | None + bound: bool = True + + +@dataclass(frozen=True) +class LocalWorkCounts: + """Work done to decide where tests run: conversions, DuckDB bindings, schema serialisations.""" + + conversions: int + bindings: int + schema_keys: int + cached: int = 0 diff --git a/src/sqlbuild/executor/pipeline/_helpers/graph_width.py b/src/sqlbuild/executor/pipeline/_helpers/graph_width.py index 53c776211f..b504deebf3 100644 --- a/src/sqlbuild/executor/pipeline/_helpers/graph_width.py +++ b/src/sqlbuild/executor/pipeline/_helpers/graph_width.py @@ -1,4 +1,4 @@ -"""Execution graph concurrency sizing.""" +"""Execution graph concurrency sizing, and whether a build's SQL phase runs anything.""" from __future__ import annotations @@ -14,3 +14,26 @@ def runnable_graph_width(*, plan: PlanOutput) -> int: default=1, ) return max(1, executable_node_count, microbatch_width) + + +def sql_phase_has_work(*, plan: PlanOutput) -> bool: + """Whether the SQL phase runs a node, audit, test, migration, retention or table change.""" + + return any( + ( + plan.execution_order, + plan.audit_entries, + plan.test_entries, + plan.migration_entries, + plan.column_migration_entries, + plan.retention_entries, + plan.old_name_view_entries, + plan.table_type_entries, + ) + ) + + +def sql_phase_concurrency(*, plan: PlanOutput, max_concurrency: int) -> int: + """The SQL phase's worker count: the requested limit, at most the plan's runnable width.""" + + return min(max(1, max_concurrency), runnable_graph_width(plan=plan)) diff --git a/src/sqlbuild/executor/pipeline/_helpers/scenario.py b/src/sqlbuild/executor/pipeline/_helpers/scenario.py index e2b083a049..d963aa00de 100644 --- a/src/sqlbuild/executor/pipeline/_helpers/scenario.py +++ b/src/sqlbuild/executor/pipeline/_helpers/scenario.py @@ -3,6 +3,7 @@ from __future__ import annotations import atexit +import json import logging import queue import sys @@ -37,6 +38,12 @@ relation_metadata_cache_scope, ) from sqlbuild.diagnostics.main.log_debug_event import log_debug_event +from sqlbuild.executor.local.constants import ( + RUN_ON_LOCAL, + RUN_ON_WAREHOUSE, + STATEMENT_CONSTRUCT, +) +from sqlbuild.executor.local.main._convert_local_sql import session_time_zone from sqlbuild.executor.pipeline._helpers.connections import ( close_connections, open_worker_connections, @@ -61,9 +68,11 @@ ) from sqlbuild.executor.scenario.main._cleanup_interrupted import cleanup_interrupted_scenarios from sqlbuild.executor.scenario.main._local import execute_local_scenario_load_only_run +from sqlbuild.executor.scenario.main._local_refusals import local_scenario_refusals from sqlbuild.executor.scenario.main._run import execute_scenario_run from sqlbuild.executor.scenario.main._snapshots import classify_scenario_snapshot_state from sqlbuild.executor.scenario.models import ( + LocalConversion, ScenarioCaptureSettings, ScenarioLocalReplaySource, ScenarioRunOptions, @@ -287,7 +296,6 @@ def run_scenario_local_test_pipeline( scenarios: tuple[CompiledSqlScenario, ...], adapter: BaseAdapter, project_name: str, - strict: bool, replay_source: ScenarioLocalReplaySource, on_scenario_start: Callable[[CompiledSqlScenario], None] | None = None, on_scenario_complete: Callable[ @@ -301,17 +309,18 @@ def run_scenario_local_test_pipeline( settings=pipeline_result.project.settings, adapter=adapter ) running: RunningScenarios = RunningScenarios(adapter=adapter) + conversion: LocalConversion = local_conversion(pipeline_result) def execute(scenario_plan: ScenarioExecutionPlan) -> ScenarioRunResult: return execute_local_scenario_load_only_run( project_dir=project_dir, scenario_plan=scenario_plan, adapter=adapter, - strict=strict, promotion_mode=promotion_mode, capture_adapter=replay_source.capture_adapter, capture_dialect=replay_source.capture_dialect, running=running, + conversion=conversion, ) def failed(*, scenario_name: str, exc: Exception) -> ScenarioRunResult: @@ -343,6 +352,87 @@ def failed(*, scenario_name: str, exc: Exception) -> ScenarioRunResult: ) +def decide_scenario_run_on( + *, + project_dir: Path, + pipeline_result: CompilePipelineResult, + scenarios: tuple[CompiledSqlScenario, ...], + adapter: BaseAdapter, + project_name: str, + replay_source: ScenarioLocalReplaySource, + run_on: str, +) -> str: + """Each scenario's decision as JSON: local with a fresh snapshot whose SQL converts.""" + + conversion: LocalConversion = local_conversion(pipeline_result) + decisions: list[dict[str, object]] = [] + scenario: CompiledSqlScenario + for scenario in scenarios: + refusals: tuple[dict[str, object], ...] = () + if run_on != RUN_ON_WAREHOUSE: + try: + refusals = local_scenario_refusals( + project_dir=project_dir, + scenario_plan=build_scenario_plan( + scenario=scenario, + pipeline_result=pipeline_result, + dialect=Dialect(adapter), + project_name=project_name, + source_lexical_syntax=replay_source.lexical_syntax, + ), + capture_adapter=replay_source.capture_adapter, + capture_dialect=replay_source.capture_dialect, + conversion=conversion, + ) + except Exception as error: + refusals = ( + { + "category": "plan", + "construct": f"scenario:{scenario.name}", + "reason": error_message(error), + }, + ) + decisions.append( + { + "name": scenario.name, + "run_on": RUN_ON_LOCAL + if run_on != RUN_ON_WAREHOUSE and not refusals + else RUN_ON_WAREHOUSE, + "refusals": [ + { + **refusal, + "construct": refusal.get("construct") or STATEMENT_CONSTRUCT, + } + for refusal in refusals + ], + } + ) + return json.dumps({"decisions": decisions}, default=str) + + +def local_conversion(pipeline_result: CompilePipelineResult) -> LocalConversion: + """The declared column types of every fully typed model, and the target's session time zone.""" + + columns: dict[str, tuple[tuple[str, str], ...]] = {} + for model in pipeline_result.project.models: + schema_entry: Any = model.schema_entry + if schema_entry is None or not schema_entry.columns: + continue + typed: tuple[tuple[str, str], ...] = tuple( + (column.name, column.type) for column in schema_entry.columns if column.type + ) + if len(typed) == len(schema_entry.columns): + columns[model.name] = typed + return LocalConversion( + model_columns=columns, + time_zone=session_time_zone(pipeline_result.project), + model_files={ + model.name: (Path(model.relative_path).as_posix(), model.authored_sql) + for model in pipeline_result.project.models + }, + ) + + def run_scenario_capture_pipeline( *, project_dir: Path, diff --git a/src/sqlbuild/executor/pipeline/_helpers/testing.py b/src/sqlbuild/executor/pipeline/_helpers/testing.py index 267c97b175..c6e8667221 100644 --- a/src/sqlbuild/executor/pipeline/_helpers/testing.py +++ b/src/sqlbuild/executor/pipeline/_helpers/testing.py @@ -26,6 +26,9 @@ from sqlbuild.compiler.compile.types import FunctionLanguage from sqlbuild.executor.build.models import FunctionExecutionResult from sqlbuild.executor.functions.main._execute import execute_function +from sqlbuild.executor.local.main._prune_local_conversion_cache import ( + prune_local_conversion_cache, +) from sqlbuild.executor.pipeline._helpers.connections import ( close_connections, open_worker_connections, @@ -178,6 +181,7 @@ def run_test_pipeline( finally: recovery.close_replacements() close_connections(adapter=adapter, connections=connections, active_error=active_error) + _ = prune_local_conversion_cache() def _run_tests( diff --git a/src/sqlbuild/executor/pipeline/main/run.py b/src/sqlbuild/executor/pipeline/main/run.py index 1acbf2c814..87ca94ae14 100644 --- a/src/sqlbuild/executor/pipeline/main/run.py +++ b/src/sqlbuild/executor/pipeline/main/run.py @@ -29,7 +29,13 @@ close_connections, prepare_build_connections, ) -from sqlbuild.executor.pipeline._helpers.graph_width import runnable_graph_width +from sqlbuild.executor.pipeline._helpers.graph_width import ( + sql_phase_concurrency, + sql_phase_has_work, +) +from sqlbuild.executor.pipeline._helpers.scenario import ( + decide_scenario_run_on as decide_scenario_run_on, +) from sqlbuild.executor.pipeline._helpers.scenario import ( run_scenario_capture_pipeline as run_scenario_capture_pipeline, ) @@ -60,6 +66,7 @@ from sqlbuild.runtime.observability.main.create_lifecycle_event import create_lifecycle_event from sqlbuild.runtime.observability.main.current_event_dispatcher import current_event_dispatcher from sqlbuild.runtime.observability.main.run_scope import run_scope +from sqlbuild.runtime.observability.types import JSONValue def run_build_pipeline( @@ -72,8 +79,9 @@ def run_build_pipeline( callbacks: BuildCallbacks | None = None, customizations: BuildCustomizations | None = None, initial_state: BuildInitialState | None = None, + execution_announced: bool = False, ) -> BuildExecutionResult: - """Execute a full build pipeline: resolve settings, open connections, run plan, close.""" + """Execute a build pipeline; a caller that ran work first announces its start itself.""" plan = plannable_plan(plan) with run_scope(runtime.run_id) as identity: @@ -109,6 +117,7 @@ def run_build_pipeline( callbacks=callbacks, customizations=customizations, initial_state=initial_state, + execution_announced=execution_announced, ) except BaseException as error: if dispatcher is not None: @@ -152,9 +161,14 @@ def _run_build_pipeline( callbacks: BuildCallbacks | None = None, customizations: BuildCustomizations | None = None, initial_state: BuildInitialState | None = None, + execution_announced: bool = False, ) -> BuildExecutionResult: """Run the build while the public wrapper owns telemetry context.""" + if not execution_announced: + _ = _publish_execution_start(plan=plan, max_concurrency=runtime.max_concurrency) + if not sql_phase_has_work(plan=plan): + return BuildExecutionResult(status=BuildStatus.SUCCESS) inputs: ResolvedBuildInputs = resolve_build_inputs( settings=settings, adapter=adapter, @@ -163,8 +177,8 @@ def _run_build_pipeline( customizations=customizations, initial_state=initial_state, ) - effective_concurrency: int = min( - max(1, runtime.max_concurrency), runnable_graph_width(plan=plan) + effective_concurrency: int = sql_phase_concurrency( + plan=plan, max_concurrency=runtime.max_concurrency ) preparation: BuildConnectionPreparation = prepare_build_connections( plan=plan, @@ -173,10 +187,6 @@ def _run_build_pipeline( connection_count=effective_concurrency, callbacks=inputs.callbacks, ) - _ = _publish_execution_start( - concurrency=effective_concurrency, - connections=len(preparation.worker_connections) + 1, - ) timing_tracker: BuildPhaseTimingTracker | None = BuildPhaseTimingTracker.current() execution_error: BaseException | None = None execution_start: float = time.monotonic() @@ -219,16 +229,14 @@ def _run_build_pipeline( ) -def _publish_execution_start(*, concurrency: int, connections: int) -> None: +def _publish_execution_start(*, plan: PlanOutput, max_concurrency: int) -> None: dispatcher: EventDispatcher | None = current_event_dispatcher() - if dispatcher is not None: - dispatcher.publish_lifecycle( - create_lifecycle_event( - event_type="invocation_phase", - payload={ - "phase": "started_execution", - "count": concurrency, - "detail": f"{connections} connections", - }, - ) - ) + if dispatcher is None: + return + concurrency: int = sql_phase_concurrency(plan=plan, max_concurrency=max_concurrency) + payload: dict[str, JSONValue] = {"phase": "started_execution", "count": concurrency} + if sql_phase_has_work(plan=plan): + payload["detail"] = f"{concurrency + 1} connections" + dispatcher.publish_lifecycle( + create_lifecycle_event(event_type="invocation_phase", payload=payload) + ) diff --git a/src/sqlbuild/executor/scenario/_helpers/local/execution.py b/src/sqlbuild/executor/scenario/_helpers/local/execution.py index fc112e07ba..b5227d458f 100644 --- a/src/sqlbuild/executor/scenario/_helpers/local/execution.py +++ b/src/sqlbuild/executor/scenario/_helpers/local/execution.py @@ -25,8 +25,21 @@ from sqlbuild.adapter.contract.classes.statement_recorder import StatementRecorder from sqlbuild.adapter.contract.types import TablePromotionMode from sqlbuild.compiler.compile.types import FunctionLanguage +from sqlbuild.errors.contracts.exceptions import LocalRunRefusedError from sqlbuild.executor.build.models import FunctionExecutionResult from sqlbuild.executor.functions.main._execute import execute_function +from sqlbuild.executor.local.constants import ( + CANNOT_RUN_LOCALLY_CODE, + SNAPSHOT_INVALID_CATEGORY, + SNAPSHOT_MISSING_CATEGORY, + SNAPSHOT_STALE_CATEGORY, + UTC_TIME_ZONE, +) +from sqlbuild.executor.local.main._local_failure_refusal import local_failure_refusal +from sqlbuild.executor.local.main._prune_local_conversion_cache import ( + prune_local_conversion_cache, +) +from sqlbuild.executor.local.main._use_local_conversion_cache import use_local_conversion_cache from sqlbuild.executor.run.models import ModelExecutionResult from sqlbuild.executor.scenario._helpers.execution.model_execution import execute_scenario_models from sqlbuild.executor.scenario._helpers.lifecycle.expectations import ( @@ -39,8 +52,8 @@ local_snapshot_table_name, ) from sqlbuild.executor.scenario._helpers.local.sql import ( + convert_sql_for_local_duckdb, replace_local_relations, - transpile_sql_for_local_duckdb, ) from sqlbuild.executor.scenario._helpers.snapshots.core import ( build_scenario_snapshot_input_fingerprint, @@ -49,6 +62,7 @@ ) from sqlbuild.executor.scenario.classes.running_scenarios import RunningScenarios from sqlbuild.executor.scenario.constants import ( + MODEL_RESOURCE_KIND, SCENARIO_EXEC_ASSERTION_ERRORED, SCENARIO_EXEC_ASSERTION_FAILED, SCENARIO_EXEC_EXPECTED_ERRORED, @@ -60,13 +74,18 @@ SCENARIO_LOCAL_SNAPSHOT_MISSING, SCENARIO_LOCAL_SNAPSHOT_STALE, ) +from sqlbuild.executor.scenario.exceptions import LocalSqlRefusedError from sqlbuild.executor.scenario.models import ( + LocalConversion, + LocalSql, ScenarioAssertionExpectationExecutionResult, ScenarioExpectedExpectationExecutionResult, ScenarioFailureDetails, ScenarioLocalSnapshotLoadedRelation, ScenarioLocalSnapshotLoadResult, ScenarioRunResult, + ScenarioSnapshotManifest, + ScenarioSnapshotRelation, ScenarioSnapshotStateResult, ) from sqlbuild.executor.scenario.types import ScenarioLocalRunStatus, ScenarioSnapshotState @@ -76,6 +95,8 @@ ) _LOCAL_STEP_FAILED_MESSAGE: str = "local scenario step failed" +_CANNOT_REPLAY_LOCALLY_HELP: str = "Run this scenario on the warehouse with --run-on warehouse." +_UTC_SESSION_SQL: str = f"SET TimeZone = '{UTC_TIME_ZONE}'" def execute_local_scenario_load_only_run( @@ -83,14 +104,16 @@ def execute_local_scenario_load_only_run( project_dir: Path, scenario_plan: ScenarioExecutionPlan, adapter: BaseAdapter, - strict: bool, promotion_mode: TablePromotionMode, capture_adapter: str | None = None, capture_dialect: str | None = None, running: RunningScenarios | None = None, + conversion: LocalConversion | None = None, ) -> ScenarioRunResult: """Run one scenario locally against a run-scoped DuckDB database.""" + resolved_conversion: LocalConversion = conversion or LocalConversion() + snapshot_state: ScenarioSnapshotStateResult = classify_scenario_snapshot_state( project_dir=project_dir, scenario_plan=scenario_plan, @@ -100,7 +123,7 @@ def execute_local_scenario_load_only_run( if snapshot_state.state == ScenarioSnapshotState.MISSING: return _local_snapshot_unavailable_result( scenario_name=scenario_plan.name, - status=ScenarioLocalRunStatus.ERROR if strict else ScenarioLocalRunStatus.SKIP, + status=ScenarioLocalRunStatus.ERROR, code=SCENARIO_LOCAL_SNAPSHOT_MISSING, message=( f"Scenario '{scenario_plan.name}' is missing local snapshot manifest " @@ -111,7 +134,7 @@ def execute_local_scenario_load_only_run( if snapshot_state.state == ScenarioSnapshotState.STALE: return _local_snapshot_unavailable_result( scenario_name=scenario_plan.name, - status=ScenarioLocalRunStatus.ERROR if strict else ScenarioLocalRunStatus.SKIP, + status=ScenarioLocalRunStatus.ERROR, code=SCENARIO_LOCAL_SNAPSHOT_STALE, message=( f"Scenario '{scenario_plan.name}' local snapshot " @@ -134,6 +157,7 @@ def execute_local_scenario_load_only_run( run_dir: Path = project_dir / "target" / "run" / "scenarios" / scenario_plan.name run_dir.mkdir(parents=True, exist_ok=True) + use_local_conversion_cache(project_dir) duckdb_path: Path = run_dir / "local.duckdb" _remove_local_duckdb_files(duckdb_path) connection: Any = ( @@ -156,11 +180,15 @@ def execute_local_scenario_load_only_run( current_input_fingerprint=input_fingerprint, connection=connection, ) - local_plan: ScenarioExecutionPlan = _build_local_execution_plan( + local_plan, macros = _build_local_execution_plan( scenario_plan=scenario_plan, load_result=load_result, source_dialect=load_result.manifest.capture_dialect, + conversion=resolved_conversion, ) + _ = adapter.execute(connection=connection, sql=_UTC_SESSION_SQL) + for macro in macros: + _ = adapter.execute(connection=connection, sql=macro) result: ScenarioRunResult = _execute_local_plan( scenario_plan=local_plan, adapter=adapter, @@ -171,30 +199,132 @@ def execute_local_scenario_load_only_run( loaded_relations=load_result.relations, ) except Exception as exc: - return ScenarioRunResult( - scenario_name=scenario_plan.name, - status=ExecutionStatus.FAILED, - local_status=ScenarioLocalRunStatus.ERROR, - retained=True, - local_duckdb_path=duckdb_path, - error_code=error_code(error=exc, fallback_code=SCENARIO_LOCAL_INTERNAL), - error_help=error_help(exc), - error_message=error_message(exc), + return _with_local_refusal( + ScenarioRunResult( + scenario_name=scenario_plan.name, + status=ExecutionStatus.FAILED, + local_status=ScenarioLocalRunStatus.ERROR, + retained=True, + local_duckdb_path=duckdb_path, + error_code=error_code(error=exc, fallback_code=SCENARIO_LOCAL_INTERNAL), + error_help=error_help(exc), + error_message=error_message(exc), + ) ) finally: if running is not None: running.finish(connection=connection) adapter.close(connection) + _ = prune_local_conversion_cache() return result +def local_scenario_refusals( + *, + project_dir: Path, + scenario_plan: ScenarioExecutionPlan, + capture_adapter: str | None, + capture_dialect: str | None, + conversion: LocalConversion, +) -> tuple[dict[str, object], ...]: + """Why a scenario cannot replay locally: its snapshot or SQLQuack's refusals, or nothing.""" + + snapshot_state: ScenarioSnapshotStateResult = classify_scenario_snapshot_state( + project_dir=project_dir, + scenario_plan=scenario_plan, + capture_adapter=capture_adapter, + capture_dialect=capture_dialect, + ) + category: str | None = { + ScenarioSnapshotState.MISSING: SNAPSHOT_MISSING_CATEGORY, + ScenarioSnapshotState.STALE: SNAPSHOT_STALE_CATEGORY, + ScenarioSnapshotState.INVALID: SNAPSHOT_INVALID_CATEGORY, + }.get(snapshot_state.state) + manifest: ScenarioSnapshotManifest | None = snapshot_state.manifest + if category is not None or manifest is None: + return ( + { + "category": category or SNAPSHOT_MISSING_CATEGORY, + "construct": f"scenario:{scenario_plan.name}", + "reason": snapshot_state.error_message + or f"{snapshot_state.manifest_path.as_posix()} is not a fresh snapshot", + "path": snapshot_state.manifest_path.relative_to(project_dir).as_posix() + if snapshot_state.manifest_path.is_relative_to(project_dir) + else snapshot_state.manifest_path.as_posix(), + }, + ) + load_result: ScenarioLocalSnapshotLoadResult = ScenarioLocalSnapshotLoadResult( + scenario_name=scenario_plan.name, + manifest=manifest, + relations=tuple( + ScenarioLocalSnapshotLoadedRelation( + kind=relation.kind, + logical_name=relation.logical_name, + file_path=relation.file_path, + table_name=local_snapshot_table_name( + kind=relation.kind, logical_name=relation.logical_name + ), + row_count=0, + ) + for relation in manifest.relations + ), + ) + try: + _ = _build_local_execution_plan( + scenario_plan=scenario_plan, + load_result=load_result, + source_dialect=manifest.capture_dialect, + conversion=conversion, + ) + except LocalSqlRefusedError as refused: + return tuple(dict(refusal) for refusal in refused.refusals) + return () + + +def _local_schema( + *, + load_result: ScenarioLocalSnapshotLoadResult, + scenario_plan: ScenarioExecutionPlan, + conversion: LocalConversion, +) -> dict[str, object]: + """The loaded snapshot tables and the scenario's model tables, as SQLQuack's schema.""" + + relations: dict[str, list[list[str]]] = {} + captured: dict[tuple[ScenarioArtifactKind, str], ScenarioSnapshotRelation] = { + (relation.kind, relation.logical_name): relation + for relation in load_result.manifest.relations + } + loaded: ScenarioLocalSnapshotLoadedRelation + for loaded in load_result.relations: + relation: ScenarioSnapshotRelation | None = captured.get((loaded.kind, loaded.logical_name)) + if relation is None: + continue + columns: list[list[str]] = [ + [column.name.upper(), column.warehouse_type] for column in relation.columns + ] + relations[loaded.table_name.upper()] = columns + model_name: str + for model_name in scenario_plan.graph_plan.model_names: + declared: tuple[tuple[str, str], ...] | None = conversion.model_columns.get(model_name) + if not declared: + continue + table: str = local_snapshot_table_name( + kind=ScenarioArtifactKind.MODEL, logical_name=model_name + ) + columns = [[name.upper(), column_type] for name, column_type in declared] + relations[table.upper()] = columns + return {"relations": relations} + + def _build_local_execution_plan( *, scenario_plan: ScenarioExecutionPlan, load_result: ScenarioLocalSnapshotLoadResult, source_dialect: str | None, -) -> ScenarioExecutionPlan: + conversion: LocalConversion, +) -> tuple[ScenarioExecutionPlan, tuple[str, ...]]: + """The scenario plan over the local snapshot tables, and the DuckDB macros its SQL calls.""" relation_replacements: dict[str, str] = _build_relation_replacements( scenario_plan=scenario_plan, load_result=load_result, @@ -203,6 +333,23 @@ def _build_local_execution_plan( scenario_plan=scenario_plan, load_result=load_result, ) + schema: dict[str, object] = _local_schema( + load_result=load_result, scenario_plan=scenario_plan, conversion=conversion + ) + + macros: list[str] = [] + + def convert(*, sql: str, resource_kind: str, resource_name: str) -> LocalSql: + return convert_sql_for_local_duckdb( + sql=sql, + source_dialect=source_dialect, + schema=schema, + time_zone=conversion.time_zone, + resource=(scenario_plan.name, resource_kind, resource_name), + file=conversion.model_files.get(resource_name) + if resource_kind == MODEL_RESOURCE_KIND + else None, + ) function_entries: list[FunctionPlanEntry] = [] function_entry: FunctionPlanEntry @@ -212,13 +359,13 @@ def _build_local_execution_plan( relation_replacements=relation_replacements, ) if function_entry.language == FunctionLanguage.SQL: - function_sql = transpile_sql_for_local_duckdb( + function_local: LocalSql = convert( sql=function_sql, - source_dialect=source_dialect, - scenario_name=scenario_plan.name, resource_kind=str(function_entry.key.resource_type), resource_name=function_entry.name, ) + function_sql = function_local.sql + macros.extend(function_local.macros) function_entries.append(replace(function_entry, body_sql=function_sql)) model_entries: list[ModelPlanEntry] = [] @@ -228,13 +375,11 @@ def _build_local_execution_plan( sql=entry.resolved_sql, relation_replacements=relation_replacements, ) - local_sql = transpile_sql_for_local_duckdb( - sql=local_sql, - source_dialect=source_dialect, - scenario_name=scenario_plan.name, - resource_kind="model", - resource_name=entry.name, + model_local: LocalSql = convert( + sql=local_sql, resource_kind=MODEL_RESOURCE_KIND, resource_name=entry.name ) + local_sql = model_local.sql + macros.extend(model_local.macros) model_entries.append( replace( entry, @@ -253,13 +398,13 @@ def _build_local_execution_plan( sql=expected_expectation.expected_sql, relation_replacements=relation_replacements, ) - expected_sql = transpile_sql_for_local_duckdb( + expected_local: LocalSql = convert( sql=expected_sql, - source_dialect=source_dialect, - scenario_name=scenario_plan.name, resource_kind="expected comparison", resource_name=expected_expectation.model_name, ) + expected_sql = expected_local.sql + macros.extend(expected_local.macros) expected_expectations.append( replace( expected_expectation, @@ -275,16 +420,16 @@ def _build_local_execution_plan( sql=assertion_expectation.sql, relation_replacements=relation_replacements, ) - assertion_sql = transpile_sql_for_local_duckdb( + assertion_local: LocalSql = convert( sql=assertion_sql, - source_dialect=source_dialect, - scenario_name=scenario_plan.name, resource_kind="assertion", resource_name=assertion_expectation.name, ) + assertion_sql = assertion_local.sql + macros.extend(assertion_local.macros) assertion_expectations.append(replace(assertion_expectation, sql=assertion_sql)) - return replace( + local_plan: ScenarioExecutionPlan = replace( scenario_plan, relation_plan=relation_plan, fixture_plans=(), @@ -294,6 +439,7 @@ def _build_local_execution_plan( expected_expectations=tuple(expected_expectations), assertion_expectations=tuple(assertion_expectations), ) + return local_plan, tuple(dict.fromkeys(macros)) def _execute_local_plan( @@ -618,7 +764,7 @@ def _local_result( resolved_failure: ScenarioFailureDetails = ( failure if failure is not None else ScenarioFailureDetails() ) - return ScenarioRunResult( + result: ScenarioRunResult = ScenarioRunResult( scenario_name=scenario_plan.name, status=ExecutionStatus.SUCCESS if local_status == ScenarioLocalRunStatus.PASS @@ -637,6 +783,40 @@ def _local_result( error_help=resolved_failure.error_help, error_message=resolved_failure.error_message, ) + return _with_local_refusal(result) if local_status == ScenarioLocalRunStatus.ERROR else result + + +def _with_local_refusal(result: ScenarioRunResult) -> ScenarioRunResult: + """`result` as a refusal when a SQLQuack guard or DuckDB internal error failed it locally.""" + + messages: list[str] = [ + message + for step in ( + result, + *result.function_results, + *result.model_results, + *result.expected_results, + *result.assertion_results, + ) + if (message := getattr(step, "error_message", None)) is not None + ] + for message in messages: + refused: LocalRunRefusedError | None = local_failure_refusal(message) + if refused is None: + continue + return replace( + result, + error_code=CANNOT_RUN_LOCALLY_CODE, + error_help=_CANNOT_REPLAY_LOCALLY_HELP, + error_message=refused.message, + local_refusal={ + "test": result.scenario_name, + "category": refused.category, + "construct": refused.construct, + "reason": refused.message, + }, + ) + return result def _local_target(table_name: str) -> CompiledRelationLocation: diff --git a/src/sqlbuild/executor/scenario/_helpers/local/snapshots.py b/src/sqlbuild/executor/scenario/_helpers/local/snapshots.py index ff719a1ee7..0f4e85ecb5 100644 --- a/src/sqlbuild/executor/scenario/_helpers/local/snapshots.py +++ b/src/sqlbuild/executor/scenario/_helpers/local/snapshots.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +from dataclasses import replace from pathlib import Path from typing import Any @@ -16,7 +17,9 @@ scenario_snapshot_root, ) from sqlbuild.executor.scenario.constants import ( + JSON_FROM_TEXT_PLACEHOLDER, LOCAL_CAPTURE_ADAPTER, + LOCAL_TYPE_JSON, LOCAL_TYPE_VARIANT, SCENARIO_LOCAL_JSONL_INVALID, SCENARIO_LOCAL_LOAD_FAILED, @@ -24,7 +27,6 @@ SCENARIO_LOCAL_SNAPSHOT_MISSING, SCENARIO_LOCAL_SNAPSHOT_STALE, SCENARIO_LOCAL_TYPE_INVALID, - VARIANT_FROM_JSON_PLACEHOLDER, ) from sqlbuild.executor.scenario.models import ( ScenarioLocalSnapshotLoadedRelation, @@ -228,7 +230,16 @@ def _load_snapshot_relation( logical_name=relation.logical_name, ) connection.execute(f"DROP TABLE IF EXISTS {_quote_identifier(table_name)}") - connection.execute(_build_create_table_sql(table_name=table_name, columns=relation.columns)) + native_values: bool = capture_adapter == LOCAL_CAPTURE_ADAPTER + connection.execute( + _build_create_table_sql( + table_name=table_name, + columns=tuple( + _storage_column(column=column, native_values=native_values) + for column in relation.columns + ), + ) + ) try: rows: tuple[dict[str, object], ...] = read_scenario_snapshot_jsonl(file_path=file_path) @@ -248,7 +259,7 @@ def _load_snapshot_relation( relation=relation, table_name=table_name, rows=rows, - native_values=capture_adapter == LOCAL_CAPTURE_ADAPTER, + native_values=native_values, ) return ScenarioLocalSnapshotLoadedRelation( kind=relation.kind, @@ -355,6 +366,16 @@ def _build_create_table_sql(*, table_name: str, columns: tuple[ScenarioSnapshotC return f"CREATE TABLE {_quote_identifier(table_name)} ({column_defs})" +def _storage_column( + *, column: ScenarioSnapshotColumn, native_values: bool +) -> ScenarioSnapshotColumn: + """The column as stored locally: SQLQuack reads a captured VARIANT as DuckDB JSON text.""" + + if native_values or column.local_type.strip().upper() != LOCAL_TYPE_VARIANT: + return column + return replace(column, local_type=LOCAL_TYPE_JSON) + + def _variant_json_text(*, value: object) -> str | None: """Another adapter's VARIANT value as JSON text; a string that parses is already JSON text.""" @@ -374,7 +395,7 @@ def _build_insert_sql( ) -> str: columns: str = ", ".join(_quote_identifier(column_name) for column_name in column_names) placeholders: str = ", ".join( - VARIANT_FROM_JSON_PLACEHOLDER if variant else "?" for variant in variant_columns + JSON_FROM_TEXT_PLACEHOLDER if variant else "?" for variant in variant_columns ) return f"INSERT INTO {_quote_identifier(table_name)} ({columns}) VALUES ({placeholders})" diff --git a/src/sqlbuild/executor/scenario/_helpers/local/sql.py b/src/sqlbuild/executor/scenario/_helpers/local/sql.py index a0e7a81d0b..2406ed6d3a 100644 --- a/src/sqlbuild/executor/scenario/_helpers/local/sql.py +++ b/src/sqlbuild/executor/scenario/_helpers/local/sql.py @@ -1,62 +1,66 @@ -"""Local scenario SQL transformation helpers.""" +"""Local scenario SQL: SQLQuack's DuckDB conversion of captured-dialect SQL, and relation names.""" from __future__ import annotations -from typing import Any, NoReturn +from collections.abc import Mapping +from typing import Any -from sqlbuild.compiler.sql_analysis.main.import_polyglot_sql import import_polyglot_sql -from sqlbuild.errors.contracts.exceptions import ExecutorInputError -from sqlbuild.executor.scenario.constants import ( - LOCAL_SCENARIO_DIALECT, - SCENARIO_LOCAL_SQL_TRANSPILE_FAILED, +from sqlbuild.executor.local.constants import ( + CONVERTED_DIALECT, + DIALECT_REASON_CATEGORY, + LOCAL_DIALECT, ) +from sqlbuild.executor.local.main._convert_local_sql import ( + convert_local_sql, + file_placed_refusal, +) +from sqlbuild.executor.local.models import ConvertedSql +from sqlbuild.executor.scenario.exceptions import LocalSqlRefusedError +from sqlbuild.executor.scenario.models import LocalSql -def transpile_sql_for_local_duckdb( +def convert_sql_for_local_duckdb( *, sql: str, source_dialect: str | None, - scenario_name: str, - resource_kind: str, - resource_name: str, -) -> str: - """Render captured-dialect SQL as DuckDB SQL; DuckDB SQL is executed as authored.""" + schema: Mapping[str, Any] | None, + time_zone: str | None, + resource: tuple[str, str, str], + file: tuple[str, str] | None = None, +) -> LocalSql: + """DuckDB SQL for `sql`, refusals placed in `file` (path, text): converted or as authored.""" - if source_dialect == LOCAL_SCENARIO_DIALECT: - return sql - polyglot_module: Any = import_polyglot_sql() - try: - transpiled: list[str] = polyglot_module.transpile( - sql, - read=source_dialect, - write=LOCAL_SCENARIO_DIALECT, - ) - except (polyglot_module.PolyglotError, ValueError) as exc: - _raise_transpile_error( - scenario_name=scenario_name, - resource_kind=resource_kind, - resource_name=resource_name, - reason=str(exc), + scenario_name, resource_kind, resource_name = resource + if source_dialect == LOCAL_DIALECT: + return LocalSql(sql=sql) + if source_dialect != CONVERTED_DIALECT: + raise LocalSqlRefusedError( + f"Scenario '{scenario_name}' cannot run locally: SQLQuack converts Snowflake SQL " + f"only, not {source_dialect}", + refusals=( + { + "category": DIALECT_REASON_CATEGORY, + "construct": str(source_dialect), + "reason": f"SQLQuack converts Snowflake SQL only, not {source_dialect}", + }, + ), ) - if len(transpiled) != 1: - _raise_transpile_error( - scenario_name=scenario_name, - resource_kind=resource_kind, - resource_name=resource_name, - reason=f"expected one statement, got {len(transpiled)}", - ) - return transpiled[0] - - -def _raise_transpile_error( - *, scenario_name: str, resource_kind: str, resource_name: str, reason: str -) -> NoReturn: - raise ExecutorInputError( - f"Local SQL transpilation failed for scenario '{scenario_name}', " - f"{resource_kind} '{resource_name}': {reason}", - code=SCENARIO_LOCAL_SQL_TRANSPILE_FAILED, - help="Rewrite unsupported SQL or adjust the scenario so it can run in DuckDB locally.", + conversion: ConvertedSql = convert_local_sql( + sql=sql, + schema=schema, + time_zone=time_zone, + path=f"{resource_kind} {resource_name}", ) + if not conversion.converted: + raise LocalSqlRefusedError( + f"SQLQuack refused the SQL of scenario '{scenario_name}', {resource_kind} " + f"'{resource_name}':\n{conversion.rendered.rstrip()}", + refusals=tuple( + file_placed_refusal(refusal=refusal, sql=sql, file=file) + for refusal in conversion.refusals + ), + ) + return LocalSql(sql=conversion.sql, macros=conversion.macros) def replace_local_relations(*, sql: str, relation_replacements: dict[str, str]) -> str: @@ -64,7 +68,6 @@ def replace_local_relations(*, sql: str, relation_replacements: dict[str, str]) result: str = sql original: str - original: str for original in sorted( relation_replacements.keys(), key=lambda value: len(value), reverse=True ): diff --git a/src/sqlbuild/executor/scenario/constants.py b/src/sqlbuild/executor/scenario/constants.py index 416287896c..fe310ef46e 100644 --- a/src/sqlbuild/executor/scenario/constants.py +++ b/src/sqlbuild/executor/scenario/constants.py @@ -225,10 +225,10 @@ TYPE_ARGUMENT_SEPARATOR: str = "," TYPE_PATTERN_WILDCARD: str = "*" JSONL_BLANK_LINE: str = "" -LOCAL_SCENARIO_DIALECT: str = "duckdb" LOCAL_CAPTURE_ADAPTER: str = "duckdb" -VARIANT_FROM_JSON_PLACEHOLDER: str = "CAST(CAST(? AS JSON) AS VARIANT)" +JSON_FROM_TEXT_PLACEHOLDER: str = "CAST(? AS JSON)" +MODEL_RESOURCE_KIND: str = "model" CANONICAL_JSON_FUNCTION: str = "sqb_canonical_json" SEMI_STRUCTURED_COMPARISON_TEMPLATE: str = ( CANONICAL_JSON_FUNCTION + "(CAST({column} AS JSON)) AS {column}" diff --git a/src/sqlbuild/executor/scenario/exceptions.py b/src/sqlbuild/executor/scenario/exceptions.py index 3243210e6a..633e67131b 100644 --- a/src/sqlbuild/executor/scenario/exceptions.py +++ b/src/sqlbuild/executor/scenario/exceptions.py @@ -2,6 +2,12 @@ from __future__ import annotations +from collections.abc import Mapping +from typing import Any + +from sqlbuild.errors.contracts.exceptions import ExecutorInputError +from sqlbuild.executor.scenario.constants import SCENARIO_LOCAL_SQL_TRANSPILE_FAILED + class ExecutorJsonTypeError(TypeError): """Raised when executor JSON serialization receives an unsupported value.""" @@ -17,3 +23,15 @@ def __init__(self, message: str, *, code: str | None = None, help: str | None = class ScenarioStopRequested(BaseException): # noqa: N818 - a control signal, not an error """Raised at a step boundary when an interrupt asked running scenarios to stop.""" + + +class LocalSqlRefusedError(ExecutorInputError): + """SQLQuack refused SQL a local scenario run needs; `refusals` are its JSON refusals.""" + + def __init__(self, message: str, *, refusals: tuple[Mapping[str, Any], ...]) -> None: + super().__init__( + message, + code=SCENARIO_LOCAL_SQL_TRANSPILE_FAILED, + help="Run this scenario on the warehouse with --run-on warehouse or --run-on auto.", + ) + self.refusals: tuple[Mapping[str, Any], ...] = refusals diff --git a/src/sqlbuild/executor/scenario/main/_local.py b/src/sqlbuild/executor/scenario/main/_local.py index 6a90e738e9..13b3597331 100644 --- a/src/sqlbuild/executor/scenario/main/_local.py +++ b/src/sqlbuild/executor/scenario/main/_local.py @@ -11,7 +11,7 @@ execute_local_scenario_load_only_run as _execute_local_scenario_load_only_run, ) from sqlbuild.executor.scenario.classes.running_scenarios import RunningScenarios -from sqlbuild.executor.scenario.models import ScenarioRunResult +from sqlbuild.executor.scenario.models import LocalConversion, ScenarioRunResult def execute_local_scenario_load_only_run( @@ -19,11 +19,11 @@ def execute_local_scenario_load_only_run( project_dir: Path, scenario_plan: ScenarioExecutionPlan, adapter: BaseAdapter, - strict: bool, promotion_mode: TablePromotionMode, capture_adapter: str | None = None, capture_dialect: str | None = None, running: RunningScenarios | None = None, + conversion: LocalConversion | None = None, ) -> ScenarioRunResult: """Run one scenario locally against a run-scoped DuckDB database.""" @@ -31,9 +31,9 @@ def execute_local_scenario_load_only_run( project_dir=project_dir, scenario_plan=scenario_plan, adapter=adapter, - strict=strict, promotion_mode=promotion_mode, capture_adapter=capture_adapter, capture_dialect=capture_dialect, running=running, + conversion=conversion, ) diff --git a/src/sqlbuild/executor/scenario/main/_local_refusals.py b/src/sqlbuild/executor/scenario/main/_local_refusals.py new file mode 100644 index 0000000000..3d06a06f1e --- /dev/null +++ b/src/sqlbuild/executor/scenario/main/_local_refusals.py @@ -0,0 +1,30 @@ +"""Why scenarios cannot replay locally.""" + +from __future__ import annotations + +from pathlib import Path + +from sqlbuild._native import ScenarioExecutionPlan +from sqlbuild.executor.scenario._helpers.local.execution import ( + local_scenario_refusals as _local_scenario_refusals, +) +from sqlbuild.executor.scenario.models import LocalConversion + + +def local_scenario_refusals( + *, + project_dir: Path, + scenario_plan: ScenarioExecutionPlan, + capture_adapter: str | None, + capture_dialect: str | None, + conversion: LocalConversion, +) -> tuple[dict[str, object], ...]: + """Why a scenario cannot replay locally; empty when it can.""" + + return _local_scenario_refusals( + project_dir=project_dir, + scenario_plan=scenario_plan, + capture_adapter=capture_adapter, + capture_dialect=capture_dialect, + conversion=conversion, + ) diff --git a/src/sqlbuild/executor/scenario/models.py b/src/sqlbuild/executor/scenario/models.py index f208128e9b..e43db37184 100644 --- a/src/sqlbuild/executor/scenario/models.py +++ b/src/sqlbuild/executor/scenario/models.py @@ -2,6 +2,7 @@ from __future__ import annotations +from collections.abc import Mapping from dataclasses import dataclass, field from pathlib import Path @@ -139,6 +140,15 @@ class ScenarioLocalReplaySource: capture_dialect: str | None = None +@dataclass(frozen=True) +class LocalConversion: + """What SQLQuack's conversion of local scenario SQL reads: model column types and time zone.""" + + model_columns: Mapping[str, tuple[tuple[str, str], ...]] = field(default_factory=dict) + time_zone: str | None = None + model_files: Mapping[str, tuple[str, str]] = field(default_factory=dict) + + @dataclass(frozen=True) class ScenarioTestSettings: """Cleanup, concurrency and time-limit settings for one warehouse scenario test run.""" @@ -370,3 +380,12 @@ class ScenarioRunResult: error_help: str | None = None error_message: str | None = None duration_ms: float | None = None + local_refusal: dict[str, str] | None = None + + +@dataclass(frozen=True) +class LocalSql: + """SQL a local scenario run executes, and the DuckDB macros it calls.""" + + sql: str + macros: tuple[str, ...] = () diff --git a/src/sqlbuild/executor/testing/main/_execute.py b/src/sqlbuild/executor/testing/main/_execute.py index b9988d86bf..1f303878ac 100644 --- a/src/sqlbuild/executor/testing/main/_execute.py +++ b/src/sqlbuild/executor/testing/main/_execute.py @@ -8,6 +8,7 @@ from sqlbuild._native import SqlTestPlanEntry, render_sql_test_comparison_sql from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter from sqlbuild.compiler.compile.exceptions import CompileInputError +from sqlbuild.errors.contracts.exceptions import LocalRunRefusedError from sqlbuild.executor.testing._helpers.comparison import compare_actual_outputs from sqlbuild.executor.testing._helpers.expected_column_probe import ( missing_expected_columns_message, @@ -150,8 +151,13 @@ def _execute_sql_test( ) if failure is not None: error, expected_columns_message = failure + refused: LocalRunRefusedError | None = ( + error if isinstance(error, LocalRunRefusedError) else None + ) error_code: str = ( - SQL_TEST_EXECUTION_ERROR_CODE + refused.code + if refused is not None + else SQL_TEST_EXECUTION_ERROR_CODE if expected_columns_message is None else SQL_TEST_EXPECTED_COLUMNS_CODE ) @@ -176,11 +182,21 @@ def _execute_sql_test( model_name=error_model_name, outcome=SqlTestOutcome.ERROR, error_code=error_code, + error_help=None if refused is None else refused.help, error_message=error_message, ), ), error_code=error_code, + error_help=None if refused is None else refused.help, error_message=error_message, + local_refusal=None + if refused is None + else { + "test": test_entry.name, + "category": refused.category, + "construct": refused.construct, + "reason": refused.message, + }, ) overall_outcome: SqlTestOutcome = SqlTestOutcome.PASS diff --git a/src/sqlbuild/executor/testing/models.py b/src/sqlbuild/executor/testing/models.py index 45187c57b9..b4a4f49418 100644 --- a/src/sqlbuild/executor/testing/models.py +++ b/src/sqlbuild/executor/testing/models.py @@ -2,6 +2,7 @@ from __future__ import annotations +from collections.abc import Mapping from dataclasses import dataclass, field from pathlib import Path @@ -65,3 +66,4 @@ class SqlTestExecutionResult: error_message: str | None = None real_model_count: int | None = None timeout: ItemTimeoutReport | None = None + local_refusal: Mapping[str, str] | None = None diff --git a/src/sqlbuild/orchestration_declarations/types.py b/src/sqlbuild/orchestration_declarations/types.py index 8db75aab4a..8375ab260b 100644 --- a/src/sqlbuild/orchestration_declarations/types.py +++ b/src/sqlbuild/orchestration_declarations/types.py @@ -30,7 +30,6 @@ class RunEventKind(StrEnum): COMPLETED = "completed" SUCCESS = "success" WARN = "warn" - PARTIAL = "partial" FAILED = "failed" CANCELLED = "cancelled" SKIPPED = "skipped" diff --git a/src/sqlbuild/runtime/observability/classes/statement_lifecycle.py b/src/sqlbuild/runtime/observability/classes/statement_lifecycle.py index eb794a9f6d..84b5dbf93b 100644 --- a/src/sqlbuild/runtime/observability/classes/statement_lifecycle.py +++ b/src/sqlbuild/runtime/observability/classes/statement_lifecycle.py @@ -32,7 +32,10 @@ from sqlbuild.runtime.observability.classes.statement_monitor import ( StatementMonitor, ) -from sqlbuild.runtime.observability.constants import STATEMENT_HEARTBEAT_THRESHOLD_SECONDS +from sqlbuild.runtime.observability.constants import ( + LOCAL_RUN_ON, + STATEMENT_HEARTBEAT_THRESHOLD_SECONDS, +) from sqlbuild.runtime.observability.exceptions import ObservabilityValidationError from sqlbuild.runtime.observability.models import ExecutionIdentity from sqlbuild.runtime.observability.types import JSONValue, StatementListener @@ -44,6 +47,7 @@ "sqlbuild_statement_lifecycle_owner", default=None ) _STATEMENT_PURPOSE: ContextVar[str | None] = ContextVar("sqlbuild_statement_purpose", default=None) +_STATEMENT_RUN_ON: ContextVar[str | None] = ContextVar("sqlbuild_statement_run_on", default=None) _HANDLED_FAILURE: ContextVar[Callable[[BaseException], bool] | None] = ContextVar( "sqlbuild_statement_handled_failure", default=None ) @@ -90,6 +94,7 @@ def __init__( self._pending_failure: tuple[BaseException, str | None, str | None] | None = None self._statement_facts: tuple[str, str] | None = None self._purpose: str | None = _STATEMENT_PURPOSE.get() + self._run_on: str | None = _STATEMENT_RUN_ON.get() self._is_handled: Callable[[BaseException], bool] | None = _HANDLED_FAILURE.get() self._item_deadline: ItemDeadline | None = None self._terminal_query_id: str | None = None @@ -113,6 +118,17 @@ def purpose_scope(purpose: str) -> Iterator[None]: finally: _STATEMENT_PURPOSE.reset(token) + @staticmethod + @contextmanager + def run_on_scope(run_on: str) -> Iterator[None]: + """Label statements in the block with where they run; local ones keep no SQL text.""" + + token: Token[str | None] = _STATEMENT_RUN_ON.set(run_on) + try: + yield + finally: + _STATEMENT_RUN_ON.reset(token) + @staticmethod @contextmanager def handled_failure_scope(is_handled: Callable[[BaseException], bool]) -> Iterator[None]: @@ -153,9 +169,10 @@ def __enter__(self) -> StatementLifecycle: self._started_monotonic = self._clock() self._execution_owner_key = execution_owner_key self._publish(event_type="statement_started", payload=self._base_payload()) - dispatcher.publish_sql_artifact( - sql=self._sql, statement_id=self._statement_id, resource_id=identity.resource_id - ) + if self._run_on != LOCAL_RUN_ON: + dispatcher.publish_sql_artifact( + sql=self._sql, statement_id=self._statement_id, resource_id=identity.resource_id + ) self._item_deadline = current_item_deadline() if self._item_deadline is not None: self._item_deadline.statement_started() @@ -339,6 +356,8 @@ def _base_payload(self) -> dict[str, JSONValue]: payload["batch_size"] = self._batch_size if self._purpose is not None: payload["purpose"] = self._purpose + if self._run_on is not None: + payload["run_on"] = self._run_on return payload def _terminal_payload(self) -> dict[str, JSONValue]: diff --git a/src/sqlbuild/runtime/observability/constants.py b/src/sqlbuild/runtime/observability/constants.py index 46a00a0f79..cf36efcc31 100644 --- a/src/sqlbuild/runtime/observability/constants.py +++ b/src/sqlbuild/runtime/observability/constants.py @@ -11,6 +11,7 @@ MODEL_BUILD_PURPOSE: str = "model_build" AUDIT_PURPOSE: str = "audit" COST_TELEMETRY_PURPOSE: str = "cost_telemetry" +LOCAL_RUN_ON: str = "local" LIFECYCLE_ENVELOPE_FIELDS_V1: frozenset[str] = frozenset( { "event_id", diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/bigquery/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/bigquery/_test_types.py index 336c367461..2c834e2f19 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/bigquery/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/bigquery/_test_types.py @@ -103,19 +103,6 @@ class BigQueryErrorE2ETestCase: expected_return_code: int = 1 -@dataclass(frozen=True) -class BigQueryScenarioLocalReplayE2ETestCase: - description: str - model_sql: str - scenario_sql: str - expected_stdout_fragments: tuple[str, ...] - expected_return_code: int = 0 - scenario_name: str = "transpilable_event_rollup" - expected_local_rows: tuple[tuple[object, ...], ...] = field(default_factory=tuple) - local_rows_sql: str = "" - corrupt_capture_dialect: bool = False - - @dataclass(frozen=True) class BigQueryScenarioRemoteE2ETestCase: description: str diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/bigquery/test_bigquery.py b/tests/e2e/src/sqlbuild/cli/commands/main/bigquery/test_bigquery.py index aaecf53a42..cf7507b072 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/bigquery/test_bigquery.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/bigquery/test_bigquery.py @@ -17,7 +17,6 @@ BigQueryIntermediateDagStrategyE2ETestCase, BigQueryModelBuildE2ETestCase, BigQueryNodeResultE2ETestCase, - BigQueryScenarioLocalReplayE2ETestCase, BigQueryScenarioRemoteE2ETestCase, BigQuerySnapshotApplyE2ETestCase, BigQuerySnapshotE2ETestCase, @@ -50,10 +49,7 @@ build_schema_behavior_project_files, ) from tests.e2e.src.sqlbuild.cli.commands.main.scenario.helpers import ( - assert_optional_local_replay_rows, - build_real_warehouse_local_replay_project_files, build_real_warehouse_remote_scenario_project_files, - maybe_corrupt_scenario_snapshot_dialect, ) from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import ( assert_dbt_profile_lifecycle, @@ -345,167 +341,6 @@ def test_given_bigquery_local_config_when_running_query_then_outputs_expected_ro cleanup_bigquery_dataset(dataset_name=dataset_name) -@pytest.mark.parametrize( - "test_case", - [ - BigQueryScenarioLocalReplayE2ETestCase( - description="captures bigquery fixtures and replays transpilable SQL locally", - model_sql=( - "MODEL (description 'Test model.', materialized table);\n\n" - "SELECT\n" - " customer_id,\n" - " TIMESTAMP_TRUNC(event_ts, DAY) AS event_day,\n" - " SUM(SAFE_CAST(amount_text AS INT64)) AS amount_cents,\n" - " COUNT(*) AS event_count\n" - 'FROM __source("raw_events")\n' - "GROUP BY customer_id, TIMESTAMP_TRUNC(event_ts, DAY)\n" - ), - scenario_sql=( - "SCENARIO (description 'Test scenario.');\n\n" - "WITH\n" - "__source__raw_events AS (\n" - " SELECT 10 AS customer_id, TIMESTAMP '2026-01-01 08:15:00 UTC' " - "AS event_ts, '1500' AS amount_text\n" - " UNION ALL\n" - " SELECT 10 AS customer_id, TIMESTAMP '2026-01-01 10:30:00 UTC' " - "AS event_ts, '500' AS amount_text\n" - "),\n" - "__expected__event_rollup AS (\n" - " SELECT 10 AS customer_id, " - "TIMESTAMP_TRUNC(TIMESTAMP '2026-01-01 00:00:00 UTC', DAY) AS event_day, " - "2000 AS amount_cents, 2 AS event_count\n" - ")\n" - "SELECT 1\n" - ), - expected_stdout_fragments=( - "transpilable_event_rollup", - "PASS", - "PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", - ), - expected_local_rows=((10, 2000, 2),), - local_rows_sql=( - "SELECT customer_id, amount_cents, event_count " - "FROM __sqb_local__model__event_rollup ORDER BY customer_id" - ), - ), - BigQueryScenarioLocalReplayE2ETestCase( - description="reports bigquery local transpilation failures as X607", - scenario_name="local_transpile_error", - model_sql=( - "MODEL (description 'Test model.', materialized table);\n\n" - "SELECT customer_id, SAFE_CAST(amount_text AS INT64) AS amount_cents\n" - 'FROM __source("raw_events")\n' - ), - scenario_sql=( - "SCENARIO (description 'Test scenario.');\n\n" - "WITH\n" - "__source__raw_events AS (\n" - " SELECT 10 AS customer_id, '1500' AS amount_text\n" - "),\n" - "__expected__event_rollup AS (\n" - " SELECT 10 AS customer_id, '1500' AS amount_text\n" - ")\n" - "SELECT 1\n" - ), - expected_stdout_fragments=( - "local_transpile_error", - "ERROR", - "error[X607]", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", - ), - expected_return_code=1, - corrupt_capture_dialect=True, - ), - BigQueryScenarioLocalReplayE2ETestCase( - description="reports bigquery local DuckDB execution failures as X608", - scenario_name="local_execution_error", - model_sql=( - "MODEL (description 'Test model.', materialized table);\n\n" - "SELECT\n" - " customer_id,\n" - " __sqb_missing_local_function(SAFE_CAST(amount_text AS INT64)) AS amount_cents\n" - 'FROM __source("raw_events")\n' - ), - scenario_sql=( - "SCENARIO (description 'Test scenario.');\n\n" - "WITH\n" - "__source__raw_events AS (\n" - " SELECT 10 AS customer_id, '1500' AS amount_text\n" - "),\n" - "__expected__event_rollup AS (\n" - " SELECT 10 AS customer_id, 1500 AS amount_cents\n" - ")\n" - "SELECT 1\n" - ), - expected_stdout_fragments=( - "local_execution_error", - "ERROR", - "error[X608]", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", - ), - expected_return_code=1, - ), - ], - ids=lambda case: case.description, -) -def test_given_bigquery_scenario_capture_when_replaying_locally_then_transpilable_sql_passes( - tmp_path: Path, - test_case: BigQueryScenarioLocalReplayE2ETestCase, -) -> None: - dataset_name: str = build_unique_dataset_name(prefix="sqlbuild_scenario_local") - project_dir: Path = prepare_inline_project( - tmp_path=tmp_path, - project_name="bigquery_scenario_local_replay", - repo_files=build_real_warehouse_local_replay_project_files( - project_toml=build_bigquery_project_toml( - project_name="bigquery_scenario_local_replay", - dataset_name=dataset_name, - ), - model_sql=test_case.model_sql, - scenario_sql=test_case.scenario_sql, - scenario_name=test_case.scenario_name, - ), - ) - ensure_bigquery_dataset_ready(dataset_name=dataset_name) - - try: - capture_result: subprocess.CompletedProcess[str] = run_sqb( - command=( - "--no-color", - "scenario", - "capture", - test_case.scenario_name, - ), - project_dir=project_dir, - ) - assert capture_result.returncode == 0, capture_result.stdout + capture_result.stderr - maybe_corrupt_scenario_snapshot_dialect( - project_dir=project_dir, - scenario_name=test_case.scenario_name, - enabled=test_case.corrupt_capture_dialect, - ) - - replay_result: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "scenario", "test", test_case.scenario_name, "--local"), - project_dir=project_dir, - ) - - assert replay_result.returncode == test_case.expected_return_code, ( - replay_result.stdout + replay_result.stderr - ) - fragment: str - for fragment in test_case.expected_stdout_fragments: - assert fragment in replay_result.stdout - assert_optional_local_replay_rows( - project_dir=project_dir, - scenario_name=test_case.scenario_name, - local_rows_sql=test_case.local_rows_sql, - expected_local_rows=test_case.expected_local_rows, - ) - finally: - cleanup_bigquery_dataset(dataset_name=dataset_name) - - @pytest.mark.parametrize( "test_case", [ diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/no_tests_no_audits/test_build_no_tests_no_audits.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/no_tests_no_audits/test_build_no_tests_no_audits.py index 775ab5d829..2dafb91763 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/no_tests_no_audits/test_build_no_tests_no_audits.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/no_tests_no_audits/test_build_no_tests_no_audits.py @@ -589,6 +589,7 @@ def test_given_task_selector_with_json_output_when_running_run_then_json_include "timeout_count": 0, "skipped_count": 0, "warning_count": 0, + "not_run_count": 0, "python_check_pass_count": 0, "python_check_warn_count": 0, "python_check_fail_count": 0, @@ -659,6 +660,7 @@ def test_given_failing_task_selector_when_running_run_then_command_fails( "timeout_count": 0, "skipped_count": 0, "warning_count": 0, + "not_run_count": 0, "python_check_pass_count": 0, "python_check_warn_count": 0, "python_check_fail_count": 0, @@ -1125,6 +1127,7 @@ def test_given_skip_and_asset_selection_with_json_when_running_run_then_json_rec "timeout_count": 0, "skipped_count": 1, "warning_count": 0, + "not_run_count": 0, "python_check_pass_count": 0, "python_check_warn_count": 0, "python_check_fail_count": 0, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_build.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_build.py index 8760d47e54..83735fdfb4 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_build.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_build.py @@ -1380,6 +1380,7 @@ def test_given_python_asset_with_json_output_when_building_then_json_includes_py "timeout_count": 0, "skipped_count": 0, "warning_count": 0, + "not_run_count": 0, "python_check_pass_count": 0, "python_check_warn_count": 0, "python_check_fail_count": 0, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_lifecycle_commands.py b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_lifecycle_commands.py index 5b0065a97a..56854662a1 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/build/test_lifecycle_commands.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/build/test_lifecycle_commands.py @@ -236,7 +236,7 @@ def test_given_waffle_shop_when_running_core_lifecycle_commands_then_outputs_are ("seed",), ("audit",), ("plan",), - ("test",), + ("test", "--run-on", "warehouse"), ("query", "SELECT 1"), ) ], diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/_test_types.py index e819e745d9..bb5e4cc012 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/_test_types.py @@ -1271,8 +1271,8 @@ class BenchmarkProjectTestPlanTestCase: description: str project_dir: Path - expected_final_line_prefix: str - expected_final_line_suffix: str + # The summary line; with --inspect, SQLQuack's full refusal diagnostics may follow it. + expected_summary_pattern: str @dataclass(frozen=True) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_duckshop_benchmark_compile.py b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_duckshop_benchmark_compile.py index de95a80121..9fbf6fdca0 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_duckshop_benchmark_compile.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/compile/test_duckshop_benchmark_compile.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import re import shutil import subprocess import sys @@ -71,8 +72,7 @@ def test_given_benchmark_project_when_compiling_then_reports_no_errors_or_warnin BenchmarkProjectTestPlanTestCase( description="duckshop", project_dir=REPO_ROOT / "benchmarks" / "duckshop" / "project", - expected_final_line_prefix="Test plan inspection complete: ", - expected_final_line_suffix=" selected, 0 errors.", + expected_summary_pattern=r"^Test plan inspection complete: \d+ selected, 0 errors\.$", ) ], ids=lambda case: case.description, @@ -94,9 +94,7 @@ def test_given_benchmark_project_when_inspecting_test_plan_then_every_unit_test_ ) assert result.returncode == 0, result.stdout + result.stderr - final_line: str = result.stdout.strip().splitlines()[-1] - assert final_line.startswith(test_case.expected_final_line_prefix), result.stdout - assert final_line.endswith(test_case.expected_final_line_suffix), result.stdout + assert re.search(test_case.expected_summary_pattern, result.stdout, re.MULTILINE), result.stdout @pytest.mark.parametrize( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/databricks/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/databricks/_test_types.py index 0efbff8e75..c471732b5a 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/databricks/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/databricks/_test_types.py @@ -86,19 +86,6 @@ class DatabricksErrorE2ETestCase: expected_return_code: int = 1 -@dataclass(frozen=True) -class DatabricksScenarioLocalReplayE2ETestCase: - description: str - model_sql: str - scenario_sql: str - expected_stdout_fragments: tuple[str, ...] - expected_return_code: int = 0 - scenario_name: str = "transpilable_event_rollup" - expected_local_rows: tuple[tuple[object, ...], ...] = field(default_factory=tuple) - local_rows_sql: str = "" - corrupt_capture_dialect: bool = False - - @dataclass(frozen=True) class DatabricksScenarioRemoteE2ETestCase: description: str diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/databricks/test_databricks.py b/tests/e2e/src/sqlbuild/cli/commands/main/databricks/test_databricks.py index 8b9a4f9c44..82e6236185 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/databricks/test_databricks.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/databricks/test_databricks.py @@ -15,7 +15,6 @@ DatabricksErrorE2ETestCase, DatabricksIntermediateDagStrategyE2ETestCase, DatabricksNodeResultE2ETestCase, - DatabricksScenarioLocalReplayE2ETestCase, DatabricksScenarioRemoteE2ETestCase, DatabricksSnapshotApplyE2ETestCase, DatabricksSnapshotE2ETestCase, @@ -44,10 +43,7 @@ build_schema_behavior_project_files, ) from tests.e2e.src.sqlbuild.cli.commands.main.scenario.helpers import ( - assert_optional_local_replay_rows, - build_real_warehouse_local_replay_project_files, build_real_warehouse_remote_scenario_project_files, - maybe_corrupt_scenario_snapshot_dialect, ) from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import ( assert_dbt_profile_lifecycle, @@ -603,167 +599,6 @@ def test_given_existing_snapshot_targets_when_building_on_databricks_then_apply_ cleanup_databricks_schema(schema_name=schema_name) -@pytest.mark.parametrize( - "test_case", - [ - DatabricksScenarioLocalReplayE2ETestCase( - description="captures databricks fixtures and replays transpilable SQL locally", - model_sql=( - "MODEL (description 'Test model.', materialized table);\n\n" - "SELECT\n" - " customer_id,\n" - " date_trunc('DAY', event_ts) AS event_day,\n" - " SUM(if(amount_cents >= 1000, amount_cents, 0)) AS large_amount_cents,\n" - " COUNT(*) AS event_count\n" - 'FROM __source("raw_events")\n' - "GROUP BY customer_id, date_trunc('DAY', event_ts)\n" - ), - scenario_sql=( - "SCENARIO (description 'Test scenario.');\n\n" - "WITH\n" - "__source__raw_events AS (\n" - " SELECT 10 AS customer_id, TIMESTAMP '2026-01-01 08:15:00' " - "AS event_ts, 1500 AS amount_cents\n" - " UNION ALL\n" - " SELECT 10 AS customer_id, TIMESTAMP '2026-01-01 10:30:00' " - "AS event_ts, 500 AS amount_cents\n" - "),\n" - "__expected__event_rollup AS (\n" - " SELECT 10 AS customer_id, " - "date_trunc('DAY', TIMESTAMP '2026-01-01 00:00:00') AS event_day, " - "1500 AS large_amount_cents, 2 AS event_count\n" - ")\n" - "SELECT 1\n" - ), - expected_stdout_fragments=( - "transpilable_event_rollup", - "PASS", - "PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", - ), - expected_local_rows=((10, 1500, 2),), - local_rows_sql=( - "SELECT customer_id, large_amount_cents, event_count " - "FROM __sqb_local__model__event_rollup ORDER BY customer_id" - ), - ), - DatabricksScenarioLocalReplayE2ETestCase( - description="reports databricks local transpilation failures as X607", - scenario_name="local_transpile_error", - model_sql=( - "MODEL (description 'Test model.', materialized table);\n\n" - "SELECT customer_id, amount_cents\n" - 'FROM __source("raw_events")\n' - ), - scenario_sql=( - "SCENARIO (description 'Test scenario.');\n\n" - "WITH\n" - "__source__raw_events AS (\n" - " SELECT 10 AS customer_id, 1500 AS amount_cents\n" - "),\n" - "__expected__event_rollup AS (\n" - " SELECT 10 AS customer_id, 1500 AS amount_cents\n" - ")\n" - "SELECT 1\n" - ), - expected_stdout_fragments=( - "local_transpile_error", - "ERROR", - "error[X607]", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", - ), - expected_return_code=1, - corrupt_capture_dialect=True, - ), - DatabricksScenarioLocalReplayE2ETestCase( - description="reports databricks local DuckDB execution failures as X608", - scenario_name="local_execution_error", - model_sql=( - "MODEL (description 'Test model.', materialized table);\n\n" - "SELECT\n" - " customer_id,\n" - " __sqb_missing_local_function(amount_cents) AS amount_cents\n" - 'FROM __source("raw_events")\n' - ), - scenario_sql=( - "SCENARIO (description 'Test scenario.');\n\n" - "WITH\n" - "__source__raw_events AS (\n" - " SELECT 10 AS customer_id, 1500 AS amount_cents\n" - "),\n" - "__expected__event_rollup AS (\n" - " SELECT 10 AS customer_id, 1500 AS amount_cents\n" - ")\n" - "SELECT 1\n" - ), - expected_stdout_fragments=( - "local_execution_error", - "ERROR", - "error[X608]", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", - ), - expected_return_code=1, - ), - ], - ids=lambda case: case.description, -) -def test_given_databricks_scenario_capture_when_replaying_locally_then_transpilable_sql_passes( - tmp_path: Path, - test_case: DatabricksScenarioLocalReplayE2ETestCase, -) -> None: - schema_name: str = build_unique_schema_name(prefix="sqlbuild_scenario_local") - project_dir: Path = prepare_inline_project( - tmp_path=tmp_path, - project_name="databricks_scenario_local_replay", - repo_files=build_real_warehouse_local_replay_project_files( - project_toml=build_databricks_project_toml( - project_name="databricks_scenario_local_replay", - schema_name=schema_name, - ), - model_sql=test_case.model_sql, - scenario_sql=test_case.scenario_sql, - scenario_name=test_case.scenario_name, - ), - ) - ensure_databricks_schema_ready(schema_name=schema_name) - - try: - capture_result: subprocess.CompletedProcess[str] = run_sqb( - command=( - "--no-color", - "scenario", - "capture", - test_case.scenario_name, - ), - project_dir=project_dir, - ) - assert capture_result.returncode == 0, capture_result.stdout + capture_result.stderr - maybe_corrupt_scenario_snapshot_dialect( - project_dir=project_dir, - scenario_name=test_case.scenario_name, - enabled=test_case.corrupt_capture_dialect, - ) - - replay_result: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "scenario", "test", test_case.scenario_name, "--local"), - project_dir=project_dir, - ) - - assert replay_result.returncode == test_case.expected_return_code, ( - replay_result.stdout + replay_result.stderr - ) - fragment: str - for fragment in test_case.expected_stdout_fragments: - assert fragment in replay_result.stdout - assert_optional_local_replay_rows( - project_dir=project_dir, - scenario_name=test_case.scenario_name, - local_rows_sql=test_case.local_rows_sql, - expected_local_rows=test_case.expected_local_rows, - ) - finally: - cleanup_databricks_schema(schema_name=schema_name) - - @pytest.mark.parametrize( "test_case", [ diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/postgres/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/postgres/_test_types.py index 6da08b7adc..f4f9d930e1 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/postgres/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/postgres/_test_types.py @@ -80,19 +80,6 @@ class PostgresSnapshotApplyE2ETestCase: expected_historical_check_rows: tuple[tuple[object, ...], ...] -@dataclass(frozen=True) -class PostgresScenarioLocalReplayE2ETestCase: - description: str - model_sql: str - scenario_sql: str - expected_stdout_fragments: tuple[str, ...] - expected_return_code: int = 0 - scenario_name: str = "transpilable_event_rollup" - expected_local_rows: tuple[tuple[object, ...], ...] = field(default_factory=tuple) - local_rows_sql: str = "" - corrupt_capture_dialect: bool = False - - @dataclass(frozen=True) class PostgresSourceDeferralE2ETestCase: description: str diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_postgres.py b/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_postgres.py index 75fb4c941b..f83f4e9ae3 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_postgres.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/postgres/test_postgres.py @@ -17,7 +17,6 @@ PostgresLoaderWaffleShopE2ETestCase, PostgresNodeResultE2ETestCase, PostgresPartialSourceTypeEnforcementE2ETestCase, - PostgresScenarioLocalReplayE2ETestCase, PostgresSnapshotApplyE2ETestCase, PostgresSnapshotE2ETestCase, PostgresSourceDeferralE2ETestCase, @@ -42,11 +41,6 @@ prepare_postgres_waffle_shop, relation_name, ) -from tests.e2e.src.sqlbuild.cli.commands.main.scenario.helpers import ( - assert_optional_local_replay_rows, - build_real_warehouse_local_replay_project_files, - maybe_corrupt_scenario_snapshot_dialect, -) from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import ( add_dbt_profile_downstream_model, build_current_check_customers_model_sql, @@ -704,135 +698,6 @@ def test_given_loader_strategy_project_when_loading_twice_on_postgres_then_write cleanup_postgres_schema(schema_name=schema_name, config=postgres_e2e_config) -@pytest.mark.parametrize( - "test_case", - [ - PostgresScenarioLocalReplayE2ETestCase( - description="captures postgres fixtures and replays transpilable SQL locally", - model_sql=( - "MODEL (description 'Test model.', materialized table);\n\n" - "SELECT\n" - " customer_id,\n" - " DATE_TRUNC('day', event_ts) AS event_day,\n" - " SUM(CASE WHEN amount_cents >= 1000 THEN amount_cents ELSE 0 END)" - " AS large_amount_cents,\n" - " COUNT(*) AS event_count\n" - 'FROM __source("raw_events")\n' - "GROUP BY customer_id, DATE_TRUNC('day', event_ts)\n" - ), - scenario_sql=( - "SCENARIO (description 'Test scenario.');\n\n" - "WITH\n" - "__source__raw_events AS (\n" - " SELECT 10 AS customer_id, CAST('2026-01-01 08:15:00' AS TIMESTAMP)" - " AS event_ts, 1500 AS amount_cents\n" - " UNION ALL\n" - " SELECT 10 AS customer_id, CAST('2026-01-01 10:30:00' AS TIMESTAMP)" - " AS event_ts, 500 AS amount_cents\n" - "),\n" - "__expected__event_rollup AS (\n" - " SELECT 10 AS customer_id," - " DATE_TRUNC('day', CAST('2026-01-01 00:00:00' AS TIMESTAMP)) AS event_day," - " 1500 AS large_amount_cents, 2 AS event_count\n" - ")\n" - "SELECT 1\n" - ), - expected_stdout_fragments=( - "transpilable_event_rollup", - "PASS", - "PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", - ), - expected_local_rows=((10, 1500, 2),), - local_rows_sql=( - "SELECT customer_id, large_amount_cents, event_count " - "FROM __sqb_local__model__event_rollup ORDER BY customer_id" - ), - ), - PostgresScenarioLocalReplayE2ETestCase( - description="reports postgres local transpilation failures as X607", - scenario_name="local_transpile_error", - model_sql=( - "MODEL (description 'Test model.', materialized table);\n\n" - "SELECT customer_id, amount_cents\n" - 'FROM __source("raw_events")\n' - ), - scenario_sql=( - "SCENARIO (description 'Test scenario.');\n\n" - "WITH\n" - "__source__raw_events AS (\n" - " SELECT 10 AS customer_id, 1500 AS amount_cents\n" - "),\n" - "__expected__event_rollup AS (\n" - " SELECT 10 AS customer_id, 1500 AS amount_cents\n" - ")\n" - "SELECT 1\n" - ), - expected_stdout_fragments=( - "local_transpile_error", - "ERROR", - "error[X607]", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", - ), - expected_return_code=1, - corrupt_capture_dialect=True, - ), - ], - ids=lambda case: case.description, -) -def test_given_postgres_scenario_capture_when_replaying_locally_then_transpilable_sql_passes( - tmp_path: Path, - test_case: PostgresScenarioLocalReplayE2ETestCase, - postgres_e2e_config: dict[str, object], -) -> None: - schema_name: str = build_unique_schema_name(prefix="sqb_scenario_local") - project_dir: Path = prepare_inline_project( - tmp_path=tmp_path, - project_name="postgres_scenario_local_replay", - repo_files=build_real_warehouse_local_replay_project_files( - project_toml=build_postgres_project_toml( - project_name="postgres_scenario_local_replay", - schema_name=schema_name, - config=postgres_e2e_config, - ), - model_sql=test_case.model_sql, - scenario_sql=test_case.scenario_sql, - scenario_name=test_case.scenario_name, - ), - ) - ensure_postgres_schema_ready(schema_name=schema_name, config=postgres_e2e_config) - - try: - capture_result: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "scenario", "capture", test_case.scenario_name), - project_dir=project_dir, - ) - assert capture_result.returncode == 0, capture_result.stdout + capture_result.stderr - maybe_corrupt_scenario_snapshot_dialect( - project_dir=project_dir, - scenario_name=test_case.scenario_name, - enabled=test_case.corrupt_capture_dialect, - ) - - replay_result: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "scenario", "test", test_case.scenario_name, "--local"), - project_dir=project_dir, - ) - - assert replay_result.returncode == test_case.expected_return_code, ( - replay_result.stdout + replay_result.stderr - ) - for fragment in test_case.expected_stdout_fragments: - assert fragment in replay_result.stdout - assert_optional_local_replay_rows( - project_dir=project_dir, - scenario_name=test_case.scenario_name, - local_rows_sql=test_case.local_rows_sql, - expected_local_rows=test_case.expected_local_rows, - ) - finally: - cleanup_postgres_schema(schema_name=schema_name, config=postgres_e2e_config) - - @pytest.mark.parametrize( "test_case", [ diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/_test_types.py index 2972c895dc..26ad7c5b32 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/_test_types.py @@ -90,7 +90,7 @@ class ScenarioLocalRuntimeArtifactTestCase: @dataclass(frozen=True) class ScenarioLocalCliE2ETestCase: - """Test case for sqb scenario test --local verification.""" + """Test case for sqb scenario test --run-on local verification.""" description: str command: tuple[str, ...] @@ -371,3 +371,13 @@ class CapturedLambdaScenarioTestCase: description: str scenario_name: str expected_stdout_fragment: str + + +@dataclass(frozen=True) +class GuardedScenarioRunOnTestCase: + """A scenario whose SQLQuack guard raises in DuckDB, run with one `--run-on` value.""" + + description: str + run_on: str + expected_text: str + expected_local_lines: int diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/helpers.py index acf0a88fc6..f2f731548c 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/helpers.py @@ -1302,7 +1302,7 @@ def build_snowflake_lambda_scenario_project_files() -> dict[str, str]: "sql/models/order_quantities.sql": ( 'MODEL (description "Quantities above each order id.");\n' "SELECT order_id,\n" - " FILTER(ARRAY_CONSTRUCT(1, 2, 3), x -> x > order_id) AS big_quantities\n" + " FILTER(ARRAY_CONSTRUCT(1, 2, 3), x -> x::NUMBER > order_id) AS big_quantities\n" 'FROM __source("raw_orders")\n' ), "tests/scenarios/order_quantities__lambda.sql": ( @@ -1317,12 +1317,41 @@ def build_snowflake_lambda_scenario_project_files() -> dict[str, str]: } -def write_snowflake_order_ids_snapshot(*, project_dir: Path, scenario_name: str) -> None: - """Write the snapshot a Snowflake capture stores for a one-column order source.""" +SNOWFLAKE_TWO_ORDER_IDS_FIXTURE_SQL: str = "SELECT 1 AS order_id UNION ALL SELECT 2" + + +def build_snowflake_guarded_scenario_project_files() -> dict[str, str]: + """An offline Snowflake project whose model's SQLQuack guard raises on the captured rows.""" + + return { + **build_snowflake_lambda_scenario_project_files(), + "sql/models/order_id_lists.sql": ( + 'MODEL (description "Every order id.");\n' + "SELECT ARRAY_AGG(order_id) AS order_ids\n" + 'FROM __source("raw_orders")\n' + ), + "tests/scenarios/order_id_lists__guarded.sql": ( + "SCENARIO (description 'ARRAY_AGG of several rows raises its guard locally.');\n" + "WITH\n" + f"__source__raw_orders AS ({SNOWFLAKE_TWO_ORDER_IDS_FIXTURE_SQL}),\n" + "__expected__order_id_lists AS (SELECT ARRAY_CONSTRUCT(1, 2) AS order_ids)\n" + "SELECT 1\n" + ), + } + + +def write_snowflake_order_ids_snapshot( + *, + project_dir: Path, + scenario_name: str, + fixture_sql: str = SNOWFLAKE_ORDER_IDS_FIXTURE_SQL, + order_ids: tuple[int, ...] = (1,), +) -> None: + """Write the snapshot a Snowflake capture of `fixture_sql` stores for a one-column source.""" snapshot_root: Path = project_dir / "tests" / "_scenario_snapshots" / scenario_name (snapshot_root / "sources").mkdir(parents=True) - row: str = json.dumps({"ORDER_ID": 1}) + "\n" + row: str = "".join(json.dumps({"ORDER_ID": order_id}) + "\n" for order_id in order_ids) (snapshot_root / "sources" / "raw_orders.jsonl").write_text(row, encoding="utf-8") manifest: dict[str, object] = { "capture_adapter": "snowflake", @@ -1336,7 +1365,7 @@ def write_snowflake_order_ids_snapshot(*, project_dir: Path, scenario_name: str) kind=ScenarioArtifactKind.SOURCE, logical_name="raw_orders", file_path=Path("sources") / "raw_orders.jsonl", - capture_sql=SNOWFLAKE_ORDER_IDS_FIXTURE_SQL, + capture_sql=fixture_sql, ), ), capture_adapter="snowflake", @@ -1355,13 +1384,13 @@ def write_snowflake_order_ids_snapshot(*, project_dir: Path, scenario_name: str) "file": "sources/raw_orders.jsonl", "kind": "source", "logical_name": "raw_orders", - "row_count": 1, + "row_count": len(order_ids), } ], "scenario_name": scenario_name, "sqlbuild_version": "0.177.0", "total_bytes": len(row.encode("utf-8")), - "total_rows": 1, + "total_rows": len(order_ids), "version": 1, } (snapshot_root / "scenario.json").write_text( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_authored_check_sql.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_authored_check_sql.py index 6d4f51e748..40974cfb47 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_authored_check_sql.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_authored_check_sql.py @@ -162,7 +162,7 @@ def test_given_unclosed_scenario_string_when_testing_then_fails_without_running( ' SELECT * FROM __ref("order_totals")\n' " WHERE total_amount <> 15 AND 'D\\'Arcy' IS NULL" ), - expected_stdout_fragment="PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + expected_stdout_fragment="PASS=1 FAIL=0 TOTAL=1", ), ], ids=lambda case: case.description, @@ -174,6 +174,17 @@ def test_given_project_dialect_scenario_sql_when_replaying_locally_then_resolves del repo_files["tests/scenarios/order_totals_pass.sql"] del repo_files["tests/scenarios/order_totals_fail.sql"] del repo_files["tests/scenarios/nested/orders_assert_pass.sql"] + # SQLQuack converts a model only when the models it reads declare their column types. + repo_files["sql/models/orders.sql"] = ( + "MODEL (\n description 'Test model orders.',\n materialized table,\n" + " columns (order_id (type NUMBER(38,0)), amount (type NUMBER(38,0))),\n);\n\n" + 'SELECT id AS order_id, amount FROM __source("raw_orders")\n' + ) + repo_files["sql/models/order_totals.sql"] = ( + "MODEL (\n description 'Test model order_totals.',\n materialized table,\n" + " columns (total_amount (type NUMBER(38,0))),\n);\n\n" + 'SELECT SUM(amount) AS total_amount FROM __ref("orders")\n' + ) repo_files[f"tests/scenarios/{test_case.scenario_name}.sql"] = ( "SCENARIO (description 'Test scenario orders_assert_pass.');\n\n" "WITH\n" @@ -200,7 +211,7 @@ def test_given_project_dialect_scenario_sql_when_replaying_locally_then_resolves ) result: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "scenario", "test", test_case.scenario_name, "--local"), + command=("--no-color", "scenario", "test", test_case.scenario_name, "--run-on", "local"), project_dir=project_dir, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_concurrency.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_concurrency.py index f6b37b0911..c0b1f32acf 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_concurrency.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_concurrency.py @@ -21,8 +21,12 @@ ) from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import prepare_inline_project, run_sqb -_SCENARIO_ROW: re.Pattern[str] = re.compile(r"^order_totals_pass\s+PASS \d+\.\d\ds$", re.M) -_SUMMARY: re.Pattern[str] = re.compile(r"PASS=2 FAIL=1 TOTAL=3 \(\d+\.\d\ds\)") +_SCENARIO_ROW: re.Pattern[str] = re.compile( + r"^order_totals_pass\s+PASS warehouse \d+\.\d\ds$", re.M +) +_SUMMARY: re.Pattern[str] = re.compile( + r"PASS=2 FAIL=1 TOTAL=3 \(0 local, 3 warehouse, \d+\.\d\ds\)" +) @pytest.mark.parametrize( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_fixture_columns.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_fixture_columns.py index b7e719d6aa..57418100fa 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_fixture_columns.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_fixture_columns.py @@ -46,8 +46,9 @@ ScenarioInlineProjectE2ETestCase( description="CONNECT BY pseudo-columns are not mock columns", repo_files=build_connect_by_scenario_project_files(), - command=("--no-color", "scenario", "test", "--local"), - expected_exit_code=0, + command=("--no-color", "scenario", "test", "--run-on", "local"), + # Fixture checks pass; local runs are strict, so the missing snapshot is an error. + expected_exit_code=1, expected_stdout_fragments=("missing local snapshot manifest",), ), ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_interrupts.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_interrupts.py index 6416667777..16e3c0a275 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_interrupts.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_interrupts.py @@ -88,7 +88,7 @@ def test_given_long_statement_when_interrupted_then_stops_promptly_and_cleans_up [ ScenarioInterruptE2ETestCase( description="local replay cancels the in-flight statement with clean json stdout", - args=("test", "--local", "--json"), + args=("test", "--run-on", "local", "--json"), trigger="order_totals START", long_model=True, ), diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_escaped_quotes.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_escaped_quotes.py index 6a56525525..e65c09c708 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_escaped_quotes.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_escaped_quotes.py @@ -84,7 +84,7 @@ "'EU' AS region", _NOTE_SQL, ), - expected_stdout_fragment="PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + expected_stdout_fragment="PASS=1 FAIL=0 TOTAL=1", ), ], ids=lambda case: case.description, @@ -103,7 +103,7 @@ def test_given_snowflake_backslash_escapes_when_compiling_and_replaying_locally_ command=("--no-color", "compile"), project_dir=project_dir ) replayed: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "scenario", "test", "--local", "--strict", test_case.scenario_name), + command=("--no-color", "scenario", "test", "--run-on", "local", test_case.scenario_name), project_dir=project_dir, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_guard.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_guard.py new file mode 100644 index 0000000000..d1d9052f67 --- /dev/null +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_guard.py @@ -0,0 +1,81 @@ +"""E2E coverage of a scenario whose SQLQuack guard raises when it replays in DuckDB.""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +import pytest + +from tests.e2e.src.sqlbuild.cli.commands.main.scenario._test_types import ( + GuardedScenarioRunOnTestCase, +) +from tests.e2e.src.sqlbuild.cli.commands.main.scenario.helpers import ( + SNOWFLAKE_TWO_ORDER_IDS_FIXTURE_SQL, + build_snowflake_guarded_scenario_project_files, + write_snowflake_order_ids_snapshot, +) +from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import prepare_inline_project, run_sqb + +_SCENARIO: str = "order_id_lists__guarded" +_LOCAL_LINE: str = "table order_id_lists__guarded/order_id_lists START" + + +@pytest.mark.parametrize( + "test_case", + [ + GuardedScenarioRunOnTestCase( + description="--run-on local makes it an error naming the guard", + run_on="local", + expected_text=( + "error[T007]: SQLQuack's guard array_agg_order raised in DuckDB: ARRAY_AGG of" + " several values in no defined order\n" + " = help: Run this scenario on the warehouse with --run-on warehouse.\n" + ), + expected_local_lines=1, + ), + GuardedScenarioRunOnTestCase( + description="--run-on local lists it under Can't run locally", + run_on="local", + expected_text=( + "Can't run locally (1 scenario)\n\nerror: SQLQuack guard: array_agg_order\n" + ), + expected_local_lines=1, + ), + GuardedScenarioRunOnTestCase( + description="auto runs it again on the warehouse and hides the local attempt", + run_on="auto", + expected_text="Connecting to snowflake...\n", + expected_local_lines=0, + ), + ], + ids=lambda case: case.description, +) +def test_given_scenario_whose_guard_raises_locally_when_testing_then_it_needs_the_warehouse( + test_case: GuardedScenarioRunOnTestCase, tmp_path: Path +) -> None: + project_dir: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="snowflake_guarded_scenario", + repo_files=build_snowflake_guarded_scenario_project_files(), + ) + write_snowflake_order_ids_snapshot( + project_dir=project_dir, + scenario_name=_SCENARIO, + fixture_sql=SNOWFLAKE_TWO_ORDER_IDS_FIXTURE_SQL, + order_ids=(1, 2), + ) + + result: subprocess.CompletedProcess[str] = run_sqb( + command=("--no-color", "scenario", "test", "--run-on", test_case.run_on, _SCENARIO), + project_dir=project_dir, + ) + + output: str = result.stdout + result.stderr + assert result.returncode == 1, output + assert test_case.expected_text in output, output + assert output.count(_LOCAL_LINE) == test_case.expected_local_lines, output + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"]) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_lambda.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_lambda.py index 707c1e5e6f..27d3e4b606 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_lambda.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_lambda.py @@ -23,7 +23,7 @@ CapturedLambdaScenarioTestCase( description="a Snowflake FILTER with an arrow lambda replays locally", scenario_name="order_quantities__lambda", - expected_stdout_fragment="PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + expected_stdout_fragment="PASS=1 FAIL=0 TOTAL=1", ), ], ids=lambda case: case.description, @@ -41,7 +41,7 @@ def test_given_snowflake_arrow_lambda_when_replaying_locally_then_the_scenario_p ) replayed: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "scenario", "test", "--local", "--strict", test_case.scenario_name), + command=("--no-color", "scenario", "test", "--run-on", "local", test_case.scenario_name), project_dir=project_dir, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_variant.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_variant.py index 6f8f81b177..4a50ffad0b 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_variant.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_local_variant.py @@ -26,7 +26,7 @@ description="a captured VARIANT fixture replays locally in strict mode", repo_files=build_local_variant_scenario_project_files(), scenario_name="orders__keep_payload", - expected_stdout_fragment="PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + expected_stdout_fragment="PASS=1 FAIL=0 TOTAL=1", ), LocalVariantScenarioTestCase( description="an expected VARIANT object compares equal to the replayed fixture", @@ -35,7 +35,7 @@ expected='\'{"qty": 2, "tags": ["a"]}\'::JSON::VARIANT AS payload', ), scenario_name="orders__keep_payload", - expected_stdout_fragment="PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + expected_stdout_fragment="PASS=1 FAIL=0 TOTAL=1", ), LocalVariantScenarioTestCase( description="a cast-built VARIANT object compares equal to the replayed fixture", @@ -45,7 +45,7 @@ expected="{'note': 'x', 'qty': 2}::VARIANT AS payload", ), scenario_name="orders__keep_payload", - expected_stdout_fragment="PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + expected_stdout_fragment="PASS=1 FAIL=0 TOTAL=1", ), LocalVariantScenarioTestCase( description="a cast-built VARIANT scalar compares equal to the replayed fixture", @@ -53,7 +53,7 @@ fixture="2::VARIANT", output="o.payload", expected="2::VARIANT AS payload" ), scenario_name="orders__keep_payload", - expected_stdout_fragment="PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + expected_stdout_fragment="PASS=1 FAIL=0 TOTAL=1", ), LocalVariantScenarioTestCase( description="a quoted VARIANT output column compares by its JSON value", @@ -63,7 +63,7 @@ expected='\'{"note": "x", "qty": 2}\'::JSON::VARIANT AS "Payload"', ), scenario_name="orders__keep_payload", - expected_stdout_fragment="PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + expected_stdout_fragment="PASS=1 FAIL=0 TOTAL=1", ), LocalVariantScenarioTestCase( description="a different cast-built VARIANT value still fails the comparison", @@ -96,8 +96,8 @@ def test_given_captured_variant_fixture_when_replaying_locally_then_the_scenario "--no-color", "scenario", "test", - "--local", - "--strict", + "--run-on", + "local", test_case.scenario_name, ), project_dir=project_dir, @@ -116,14 +116,14 @@ def test_given_captured_variant_fixture_when_replaying_locally_then_the_scenario captured_payload_text='{\n "note": "x",\n "qty": 2\n}', expected_payload_json='{"qty": 2, "note": "x"}', expected_returncode=0, - expected_stdout_fragment="PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + expected_stdout_fragment="PASS=1 FAIL=0 TOTAL=1", ), CapturedVariantTextScenarioTestCase( description="nested objects in another key order equal the expected value", captured_payload_text='{\n "a": [\n 1,\n {\n "d": 2,\n "c": 3\n }\n ],\n "b": null\n}', expected_payload_json='{"b": null, "a": [1, {"c": 3, "d": 2}]}', expected_returncode=0, - expected_stdout_fragment="PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + expected_stdout_fragment="PASS=1 FAIL=0 TOTAL=1", ), CapturedVariantTextScenarioTestCase( description="a different value still fails the comparison", @@ -156,8 +156,8 @@ def test_given_snowflake_variant_text_snapshot_when_replaying_locally_then_json_ "--no-color", "scenario", "test", - "--local", - "--strict", + "--run-on", + "local", "payloads__variant_compare", ), project_dir=project_dir, diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_promotion.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_promotion.py index fb25e63a23..5e97777867 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_promotion.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_promotion.py @@ -158,7 +158,7 @@ def test_given_enforced_contract_and_immediate_promotion_when_running_then_fails ("plan", ("plan",)), ("build", ("build",)), ("scenario", ("scenario", "test")), - ("scenario_local", ("scenario", "test", "--local")), + ("scenario_local", ("scenario", "test", "--run-on", "local")), ) } diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_scenario.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_scenario.py index e25ad2f19b..a4a3b2284b 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_scenario.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_scenario.py @@ -135,12 +135,12 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n description="captured snapshot keeps local DuckDB by default", scenario_name="order_totals_pass", capture_command=("--no-color", "scenario", "capture", "order_totals_pass"), - command=("--no-color", "scenario", "test", "order_totals_pass", "--local"), + command=("--no-color", "scenario", "test", "order_totals_pass", "--run-on", "local"), expected_exit_code=0, expected_stdout_fragments=( "order_totals_pass", "Retained local DuckDB:", - "PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + "PASS=1 FAIL=0 TOTAL=1", ), retained_duckdb_relative_path=Path("target/run/scenarios/order_totals_pass/local.duckdb"), retained_count_sql='SELECT COUNT(*) FROM "__sqb_local__source__raw_orders"', @@ -152,14 +152,14 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n description="malformed local JSONL errors and retains local DuckDB", scenario_name="order_totals_pass", capture_command=("--no-color", "scenario", "capture", "order_totals_pass"), - command=("--no-color", "scenario", "test", "order_totals_pass", "--local"), + command=("--no-color", "scenario", "test", "order_totals_pass", "--run-on", "local"), expected_exit_code=1, expected_stdout_fragments=( "order_totals_pass", "ERROR", "error[X604]:", "Retained local DuckDB:", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), retained_duckdb_relative_path=Path("target/run/scenarios/order_totals_pass/local.duckdb"), retained_count_sql='SELECT COUNT(*) FROM "__sqb_local__source__raw_orders"', @@ -170,14 +170,14 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n description="expected mismatch is local FAIL", scenario_name="order_totals_fail", capture_command=("--no-color", "scenario", "capture", "order_totals_fail"), - command=("--no-color", "scenario", "test", "order_totals_fail", "--local"), + command=("--no-color", "scenario", "test", "order_totals_fail", "--run-on", "local"), expected_exit_code=1, expected_stdout_fragments=( "order_totals_fail", "FAIL", "error[X506]:", "expect expected order_totals", - "PASS=0 FAIL=1 ERROR=0 SKIP=0 TOTAL=1", + "PASS=0 FAIL=1 TOTAL=1", ), retained_duckdb_relative_path=Path("target/run/scenarios/order_totals_fail/local.duckdb"), retained_count_sql='SELECT COUNT(*) FROM "__sqb_local__source__raw_orders"', @@ -189,14 +189,14 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n description="local model execution error is ERROR", scenario_name="local_model_error", capture_command=("--no-color", "scenario", "capture", "local_model_error"), - command=("--no-color", "scenario", "test", "local_model_error", "--local"), + command=("--no-color", "scenario", "test", "local_model_error", "--run-on", "local"), expected_exit_code=1, expected_stdout_fragments=( "local_model_error", "ERROR", "error[X608]:", "not_a_number_", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), retained_duckdb_relative_path=Path("target/run/scenarios/local_model_error/local.duckdb"), retained_count_sql='SELECT COUNT(*) FROM "__sqb_local__source__raw_orders"', @@ -226,11 +226,11 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n description="local SQL function scenario passes", scenario_name="local_sql_function_pass", capture_command=("--no-color", "scenario", "capture", "local_sql_function_pass"), - command=("--no-color", "scenario", "test", "local_sql_function_pass", "--local"), + command=("--no-color", "scenario", "test", "local_sql_function_pass", "--run-on", "local"), expected_exit_code=0, expected_stdout_fragments=( "local_sql_function_pass", - "PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + "PASS=1 FAIL=0 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/local_sql_function_pass/local.duckdb" @@ -270,7 +270,14 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n description="local SQL function setup error is ERROR", scenario_name="local_sql_function_setup_error", capture_command=("--no-color", "scenario", "capture", "local_sql_function_setup_error"), - command=("--no-color", "scenario", "test", "local_sql_function_setup_error", "--local"), + command=( + "--no-color", + "scenario", + "test", + "local_sql_function_setup_error", + "--run-on", + "local", + ), expected_exit_code=1, expected_stdout_fragments=( "local_sql_function_setup_error", @@ -278,7 +285,7 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n "error[X609]:", "local function 'bad_sql_function' failed", "missing_col", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/local_sql_function_setup_error/local.duckdb" @@ -324,15 +331,16 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n "scenario", "test", "local_sql_function_transpile_error", - "--local", + "--run-on", + "local", ), expected_exit_code=1, expected_stdout_fragments=( "local_sql_function_transpile_error", "ERROR", "error[X607]:", - "bad_transpile_function", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "cannot run locally: SQLQuack converts Snowflake SQL only", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/local_sql_function_transpile_error/local.duckdb" @@ -369,14 +377,21 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n description="local SQL function runtime error is ERROR", scenario_name="local_sql_function_runtime_error", capture_command=("--no-color", "scenario", "capture", "local_sql_function_runtime_error"), - command=("--no-color", "scenario", "test", "local_sql_function_runtime_error", "--local"), + command=( + "--no-color", + "scenario", + "test", + "local_sql_function_runtime_error", + "--run-on", + "local", + ), expected_exit_code=1, expected_stdout_fragments=( "local_sql_function_runtime_error", "ERROR", "error[X608]:", "Could not convert string", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/local_sql_function_runtime_error/local.duckdb" @@ -413,11 +428,18 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n description="local Python function scenario passes", scenario_name="local_python_function_pass", capture_command=("--no-color", "scenario", "capture", "local_python_function_pass"), - command=("--no-color", "scenario", "test", "local_python_function_pass", "--local"), + command=( + "--no-color", + "scenario", + "test", + "local_python_function_pass", + "--run-on", + "local", + ), expected_exit_code=0, expected_stdout_fragments=( "local_python_function_pass", - "PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + "PASS=1 FAIL=0 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/local_python_function_pass/local.duckdb" @@ -464,14 +486,21 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n description="local Python function setup error is ERROR", scenario_name="local_python_function_error", capture_command=("--no-color", "scenario", "capture", "local_python_function_error"), - command=("--no-color", "scenario", "test", "local_python_function_error", "--local"), + command=( + "--no-color", + "scenario", + "test", + "local_python_function_error", + "--run-on", + "local", + ), expected_exit_code=1, expected_stdout_fragments=( "local_python_function_error", "ERROR", "error[X609]:", "cannot set database or schema", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/local_python_function_error/local.duckdb" @@ -525,7 +554,8 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n "scenario", "test", "local_python_function_runtime_error", - "--local", + "--run-on", + "local", ), expected_exit_code=1, expected_stdout_fragments=( @@ -533,7 +563,7 @@ def test_given_partial_scenario_fixture_when_required_type_is_known_then_typed_n "ERROR", "error[X608]:", "python udf exploded", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/local_python_function_runtime_error/local.duckdb" @@ -772,32 +802,31 @@ def test_given_scenario_project_with_python_hooks_when_running_cli_then_hooks_ex "test_case", ( ScenarioLocalCliE2ETestCase( - description="missing snapshot skips by default", - command=("--no-color", "scenario", "test", "order_totals_pass", "--local"), + description="missing snapshot runs on the warehouse under auto", + command=("--no-color", "scenario", "test", "order_totals_pass"), expected_exit_code=0, expected_stdout_fragments=( "order_totals_pass", - "SKIP", - "error[X601]:", - "PASS=0 FAIL=0 ERROR=0 SKIP=1 TOTAL=1", + "PASS warehouse", + "PASS=1 FAIL=0 TOTAL=1 (0 local, 1 warehouse", ), ), ScenarioLocalCliE2ETestCase( - description="missing snapshot errors with strict", + description="missing snapshot errors locally", command=( "--no-color", "scenario", "test", "order_totals_pass", - "--local", - "--strict", + "--run-on", + "local", ), expected_exit_code=1, expected_stdout_fragments=( "order_totals_pass", "ERROR", "error[X601]:", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), ), ), @@ -831,12 +860,12 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte description="captured snapshot keeps local DuckDB by default", scenario_name="order_totals_pass", capture_command=("--no-color", "scenario", "capture", "order_totals_pass"), - command=("--no-color", "scenario", "test", "order_totals_pass", "--local"), + command=("--no-color", "scenario", "test", "order_totals_pass", "--run-on", "local"), expected_exit_code=0, expected_stdout_fragments=( "order_totals_pass", "Retained local DuckDB:", - "PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + "PASS=1 FAIL=0 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/order_totals_pass/local.duckdb" @@ -852,14 +881,14 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte description="malformed local JSONL errors and retains local DuckDB", scenario_name="order_totals_pass", capture_command=("--no-color", "scenario", "capture", "order_totals_pass"), - command=("--no-color", "scenario", "test", "order_totals_pass", "--local"), + command=("--no-color", "scenario", "test", "order_totals_pass", "--run-on", "local"), expected_exit_code=1, expected_stdout_fragments=( "order_totals_pass", "ERROR", "error[X604]:", "Retained local DuckDB:", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/order_totals_pass/local.duckdb" @@ -872,14 +901,14 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte description="expected mismatch is local FAIL", scenario_name="order_totals_fail", capture_command=("--no-color", "scenario", "capture", "order_totals_fail"), - command=("--no-color", "scenario", "test", "order_totals_fail", "--local"), + command=("--no-color", "scenario", "test", "order_totals_fail", "--run-on", "local"), expected_exit_code=1, expected_stdout_fragments=( "order_totals_fail", "FAIL", "error[X506]:", "expect expected order_totals", - "PASS=0 FAIL=1 ERROR=0 SKIP=0 TOTAL=1", + "PASS=0 FAIL=1 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/order_totals_fail/local.duckdb" @@ -895,14 +924,14 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte description="local model execution error is ERROR", scenario_name="local_model_error", capture_command=("--no-color", "scenario", "capture", "local_model_error"), - command=("--no-color", "scenario", "test", "local_model_error", "--local"), + command=("--no-color", "scenario", "test", "local_model_error", "--run-on", "local"), expected_exit_code=1, expected_stdout_fragments=( "local_model_error", "ERROR", "error[X608]:", "not_a_number_", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/local_model_error/local.duckdb" @@ -934,11 +963,18 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte description="local SQL function scenario passes", scenario_name="local_sql_function_pass", capture_command=("--no-color", "scenario", "capture", "local_sql_function_pass"), - command=("--no-color", "scenario", "test", "local_sql_function_pass", "--local"), + command=( + "--no-color", + "scenario", + "test", + "local_sql_function_pass", + "--run-on", + "local", + ), expected_exit_code=0, expected_stdout_fragments=( "local_sql_function_pass", - "PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + "PASS=1 FAIL=0 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/local_sql_function_pass/local.duckdb" @@ -978,7 +1014,14 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte description="local SQL function setup error is ERROR", scenario_name="local_sql_function_setup_error", capture_command=("--no-color", "scenario", "capture", "local_sql_function_setup_error"), - command=("--no-color", "scenario", "test", "local_sql_function_setup_error", "--local"), + command=( + "--no-color", + "scenario", + "test", + "local_sql_function_setup_error", + "--run-on", + "local", + ), expected_exit_code=1, expected_stdout_fragments=( "local_sql_function_setup_error", @@ -986,7 +1029,7 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte "error[X609]:", "local function 'bad_sql_function' failed", "missing_col", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/local_sql_function_setup_error/local.duckdb" @@ -1032,15 +1075,16 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte "scenario", "test", "local_sql_function_transpile_error", - "--local", + "--run-on", + "local", ), expected_exit_code=1, expected_stdout_fragments=( "local_sql_function_transpile_error", "ERROR", "error[X607]:", - "bad_transpile_function", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "cannot run locally: SQLQuack converts Snowflake SQL only", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/local_sql_function_transpile_error/local.duckdb" @@ -1087,7 +1131,8 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte "scenario", "test", "local_sql_function_runtime_error", - "--local", + "--run-on", + "local", ), expected_exit_code=1, expected_stdout_fragments=( @@ -1095,7 +1140,7 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte "ERROR", "error[X608]:", "Could not convert string", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/local_sql_function_runtime_error/local.duckdb" @@ -1132,11 +1177,18 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte description="local Python function scenario passes", scenario_name="local_python_function_pass", capture_command=("--no-color", "scenario", "capture", "local_python_function_pass"), - command=("--no-color", "scenario", "test", "local_python_function_pass", "--local"), + command=( + "--no-color", + "scenario", + "test", + "local_python_function_pass", + "--run-on", + "local", + ), expected_exit_code=0, expected_stdout_fragments=( "local_python_function_pass", - "PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + "PASS=1 FAIL=0 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/local_python_function_pass/local.duckdb" @@ -1183,14 +1235,21 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte description="local Python function setup error is ERROR", scenario_name="local_python_function_error", capture_command=("--no-color", "scenario", "capture", "local_python_function_error"), - command=("--no-color", "scenario", "test", "local_python_function_error", "--local"), + command=( + "--no-color", + "scenario", + "test", + "local_python_function_error", + "--run-on", + "local", + ), expected_exit_code=1, expected_stdout_fragments=( "local_python_function_error", "ERROR", "error[X609]:", "cannot set database or schema", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/local_python_function_error/local.duckdb" @@ -1244,7 +1303,8 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte "scenario", "test", "local_python_function_runtime_error", - "--local", + "--run-on", + "local", ), expected_exit_code=1, expected_stdout_fragments=( @@ -1252,7 +1312,7 @@ def test_given_missing_snapshot_when_running_local_scenario_then_reports_expecte "ERROR", "error[X608]:", "python udf exploded", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), retained_duckdb_relative_path=Path( "target/run/scenarios/local_python_function_runtime_error/local.duckdb" @@ -1330,7 +1390,7 @@ def test_given_captured_snapshot_when_running_local_scenario_then_manages_local_ assert result.returncode == test_case.expected_exit_code, result.stdout + result.stderr expected_fragment: str for expected_fragment in test_case.expected_stdout_fragments: - assert expected_fragment in result.stdout + assert expected_fragment in result.stdout, result.stdout assert_local_duckdb_state( db_path=local_duckdb_path, stdout=result.stdout, @@ -1349,11 +1409,11 @@ def test_given_captured_snapshot_when_running_local_scenario_then_manages_local_ ScenarioLocalCommittedSnapshotE2ETestCase( description="replays committed local snapshot without capture", scenario_name="order_totals_pass", - command=("--no-color", "scenario", "test", "order_totals_pass", "--local"), + command=("--no-color", "scenario", "test", "order_totals_pass", "--run-on", "local"), expected_exit_code=0, expected_stdout_fragments=( "order_totals_pass", - "PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + "PASS=1 FAIL=0 TOTAL=1", ), unexpected_stdout_fragments=("Snapshot Capture",), retained_duckdb_relative_path=Path( @@ -1416,7 +1476,8 @@ def test_given_committed_snapshot_when_running_local_scenario_then_replays_witho "scenario", "test", "order_totals_pass", - "--local", + "--run-on", + "local", "--sync-snapshots", ), expected_exit_code=0, @@ -1428,7 +1489,7 @@ def test_given_committed_snapshot_when_running_local_scenario_then_replays_witho "snapshot tests/_scenario_snapshots/order_totals_pass/scenario.json", "SYNC_PASS=1 SYNC_FAIL=0", "order_totals_pass", - "PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + "PASS=1 FAIL=0 TOTAL=1", ), ), ScenarioLocalSnapshotSyncE2ETestCase( @@ -1439,7 +1500,8 @@ def test_given_committed_snapshot_when_running_local_scenario_then_replays_witho "scenario", "test", "order_totals_pass", - "--local", + "--run-on", + "local", "--sync-snapshots", ), expected_exit_code=1, @@ -1448,7 +1510,7 @@ def test_given_committed_snapshot_when_running_local_scenario_then_replays_witho "order_totals_pass", "ERROR", "error[X604]:", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), initial_capture=True, corrupt_jsonl=True, @@ -1462,7 +1524,8 @@ def test_given_committed_snapshot_when_running_local_scenario_then_replays_witho "scenario", "test", "order_totals_pass", - "--local", + "--run-on", + "local", "--refresh", ), expected_exit_code=0, @@ -1474,7 +1537,7 @@ def test_given_committed_snapshot_when_running_local_scenario_then_replays_witho "snapshot tests/_scenario_snapshots/order_totals_pass/scenario.json", "REFRESH_PASS=1 REFRESH_FAIL=0", "order_totals_pass", - "PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + "PASS=1 FAIL=0 TOTAL=1", ), initial_capture=True, corrupt_jsonl=True, @@ -1487,7 +1550,8 @@ def test_given_committed_snapshot_when_running_local_scenario_then_replays_witho "scenario", "test", "order_totals_pass", - "--local", + "--run-on", + "local", "--sync-snapshots", ), expected_exit_code=0, @@ -1499,7 +1563,7 @@ def test_given_committed_snapshot_when_running_local_scenario_then_replays_witho "snapshot tests/_scenario_snapshots/order_totals_pass/scenario.json", "SYNC_PASS=1 SYNC_FAIL=0", "order_totals_pass", - "PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + "PASS=1 FAIL=0 TOTAL=1", ), initial_capture=True, update_scenario_after_capture=True, @@ -1735,11 +1799,12 @@ def test_given_unknown_scenario_selector_when_running_scenario_test_then_fails_c "scenario", "test", "order_totals_pass", - "--local", + "--run-on", + "local", ), expected_exit_code=1, expected_stderr_fragments=( - "error[C455]: scenario test --local requires SQL analysis; " + "error[C455]: scenario test --run-on local requires SQL analysis; " "sqlbuild_project.toml sets [settings] sql_analysis = false", "= help: to run local scenario replay, snapshot sync, or snapshot refresh, " "set this in sqlbuild_project.toml:\n" @@ -1755,12 +1820,13 @@ def test_given_unknown_scenario_selector_when_running_scenario_test_then_fails_c "scenario", "test", "order_totals_pass", - "--local", + "--run-on", + "local", "--sync-snapshots", ), expected_exit_code=1, expected_stderr_fragments=( - "error[C455]: scenario test --local requires SQL analysis; " + "error[C455]: scenario test --run-on local requires SQL analysis; " "sqlbuild_project.toml sets [settings] sql_analysis = false", "= help: to run local scenario replay, snapshot sync, or snapshot refresh, " "set this in sqlbuild_project.toml:\n" @@ -1997,7 +2063,7 @@ def test_given_scenario_project_when_running_scenario_test_then_writes_runtime_a description="writes local fixture artifact", scenario_name="order_totals_pass", capture_command=("--no-color", "scenario", "capture", "order_totals_pass"), - command=("--no-color", "scenario", "test", "order_totals_pass", "--local"), + command=("--no-color", "scenario", "test", "order_totals_pass", "--run-on", "local"), expected_exit_code=0, artifact_relative_path=Path( "target/run/scenarios/order_totals_pass/local/fixtures/source__raw_orders.sql" @@ -2012,7 +2078,7 @@ def test_given_scenario_project_when_running_scenario_test_then_writes_runtime_a description="writes local model artifact", scenario_name="order_totals_pass", capture_command=("--no-color", "scenario", "capture", "order_totals_pass"), - command=("--no-color", "scenario", "test", "order_totals_pass", "--local"), + command=("--no-color", "scenario", "test", "order_totals_pass", "--run-on", "local"), expected_exit_code=0, artifact_relative_path=Path( "target/run/scenarios/order_totals_pass/local/sql/models/order_totals.sql" @@ -2026,7 +2092,7 @@ def test_given_scenario_project_when_running_scenario_test_then_writes_runtime_a description="writes local expected comparison artifact", scenario_name="order_totals_pass", capture_command=("--no-color", "scenario", "capture", "order_totals_pass"), - command=("--no-color", "scenario", "test", "order_totals_pass", "--local"), + command=("--no-color", "scenario", "test", "order_totals_pass", "--run-on", "local"), expected_exit_code=0, artifact_relative_path=Path( "target/run/scenarios/order_totals_pass/local/expectations/expected__order_totals.sql" @@ -2041,7 +2107,14 @@ def test_given_scenario_project_when_running_scenario_test_then_writes_runtime_a description="writes local SQL function artifact", scenario_name="local_sql_function_pass", capture_command=("--no-color", "scenario", "capture", "local_sql_function_pass"), - command=("--no-color", "scenario", "test", "local_sql_function_pass", "--local"), + command=( + "--no-color", + "scenario", + "test", + "local_sql_function_pass", + "--run-on", + "local", + ), expected_exit_code=0, artifact_relative_path=Path( "target/run/scenarios/local_sql_function_pass/local/sql/functions/sql/is_large_order.sql" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_snapshot_staleness.py b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_snapshot_staleness.py index 588da673b1..862e3e1369 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_snapshot_staleness.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/scenario/test_snapshot_staleness.py @@ -39,7 +39,7 @@ edited_from="__expected__stg_orders AS (SELECT 1 AS order_id)", edited_to="__expected__stg_orders AS (SELECT 1 AS order_id\n)", expected_exit_code=0, - expected_stdout_fragment="PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + expected_stdout_fragment="PASS=1 FAIL=0 TOTAL=1", ), ], ids=lambda case: case.description, @@ -62,7 +62,7 @@ def test_given_captured_snapshot_when_fixture_sql_changes_then_local_replay_repo ) replayed: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "scenario", "test", "--local", "--strict", test_case.scenario_name), + command=("--no-color", "scenario", "test", "--run-on", "local", test_case.scenario_name), project_dir=project_dir, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/snowflake/test_snowflake.py b/tests/e2e/src/sqlbuild/cli/commands/main/snowflake/test_snowflake.py index 82e910b4b4..3376f70a48 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/snowflake/test_snowflake.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/snowflake/test_snowflake.py @@ -576,7 +576,7 @@ def test_given_existing_snapshot_targets_when_building_on_snowflake_then_apply_s expected_stdout_fragments=( "transpilable_event_rollup", "PASS", - "PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + "PASS=1 FAIL=0 TOTAL=1", ), expected_local_rows=((10, 1500, 2),), local_rows_sql=( @@ -607,7 +607,7 @@ def test_given_existing_snapshot_targets_when_building_on_snowflake_then_apply_s "local_transpile_error", "ERROR", "error[X607]", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), expected_return_code=1, corrupt_capture_dialect=True, @@ -637,7 +637,7 @@ def test_given_existing_snapshot_targets_when_building_on_snowflake_then_apply_s "local_execution_error", "ERROR", "error[X608]", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), expected_return_code=1, ), @@ -682,7 +682,14 @@ def test_given_snowflake_scenario_capture_when_replaying_locally_then_transpilab ) replay_result: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "scenario", "test", test_case.scenario_name, "--local"), + command=( + "--no-color", + "scenario", + "test", + test_case.scenario_name, + "--run-on", + "local", + ), project_dir=project_dir, ) @@ -712,7 +719,7 @@ def test_given_snowflake_scenario_capture_when_replaying_locally_then_transpilab expected_stdout_fragments=( "dbt_event_rollup", "expect expected event_rollup", - "PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", + "PASS=1 FAIL=0 TOTAL=1", ), expected_local_rows=((10, 2),), local_rows_sql=( @@ -727,7 +734,7 @@ def test_given_snowflake_scenario_capture_when_replaying_locally_then_transpilab "dbt_event_rollup", "ERROR", "error[X607]", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", + "PASS=0 FAIL=0 ERROR=1 TOTAL=1", ), expected_return_code=1, corrupt_capture_dialect=True, @@ -783,7 +790,15 @@ def test_given_snowflake_dbt_scenario_capture_when_replaying_locally_then_transp ) replay_result: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "dbt", "scenario", "test", test_case.scenario_name, "--local"), + command=( + "--no-color", + "dbt", + "scenario", + "test", + test_case.scenario_name, + "--run-on", + "local", + ), project_dir=sqlbuild_project_dir, ) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_scenarios.py b/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_scenarios.py index 28abb775e3..4042c1a46c 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_scenarios.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/sqlite/test_scenarios.py @@ -36,9 +36,9 @@ expected_tables=("_sqlbuild_relations", "_sqlbuild_schemas"), ), SqliteScenarioE2ETestCase( - description="snapshots captured from SQLite replay locally in DuckDB", - command=("scenario", "test", "--local", "--sync-snapshots"), - expected_outcomes=SCENARIO_OUTCOMES, + description="SQLite scenarios can't run locally: SQLQuack converts Snowflake SQL only", + command=("scenario", "test", "--run-on", "local", "--sync-snapshots"), + expected_outcomes=dict.fromkeys(SCENARIO_OUTCOMES, ("failed", "X607")), expected_tables=("_sqlbuild_relations", "_sqlbuild_schemas"), ), SqliteScenarioE2ETestCase( diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/sqlserver/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/sqlserver/_test_types.py index 6945299c9a..84673c6717 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/sqlserver/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/sqlserver/_test_types.py @@ -95,19 +95,6 @@ class SqlServerSourceLoaderDagE2ETestCase: expected_return_code: int = 0 -@dataclass(frozen=True) -class SqlServerScenarioLocalReplayE2ETestCase: - description: str - model_sql: str - scenario_sql: str - expected_stdout_fragments: tuple[str, ...] - expected_return_code: int = 0 - scenario_name: str = "transpilable_event_rollup" - expected_local_rows: tuple[tuple[object, ...], ...] = field(default_factory=tuple) - local_rows_sql: str = "" - corrupt_capture_dialect: bool = False - - @dataclass(frozen=True) class SqlServerSnapshotE2ETestCase: description: str diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/sqlserver/test_sqlserver.py b/tests/e2e/src/sqlbuild/cli/commands/main/sqlserver/test_sqlserver.py index 3844f2d9bb..a9084730e4 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/sqlserver/test_sqlserver.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/sqlserver/test_sqlserver.py @@ -9,11 +9,6 @@ build_loader_waffle_shop_project_files, build_schema_behavior_project_files, ) -from tests.e2e.src.sqlbuild.cli.commands.main.scenario.helpers import ( - assert_optional_local_replay_rows, - build_real_warehouse_local_replay_project_files, - maybe_corrupt_scenario_snapshot_dialect, -) from tests.e2e.src.sqlbuild.cli.commands.main.sqlserver._test_types import ( SqlServerBuildE2ETestCase, SqlServerCloneE2ETestCase, @@ -22,7 +17,6 @@ SqlServerIntermediateDagStrategyE2ETestCase, SqlServerLoaderWaffleShopE2ETestCase, SqlServerNodeResultE2ETestCase, - SqlServerScenarioLocalReplayE2ETestCase, SqlServerSnapshotApplyE2ETestCase, SqlServerSnapshotE2ETestCase, SqlServerSourceDeferralE2ETestCase, @@ -554,135 +548,6 @@ def test_given_waffle_shop_when_running_full_build_on_sqlserver_then_expected_ta cleanup_sqlserver_schema(schema_name=schema_name, config=config) -@pytest.mark.parametrize( - "test_case", - [ - SqlServerScenarioLocalReplayE2ETestCase( - description="captures SQL Server fixtures and replays transpilable SQL locally", - model_sql=( - "MODEL (description 'Test model.', materialized table);\n\n" - "SELECT\n" - " customer_id,\n" - " CAST(CAST(event_ts AS DATE) AS DATETIME2) AS event_day,\n" - " SUM(CASE WHEN amount_cents >= 1000 THEN amount_cents ELSE 0 END)" - " AS large_amount_cents,\n" - " COUNT(*) AS event_count\n" - 'FROM __source("raw_events")\n' - "GROUP BY customer_id, CAST(CAST(event_ts AS DATE) AS DATETIME2)\n" - ), - scenario_sql=( - "SCENARIO (description 'Test scenario.');\n\n" - "WITH\n" - "__source__raw_events AS (\n" - " SELECT 10 AS customer_id, CAST('2026-01-01 08:15:00' AS DATETIME2)" - " AS event_ts, 1500 AS amount_cents\n" - " UNION ALL\n" - " SELECT 10 AS customer_id, CAST('2026-01-01 10:30:00' AS DATETIME2)" - " AS event_ts, 500 AS amount_cents\n" - "),\n" - "__expected__event_rollup AS (\n" - " SELECT 10 AS customer_id," - " CAST(CAST('2026-01-01 00:00:00' AS DATE) AS DATETIME2) AS event_day," - " 1500 AS large_amount_cents, 2 AS event_count\n" - ")\n" - "SELECT 1\n" - ), - expected_stdout_fragments=( - "transpilable_event_rollup", - "PASS", - "PASS=1 FAIL=0 ERROR=0 SKIP=0 TOTAL=1", - ), - expected_local_rows=((10, 1500, 2),), - local_rows_sql=( - "SELECT customer_id, large_amount_cents, event_count " - "FROM __sqb_local__model__event_rollup ORDER BY customer_id" - ), - ), - SqlServerScenarioLocalReplayE2ETestCase( - description="reports SQL Server local transpilation failures as X607", - scenario_name="local_transpile_error", - model_sql=( - "MODEL (description 'Test model.', materialized table);\n\n" - "SELECT customer_id, amount_cents\n" - 'FROM __source("raw_events")\n' - ), - scenario_sql=( - "SCENARIO (description 'Test scenario.');\n\n" - "WITH\n" - "__source__raw_events AS (\n" - " SELECT 10 AS customer_id, 1500 AS amount_cents\n" - "),\n" - "__expected__event_rollup AS (\n" - " SELECT 10 AS customer_id, 1500 AS amount_cents\n" - ")\n" - "SELECT 1\n" - ), - expected_stdout_fragments=( - "local_transpile_error", - "ERROR", - "error[X607]", - "PASS=0 FAIL=0 ERROR=1 SKIP=0 TOTAL=1", - ), - expected_return_code=1, - corrupt_capture_dialect=True, - ), - ], - ids=lambda case: case.description, -) -def test_given_sqlserver_scenario_capture_when_replaying_locally_then_transpilable_sql_passes( - tmp_path: Path, - test_case: SqlServerScenarioLocalReplayE2ETestCase, -) -> None: - config: dict[str, object] = build_sqlserver_config() - schema_name: str = build_unique_schema_name(prefix="sqb_scenario_local") - project_dir: Path = prepare_inline_project( - tmp_path=tmp_path, - project_name="sqlserver_scenario_local_replay", - repo_files=build_real_warehouse_local_replay_project_files( - project_toml=build_sqlserver_project_toml( - project_name="sqlserver_scenario_local_replay", - schema_name=schema_name, - config=config, - ), - model_sql=test_case.model_sql, - scenario_sql=test_case.scenario_sql, - scenario_name=test_case.scenario_name, - ), - ) - ensure_sqlserver_schema_ready(schema_name=schema_name, config=config) - - try: - capture_result: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "scenario", "capture", test_case.scenario_name), - project_dir=project_dir, - ) - assert capture_result.returncode == 0, capture_result.stdout + capture_result.stderr - maybe_corrupt_scenario_snapshot_dialect( - project_dir=project_dir, - scenario_name=test_case.scenario_name, - enabled=test_case.corrupt_capture_dialect, - ) - - replay_result: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "scenario", "test", test_case.scenario_name, "--local"), - project_dir=project_dir, - ) - - assert replay_result.returncode == test_case.expected_return_code, ( - replay_result.stdout + replay_result.stderr - ) - for fragment in test_case.expected_stdout_fragments: - assert fragment in replay_result.stdout - assert_optional_local_replay_rows( - project_dir=project_dir, - scenario_name=test_case.scenario_name, - local_rows_sql=test_case.local_rows_sql, - expected_local_rows=test_case.expected_local_rows, - ) - finally: - cleanup_sqlserver_schema(schema_name=schema_name, config=config) - - @pytest.mark.parametrize( "test_case", [ diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/_test_types.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/_test_types.py index 56119d8abd..69c287aaeb 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/_test_types.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/_test_types.py @@ -669,3 +669,58 @@ class PartitionedCallFixtureE2ETestCase: expected_rows: str expected_exit_code: int expected_stdout_fragment: str + + +@dataclass(frozen=True) +class RunOnPrecedenceE2ETestCase: + """Where `test_run_on` set in each place sends a DuckDB project's tests.""" + + description: str + settings_toml: str + target_line: str + local_toml: str + run_on_args: tuple[str, ...] + expected_counts: tuple[int, int] + + +@dataclass(frozen=True) +class RunOnTextE2ETestCase: + """One `sqb test` invocation and the exact lines its output must contain.""" + + description: str + command: tuple[str, ...] + expected_exit_code: int + expected_text: str + + +@dataclass(frozen=True) +class RunOnFallbackProgressE2ETestCase: + """An `auto` run whose local attempt falls back: its final row and how often lines appear.""" + + description: str + concurrency: str + expected_row: str + expected_starts: int + expected_assertion_lines: int + + +@dataclass(frozen=True) +class ScenarioRunOnFlagsE2ETestCase: + """A `sqb scenario test` flag combination the command refuses.""" + + description: str + command: tuple[str, ...] + expected_fragment: str + + +@dataclass(frozen=True) +class RunOnLocalJsonE2ETestCase: + """A `sqb test --run-on local --json` run and where each test ran and why.""" + + description: str + project: str + expected_exit_code: int + expected_placements: Mapping[str, tuple[object, ...]] + expected_counts: tuple[int, int] | None + expected_refusal_places: frozenset[tuple[object, ...]] + expected_refused_tests: tuple[str, ...] diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/helpers.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/helpers.py index c1a750a6ac..a43d69ce90 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/helpers.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/helpers.py @@ -6,15 +6,18 @@ import os import re import subprocess -from collections.abc import Mapping +from collections.abc import Mapping, Sequence from pathlib import Path +from subprocess import CompletedProcess from typing import Any import duckdb +from tests.e2e.src.sqlbuild.cli.commands.main.test._test_types import RunOnPrecedenceE2ETestCase from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import ( execute_duckdb, prepare_inline_project, + run_sqb, ) _OPTIONAL_CEREMONY_PROJECT_FILES: dict[str, str] = { @@ -2530,3 +2533,186 @@ def partitioned_call_fixture_files(*, query: str, expected_rows: str) -> dict[st "SELECT 1\n" ), } + + +DUCKDB_PROJECT: str = 'name = "orders"\nadapter = "duckdb"\ndefault_target = "dev"\n' +DUCKDB_TARGET: str = ( + '\n[targets.dev]\nconnection = "main"\n\n[connections.main]\ndatabase = "orders.duckdb"\n' +) +DUCKDB_FILES: dict[str, str] = { + "sql/sources/raw_orders.yml": ( + "sources:\n" + " - name: raw_orders\n description: Raw orders.\n" + " schema: main\n table: raw_orders\n" + " columns:\n" + " - name: order_id\n type: INTEGER\n" + " - name: amount\n type: INTEGER\n" + ), + "sql/models/orders.sql": ( + "MODEL (description 'Orders with doubled amounts.');\n\n" + 'SELECT order_id, amount * 2 AS doubled FROM __source("raw_orders")\n' + ), + "tests/unit/test_orders.sql": ( + "TEST();\n\nWITH\n" + "__source__raw_orders AS (SELECT 1 AS order_id, 5 AS amount),\n" + "__expected__orders AS (SELECT 1 AS order_id, 10 AS doubled)\n" + "SELECT 1\n" + ), +} + +SNOWFLAKE_FILES: dict[str, str] = { + "sqlbuild_project.toml": ( + 'name = "orders"\nadapter = "snowflake"\ndefault_target = "dev"\n\n' + '[defaults]\ndatabase = "ANALYTICS"\n\n' + '[targets.dev]\nconnection = "main"\nschema = "dev"\n\n' + '[connections.main]\naccount = "example"\nuser = "example"\n' + ), + "sql/sources/raw_orders.yml": ( + "sources:\n" + " - name: raw_orders\n description: Raw orders.\n" + " database: RAW\n schema: shop\n table: orders\n" + " columns:\n" + " - name: order_id\n type: NUMBER(38,0)\n" + " - name: status\n type: VARCHAR\n" + ), + "sql/models/staging/stg_orders.sql": ( + "MODEL (description 'Orders with a status hash.');\n\n" + "SELECT\n" + " order_id,\n" + " status,\n" + " HASH(status) AS status_hash\n" + 'FROM __source("raw_orders")\n' + ), + "sql/models/staging/stg_order_flags.sql": ( + "MODEL (description 'Orders with a hashed status from a macro.');\n\n" + "SELECT\n" + " order_id,\n" + ' @py.status_hash("status") AS status_hash\n' + 'FROM __source("raw_orders")\n' + ), + "sql/models/staging/_sqlbuild/_macros/python/hashing.py": ( + '"""Staging hash macros."""\n\n\n' + "def status_hash(column: str) -> str:\n" + ' """Hash a status column."""\n' + ' return f"HASH({column})"\n' + ), + "sql/models/marts/order_status.sql": ( + "MODEL (description 'Order status flags.');\n\n" + "SELECT\n" + " order_id,\n" + " IFF(status = 'completed', 1, 0) AS is_completed\n" + 'FROM __source("raw_orders")\n' + ), + "tests/unit/test_stg_orders.sql": ( + "TEST();\n\nWITH\n" + "__source__raw_orders AS (SELECT 1 AS order_id, 'completed' AS status),\n" + "__expected__stg_orders AS (SELECT 1 AS order_id, 'completed' AS status)\n" + "SELECT 1\n" + ), + "tests/unit/test_stg_order_flags.sql": ( + "TEST();\n\nWITH\n" + "__source__raw_orders AS (SELECT 1 AS order_id, 'completed' AS status),\n" + "__expected__stg_order_flags AS (SELECT 1 AS order_id)\n" + "SELECT 1\n" + ), + "tests/unit/test_order_status.sql": ( + "TEST();\n\nWITH\n" + "__source__raw_orders AS (SELECT 1 AS order_id, 'completed' AS status),\n" + "__expected__order_status AS (SELECT 1 AS order_id, 1 AS is_completed)\n" + "SELECT 1\n" + ), +} + + +UNMOCKED_SOURCE_FILES: dict[str, str] = { + "sql/sources/raw_customers.yml": ( + "sources:\n" + " - name: raw_customers\n description: Raw customers.\n" + " database: RAW\n schema: shop\n table: customers\n" + " columns:\n" + " - name: order_id\n type: NUMBER(38,0)\n" + " - name: customer_id\n type: NUMBER(38,0)\n" + ), + "sql/models/marts/order_customers.sql": ( + "MODEL (description 'Each order with its customer.');\n\n" + "SELECT\n" + " orders.order_id,\n" + " customers.customer_id\n" + 'FROM __source("raw_orders") AS orders\n' + "JOIN RAW.shop.customers AS customers ON customers.order_id = orders.order_id\n" + ), + "tests/unit/test_order_customers_unmocked.sql": ( + "TEST();\n\nWITH\n" + "__source__raw_orders AS (SELECT 1 AS order_id, 'completed' AS status),\n" + "__expected__order_customers AS (SELECT 1 AS order_id, 7 AS customer_id)\n" + "SELECT 1\n" + ), +} + + +GUARDED_FILES: dict[str, str] = { + "sql/models/marts/order_statuses.sql": ( + "MODEL (description 'Every order status.');\n\n" + "SELECT ARRAY_AGG(status) AS statuses\n" + 'FROM __source("raw_orders")\n' + ), + "tests/unit/test_order_statuses.sql": ( + "TEST();\n\nWITH\n" + "__source__raw_orders AS (\n" + " SELECT 1 AS order_id, 'completed' AS status UNION ALL SELECT 2, 'open'\n" + "),\n" + "__expected__order_statuses AS (SELECT ARRAY_CONSTRUCT('completed', 'open') AS statuses)\n" + "SELECT 1\n" + ), +} + + +def run_on_precedence_files(test_case: RunOnPrecedenceE2ETestCase) -> dict[str, str]: + """The DuckDB project with `test_run_on` set where the case sets it.""" + + target: str = DUCKDB_TARGET.replace( + 'connection = "main"\n', f'connection = "main"\n{test_case.target_line}' + ) + return { + **DUCKDB_FILES, + "sqlbuild_project.toml": DUCKDB_PROJECT + test_case.settings_toml + target, + "sqlbuild_local.toml": test_case.local_toml, + } + + +def run_on_counts(*, project: Path, run_on_args: tuple[str, ...]) -> tuple[int, int]: + """`(local_count, warehouse_count)` of a passing `sqb test --sql --json` run.""" + + result: CompletedProcess[str] = run_sqb( + command=("--no-color", "test", "--sql", "--json", *run_on_args), project_dir=project + ) + assert result.returncode == 0, result.stdout + result.stderr + summary: Mapping[str, int] = json.loads(result.stdout)["summary"] + return summary["local_count"], summary["warehouse_count"] + + +def check_placements(checks: Sequence[Mapping[str, object]]) -> dict[str, tuple[object, ...]]: + """Each check's `(status, run_on, run_on_reason)` by name.""" + + return { + str(check["name"]): (check["status"], check["run_on"], check["run_on_reason"]) + for check in checks + } + + +def refusal_places(refusals: Sequence[Mapping[str, object]]) -> set[tuple[object, ...]]: + """Each refusal's `(code, construct, path, line)`.""" + + return { + (refusal["code"], refusal["construct"], refusal["path"], refusal["line"]) + for refusal in refusals + } + + +def refused_tests(refusals: Sequence[Mapping[str, Sequence[str]]]) -> list[str]: + """Every test the refusals name, sorted.""" + + names: list[str] = [] + for refusal in refusals: + names.extend(refusal["tests"]) + return sorted(names) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_cost_guards.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_cost_guards.py index b38cc41097..38fc331900 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_cost_guards.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_cost_guards.py @@ -164,7 +164,7 @@ def test_given_unit_test_when_comparing_stored_output_then_results_and_samples_a ) result: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "--debug", "test"), project_dir=project_dir + command=("--no-color", "--debug", "test", "--run-on", "warehouse"), project_dir=project_dir ) output: str = result.stdout + result.stderr diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_output_evaluation_errors.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_output_evaluation_errors.py index 189dc32ed0..a77d9e87ba 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_output_evaluation_errors.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_output_evaluation_errors.py @@ -157,10 +157,10 @@ def test_given_output_store_failure_when_testing_then_only_storage_problems_fall ) tested: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "test"), project_dir=project_dir + command=("--no-color", "test", "--run-on", "warehouse"), project_dir=project_dir ) as_json: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "test", "--json"), project_dir=project_dir + command=("--no-color", "test", "--run-on", "warehouse", "--json"), project_dir=project_dir ) payload: dict[str, Any] = json.loads(as_json.stdout) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_run_on.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_run_on.py new file mode 100644 index 0000000000..f3d305f2b6 --- /dev/null +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_run_on.py @@ -0,0 +1,467 @@ +"""`sqb test --run-on`: unit tests run locally in DuckDB when SQLQuack converts them.""" + +import json +import re +from pathlib import Path +from subprocess import CompletedProcess + +import pytest + +from tests.e2e.src.sqlbuild.cli.commands.main.scenario.helpers import ( + build_scenario_project_files, +) +from tests.e2e.src.sqlbuild.cli.commands.main.test._test_types import ( + RunOnFallbackProgressE2ETestCase, + RunOnLocalJsonE2ETestCase, + RunOnPrecedenceE2ETestCase, + RunOnTextE2ETestCase, + ScenarioRunOnFlagsE2ETestCase, +) +from tests.e2e.src.sqlbuild.cli.commands.main.test.helpers import ( + GUARDED_FILES, + SNOWFLAKE_FILES, + UNMOCKED_SOURCE_FILES, + check_placements, + refusal_places, + refused_tests, + run_on_counts, + run_on_precedence_files, +) +from tests.e2e.src.sqlbuild.cli.commands.shared.helpers import ( + prepare_inline_project, + prepare_waffle_shop, + run_sqb, +) + +_DURATION: re.Pattern[str] = re.compile(r" \d+\.\d+s$", re.MULTILINE) +_PROJECTS: dict[str, dict[str, str]] = {"snowflake": SNOWFLAKE_FILES} + + +@pytest.mark.parametrize( + "test_case", + ( + RunOnLocalJsonE2ETestCase( + description="waffle shop runs every test in DuckDB; the table function reads a table", + project="waffle_shop", + expected_exit_code=1, + expected_placements={ + "returns_customer_orders": ( + "error", + "local", + "project function: customer_orders", + ), + "test_fact_orders": ("pass", "local", None), + "detects_completed_orders": ("pass", "local", None), + "calculates_line_total_cents": ("pass", "local", None), + "test_stg_orders": ("pass", "local", None), + }, + expected_counts=(5, 0), + expected_refusal_places=frozenset({("", "customer_orders", None, None)}), + expected_refused_tests=("returns_customer_orders",), + ), + ), + ids=lambda case: case.description, +) +def test_given_waffle_shop_when_testing_locally_then_unit_tests_run_in_duckdb_without_building( + tmp_path: Path, test_case: RunOnLocalJsonE2ETestCase +) -> None: + project: Path = prepare_waffle_shop(tmp_path) + + result: CompletedProcess[str] = run_sqb( + command=("--no-color", "test", "--sql", "--run-on", "local", "--json"), + project_dir=project, + ) + + assert result.returncode == test_case.expected_exit_code, result.stdout + result.stderr + payload: dict[str, object] = json.loads(result.stdout) + assert check_placements(payload["checks"]) == test_case.expected_placements # type: ignore[arg-type] + summary: dict[str, int] = payload["summary"] # type: ignore[assignment] + assert (summary["local_count"], summary["warehouse_count"]) == test_case.expected_counts + assert refused_tests(payload["refusals"]) == list(test_case.expected_refused_tests) # type: ignore[arg-type] + assert "Statements:" not in result.stderr + assert not (project / "waffle_shop.duckdb").exists() + + +@pytest.mark.parametrize( + "test_case", + ( + RunOnPrecedenceE2ETestCase( + description="DuckDB projects run locally by default", + settings_toml="", + target_line="", + local_toml="", + run_on_args=(), + expected_counts=(1, 0), + ), + RunOnPrecedenceE2ETestCase( + description="project settings choose the warehouse", + settings_toml='\n[settings]\ntest_run_on = "warehouse"\n', + target_line="", + local_toml="", + run_on_args=(), + expected_counts=(0, 1), + ), + RunOnPrecedenceE2ETestCase( + description="the local file's settings replace the project file's", + settings_toml='\n[settings]\ntest_run_on = "warehouse"\n', + target_line="", + local_toml='[settings]\ntest_run_on = "local"\n', + run_on_args=(), + expected_counts=(1, 0), + ), + RunOnPrecedenceE2ETestCase( + description="the target replaces settings", + settings_toml='\n[settings]\ntest_run_on = "local"\n', + target_line='test_run_on = "warehouse"\n', + local_toml='[settings]\ntest_run_on = "local"\n', + run_on_args=(), + expected_counts=(0, 1), + ), + RunOnPrecedenceE2ETestCase( + description="the flag replaces the target", + settings_toml='\n[settings]\ntest_run_on = "warehouse"\n', + target_line='test_run_on = "warehouse"\n', + local_toml="", + run_on_args=("--run-on", "local"), + expected_counts=(1, 0), + ), + RunOnPrecedenceE2ETestCase( + description="the local file's target replaces the project file's", + settings_toml="", + target_line='test_run_on = "warehouse"\n', + local_toml='[targets.dev]\ntest_run_on = "local"\n', + run_on_args=(), + expected_counts=(1, 0), + ), + ), + ids=lambda case: case.description, +) +def test_given_run_on_set_in_several_places_when_testing_then_flag_target_settings_win_in_order( + tmp_path: Path, test_case: RunOnPrecedenceE2ETestCase +) -> None: + project: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="run_on_precedence", + repo_files=run_on_precedence_files(test_case), + ) + + counts: tuple[int, int] = run_on_counts(project=project, run_on_args=test_case.run_on_args) + + assert counts == test_case.expected_counts + + +@pytest.mark.parametrize( + "test_case", + ( + RunOnTextE2ETestCase( + description="local mode lists SQLQuack's refusals at the model and macro call", + command=("test", "--sql", "--run-on", "local"), + expected_exit_code=1, + expected_text=( + "PASS=1 FAIL=2 TOTAL=3 (3 local, 0 warehouse)\n" + "\n" + "Can't run locally (2 tests)\n" + "\n" + "error[SQ0008]: HASH gives a different value in DuckDB\n" + " --> sql/models/staging/stg_order_flags.sql:5:3\n" + " |\n" + "5 | HASH(status) AS status_hash\n" + " | ^^^^^^^^^^^^ DuckDB computes its own hash, never Snowflake's\n" + " |\n" + " = note: Equal inputs still get equal hashes within one run.\n" + " = note: fine when: Joins, grouping, removing duplicates and spotting changed" + " rows by hash.\n" + " = note: wrong when: Storing, comparing or sorting by the hash value itself:" + " it differs, with no error.\n" + " = help: allow it with hash = true under [allow] in a sqlquack.toml in the" + " project folder;\n" + " `sqlquack explain hash` says when it is safe\n" + " = expanded from @py.status_hash at" + " sql/models/staging/stg_order_flags.sql:5:3\n" + " = tests: test_stg_order_flags\n" + "\n" + "error[SQ0008]: HASH gives a different value in DuckDB\n" + " --> sql/models/staging/stg_orders.sql:6:3\n" + " |\n" + "6 | HASH(status) AS status_hash\n" + " | ^^^^^^^^^^^^ DuckDB computes its own hash, never Snowflake's\n" + ), + ), + RunOnTextE2ETestCase( + description="inspect names where each test runs and why", + command=("test", "--sql", "--inspect"), + expected_exit_code=0, + expected_text=("test_order_status\n runs on: local\n"), + ), + RunOnTextE2ETestCase( + description="inspect gives the refusal as the warehouse reason", + command=("test", "--sql", "--inspect"), + expected_exit_code=0, + expected_text=( + "test_stg_orders\n" + " runs on: warehouse (a known difference that isn't allowed: fn:HASH)\n" + ), + ), + ), + ids=lambda case: case.description, +) +def test_given_snowflake_project_when_tests_need_conversion_then_reports_sqlquack_refusals( + tmp_path: Path, test_case: RunOnTextE2ETestCase +) -> None: + project: Path = prepare_inline_project( + tmp_path=tmp_path, project_name="run_on_snowflake", repo_files=SNOWFLAKE_FILES + ) + + result: CompletedProcess[str] = run_sqb( + command=("--no-color", *test_case.command), project_dir=project + ) + + assert result.returncode == test_case.expected_exit_code, result.stdout + result.stderr + assert test_case.expected_text in _DURATION.sub("", result.stdout), result.stdout + + +@pytest.mark.parametrize( + "test_case", + ( + RunOnTextE2ETestCase( + description="inspect sends a test reading an unmocked declared source to the warehouse", + command=("test", "--sql", "--inspect", "--select", "test_order_customers_unmocked"), + expected_exit_code=0, + expected_text=( + "test_order_customers_unmocked\n" + " runs on: warehouse (warehouse relation: RAW.SHOP.CUSTOMERS)\n" + ), + ), + RunOnTextE2ETestCase( + description="--run-on local refuses a test reading an unmocked declared source", + command=( + "test", + "--sql", + "--run-on", + "local", + "--select", + "test_order_customers_unmocked", + ), + expected_exit_code=1, + expected_text="warehouse relation: RAW.SHOP.CUSTOMERS", + ), + ), + ids=lambda case: case.description, +) +def test_given_snowflake_test_reading_an_unmocked_source_when_testing_then_it_needs_the_warehouse( + tmp_path: Path, test_case: RunOnTextE2ETestCase +) -> None: + project: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="run_on_snowflake_unmocked", + repo_files={**SNOWFLAKE_FILES, **UNMOCKED_SOURCE_FILES}, + ) + + result: CompletedProcess[str] = run_sqb( + command=("--no-color", *test_case.command), project_dir=project + ) + + output: str = _DURATION.sub("", result.stdout + result.stderr) + assert result.returncode == test_case.expected_exit_code, output + assert test_case.expected_text in output, output + + +@pytest.mark.parametrize( + "test_case", + ( + RunOnTextE2ETestCase( + description="auto sends a test whose guard raises in DuckDB to the warehouse", + command=("test", "--sql", "--select", "test_order_statuses"), + expected_exit_code=1, + expected_text=( + "[T008] needs the warehouse (no connection)\n\n" + "PASS=0 FAIL=1 TOTAL=1 (0 local, 1 warehouse)\n\n" + "On the warehouse (1 test)\n" + " SQLQuack guard: array_agg_order 1 test\n" + ), + ), + RunOnTextE2ETestCase( + description="--run-on local makes a test whose guard raises an error naming the guard", + command=("test", "--sql", "--run-on", "local", "--select", "test_order_statuses"), + expected_exit_code=1, + expected_text=( + "Can't run locally (1 test)\n\n" + "error: SQLQuack guard: array_agg_order\n" + " = note: SQLQuack's guard array_agg_order raised in DuckDB: ARRAY_AGG of several" + " values in no defined order\n" + " = tests: test_order_statuses\n" + ), + ), + ), + ids=lambda case: case.description, +) +def test_given_snowflake_test_whose_guard_raises_when_testing_then_it_needs_the_warehouse( + tmp_path: Path, test_case: RunOnTextE2ETestCase +) -> None: + project: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="run_on_snowflake_guarded", + repo_files={**SNOWFLAKE_FILES, **GUARDED_FILES}, + ) + + result: CompletedProcess[str] = run_sqb( + command=("--no-color", *test_case.command), project_dir=project + ) + + output: str = _DURATION.sub("", result.stdout + result.stderr) + assert result.returncode == test_case.expected_exit_code, output + assert test_case.expected_text in output, output + + +@pytest.mark.parametrize( + "test_case", + ( + RunOnFallbackProgressE2ETestCase( + description="one test at a time", + concurrency="1", + expected_row=( + "test_order_statuses ERROR warehouse" + " (SQLQuack guard: array_agg_order) 1 real model\n" + ), + expected_starts=1, + expected_assertion_lines=0, + ), + RunOnFallbackProgressE2ETestCase( + description="four tests at a time", + concurrency="4", + expected_row=( + "test_order_statuses ERROR warehouse" + " (SQLQuack guard: array_agg_order) 1 real model\n" + ), + expected_starts=1, + expected_assertion_lines=0, + ), + ), + ids=lambda case: case.description, +) +def test_given_auto_test_that_falls_back_when_testing_then_only_its_warehouse_attempt_shows( + tmp_path: Path, test_case: RunOnFallbackProgressE2ETestCase +) -> None: + project: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="run_on_snowflake_fallback_progress", + repo_files={**SNOWFLAKE_FILES, **GUARDED_FILES}, + ) + + result: CompletedProcess[str] = run_sqb( + command=( + "--no-color", + "test", + "--sql", + "--concurrency", + test_case.concurrency, + "--select", + "test_order_statuses", + ), + project_dir=project, + ) + + output: str = _DURATION.sub("", result.stdout + result.stderr) + assert test_case.expected_row in output, output + assert output.count("test_order_statuses START") == test_case.expected_starts, output + assert output.count("SQL test assertion") == test_case.expected_assertion_lines, output + + +@pytest.mark.parametrize( + "test_case", + ( + RunOnLocalJsonE2ETestCase( + description="Snowflake tests report where they ran, why, and SQLQuack's refusals", + project="snowflake", + expected_exit_code=1, + expected_placements={ + "test_order_status": ("pass", "local", None), + "test_stg_orders": ( + "error", + "local", + "a known difference that isn't allowed: fn:HASH", + ), + "test_stg_order_flags": ( + "error", + "local", + "a known difference that isn't allowed: fn:HASH", + ), + }, + expected_counts=(3, 0), + expected_refusal_places=frozenset( + { + ("SQ0008", "fn:HASH", "sql/models/staging/stg_orders.sql", 6), + ("SQ0008", "fn:HASH", "sql/models/staging/stg_order_flags.sql", 5), + } + ), + expected_refused_tests=("test_stg_order_flags", "test_stg_orders"), + ), + ), + ids=lambda case: case.description, +) +def test_given_project_when_testing_locally_with_json_then_reports_where_and_why( + tmp_path: Path, test_case: RunOnLocalJsonE2ETestCase +) -> None: + project: Path = prepare_inline_project( + tmp_path=tmp_path, project_name="run_on_json", repo_files=_PROJECTS[test_case.project] + ) + + result: CompletedProcess[str] = run_sqb( + command=("--no-color", "test", "--sql", "--run-on", "local", "--json"), + project_dir=project, + ) + + assert result.returncode == test_case.expected_exit_code, result.stdout + result.stderr + payload: dict[str, object] = json.loads(result.stdout) + assert check_placements(payload["checks"]) == test_case.expected_placements # type: ignore[arg-type] + summary: dict[str, int] = payload["summary"] # type: ignore[assignment] + assert (summary["local_count"], summary["warehouse_count"]) == test_case.expected_counts + assert refusal_places(payload["refusals"]) == test_case.expected_refusal_places # type: ignore[arg-type] + assert refused_tests(payload["refusals"]) == list(test_case.expected_refused_tests) # type: ignore[arg-type] + + +@pytest.mark.parametrize( + "test_case", + ( + ScenarioRunOnFlagsE2ETestCase( + description="--local is gone", + command=("scenario", "test", "--local"), + expected_fragment="unrecognized arguments: --local", + ), + ScenarioRunOnFlagsE2ETestCase( + description="--strict is gone", + command=("scenario", "test", "--strict"), + expected_fragment="unrecognized arguments: --strict", + ), + ScenarioRunOnFlagsE2ETestCase( + description="local runs keep no warehouse artifacts to retain", + command=("scenario", "test", "--run-on", "local", "--retain"), + expected_fragment="scenario test --run-on local does not support --retain", + ), + ScenarioRunOnFlagsE2ETestCase( + description="snapshot sync needs scenarios that run locally", + command=("scenario", "test", "--run-on", "warehouse", "--sync-snapshots"), + expected_fragment="scenario snapshot sync flags need scenarios that run locally", + ), + ), + ids=lambda case: case.description, +) +def test_given_scenario_run_on_flags_when_combined_then_refuses_unsupported_ones( + tmp_path: Path, test_case: ScenarioRunOnFlagsE2ETestCase +) -> None: + project: Path = prepare_inline_project( + tmp_path=tmp_path, + project_name="scenario_run_on", + repo_files=build_scenario_project_files(), + ) + + result: CompletedProcess[str] = run_sqb( + command=("--no-color", *test_case.command), project_dir=project + ) + + assert result.returncode != 0 + assert test_case.expected_fragment in result.stdout + result.stderr + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"]) diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_since.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_since.py index f843eda178..3548cb8830 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_since.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_since.py @@ -41,7 +41,7 @@ _ARCHIVE_SQL: str = ( "MODEL (description 'Archived orders.');\n\nSELECT order_id FROM __ref(\"stg_orders\")\n" ) -_TEST_COMMAND: tuple[str, ...] = ("--no-color", "test", "--since", "main") +_TEST_COMMAND: tuple[str, ...] = ("--no-color", "test", "--run-on", "warehouse", "--since", "main") _BASE_REF_CONFIG: str = _FILES["sqlbuild_project.toml"] + '\n[git]\nbase_ref = "main"\n' _INDIRECT: dict[str, str] = build_since_indirect_files() _PROJECT_CONFIG: str = "sqlbuild_project.toml" diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_statement_summary.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_statement_summary.py index f90a2d7269..5b39d18749 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_statement_summary.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_statement_summary.py @@ -46,7 +46,8 @@ expected_exit_code=0, expected_by_kind={"CREATE": 2, "DROP": 2, "WITH": 2}, expected_line=( - "Statements: 6 (CREATE 2, DROP 2, WITH 2); compile time not reported by duckdb" + "Statements: 6 on the warehouse (CREATE 2, DROP 2, WITH 2); compile time not reported " + "by duckdb" ), ), # A failed comparison also reads its unexpected and missing sample rows (two more WITH). @@ -56,7 +57,8 @@ expected_exit_code=1, expected_by_kind={"CREATE": 2, "DROP": 2, "WITH": 4}, expected_line=( - "Statements: 8 (WITH 4, CREATE 2, DROP 2); compile time not reported by duckdb" + "Statements: 8 on the warehouse (WITH 4, CREATE 2, DROP 2); compile time not reported " + "by duckdb" ), ), ), @@ -74,9 +76,11 @@ def test_given_sql_tests_when_running_then_statement_summary_counts_each_stateme tmp_path=tmp_path, project_name="statement_summary", repo_files=files ) - text_run: CompletedProcess[str] = run_sqb(command=("--no-color", "test"), project_dir=project) + text_run: CompletedProcess[str] = run_sqb( + command=("--no-color", "test", "--run-on", "warehouse"), project_dir=project + ) json_run: CompletedProcess[str] = run_sqb( - command=("--no-color", "test", "--json"), project_dir=project + command=("--no-color", "test", "--run-on", "warehouse", "--json"), project_dir=project ) assert text_run.returncode == test_case.expected_exit_code, text_run.stdout + text_run.stderr @@ -125,8 +129,8 @@ def test_given_scenarios_when_running_with_json_then_statement_summary_matches_p for kind, count in sorted(by_kind.items(), key=lambda item: (-item[1], item[0])) ) assert ( - f"Statements: {statements['total']} ({kinds}); compile time not reported by duckdb" - in result.stderr.splitlines() + f"Statements: {statements['total']} on the warehouse ({kinds}); compile time not " + "reported by duckdb" in result.stderr.splitlines() ), result.stderr diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_temporary_functions.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_temporary_functions.py index cb3799b2ae..91df9eeed1 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_temporary_functions.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_temporary_functions.py @@ -292,7 +292,7 @@ def test_given_copy_refused_when_testing_built_function_then_reports_coded_error ) tested: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "test"), project_dir=project_dir + command=("--no-color", "test", "--run-on", "warehouse"), project_dir=project_dir ) output: str = tested.stdout + tested.stderr @@ -328,7 +328,8 @@ def test_given_connection_refusing_copies_when_testing_concurrently_then_reports ) tested: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "test", "--concurrency", "2"), project_dir=project_dir + command=("--no-color", "test", "--run-on", "warehouse", "--concurrency", "2"), + project_dir=project_dir, ) output: str = tested.stdout + tested.stderr diff --git a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_test.py b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_test.py index 63170c2423..ae2f81a354 100644 --- a/tests/e2e/src/sqlbuild/cli/commands/main/test/test_test.py +++ b/tests/e2e/src/sqlbuild/cli/commands/main/test/test_test.py @@ -686,7 +686,8 @@ def test_given_waffle_shop_project_when_running_test_then_all_tests_pass( assert build_result.returncode == 0, build_result.stdout + build_result.stderr result: subprocess.CompletedProcess[str] = run_sqb( - command=("--no-color", "test", "--concurrency", "5"), project_dir=project_dir + command=("--no-color", "test", "--run-on", "warehouse", "--concurrency", "5"), + project_dir=project_dir, ) assert result.returncode == test_case.expected_exit_code, result.stdout + result.stderr diff --git a/tests/goldens/compiler/failure/local-config-unknown-key.json b/tests/goldens/compiler/failure/local-config-unknown-key.json index da518bfee3..3ba5d43c5f 100644 --- a/tests/goldens/compiler/failure/local-config-unknown-key.json +++ b/tests/goldens/compiler/failure/local-config-unknown-key.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D001", - "message": "/sqlbuild_local.toml settings contains unknown key(s): sql_analysiss. Allowed keys: allow_missing_secrets, allow_warehouse_round_trips, auto_load_sources, check_declared_columns, column_contract_mode, concurrency, default_audit_run_scope, default_audit_severity, delta_compile, ignore_audit_failures, max_concurrency, microbatch_concurrency, microbatch_unaccounted_partition_policy, query_change_tracking, record_run_host, require_sql_analysis, scenario_timeout, sql_analysis, sql_validation, table_promotion_mode, test_timeout, unit_test_max_real_models", + "message": "/sqlbuild_local.toml settings contains unknown key(s): sql_analysiss. Allowed keys: allow_missing_secrets, allow_warehouse_round_trips, auto_load_sources, check_declared_columns, column_contract_mode, concurrency, default_audit_run_scope, default_audit_severity, delta_compile, ignore_audit_failures, max_concurrency, microbatch_concurrency, microbatch_unaccounted_partition_policy, query_change_tracking, record_run_host, require_sql_analysis, scenario_run_on, scenario_timeout, sql_analysis, sql_validation, table_promotion_mode, test_run_on, test_timeout, unit_test_max_real_models", "help": "did you mean 'sql_analysis'?" } ] diff --git a/tests/goldens/compiler/failure/target-unknown-key.json b/tests/goldens/compiler/failure/target-unknown-key.json index 913f9432e6..8089faa274 100644 --- a/tests/goldens/compiler/failure/target-unknown-key.json +++ b/tests/goldens/compiler/failure/target-unknown-key.json @@ -8,7 +8,7 @@ "phase": "compile", "severity": "error", "code": "D001", - "message": "/sqlbuild_project.toml targets.ci contains unknown key(s): warehouse_size. Allowed keys: allow_missing_secrets, catalog_connection, clone, compile_cache, concurrency, connection, database, default_table_type, defer_clone_from, defer_sources_to, diff, env_file, execution_limits, ignore_audit_failures, loader_schema, missing_migration_origin, owns_time_travel_retention_namespace, pause_dynamic, plan_from, pools, recall, schema, table_type_downgrade, time_travel_retention, time_travel_retention_decrease, vars, warehouses", + "message": "/sqlbuild_project.toml targets.ci contains unknown key(s): warehouse_size. Allowed keys: allow_missing_secrets, catalog_connection, clone, compile_cache, concurrency, connection, database, default_table_type, defer_clone_from, defer_sources_to, diff, env_file, execution_limits, ignore_audit_failures, loader_schema, missing_migration_origin, owns_time_travel_retention_namespace, pause_dynamic, plan_from, pools, recall, scenario_run_on, schema, table_type_downgrade, test_run_on, time_travel_retention, time_travel_retention_decrease, vars, warehouses", "help": "did you mean 'warehouses'?" } ] diff --git a/tests/integration/src/sqlbuild/cli/commands/main/_test_types.py b/tests/integration/src/sqlbuild/cli/commands/main/_test_types.py index cb84d63a02..b4d9974866 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/_test_types.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/_test_types.py @@ -1672,3 +1672,31 @@ class MidSubmitCancelTestCase: sent_signal: signal.Signals expected_exit_code: int expected_notice: str + + +@dataclass(frozen=True) +class RunSelectorPlanTestCase: + description: str + # The plan's selectors; `{run}` is the failed run's ID, `{prefix}` its first 8 characters. + selectors: tuple[str, ...] + expected_models: list[str] + expected_audits: list[str] + + +@dataclass(frozen=True) +class RunSelectorRefusalTestCase: + description: str + # The plan's selectors; `{short}` is the failed run's first 7 characters. + selectors: tuple[str, ...] + expected_error: str + + +@dataclass(frozen=True) +class NotRunAuditTestCase: + description: str + # Builds run first, each as its sqb arguments, to put reads in the target. + setup: tuple[tuple[str, ...], ...] + command: tuple[str, ...] + expected_exit_code: int + expected_texts: tuple[str, ...] + expected_absent: tuple[str, ...] = () diff --git a/tests/integration/src/sqlbuild/cli/commands/main/helpers.py b/tests/integration/src/sqlbuild/cli/commands/main/helpers.py index d95bf1b334..5656236ef3 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/helpers.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/helpers.py @@ -2099,3 +2099,73 @@ def build_arguments(project: Path) -> list[str]: "build", "--discover", ] + + +RUN_SELECTOR_PROJECT_FILES: dict[str, str] = { + "sqlbuild_project.toml": ( + 'name = "demo"\nadapter = "duckdb"\ndefault_target = "dev"\n\n' + '[connection]\ndatabase = "demo.duckdb"\n\n[targets.dev]\nschema = "dev"\n' + ), + "sql/models/a.sql": "MODEL (description 'A.', materialized table);\nSELECT 1 AS id\n", + "sql/models/b.sql": ( + "MODEL (description 'B.', materialized table);\nSELECT CAST('x' AS INTEGER) AS id\n" + ), + "sql/models/c.sql": ( + "MODEL (description 'C.', materialized table);\nSELECT id FROM __ref(\"a\")\n" + ), + "sql/models/d.sql": ( + "MODEL (description 'D.', materialized table);\nSELECT id FROM __ref(\"b\")\n" + ), + "sql/audits/singular/a_matches_c.sql": ( + 'AUDIT (name "a_matches_c", severity error);\n' + 'SELECT a.id FROM __ref("a") a JOIN __ref("c") c ON a.id = c.id\n' + ), +} + + +def write_run_selector_project(project_dir: Path) -> None: + """A project whose build fails `b`, fails `c` on an error audit and skips `d`, reading `b`.""" + + for relative_path, contents in RUN_SELECTOR_PROJECT_FILES.items(): + destination: Path = project_dir / relative_path + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(contents, encoding="utf-8") + + +def recalled_run_ids(project_dir: Path) -> list[str]: + """The run IDs the project's local Recall history holds, oldest first.""" + + with sqlite3.connect( + f"file:{project_dir / 'logs' / 'recall.sqlite3'}?mode=ro", uri=True + ) as store: + rows: list[tuple[str]] = store.execute( + "SELECT run_id FROM recall_events WHERE run_id IS NOT NULL " + "GROUP BY run_id ORDER BY MIN(occurred_at)" + ).fetchall() + return [row[0] for row in rows] + + +NOT_RUN_AUDIT_PROJECT_FILES: dict[str, str] = { + "sqlbuild_project.toml": ( + 'name = "demo"\nadapter = "duckdb"\ndefault_target = "dev"\n\n' + '[connection]\ndatabase = "demo.duckdb"\n\n[targets.dev]\nschema = "dev"\n' + ), + "sql/models/orders.sql": "MODEL (description 'Orders.', materialized table);\nSELECT 1 AS id\n", + "sql/models/payments.sql": ( + "MODEL (description 'Payments.', materialized table);\nSELECT 1 AS id\n" + ), + "sql/audits/singular/orders_have_payments.sql": ( + 'AUDIT (name "orders_have_payments", severity error);\n' + 'SELECT o.id FROM __ref("orders") o LEFT JOIN __ref("payments") p ON o.id = p.id ' + "WHERE p.id IS NULL\n" + ), +} + + +def write_not_run_audit_project(project_dir: Path) -> None: + """Two unrelated models and a singular audit that reads both.""" + + for relative_path, contents in NOT_RUN_AUDIT_PROJECT_FILES.items(): + destination: Path = project_dir / relative_path + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(contents, encoding="utf-8") diff --git a/tests/integration/src/sqlbuild/cli/commands/main/statement_counts/test_statement_budget.py b/tests/integration/src/sqlbuild/cli/commands/main/statement_counts/test_statement_budget.py index 8460cb562a..a9d17d5a36 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/statement_counts/test_statement_budget.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/statement_counts/test_statement_budget.py @@ -68,7 +68,9 @@ _UNCHANGED_BUILD, ), StatementStep("audit", ("audit",), 0, {}), - StatementStep("unit tests", ("test",), 0, {"DROP TABLE relation": 2}), + StatementStep( + "unit tests", ("test", "--run-on", "warehouse"), 0, {"DROP TABLE relation": 2} + ), StatementStep( "scenario", ("scenario", "test"), diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_default_connection.py b/tests/integration/src/sqlbuild/cli/commands/main/test_default_connection.py index 1a411ebec1..4d1f7560ec 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_default_connection.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_default_connection.py @@ -233,9 +233,9 @@ def test_given_target_without_connection_when_resolving_offline_then_connection_ ), ), DefaultConnectionCliTestCase( - description="test execution fails before connecting without any connection", + description="warehouse test execution fails before connecting without any connection", project_toml=_NO_CONNECTION_PROJECT, - argv=("test",), + argv=("test", "--run-on", "warehouse"), expected_exit_code=1, expected_output_fragments=("error[D001]", "target dev has no connection"), ), diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_not_run_audits.py b/tests/integration/src/sqlbuild/cli/commands/main/test_not_run_audits.py new file mode 100644 index 0000000000..d90e947c15 --- /dev/null +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_not_run_audits.py @@ -0,0 +1,153 @@ +"""A singular audit whose reads the target doesn't have is not run, counted on its own, and the build succeeds.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest +from _pytest.capture import CaptureResult + +from sqlbuild._native import run_cli as main +from tests.integration.src.sqlbuild.cli.commands.main._test_types import NotRunAuditTestCase +from tests.integration.src.sqlbuild.cli.commands.main.helpers import write_not_run_audit_project + + +@pytest.mark.parametrize( + "test_case", + [ + NotRunAuditTestCase( + description="in a fresh schema the audit is not run, named with its missing read", + setup=(), + command=("build", "orders"), + expected_exit_code=0, + expected_texts=( + "NOT RUN", + "NOT_RUN=1", + "orders_have_payments (audit) reads payments, which doesn't exist in the target", + ), + expected_absent=("SKIP=1", "FAIL=1", "orders_have_payments START"), + ), + NotRunAuditTestCase( + description="when every read exists the audit runs against what is there", + setup=(("build", "payments"),), + command=("build", "orders"), + expected_exit_code=0, + expected_texts=("PASS=2",), + expected_absent=("NOT RUN", "NOT_RUN"), + ), + NotRunAuditTestCase( + description="audit: with every read in the target plans that audit and no models", + setup=(("build", "orders", "payments"),), + command=("plan", "audit:orders_have_payments"), + expected_exit_code=0, + expected_texts=("Plan ready 1 audit", "Audits (1)"), + expected_absent=("Models (", "not run"), + ), + NotRunAuditTestCase( + description="selecting the audit itself fails planning with S301", + setup=(), + command=("build", "audit:orders_have_payments"), + expected_exit_code=1, + expected_texts=( + "S301", + "audit 'orders_have_payments' reads 'payments'", + ), + ), + NotRunAuditTestCase( + description="the plan lists the audit as not run, with its missing read", + setup=(), + command=("plan", "orders"), + expected_exit_code=0, + expected_texts=( + "1 audit not run", + "orders_have_payments reads payments, which doesn't exist in the target", + ), + ), + ], + ids=lambda case: case.description, +) +def test_given_a_singular_audit_reading_an_unbuilt_model_when_building_then_it_is_not_run( + test_case: NotRunAuditTestCase, + tmp_path: Path, + capsys: pytest.CaptureFixture[str], +) -> None: + write_not_run_audit_project(tmp_path) + for setup in test_case.setup: + main(["--project-dir", str(tmp_path), "--no-color", *setup]) + capsys.readouterr() + + exit_code: int = main(["--project-dir", str(tmp_path), "--no-color", *test_case.command]) + captured: CaptureResult[str] = capsys.readouterr() + output: str = captured.out + captured.err + + assert exit_code == test_case.expected_exit_code, captured.out + captured.err + assert {text: text in output for text in test_case.expected_texts} == dict.fromkeys( + test_case.expected_texts, True + ), output + assert {text: text in output for text in test_case.expected_absent} == dict.fromkeys( + test_case.expected_absent, False + ), test_case.description + + +@pytest.mark.parametrize( + "test_case", + [ + NotRunAuditTestCase( + description="the plan JSON lists the audit under audits_not_run, with its missing read", + setup=(), + command=("plan", "--json", "orders"), + expected_exit_code=0, + expected_texts=(), + ), + ], + ids=lambda case: case.description, +) +def test_given_a_singular_audit_reading_an_unbuilt_model_when_planning_json_then_it_is_listed( + test_case: NotRunAuditTestCase, + tmp_path: Path, + capsys: pytest.CaptureFixture[str], +) -> None: + write_not_run_audit_project(tmp_path) + + exit_code: int = main(["--project-dir", str(tmp_path), "--no-color", *test_case.command]) + captured: CaptureResult[str] = capsys.readouterr() + plan: dict[str, Any] = json.loads(captured.out) + + assert (exit_code, plan["audits_not_run"]) == ( + test_case.expected_exit_code, + [{"name": "orders_have_payments", "missing": ["payments"]}], + ), test_case.description + + +@pytest.mark.parametrize( + "test_case", + [ + NotRunAuditTestCase( + description="the build JSON counts the audit as not run, apart from skipped and failed", + setup=(), + command=("build", "--json", "orders"), + expected_exit_code=0, + expected_texts=(), + ), + ], + ids=lambda case: case.description, +) +def test_given_a_singular_audit_reading_an_unbuilt_model_when_building_json_then_it_counts_as_not_run( + test_case: NotRunAuditTestCase, + tmp_path: Path, + capsys: pytest.CaptureFixture[str], +) -> None: + write_not_run_audit_project(tmp_path) + + exit_code: int = main(["--project-dir", str(tmp_path), "--no-color", *test_case.command]) + captured: CaptureResult[str] = capsys.readouterr() + summary: dict[str, Any] = json.loads(captured.out)["summary"] + + assert ( + exit_code, + summary["not_run_count"], + summary["skipped_count"], + summary["failure_count"], + ) == (test_case.expected_exit_code, 1, 0, 0), test_case.description diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_run_records.py b/tests/integration/src/sqlbuild/cli/commands/main/test_run_records.py index ec8296130d..8daadf7ef8 100644 --- a/tests/integration/src/sqlbuild/cli/commands/main/test_run_records.py +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_run_records.py @@ -101,7 +101,7 @@ ], ), RunRecordTestCase( - description="a failing model beside successes finishes partial", + description="a failing model beside successes fails the run", build_args=("--select", "stg_orders", "broken_orders"), expected_exit_code=1, expected_rows=[ @@ -112,7 +112,7 @@ '["stg_orders","broken_orders"]', "[]", "[]", - "partial", + "failed", '{"succeeded":1,"warned":0,"failed":1,"skipped":0,"not_started":0}', ), ], @@ -495,7 +495,7 @@ def test_given_a_killed_build_when_reading_its_runs_then_only_started_remains( expected_phases={"main": _PAIR}, expected_absent_schemas=frozenset(), expected_warnings=(), - expected_finished_status="partial", + expected_finished_status="failed", ), RunRecordSchemasTestCase( description="a function's schema records the run that deploys it", diff --git a/tests/integration/src/sqlbuild/cli/commands/main/test_run_selectors.py b/tests/integration/src/sqlbuild/cli/commands/main/test_run_selectors.py new file mode 100644 index 0000000000..ce9bf32b49 --- /dev/null +++ b/tests/integration/src/sqlbuild/cli/commands/main/test_run_selectors.py @@ -0,0 +1,106 @@ +"""Run selectors read a past run from the local Recall history; audit: selects an audit by name.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest +from _pytest.capture import CaptureResult + +from sqlbuild._native import run_cli as main +from tests.integration.src.sqlbuild.cli.commands.main._test_types import ( + RunSelectorPlanTestCase, + RunSelectorRefusalTestCase, +) +from tests.integration.src.sqlbuild.cli.commands.main.helpers import ( + recalled_run_ids, + write_run_selector_project, +) + + +@pytest.mark.parametrize( + "test_case", + [ + RunSelectorPlanTestCase( + description="failed: plans the failed models and the failed audit", + selectors=("failed:{run}",), + expected_models=["b", "c"], + expected_audits=["a_matches_c"], + ), + RunSelectorPlanTestCase( + description="failed:+ adds what reads the failed models, as rerunning from failure", + selectors=("failed:{prefix}+",), + expected_models=["b", "c", "d"], + expected_audits=["a_matches_c"], + ), + RunSelectorPlanTestCase( + description="run: less skipped: plans what the run selected but didn't skip", + selectors=("run:{run}", "--exclude", "skipped:{run}"), + expected_models=["a", "b", "c"], + expected_audits=[], + ), + ], + ids=lambda case: case.description, +) +def test_given_a_failed_local_build_when_planning_with_run_selectors_then_its_results_are_selected( + test_case: RunSelectorPlanTestCase, + tmp_path: Path, + capsys: pytest.CaptureFixture[str], +) -> None: + write_run_selector_project(tmp_path) + main(["--project-dir", str(tmp_path), "--no-color", "build", "--no-tests"]) + capsys.readouterr() + [run_id] = recalled_run_ids(tmp_path) + selectors: list[str] = [ + selector.format(run=run_id, prefix=run_id[:8]) for selector in test_case.selectors + ] + + exit_code: int = main( + ["--project-dir", str(tmp_path), "--no-color", "plan", "--json", *selectors] + ) + captured: CaptureResult[str] = capsys.readouterr() + + assert exit_code == 0, captured.err + plan: dict[str, Any] = json.loads(captured.out) + assert ( + sorted(model["name"] for model in plan["models"]), + plan["audits"], + ) == (test_case.expected_models, test_case.expected_audits), captured.err + + +@pytest.mark.parametrize( + "test_case", + [ + RunSelectorRefusalTestCase( + description="a run ID shorter than 8 characters is refused", + selectors=("failed:{short}",), + expected_error="is too short: give the full ID or at least 8 characters of it", + ), + RunSelectorRefusalTestCase( + description="audit: whose read the failed build never built is refused with S301", + selectors=("audit:a_matches_c",), + expected_error="audit 'a_matches_c' reads 'c', which is not selected", + ), + ], + ids=lambda case: case.description, +) +def test_given_a_failed_local_build_when_a_run_selector_is_too_short_then_the_plan_is_refused( + test_case: RunSelectorRefusalTestCase, + tmp_path: Path, + capsys: pytest.CaptureFixture[str], +) -> None: + write_run_selector_project(tmp_path) + main(["--project-dir", str(tmp_path), "--no-color", "build", "--no-tests"]) + capsys.readouterr() + [run_id] = recalled_run_ids(tmp_path) + selectors: list[str] = [selector.format(short=run_id[:7]) for selector in test_case.selectors] + + exit_code: int = main(["--project-dir", str(tmp_path), "--no-color", "plan", *selectors]) + captured: CaptureResult[str] = capsys.readouterr() + + assert (exit_code != 0, test_case.expected_error in captured.err + captured.out) == ( + True, + True, + ), test_case.description diff --git a/tests/integration/src/sqlbuild/cli/recall/_test_types.py b/tests/integration/src/sqlbuild/cli/recall/_test_types.py index 15ca0d59cb..fdd83d2519 100644 --- a/tests/integration/src/sqlbuild/cli/recall/_test_types.py +++ b/tests/integration/src/sqlbuild/cli/recall/_test_types.py @@ -417,3 +417,11 @@ class ClosingTerminationTestCase: description: str shutdown_timeout: str expected_exit_code: int + + +@dataclass(frozen=True) +class LocalStatementsTestCase: + description: str + args: tuple[str, ...] + sql: str + expected_rows: list[list[object]] diff --git a/tests/integration/src/sqlbuild/cli/recall/helpers.py b/tests/integration/src/sqlbuild/cli/recall/helpers.py index 8f4b91c49e..833478431b 100644 --- a/tests/integration/src/sqlbuild/cli/recall/helpers.py +++ b/tests/integration/src/sqlbuild/cli/recall/helpers.py @@ -749,3 +749,27 @@ def selected_columns(*, result: dict[str, Any], columns: tuple[str, ...]) -> lis for row in result["rows"]: rows.append([row[position] for position in positions]) return rows + + +def write_tested_project(project_dir: Path) -> Path: + """The Recall project with a model reading `orders` and a unit test of it.""" + + _ = write_project(project_dir) + files: dict[str, str] = { + "sql/models/order_dates.sql": ( + 'MODEL (description "Each order\'s date");\n\n' + 'SELECT order_id, ordered_on FROM __ref("orders")\n' + ), + "tests/unit/test_order_dates.sql": ( + "TEST();\n\nWITH\n" + "__ref__orders AS (SELECT 1 AS order_id, CAST('2026-04-01' AS DATE) AS ordered_on),\n" + "__expected__order_dates AS (" + "SELECT 1 AS order_id, CAST('2026-04-01' AS DATE) AS ordered_on)\n" + "SELECT 1\n" + ), + } + for relative, contents in files.items(): + path: Path = project_dir / relative + path.parent.mkdir(parents=True, exist_ok=True) + _ = path.write_text(contents, encoding="utf-8") + return project_dir diff --git a/tests/integration/src/sqlbuild/cli/recall/test_local_statements.py b/tests/integration/src/sqlbuild/cli/recall/test_local_statements.py new file mode 100644 index 0000000000..67a8cacc22 --- /dev/null +++ b/tests/integration/src/sqlbuild/cli/recall/test_local_statements.py @@ -0,0 +1,65 @@ +"""Statements of tests run locally are recorded by digest, without their SQL text.""" + +import subprocess +from pathlib import Path + +import pytest + +from tests.integration.src.sqlbuild.cli.recall._test_types import LocalStatementsTestCase +from tests.integration.src.sqlbuild.cli.recall.helpers import ( + INCOMPLETE_HISTORY, + recall_rows, + run, + write_tested_project, +) + +_STATEMENTS: str = ( + "SELECT COUNT(*) > 0, " + "COALESCE(SUM(json_extract(payload, '$.run_on') = 'local'), 0) > 0, " + "(SELECT COUNT(*) FROM recall_artifact_refs AS ref WHERE ref.digest IN (" + "SELECT 'sha256:' || sql_digest FROM recall_events " + "WHERE json_extract(payload, '$.run_on') = 'local')) " + "FROM recall_events WHERE event_type IN ('statement_completed', 'statement_failed')" +) + + +@pytest.mark.parametrize( + "test_case", + [ + LocalStatementsTestCase( + description="a local run records its statements with run_on local and no SQL text", + args=("test", "--sql", "--run-on", "local"), + sql=_STATEMENTS, + expected_rows=[[1, 1, 0]], + ), + LocalStatementsTestCase( + description="a warehouse run records no local statements", + args=("test", "--sql", "--run-on", "warehouse"), + sql=_STATEMENTS, + expected_rows=[[1, 0, 0]], + ), + LocalStatementsTestCase( + description="a warehouse run keeps the SQL text of its statements", + args=("test", "--sql", "--run-on", "warehouse"), + sql="SELECT COUNT(*) > 0 FROM recall_artifact_refs", + expected_rows=[[1]], + ), + ], + ids=lambda case: case.description, +) +def test_given_tests_run_locally_when_recorded_then_their_statements_keep_no_sql_text( + test_case: LocalStatementsTestCase, tmp_path: Path +) -> None: + project_dir: Path = write_tested_project(tmp_path / "orders_shop") + + completed: subprocess.CompletedProcess[bytes] = run(project_dir, *test_case.args) + rows: list[list[object]] = recall_rows(project_dir, test_case.sql) + + stderr: str = completed.stderr.decode(errors="replace") + assert completed.returncode == 0, stderr + assert INCOMPLETE_HISTORY.search(stderr) is None, stderr + assert rows == test_case.expected_rows + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"]) 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 4c5415f511..81c552ea04 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 @@ -145,6 +145,8 @@ class WorkerExecutionTestCase: ) # Whether the build compiles again instead of planning from the compile the worker verified. expected_compiles_again: bool = False + # Each failed run node as (key, the phase its worker reported it failed in). + expected_failed_phases: list[tuple[str, str | None]] = field(default_factory=list) @dataclass(frozen=True) @@ -156,6 +158,13 @@ class NodeResultsTestCase(WorkerExecutionTestCase): ) +@dataclass(frozen=True) +class CheckResultsTestCase(WorkerExecutionTestCase): + description: str + # Each attached check the run reported, as (key, status). + expected_checks: list[tuple[str, str]] = field(default_factory=list) + + @dataclass(frozen=True) class ClaimedLoadTestCase(WorkerExecutionTestCase): description: str @@ -196,8 +205,17 @@ class NulLogTestCase(WorkerExecutionTestCase): class PhaseEventsTestCase(WorkerExecutionTestCase): description: str backend: Literal["sqlite", "postgres"] = "sqlite" - # Each phase in order, and whether it reports a duration. + # Each phase in order up to the first node event, and whether it reports a duration. expected_phases: tuple[tuple[str, bool], ...] = () + # What the planned phase says the plan runs. + expected_planned: str = "" + + +@dataclass(frozen=True) +class SinkDeliveryTestCase(WorkerExecutionTestCase): + description: str + # Each sink's name, and whether it failed every event it accepted. + expected_sinks: tuple[tuple[str, bool], ...] = () @dataclass(frozen=True) @@ -1029,3 +1047,23 @@ class UnknownTagTestCase: edits: dict[str, str] expected_nodes: frozenset[str] expected_error: str + + +@dataclass(frozen=True) +class ServerOutageTestCase: + """A server whose control database can't be reached: its URL and what health says.""" + + description: str + database_url: str + expected_reason: str + expected_case: str + + +@dataclass(frozen=True) +class RuntimeSinkTestCase: + """A location interpreter's sinks and what it says each delivered.""" + + description: str + sink_source: str + # Each sink's name, and whether it failed every event it accepted. + expected_sinks: tuple[tuple[str, bool], ...] diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/helpers.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/helpers.py index 72c5f8994f..76faed284c 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/helpers.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/helpers.py @@ -19,6 +19,7 @@ import subprocess import sys import termios +import threading import time from collections.abc import Callable, Iterator from contextlib import ( @@ -2519,3 +2520,169 @@ def launch_adhoc(worker: ScheduledWorker, command: list[str]) -> dict[str, Any]: " managed: true\n write_strategy: table\n" ), } + + +@contextmanager +def outage_server(directory: Path, database_url: str) -> Iterator[tuple[str, Path]]: + """`sqb server` over a control database it may not reach yet, from the moment it listens.""" + directory.mkdir(parents=True) + log: Path = directory / "server.log" + environment: dict[str, str] = os.environ.copy() + environment.pop("SQLBUILD_PLATFORM_WEBHOOK_URL", None) + environment.pop("SQLBUILD_SECURITY_AUDIT_WEBHOOK_URL", None) + environment["XDG_STATE_HOME"] = str(directory / "state") + environment["SQLBUILD_CONTROL_DATABASE_URL"] = database_url + with log.open("wb") as stderr: + process: subprocess.Popen[bytes] = subprocess.Popen( + [str(Path(sys.executable).with_name("sqb")), "server", "--port", "0", "--no-scheduler"], + cwd=directory, + env=environment, + stdout=subprocess.DEVNULL, + stderr=stderr, + ) + try: + yield listening_address(process, log), log + finally: + process.terminate() + try: + _ = process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + _ = process.wait(timeout=5) + + +def listening_address(process: subprocess.Popen[bytes], log: Path) -> str: + """The address a server answers on before its control database is open.""" + deadline: float = time.monotonic() + 10 + while "Control API listening: " not in log.read_text(): + assert process.poll() is None, log.read_text() + assert time.monotonic() < deadline, "the server did not start listening" + time.sleep(0.02) + return "http://" + log.read_text().partition("Control API listening: ")[2].splitlines()[0] + + +def http_reply(url: str) -> tuple[int, dict[str, str], str]: + """A GET's status, headers and body text, whatever the status.""" + try: + with urlopen(url, timeout=10) as response: + return ( + response.status, + {key.lower(): value for key, value in response.headers.items()}, + response.read().decode(), + ) + except HTTPError as error: + return ( + error.code, + {key.lower(): value for key, value in error.headers.items()}, + error.read().decode(), + ) + + +def health_report(url: str) -> dict[str, Any]: + """The server's health report, which it answers with 200 or 503.""" + report: dict[str, Any] = json.loads(http_reply(f"{url}/api/health")[2]) + return report + + +def wait_for_health( + url: str, wanted: Callable[[dict[str, Any]], bool], seconds: float +) -> dict[str, Any]: + """The first health report `wanted` accepts, read every half second.""" + deadline: float = time.monotonic() + seconds + report: dict[str, Any] = health_report(url) + while not wanted(report) and time.monotonic() < deadline: + time.sleep(0.5) + report = health_report(url) + assert wanted(report), f"health never became what was wanted: {report}" + return report + + +def control_database_row(report: dict[str, Any]) -> dict[str, Any]: + """The control database's row of a health report, by what anyone may see of it.""" + rows: dict[str, dict[str, Any]] = {row["component"]: row for row in report["components"]} + row: dict[str, Any] = rows["control_database"] + return {"status": row["status"], "reason": row["reason"], "case": row.get("case")} + + +def free_port() -> int: + """A local port nothing listens on yet.""" + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + port: int = probe.getsockname()[1] + return port + + +@contextmanager +def forwarded_port(port: int, target: tuple[str, int]) -> Iterator[None]: + """Accept on `port` and relay every connection to `target` until the block ends.""" + listener: socket.socket = socket.create_server(("127.0.0.1", port)) + stop: threading.Event = threading.Event() + + def relay(source: socket.socket, sink: socket.socket) -> None: + with suppress(OSError): + while chunk := source.recv(65536): + sink.sendall(chunk) + with suppress(OSError): + sink.shutdown(socket.SHUT_WR) + + def accept() -> None: + listener.settimeout(0.2) + while not stop.is_set(): + try: + client, _ = listener.accept() + except TimeoutError: + continue + upstream: socket.socket = socket.create_connection(target) + threading.Thread(target=relay, args=(client, upstream), daemon=True).start() + threading.Thread(target=relay, args=(upstream, client), daemon=True).start() + + acceptor: threading.Thread = threading.Thread(target=accept, daemon=True) + acceptor.start() + try: + yield + finally: + stop.set() + acceptor.join(timeout=2) + listener.close() + + +def runtime_sink_totals( + project: Path, settled: Callable[[dict[str, Any]], bool], seconds: float +) -> dict[str, Any]: + """The location interpreter's sink totals, asked every half second until `settled`.""" + child: subprocess.Popen[str] = subprocess.Popen( + [ + str(Path(sys.executable).with_name("sqb")), + "--project-dir", + str(project), + "location", + "runtime", + "--server", + "http://127.0.0.1:9", + "--location-id", + str(uuid4()), + "--target", + "development", + ], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + cwd=project, + ) + stdin, stdout = cast(Any, child.stdin), cast(Any, child.stdout) + + def ask() -> dict[str, Any]: + stdin.write('{"sink_deliveries": {}}\n') + stdin.flush() + reply: dict[str, Any] = json.loads(stdout.readline()) + return reply + + deadline: float = time.monotonic() + seconds + totals: dict[str, Any] = ask() + while not settled(totals) and time.monotonic() < deadline: + time.sleep(0.5) + totals = ask() + stdin.close() + child.wait(timeout=60) + return totals diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_adhoc.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_adhoc.py index ae2e88e5d2..ee055c82ed 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_adhoc.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_adhoc.py @@ -252,6 +252,24 @@ def test_given_an_ad_hoc_command_when_checked_and_launched_then_the_worker_runs_ ], rewrites={"sql/models/customers.sql": CUSTOMERS_SQL.replace("not_null", "unique_x")}, ), + AdhocVerbTestCase( + description="audit reports a singular audit under its own check", + prerequisites=[SEED, BUILD], + command=["audit", "--select", "customers"], + expected_selection=["model:customers"], + expected_run_nodes=[ + ("audit:customers_match_orders", "check", "success"), + ("audit:not_null:model:customers:id", "check", "success"), + ("model:customers", "node", "success"), + ], + files={ + "sql/audits/singular/customers_match_orders.sql": ( + 'AUDIT (name "customers_match_orders", severity error);\n' + 'SELECT c.id FROM __ref("customers") c CROSS JOIN __ref("orders") o ' + "WHERE c.id IS NULL\n" + ), + }, + ), AdhocVerbTestCase( description="test reports each verified SQL test and the model it tests", prerequisites=[], diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_check_sensors.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_check_sensors.py index 159e27dafc..f79e692ded 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_check_sensors.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_check_sensors.py @@ -64,7 +64,7 @@ "orders with a failing SQL test", "SELECT 3 AS amount", "SELECT count(*) FROM duckdb_tables() WHERE table_name = 'stg_orders'", - "partial", + "failed", [(0,)], files={ "sql/models/raw_orders.sql": ( diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_interrupted_steps.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_interrupted_steps.py index ebd41fc80a..3075519291 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_interrupted_steps.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_interrupted_steps.py @@ -86,7 +86,7 @@ def execute(self, *, connection, sql): [ InterruptedStepsTestCase( description="one finished, one finishing in the grace and one ignoring the cancel", - expected_status="partial", + expected_status="failed", expected_statuses={ "asset:fulfil[pick]": "success", "asset:fulfil[label]": "success", diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_location_sinks.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_location_sinks.py new file mode 100644 index 0000000000..c4397fd872 --- /dev/null +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_location_sinks.py @@ -0,0 +1,66 @@ +"""A location's interpreter says what each of its event sinks delivered, for the location to report.""" + +import subprocess +from pathlib import Path +from typing import Any + +import pytest + +from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( + RuntimeSinkTestCase, +) +from tests.integration.src.sqlbuild.compiler.compiled_project.publication.helpers import ( + runtime_sink_totals, +) +from tests.integration.src.sqlbuild.compiler.graph.helpers import write_files + +FAILING_SINK: str = ( + "from sqlbuild.event_sinks import LifecycleEvent, lifecycle_event_sink\n\n\n" + "@lifecycle_event_sink\n" + "def broker(event: LifecycleEvent) -> None:\n" + " raise RuntimeError('broker unavailable')\n\n\n" + "@lifecycle_event_sink\n" + "def archive(event: LifecycleEvent) -> None:\n" + " del event\n" +) + + +@pytest.mark.parametrize( + "test_case", + [ + RuntimeSinkTestCase( + description="a sink that fails every event and one that delivers them", + sink_source=FAILING_SINK, + expected_sinks=(("archive", False), ("broker", True)), + ) + ], + ids=lambda case: case.description, +) +def test_given_a_location_interpreter_with_event_sinks_when_asked_then_it_says_what_each_delivered( + test_case: RuntimeSinkTestCase, tmp_path: Path +) -> None: + write_files( + project_dir=tmp_path, + files={ + "sqlbuild_project.toml": ( + 'name = "orders"\nadapter = "duckdb"\n' + '[connections.local]\ndatabase = "warehouse.duckdb"\n' + '[targets.development]\nschema = "main"\n' + ), + "sql/models/orders.sql": ( + "MODEL (description 'Orders.', materialized table);\nSELECT 1 AS id\n" + ), + "python/event_sinks/events.py": test_case.sink_source, + }, + ) + _ = subprocess.run(["git", "init", "-q", str(tmp_path)], check=True, capture_output=True) + totals: dict[str, Any] = runtime_sink_totals( + tmp_path, + lambda totals: all( + sink["delivered"] + sink["failed"] == sink["accepted"] > 0 for sink in totals["sinks"] + ), + 30, + ) + assert sorted( + (sink["name"], sink["failed"] == sink["accepted"] > 0) for sink in totals["sinks"] + ) == list(test_case.expected_sinks), (test_case.description, totals) diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_node_status.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_node_status.py index 0a0fb5e1cb..c784b57ae1 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_node_status.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_node_status.py @@ -137,7 +137,7 @@ def test_given_a_chain_of_three_when_the_second_is_interrupted_then_the_first_st description=test_case.description, model_sql="SELECT 1 AS amount", warehouse_query="", - expected_status="partial", + expected_status="failed", expected_rows=[], files={**node_module_files("python/nodes/steps.py", chain)} | test_case.files, default_job_files={ diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_publication.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_publication.py index 6443550f54..c57a82b7c7 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_publication.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_publication.py @@ -161,7 +161,7 @@ def test_given_retained_compiler_data_when_publishing_then_http_updates_atomical assert by_name["edge_job_outcomes_sensor"]["definition_json"]["when"] == { "kind": "run_event", "job_key": "edge_snapshot_orders_job", - "kinds": ["warn", "partial"], + "kinds": ["warn", "failed"], } assert by_name["edge_group_outcomes_sensor"]["definition_json"]["when"] == { "kind": "run_event", diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rerun.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rerun.py index ee9a4c53f7..a9dc97bd76 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rerun.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_rerun.py @@ -42,7 +42,7 @@ ], ids=lambda case: case.description, ) -def test_given_a_partial_group_when_retrying_from_failure_then_successful_nodes_are_not_rewritten( +def test_given_a_failed_group_when_retrying_from_failure_then_successful_nodes_are_not_rewritten( test_case: WorkerExecutionTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: test_case = replace( @@ -83,7 +83,7 @@ def test_given_a_partial_group_when_retrying_from_failure_then_successful_nodes_ source: dict[str, Any] = wait_for_run( worker.api, worker.process, worker.log, job_key="annual_orders_job_group" ) - assert source["status"] == "partial", worker.log.read_text() + assert source["status"] == "failed", worker.log.read_text() with duckdb.connect(str(worker.project / "warehouse.duckdb")) as warehouse: warehouse.execute("CREATE TABLE retry_ready AS SELECT 1 AS id") warehouse.execute("UPDATE orders SET amount=99") diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_run_output.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_run_output.py index b003916e51..4be4cd2db7 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_run_output.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_run_output.py @@ -13,6 +13,7 @@ PhaseEventsTestCase, PythonFailureTestCase, RunOutputTestCase, + SinkDeliveryTestCase, ) from tests.integration.src.sqlbuild.compiler.compiled_project.publication.helpers import ( control_database, @@ -139,7 +140,7 @@ def test_given_a_node_printing_a_large_log_when_a_worker_runs_it_then_its_lines_ "an asset failing sixty calls deep", "SELECT 17 AS amount", "SELECT amount FROM orders", - "partial", + "failed", [(17,)], files={ "python/nodes/assets/score_orders/asset.py": ( @@ -291,7 +292,7 @@ def test_given_a_nul_in_a_ctx_log_message_when_a_worker_reports_it_then_the_log_ "SQLite", "SELECT 17 AS amount", "SELECT amount FROM orders", - "partial", + "failed", [(17,)], backend="sqlite", files=NUL_FAILURE_FILES, @@ -301,7 +302,7 @@ def test_given_a_nul_in_a_ctx_log_message_when_a_worker_reports_it_then_the_log_ "PostgreSQL", "SELECT 17 AS amount", "SELECT amount FROM orders", - "partial", + "failed", [(17,)], backend="postgres", files=NUL_FAILURE_FILES, @@ -356,9 +357,11 @@ def test_given_a_nul_in_an_exception_when_its_traceback_is_reported_then_the_fai ("connected", True), ("inspected", True), ("planned", True), - ("connected", True), ("started_execution", False), + ("connected", True), + ("node", False), ), + expected_planned="1 selected", ), PhaseEventsTestCase( "PostgreSQL", @@ -374,9 +377,44 @@ def test_given_a_nul_in_an_exception_when_its_traceback_is_reported_then_the_fai ("connected", True), ("inspected", True), ("planned", True), + ("started_execution", False), + ("connected", True), + ("node", False), + ), + expected_planned="1 selected", + ), + PhaseEventsTestCase( + "a job of one Python asset starts execution before the asset and opens no SQL connections", + "SELECT 17 AS amount", + "SELECT 1", + "success", + [(1,)], + files={ + "python/nodes/assets/score_orders/asset.py": ( + "from sqlbuild.assets import asset\n\n\n" + "@asset(description='Scores orders.')\n" + "def score_orders(ctx):\n" + " return 17\n" + ), + "orchestration/jobs/annual_orders_job.toml": ( + 'name = "annual_orders_job"\n' + 'description = "Score orders."\n' + 'select = "score_orders"\n' + 'schedule = { cron = "0 0 * * *", timezone = "UTC", ' + 'starts_at = "2000-01-01T00:00:00Z" }\n' + ), + }, + expected_phases=( + ("discovered", True), + ("compiled", True), + ("matched", True), ("connected", True), + ("inspected", True), + ("planned", True), ("started_execution", False), + ("node", False), ), + expected_planned="1 Python node", ), ], ids=lambda case: case.description, @@ -390,14 +428,70 @@ def test_given_a_worker_run_when_it_prepares_then_each_phase_is_a_run_event_with ): run: dict[str, Any] = wait_for_run(worker.api, worker.process, worker.log) database: str = url or f"sqlite://{worker.control_store}" - phases: list[tuple[str, bool]] = [ - (str(phase), duration is not None) - for phase, duration in control_query( - database, - "SELECT payload->>'phase', duration_ms FROM recall_events " - "WHERE event_type='invocation_phase' ORDER BY occurred_at, storage_id", - ) - ] + events: list[tuple[Any, ...]] = control_query( + database, + "SELECT COALESCE(payload->>'phase', 'node'), duration_ms, payload->>'name' " + "FROM recall_events " + "WHERE event_type IN ('invocation_phase', 'resource_attempt_started') " + "ORDER BY occurred_at, storage_id", + ) + first_node: int = [phase for phase, _, _ in events].index("node") + phases: list[tuple[str, bool]] = [ + (str(phase), duration is not None) for phase, duration, _ in events[: first_node + 1] + ] + planned: Any = {phase: name for phase, _, name in events}["planned"] assert run["status"] == test_case.expected_status, worker.log.read_text()[-4000:] - assert phases == list(test_case.expected_phases), phases + assert (phases, planned) == ( + list(test_case.expected_phases), + test_case.expected_planned, + ), test_case.description + + +SINK_FILES: dict[str, str] = { + "python/event_sinks/events.py": ( + "from sqlbuild.event_sinks import LifecycleEvent, lifecycle_event_sink\n\n\n" + "@lifecycle_event_sink\n" + "def broker(event: LifecycleEvent) -> None:\n" + " raise RuntimeError('broker unavailable')\n\n\n" + "@lifecycle_event_sink\n" + "def archive(event: LifecycleEvent) -> None:\n" + " del event\n" + ), +} + + +@pytest.mark.parametrize( + "test_case", + [ + SinkDeliveryTestCase( + "a sink that fails every event and one that delivers them", + "SELECT 17 AS amount", + "SELECT amount FROM orders", + "success", + [(17,)], + files=SINK_FILES, + expected_sinks=(("archive", False), ("broker", True)), + ) + ], + ids=lambda case: case.description, +) +def test_given_a_worker_run_with_event_sinks_when_it_finishes_then_it_reports_each_sinks_deliveries( + test_case: SinkDeliveryTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + with scheduled_worker(tmp_path, monkeypatch, test_case) as worker: + run: dict[str, Any] = wait_for_run(worker.api, worker.process, worker.log) + events: list[tuple[Any, ...]] = control_query( + f"sqlite://{worker.control_store}", + "SELECT event_type, payload FROM recall_events " + "WHERE event_type IN ('run_sink_deliveries', 'run_terminated') ORDER BY storage_id", + ) + reported: dict[str, Any] = json.loads(events[0][1])["change"]["change"] + sinks: list[tuple[str, bool]] = sorted( + (sink["name"], sink["failed"] == sink["accepted"] > 0) for sink in reported["sinks"] + ) + assert (run["status"], [event_type for event_type, _ in events], sinks) == ( + test_case.expected_status, + ["run_sink_deliveries", "run_terminated"], + list(test_case.expected_sinks), + ), worker.log.read_text()[-4000:] diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_server_health.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_server_health.py new file mode 100644 index 0000000000..3dab630827 --- /dev/null +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_server_health.py @@ -0,0 +1,133 @@ +"""A server whose control database can't be reached answers health, liveness and API errors with the real cause.""" + +import json +from pathlib import Path +from typing import Any +from urllib.parse import SplitResult, urlsplit + +import pytest + +from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( + ServerOutageTestCase, +) +from tests.integration.src.sqlbuild.compiler.compiled_project.publication.helpers import ( + control_database_row, + forwarded_port, + free_port, + http_reply, + outage_server, + postgres_database, + wait_for_health, +) + +DNS_REASON: str = "Can't reach the control database: control-db.invalid doesn't resolve (DNS)" + + +@pytest.mark.parametrize( + "test_case", + [ + ServerOutageTestCase( + description="a host that doesn't resolve", + database_url="postgresql://sqb:hunter2-secret@control-db.invalid:5432/sqb", + expected_reason=DNS_REASON, + expected_case="name_lookup", + ) + ], + ids=lambda case: case.description, +) +def test_given_an_unresolvable_control_database_when_asked_then_health_names_the_dns_failure( + test_case: ServerOutageTestCase, tmp_path: Path +) -> None: + with outage_server(tmp_path / "server", test_case.database_url) as (url, log): + report: dict[str, Any] = wait_for_health( + url, + lambda report: control_database_row(report)["reason"] == test_case.expected_reason, + 30, + ) + health_status: int = http_reply(f"{url}/api/health")[0] + live: tuple[int, str] = http_reply(f"{url}/livez")[0::2] + api_status, api_headers, api_text = http_reply(f"{url}/api/control/bootstrap") + api_body: dict[str, Any] = json.loads(api_text) + unknown_status, unknown_headers, unknown_text = http_reply(f"{url}/api/no-such-thing") + assert { + "health": (health_status, report["status"], control_database_row(report)), + "live": live, + "api": ( + api_status, + api_body["error"], + api_body["cause"]["case"], + api_body["request_id"] == api_headers["x-request-id"], + ), + "unknown api path while waiting": ( + unknown_status, + unknown_headers["content-type"], + json.loads(unknown_text)["error"], + ), + "password in the log": "hunter2-secret" in log.read_text(), + } == { + "health": ( + 503, + "unavailable", + { + "status": "unavailable", + "reason": test_case.expected_reason, + "case": test_case.expected_case, + }, + ), + "live": (200, "ok\n"), + "api": (503, test_case.expected_reason, test_case.expected_case, True), + "unknown api path while waiting": (503, "application/json", test_case.expected_reason), + "password in the log": False, + }, test_case.description + + +@pytest.mark.parametrize( + "test_case", + [ + ServerOutageTestCase( + description="a refused connection that a database answers later", + database_url="", + expected_reason="Can't reach the control database at 127.0.0.1:{port}", + expected_case="unreachable", + ) + ], + ids=lambda case: case.description, +) +def test_given_a_control_database_that_comes_back_when_asked_then_health_recovers_without_a_restart( + test_case: ServerOutageTestCase, tmp_path: Path +) -> None: + port: int = free_port() + with postgres_database() as database: + address: SplitResult = urlsplit(database) + reachable_later: str = database.replace( + f"{address.hostname}:{address.port}", f"127.0.0.1:{port}" + ) + with outage_server(tmp_path / "server", reachable_later) as (url, log): + refused: dict[str, Any] = wait_for_health( + url, + lambda report: control_database_row(report)["case"] == test_case.expected_case, + 90, + ) + with forwarded_port(port, (str(address.hostname), int(address.port or 5432))): + recovered: dict[str, Any] = wait_for_health( + url, lambda report: report["status"] == "healthy", 120 + ) + bootstrap_status: int = http_reply(f"{url}/api/control/bootstrap")[0] + unknown_status, _, unknown_text = http_reply(f"{url}/api/no-such-thing") + assert { + "while refused": control_database_row(refused), + "after": (recovered["status"], control_database_row(recovered)), + "api no longer refused": bootstrap_status != 503, + "unknown api path": (unknown_status, json.loads(unknown_text)["error"]), + "ready": "Control API ready: " in log.read_text(), + } == { + "while refused": { + "status": "unavailable", + "reason": test_case.expected_reason.format(port=port), + "case": test_case.expected_case, + }, + "after": ("healthy", {"status": "healthy", "reason": None, "case": None}), + "api no longer refused": True, + "unknown api path": (404, "no such API endpoint"), + "ready": True, + }, test_case.description diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_warehouse_metadata.py b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_warehouse_metadata.py index 1f6db0e237..b79e7bcd02 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_warehouse_metadata.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/publication/test_warehouse_metadata.py @@ -103,6 +103,8 @@ "failed": { "reason": "OperationalError: unable to open database file", "page_size": False, + # The read never reached the warehouse, so it never stops the sync. + "connection": True, } }, ) 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 a987e2cf1d..cd075f24ea 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 @@ -31,6 +31,7 @@ ) from tests.integration.src.sqlbuild.compiler.compiled_project.publication._test_types import ( CheckExecutionTestCase, + CheckResultsTestCase, ClaimedLoadTestCase, ClaimedWorker, ForcedWorkerStopTestCase, @@ -78,9 +79,9 @@ "group execution preserves independent downstream work", "WITH source(value) AS (VALUES ('invalid')) SELECT CAST(value AS INTEGER) AS amount FROM source", "SELECT amount FROM orders", - "partial", + "failed", [(11,)], - expected_child_statuses={"staging_job": ("partial",), "marts_job": ("partial",)}, + expected_child_statuses={"staging_job": ("failed",), "marts_job": ("failed",)}, ), GroupExecutionTestCase( "successful jobs honor compiled boundaries", @@ -121,7 +122,7 @@ "failed", [(0,)], expected_child_statuses={ - "staging_job": ("partial", "cancelled"), + "staging_job": ("failed", "cancelled"), "marts_job": ("cancelled",), }, expected_totals=("cancelled", None), @@ -236,7 +237,7 @@ def test_given_a_scheduled_group_when_workers_execute_then_dependencies_and_fail "a failing unit test fails its model, and what reads it is skipped because of it", "SELECT 3 AS amount", "SELECT count(*) FROM duckdb_tables() WHERE table_name IN ('stg_orders', 'order_totals')", - "partial", + "failed", [(0,)], files={ "sql/models/raw_orders.sql": ( @@ -278,7 +279,7 @@ def test_given_a_scheduled_group_when_workers_execute_then_dependencies_and_fail "a failing case of a parameterised test fails its model", "SELECT 3 AS amount", "SELECT count(*) FROM duckdb_tables() WHERE table_name IN ('stg_orders', 'order_totals')", - "partial", + "failed", [(0,)], files={ "sql/models/raw_orders.sql": ( @@ -320,7 +321,7 @@ def test_given_a_scheduled_group_when_workers_execute_then_dependencies_and_fail "a failing assertion fails the model it reads, with no expected output", "SELECT 3 AS amount", "SELECT count(*) FROM duckdb_tables() WHERE table_name IN ('stg_orders', 'order_totals')", - "partial", + "failed", [(0,)], files={ "sql/models/raw_orders.sql": ( @@ -362,7 +363,7 @@ def test_given_a_scheduled_group_when_workers_execute_then_dependencies_and_fail "a failing function test fails its function, and the models calling it are skipped because of it", "SELECT 3 AS amount", "SELECT count(*) FROM duckdb_tables() WHERE table_name IN ('stg_orders', 'order_totals')", - "partial", + "failed", [(0,)], files={ "sql/functions/sql/udf__order_band.sql": ( @@ -529,7 +530,7 @@ def test_given_a_failing_unit_test_when_a_worker_builds_then_its_model_fails_and "a stale source blocks only its own branch", "SELECT 11 AS amount", "SELECT amount FROM orders UNION ALL SELECT return_id FROM returns ORDER BY 1", - "partial", + "failed", [(2,), (11,)], files={ "sql/sources/raw.yml": Path( @@ -592,7 +593,7 @@ def test_given_a_stale_source_when_a_worker_builds_then_blocked_nodes_finish_ski description="a failing seed audit fails its seed, and what reads it is skipped", model_sql="SELECT 3 AS amount", warehouse_query="SELECT count(*) FROM duckdb_tables() WHERE table_name='coded_orders'", - expected_status="partial", + expected_status="failed", expected_rows=[(0,)], files={ "sql/seeds/order_codes.csv": "code\nA\nZ\n", @@ -645,6 +646,45 @@ def test_given_a_failing_seed_audit_when_a_worker_builds_then_its_seed_fails_wit assert warehouse.sql(test_case.warehouse_query).fetchall() == test_case.expected_rows +@pytest.mark.parametrize( + "test_case", + [ + WorkerExecutionTestCase( + description="a model failing in its post-hook reports that phase", + model_sql="SELECT 1 AS amount", + warehouse_query="SELECT 1", + expected_status="failed", + expected_rows=[], + files={ + "sql/models/orders.sql": ( + "MODEL (description 'Orders.', materialized table, " + 'post_hooks [inline_sql("SELECT * FROM missing_post_hook_table")]);\n' + "SELECT 1 AS amount\n" + ), + }, + expected_failed_phases=[("model:orders", "post_hook")], + ) + ], + ids=lambda case: case.description, +) +def test_given_a_failing_post_hook_when_a_worker_builds_then_the_node_reports_its_failure_phase( + test_case: WorkerExecutionTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + with scheduled_worker(tmp_path, monkeypatch, test_case) as worker: + run: dict[str, Any] = wait_for_run( + worker.api, worker.process, worker.log, job_key="annual_orders_job" + ) + assert run["status"] == test_case.expected_status, worker.log.read_text() + with sqlite3.connect(worker.control_store) as control: + phases: list[tuple[str, str | None]] = control.execute( + "SELECT n.node_key, json_extract(e.payload, '$.change.change.phase') " + "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' AND n.status='failed' ORDER BY n.node_key", + (run["run_id"],), + ).fetchall() + assert phases == test_case.expected_failed_phases, worker.log.read_text() + + @pytest.mark.parametrize( "test_case", [ @@ -1682,7 +1722,7 @@ def test_given_an_executing_scheduled_worker_when_cancelled_then_the_statement_s "SELECT count(*) AS amount FROM range(500000000) t(value) WHERE value % 7 = 0", "SELECT table_name FROM duckdb_tables() " "WHERE table_name IN ('orders', 'refunds', 'returns') ORDER BY table_name", - "partial", + "failed", [("orders",)], files={ "sqlbuild_project.toml": ( @@ -2282,7 +2322,7 @@ def test_given_a_worker_run_when_its_output_is_captured_then_it_holds_no_json_re "rebuilt tables report their rows and a hard skip names itself to what it blocks", "SELECT 11 AS amount", "SELECT count(*) FROM events", - "partial", + "failed", [(3,)], files=NODE_RESULT_FILES, expected_node_results=[ @@ -2339,3 +2379,48 @@ def test_given_a_worker_build_when_it_finishes_then_each_node_reports_what_it_di ) ) assert nodes == test_case.expected_node_results, f"{nodes}\n{worker.log.read_text()}" + + +@pytest.mark.parametrize( + "test_case", + [ + CheckResultsTestCase( + "a singular audit reading a model the target doesn't have is not run, and the job succeeds", + "SELECT 11 AS amount", + "SELECT count(*) FROM orders", + "success", + [(1,)], + files={ + "sql/models/payments.sql": ( + "MODEL (description 'Payments.', materialized table);\nSELECT 11 AS amount\n" + ), + "sql/audits/singular/orders_have_payments.sql": ( + 'AUDIT (name "orders_have_payments", severity error);\n' + 'SELECT o.amount FROM __ref("orders") o ' + 'LEFT JOIN __ref("payments") p ON o.amount = p.amount WHERE p.amount IS NULL\n' + ), + }, + expected_checks=[("audit:orders_have_payments", "not_run")], + ), + ], + ids=lambda case: case.description, +) +def test_given_a_worker_build_when_an_audit_read_is_missing_then_the_audit_is_not_run( + test_case: CheckResultsTestCase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + with scheduled_worker(tmp_path, monkeypatch, test_case) as worker: + run: dict[str, Any] = wait_for_run( + worker.api, worker.process, worker.log, job_key="annual_orders_job" + ) + with sqlite3.connect(worker.control_store) as control: + checks: list[tuple[str, str]] = list( + control.execute( + "SELECT node_key, status FROM sqb_run_nodes " + "WHERE run_id=? AND kind='check' ORDER BY node_key", + (run["run_id"],), + ) + ) + assert (run["status"], checks) == ( + test_case.expected_status, + test_case.expected_checks, + ), worker.log.read_text() diff --git a/tests/integration/src/sqlbuild/compiler/compiled_project/test_orchestration_snapshot.py b/tests/integration/src/sqlbuild/compiler/compiled_project/test_orchestration_snapshot.py index dd0c05f015..7c39410984 100644 --- a/tests/integration/src/sqlbuild/compiler/compiled_project/test_orchestration_snapshot.py +++ b/tests/integration/src/sqlbuild/compiler/compiled_project/test_orchestration_snapshot.py @@ -1374,13 +1374,13 @@ def test_given_invalid_declarations_when_compiling_then_native_validation_reject }, }, "edge_job_outcomes_sensor": { - "description": "Keep warning and partial outcomes distinct from success.", + "description": "Keep warning and failed outcomes distinct from success.", "function": "edge_job_outcomes_sensor", "timeout_seconds": 60, "when": { "kind": "run_event", "job_key": "edge_snapshot_orders_job", - "kinds": ["warn", "partial"], + "kinds": ["warn", "failed"], }, "minimum_interval_seconds": 30, "default_status": "paused", diff --git a/tests/unit/src/sqlbuild/cli/commands/main/entry/test_main.py b/tests/unit/src/sqlbuild/cli/commands/main/entry/test_main.py index 88b27cdd89..1fdced28a0 100644 --- a/tests/unit/src/sqlbuild/cli/commands/main/entry/test_main.py +++ b/tests/unit/src/sqlbuild/cli/commands/main/entry/test_main.py @@ -747,8 +747,8 @@ def run_diff(request: DiffCommandRequest) -> int: "tests/scenarios/nested", "--exclude", "tests/scenarios/slow", - "--local", - "--strict", + "--run-on", + "local", "--sync-snapshots", "--force", "--max-snapshot-rows", @@ -774,8 +774,8 @@ def run_scenario(request: ScenarioTestCommandRequest) -> int: request.selectors, request.exclude, request.retain, - request.local, - request.strict, + request.run_on, + request.verbose, request.sync_snapshots, request.refresh, request.limit_inputs.force, @@ -803,8 +803,8 @@ def run_scenario(request: ScenarioTestCommandRequest) -> int: test_case.expected_scenario_selectors, ("tests/scenarios/slow",), False, - True, - True, + "local", + False, True, False, True, @@ -1057,35 +1057,6 @@ def run_load(request: LoadCommandRequest) -> int: ] -@pytest.mark.parametrize( - "test_case", - [ - MainTestCase( - description="rejects local scenario retain flag", - argv=["scenario", "test", "order_totals_pass", "--local", "--retain"], - expected_exit_code=1, - ) - ], - ids=lambda case: case.description, -) -def test_given_local_scenario_test_with_retain_when_running_then_returns_cli_error( - test_case: MainTestCase, - capsys: pytest.CaptureFixture[str], -) -> None: - exit_code: int = _main_with_dependencies( - argv=test_case.argv, - handlers=build_handlers(), - ) - rendered_stderr: str = capsys.readouterr().err - - assert exit_code == test_case.expected_exit_code - assert "error[C452]: scenario test --local does not support --retain" in rendered_stderr - assert ( - "Local scenario DuckDB files are always kept under target/run/scenarios/." - in rendered_stderr - ) - - @pytest.mark.parametrize( "test_case", [ diff --git a/tests/unit/src/sqlbuild/cli/output/main/build_execution_json/test_execution_protocol_v1.py b/tests/unit/src/sqlbuild/cli/output/main/build_execution_json/test_execution_protocol_v1.py index f2a8d05065..700427dc25 100644 --- a/tests/unit/src/sqlbuild/cli/output/main/build_execution_json/test_execution_protocol_v1.py +++ b/tests/unit/src/sqlbuild/cli/output/main/build_execution_json/test_execution_protocol_v1.py @@ -93,6 +93,7 @@ def test_given_microbatch_limit_result_when_formatting_execution_json_then_metad "timeout_count": 0, "skipped_count": 0, "warning_count": 0, + "not_run_count": 0, "python_check_pass_count": 0, "python_check_warn_count": 0, "python_check_fail_count": 0, diff --git a/tests/unit/src/sqlbuild/cli/output/main/plan/test_plan_text.py b/tests/unit/src/sqlbuild/cli/output/main/plan/test_plan_text.py index 49783efbb9..d981c567a6 100644 --- a/tests/unit/src/sqlbuild/cli/output/main/plan/test_plan_text.py +++ b/tests/unit/src/sqlbuild/cli/output/main/plan/test_plan_text.py @@ -766,7 +766,7 @@ ), ), expected_fragments=( - "Plan ready 0 selected, 3 sources to load", + "Plan ready 3 sources to load", "raw_events", "delete_insert (cursor: event_at)", "raw_orders", diff --git a/tests/unit/src/sqlbuild/cli/project_metadata/test_dependencies.py b/tests/unit/src/sqlbuild/cli/project_metadata/test_dependencies.py index 9035e3ceaa..2f0263aefa 100644 --- a/tests/unit/src/sqlbuild/cli/project_metadata/test_dependencies.py +++ b/tests/unit/src/sqlbuild/cli/project_metadata/test_dependencies.py @@ -22,8 +22,14 @@ expected_optional_extra_absent=True, ), ProjectDependencyTestCase( - description="maintained polyglot fork is a core dependency", + description="the polyglot fork's Python package is not a dependency: analysis is native", dependency_name="polyglot-sql-chio", + expected_in_core_dependencies=False, + expected_optional_extra_absent=True, + ), + ProjectDependencyTestCase( + description="SQLQuack, which converts local test SQL, is a core dependency", + dependency_name="sqlquack", expected_in_core_dependencies=True, expected_optional_extra_absent=True, ), diff --git a/tests/unit/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/helpers.py b/tests/unit/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/helpers.py index cea69cc114..710a545763 100644 --- a/tests/unit/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/helpers.py +++ b/tests/unit/src/sqlbuild/compiler/planner/_helpers/sql_test_assembly/helpers.py @@ -5,7 +5,6 @@ from collections.abc import Callable from pathlib import Path from types import MappingProxyType -from typing import Any from sqlbuild._native import ( CompiledFunction, @@ -44,7 +43,6 @@ CompiledModelView, CompiledProjectView, ) -from sqlbuild.compiler.sql_analysis.main.import_polyglot_sql import import_polyglot_sql from tests.unit.src.sqlbuild.compiler.planner._helpers.sql_test_assembly._test_types import ( PlanTestChainTestCase, ) @@ -148,16 +146,7 @@ def assert_native_artifact_matches_runtime_plan( sql_analysis_enabled=sql_analysis_enabled, ) - polyglot_sql: Any = import_polyglot_sql() - native_expression: Any = polyglot_sql.parse_one( - artifact.sql, dialect=adapter.sql_analysis_dialect() - ) - expected_expression: Any = polyglot_sql.parse_one( - expected_sql, dialect=adapter.sql_analysis_dialect() - ) - assert native_expression.sql(dialect=adapter.sql_analysis_dialect()) == expected_expression.sql( - dialect=adapter.sql_analysis_dialect() - ) + assert " ".join(artifact.sql.split()) == " ".join(expected_sql.split()) assert artifact.model_names == tuple(step.model_name for step in entry.chain) assert artifact.error_messages == sql_test_plan_error_messages(warnings=warnings) return True diff --git a/tests/unit/src/sqlbuild/compiler/sql_analysis/main/test_import_polyglot_sql.py b/tests/unit/src/sqlbuild/compiler/sql_analysis/main/test_import_polyglot_sql.py deleted file mode 100644 index 09551cef1a..0000000000 --- a/tests/unit/src/sqlbuild/compiler/sql_analysis/main/test_import_polyglot_sql.py +++ /dev/null @@ -1,94 +0,0 @@ -from __future__ import annotations - -from typing import Any - -import pytest - -from sqlbuild.compiler.sql_analysis.main.import_polyglot_sql import import_polyglot_sql -from tests.unit.src.sqlbuild.compiler.sql_analysis.main._test_types import ( - PolyglotDefaultGuardTestCase, - PolyglotExplicitGuardTestCase, -) -from tests.unit.src.sqlbuild.compiler.sql_analysis.main.helpers import nested_coalesce_sql - - -@pytest.mark.parametrize( - "test_case", - ( - PolyglotDefaultGuardTestCase( - description="trusted SQL exceeds the defensive default", - function_depth=65, - expected_kind="select", - ), - ), - ids=lambda case: case.description, -) -def test_given_deep_trusted_sql_when_parsing_then_sqlbuild_uses_bounded_budget( - test_case: PolyglotDefaultGuardTestCase, -) -> None: - polyglot_module: Any = import_polyglot_sql() - - parsed: Any = polyglot_module.parse_one( - nested_coalesce_sql(function_depth=test_case.function_depth), - dialect="snowflake", - ) - - assert parsed.kind == test_case.expected_kind - - -@pytest.mark.parametrize( - "test_case", - ( - PolyglotExplicitGuardTestCase( - description="caller retains the defensive default", - function_depth=65, - maximum_function_depth=64, - expected_error_pattern="FUNCTION_NESTING_DEPTH_EXCEEDED", - ), - ), - ids=lambda case: case.description, -) -def test_given_explicit_guard_when_parsing_then_caller_budget_is_preserved( - test_case: PolyglotExplicitGuardTestCase, -) -> None: - polyglot_module: Any = import_polyglot_sql() - - with pytest.raises(polyglot_module.ParseError, match=test_case.expected_error_pattern): - polyglot_module.parse_one( - nested_coalesce_sql(function_depth=test_case.function_depth), - dialect="snowflake", - complexity_guard={"maxFunctionCallDepth": test_case.maximum_function_depth}, - ) - - -@pytest.mark.parametrize( - "test_case", - ( - PolyglotExplicitGuardTestCase( - description="analysis options retain the caller guard", - function_depth=65, - maximum_function_depth=64, - expected_error_pattern="FUNCTION_NESTING_DEPTH_EXCEEDED", - ), - ), - ids=lambda case: case.description, -) -def test_given_options_guard_when_analyzing_then_caller_budget_is_preserved( - test_case: PolyglotExplicitGuardTestCase, -) -> None: - polyglot_module: Any = import_polyglot_sql() - - with pytest.raises(polyglot_module.ParseError, match=test_case.expected_error_pattern): - polyglot_module.analyze_query( - nested_coalesce_sql(function_depth=test_case.function_depth), - { - "dialect": "snowflake", - "complexityGuard": { - "maxFunctionCallDepth": test_case.maximum_function_depth, - }, - }, - ) - - -if __name__ == "__main__": - pytest.main([__file__, "-vv"]) diff --git a/tests/unit/src/sqlbuild/executor/build/_helpers/_test_types.py b/tests/unit/src/sqlbuild/executor/build/_helpers/_test_types.py index 1cbf267c7a..1165dea2a6 100644 --- a/tests/unit/src/sqlbuild/executor/build/_helpers/_test_types.py +++ b/tests/unit/src/sqlbuild/executor/build/_helpers/_test_types.py @@ -20,6 +20,9 @@ class AuditExecutionIndexTestCase: description: str expected_model_audit_count: int expected_end_audit_count: int + attachment_kind: str = "end" + # Audits the plan selects by name, as audit: or a past run's failed audits select them. + selected_audit_names: tuple[str, ...] = () @dataclass(frozen=True) diff --git a/tests/unit/src/sqlbuild/executor/build/_helpers/test_indexes.py b/tests/unit/src/sqlbuild/executor/build/_helpers/test_indexes.py index be9bbf98d6..57232af471 100644 --- a/tests/unit/src/sqlbuild/executor/build/_helpers/test_indexes.py +++ b/tests/unit/src/sqlbuild/executor/build/_helpers/test_indexes.py @@ -23,7 +23,20 @@ description="end-scheduled model audit is indexed exactly once at end", expected_model_audit_count=0, expected_end_audit_count=1, - ) + ), + AuditExecutionIndexTestCase( + description="a model audit selected by name whose model isn't built runs at the end", + expected_model_audit_count=0, + expected_end_audit_count=1, + attachment_kind="model", + selected_audit_names=("cross_model_consistency",), + ), + AuditExecutionIndexTestCase( + description="a model audit not selected by name stays its model's gate", + expected_model_audit_count=1, + expected_end_audit_count=0, + attachment_kind="model", + ), ], ids=lambda case: case.description, ) @@ -36,7 +49,7 @@ def test_given_end_scheduled_model_audit_when_building_indexes_then_it_is_not_a_ definition_name="test_audit", resolved_sql="SELECT 1 WHERE FALSE", unresolved_sql="SELECT 1 WHERE FALSE", - attachment_kind=AuditAttachmentKind.END, + attachment_kind=AuditAttachmentKind(test_case.attachment_kind), attached_target_kind=AttachedAuditTargetKind.MODEL, attached_target_name="orders", severity=AuditSeverity.ERROR, @@ -44,10 +57,12 @@ def test_given_end_scheduled_model_audit_when_building_indexes_then_it_is_not_a_ effective_run_scope=AuditRunScope.FINAL, ) - indexes: BuildIndexes = build_execution_indexes(PlanOutput(audit_entries=(audit,))) - - assert sum(len(audits) for audits in indexes.model_audits_by_model.values()) == ( - test_case.expected_model_audit_count + indexes: BuildIndexes = build_execution_indexes( + PlanOutput(audit_entries=(audit,), selected_audit_names=test_case.selected_audit_names) ) - assert len(indexes.end_audits) == test_case.expected_end_audit_count - assert indexes.end_audits[0].attached_target_name == "orders" + + assert ( + sum(len(audits) for audits in indexes.model_audits_by_model.values()), + len(indexes.end_audits), + ) == (test_case.expected_model_audit_count, test_case.expected_end_audit_count) + assert all(entry.attached_target_name == "orders" for entry in indexes.end_audits) diff --git a/src/sqlbuild/compiler/sql_analysis/__init__.py b/tests/unit/src/sqlbuild/executor/local/__init__.py similarity index 100% rename from src/sqlbuild/compiler/sql_analysis/__init__.py rename to tests/unit/src/sqlbuild/executor/local/__init__.py diff --git a/src/sqlbuild/compiler/sql_analysis/_helpers/__init__.py b/tests/unit/src/sqlbuild/executor/local/_helpers/__init__.py similarity index 100% rename from src/sqlbuild/compiler/sql_analysis/_helpers/__init__.py rename to tests/unit/src/sqlbuild/executor/local/_helpers/__init__.py diff --git a/tests/unit/src/sqlbuild/executor/local/_helpers/_test_types.py b/tests/unit/src/sqlbuild/executor/local/_helpers/_test_types.py new file mode 100644 index 0000000000..21324073ee --- /dev/null +++ b/tests/unit/src/sqlbuild/executor/local/_helpers/_test_types.py @@ -0,0 +1,106 @@ +from dataclasses import dataclass + + +@dataclass(frozen=True) +class ConversionWorkTestCase: + """Statements checked for a run, and the work each kind of step may take.""" + + description: str + statements: tuple[str, ...] + repeats: int + expected_conversions: int + expected_schema_keys: int + expected_relations: frozenset[str] + + +@dataclass(frozen=True) +class PooledConversionWorkTestCase: + """Enough statements to convert in worker processes, then read again for each test.""" + + description: str + statement_count: int + expected_conversions: int + expected_schema_keys: int + + +@dataclass(frozen=True) +class BindingWorkTestCase: + """DuckDB statements bound once each against an empty database.""" + + description: str + statements: tuple[str, ...] + repeats: int + expected_bindings: int + expected_missing: tuple[str | None, ...] + + +@dataclass(frozen=True) +class CachedConversionTestCase: + """Statements converted in one run, then read from the disk cache by a later one.""" + + description: str + statement_count: int + expected_first_conversions: int + expected_later_conversions: int + expected_later_cached: int + + +@dataclass(frozen=True) +class CachePruningTestCase: + """Entries one run keeps, a later run using some of them `days_later`, then pruning.""" + + description: str + statement_count: int + later_used_count: int + days_later: int + expected_pruned: int + expected_kept: int + + +@dataclass(frozen=True) +class WarehouseRelationsTestCase: + """A statement over declared relations, and those only the warehouse can give it.""" + + description: str + sql: str + expected_relations: tuple[str, ...] + + +@dataclass(frozen=True) +class LocalRunRefusalTestCase: + """A DuckDB failure of converted SQL that keeps the test off DuckDB, and the refusal title.""" + + description: str + error_type: str + message: str + fatal: bool + expected_title: str + + +@dataclass(frozen=True) +class OwnFailureTestCase: + """A DuckDB failure of converted SQL that is the test's own result.""" + + description: str + error_type: str + message: str + fatal: bool + expected_refused: bool + + +@dataclass(frozen=True) +class FailureTextRefusalTestCase: + """A scenario step's failure text that keeps the scenario off DuckDB, and the refusal title.""" + + description: str + message: str + expected_title: str + + +@dataclass(frozen=True) +class OwnFailureTextTestCase: + """A scenario step's failure text that Snowflake would raise too: the scenario's own result.""" + + description: str + message: str + expected_refused: bool diff --git a/tests/unit/src/sqlbuild/executor/local/_helpers/helpers.py b/tests/unit/src/sqlbuild/executor/local/_helpers/helpers.py new file mode 100644 index 0000000000..613c30a384 --- /dev/null +++ b/tests/unit/src/sqlbuild/executor/local/_helpers/helpers.py @@ -0,0 +1,74 @@ +"""Counting SQLQuack calls while local work is checked.""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from typing import Any + +import pytest +import sqlquack + +from sqlbuild.executor.local._helpers import conversion as conversion_module +from sqlbuild.executor.local._helpers.conversion import check_all, local_check +from sqlbuild.executor.local.models import LocalWorkCounts + +ORDERS_SCHEMA_RELATIONS: dict[str, list[list[str]]] = { + "SHOP.RAW.ORDERS": [["ID", "NUMBER(38,0)"], ["AMOUNT", "NUMBER(38,0)"]], + "SHOP.RAW.CUSTOMERS": [["ID", "NUMBER(38,0)"]], +} + + +def counting_convert( + monkeypatch: pytest.MonkeyPatch, +) -> list[frozenset[str]]: + """Replace `sqlquack.convert` with one that records each call's schema relations.""" + + calls: list[frozenset[str]] = [] + original: Callable[..., Any] = sqlquack.convert + + def convert(*, sql: str, options: Any, **rest: Any) -> Any: + calls.append(frozenset(dict(options.schema or {}).get("relations", {}))) + return original(sql=sql, options=options, **rest) + + monkeypatch.setattr(sqlquack, "convert", convert) + return calls + + +def check_each( + *, statements: Sequence[str], schema: dict[str, Any] | None, repeats: int, convert: bool +) -> tuple[int, list[Any]]: + """How many statements workers checked up front, then each check read `repeats` times.""" + + pooled: int = check_all(sqls=list(statements), schema=schema, time_zone=None, convert=convert) + repeated: list[str] = list(statements) * repeats + return pooled, [ + local_check(sql=sql, schema=schema, time_zone=None, path="test.sql", convert=convert) + for sql in repeated + ] + + +def work_counts() -> LocalWorkCounts: + """Conversions, bindings, schema serialisations and cache reads this process did so far.""" + + return conversion_module._WORK.counts() + + +def work_delta(before: LocalWorkCounts) -> LocalWorkCounts: + """The work done since `before`.""" + + after: LocalWorkCounts = work_counts() + return LocalWorkCounts( + conversions=after.conversions - before.conversions, + bindings=after.bindings - before.bindings, + schema_keys=after.schema_keys - before.schema_keys, + cached=after.cached - before.cached, + ) + + +def fresh_run(monkeypatch: pytest.MonkeyPatch) -> None: + """Forget this process's checks, as a new `sqb` process starts without them.""" + + monkeypatch.setattr( + "sqlbuild.executor.local._helpers.conversion._WORK", + conversion_module._LocalWork(), + ) diff --git a/tests/unit/src/sqlbuild/executor/local/_helpers/test_conversion_cache.py b/tests/unit/src/sqlbuild/executor/local/_helpers/test_conversion_cache.py new file mode 100644 index 0000000000..ffc7a726ba --- /dev/null +++ b/tests/unit/src/sqlbuild/executor/local/_helpers/test_conversion_cache.py @@ -0,0 +1,110 @@ +"""Conversions kept on disk: a later run reads them instead of converting again.""" + +from pathlib import Path + +import pytest +import sqlquack + +from sqlbuild.executor.local._helpers.conversion import use_conversion_cache +from sqlbuild.executor.local.models import LocalWorkCounts +from tests.unit.src.sqlbuild.executor.local._helpers._test_types import CachedConversionTestCase +from tests.unit.src.sqlbuild.executor.local._helpers.helpers import ( + ORDERS_SCHEMA_RELATIONS, + check_each, + fresh_run, + work_counts, + work_delta, +) + + +@pytest.mark.parametrize( + "test_case", + [ + CachedConversionTestCase( + description="two statements, checked one at a time", + statement_count=2, + expected_first_conversions=2, + expected_later_conversions=0, + expected_later_cached=2, + ), + CachedConversionTestCase( + description="ten statements, enough to convert in worker processes", + statement_count=10, + expected_first_conversions=10, + expected_later_conversions=0, + expected_later_cached=10, + ), + ], + ids=lambda case: case.description, +) +def test_given_conversions_kept_on_disk_when_a_later_run_checks_them_then_none_convert_again( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, test_case: CachedConversionTestCase +) -> None: + schema: dict[str, object] = {"relations": dict(ORDERS_SCHEMA_RELATIONS)} + statements: tuple[str, ...] = tuple( + f"SELECT id + {index} AS id FROM shop.raw.orders" + for index in range(test_case.statement_count) + ) + fresh_run(monkeypatch) + use_conversion_cache(tmp_path) + first: LocalWorkCounts = work_counts() + _pooled, first_checks = check_each( + statements=statements, schema=schema, repeats=1, convert=True + ) + first_work: LocalWorkCounts = work_delta(first) + fresh_run(monkeypatch) + use_conversion_cache(tmp_path) + later: LocalWorkCounts = work_counts() + + _pooled, later_checks = check_each( + statements=statements, schema=schema, repeats=1, convert=True + ) + + later_work: LocalWorkCounts = work_delta(later) + assert first_work.conversions == test_case.expected_first_conversions + assert later_work.conversions == test_case.expected_later_conversions + assert later_work.cached == test_case.expected_later_cached + assert later_checks == first_checks + + +@pytest.mark.parametrize( + "test_case", + [ + CachedConversionTestCase( + description="another SQLQuack version converts again", + statement_count=2, + expected_first_conversions=2, + expected_later_conversions=2, + expected_later_cached=0, + ), + ], + ids=lambda case: case.description, +) +def test_given_another_sqlquack_version_when_checking_then_kept_conversions_are_not_read( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, test_case: CachedConversionTestCase +) -> None: + schema: dict[str, object] = {"relations": dict(ORDERS_SCHEMA_RELATIONS)} + statements: tuple[str, ...] = tuple( + f"SELECT id * {index} AS id FROM shop.raw.orders" + for index in range(test_case.statement_count) + ) + fresh_run(monkeypatch) + use_conversion_cache(tmp_path) + first: LocalWorkCounts = work_counts() + _ = check_each(statements=statements, schema=schema, repeats=1, convert=True) + first_work: LocalWorkCounts = work_delta(first) + fresh_run(monkeypatch) + use_conversion_cache(tmp_path) + monkeypatch.setattr(sqlquack, "__version__", f"{sqlquack.__version__}.other") + later: LocalWorkCounts = work_counts() + + _ = check_each(statements=statements, schema=schema, repeats=1, convert=True) + + later_work: LocalWorkCounts = work_delta(later) + assert first_work.conversions == test_case.expected_first_conversions + assert later_work.conversions == test_case.expected_later_conversions + assert later_work.cached == test_case.expected_later_cached + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"]) diff --git a/tests/unit/src/sqlbuild/executor/local/_helpers/test_conversion_cache_pruning.py b/tests/unit/src/sqlbuild/executor/local/_helpers/test_conversion_cache_pruning.py new file mode 100644 index 0000000000..2b1b6e519a --- /dev/null +++ b/tests/unit/src/sqlbuild/executor/local/_helpers/test_conversion_cache_pruning.py @@ -0,0 +1,74 @@ +"""Kept conversions that no run used for a week are deleted when a run ends.""" + +from pathlib import Path + +import pytest + +from sqlbuild.executor.local._helpers.conversion import ( + prune_conversion_cache, + use_conversion_cache, +) +from tests.unit.src.sqlbuild.executor.local._helpers._test_types import CachePruningTestCase +from tests.unit.src.sqlbuild.executor.local._helpers.helpers import ( + ORDERS_SCHEMA_RELATIONS, + check_each, + fresh_run, +) + +_FIRST_RUN: float = 1_000_000_000.0 +_DAY: float = 24 * 60 * 60 + + +@pytest.mark.parametrize( + "test_case", + [ + CachePruningTestCase( + description="unused for eight days", + statement_count=3, + later_used_count=1, + days_later=8, + expected_pruned=2, + expected_kept=1, + ), + CachePruningTestCase( + description="unused for six days", + statement_count=3, + later_used_count=1, + days_later=6, + expected_pruned=0, + expected_kept=3, + ), + CachePruningTestCase( + description="all used again", + statement_count=3, + later_used_count=3, + days_later=30, + expected_pruned=0, + expected_kept=3, + ), + ], + ids=lambda case: case.description, +) +def test_given_kept_conversions_when_a_run_ends_then_those_unused_for_a_week_are_deleted( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, test_case: CachePruningTestCase +) -> None: + schema: dict[str, object] = {"relations": dict(ORDERS_SCHEMA_RELATIONS)} + statements: tuple[str, ...] = tuple( + f"SELECT id - {index} AS id FROM shop.raw.orders" + for index in range(test_case.statement_count) + ) + fresh_run(monkeypatch) + use_conversion_cache(tmp_path) + _ = check_each(statements=statements, schema=schema, repeats=1, convert=True) + first_pruned: int = prune_conversion_cache(now=_FIRST_RUN) + fresh_run(monkeypatch) + use_conversion_cache(tmp_path) + _ = check_each( + statements=statements[: test_case.later_used_count], schema=schema, repeats=1, convert=True + ) + + later_pruned: int = prune_conversion_cache(now=_FIRST_RUN + test_case.days_later * _DAY) + + assert first_pruned == 0 + assert later_pruned == test_case.expected_pruned + assert len(list(tmp_path.glob("*/*.json"))) == test_case.expected_kept diff --git a/tests/unit/src/sqlbuild/executor/local/_helpers/test_conversion_work.py b/tests/unit/src/sqlbuild/executor/local/_helpers/test_conversion_work.py new file mode 100644 index 0000000000..87f65d1f43 --- /dev/null +++ b/tests/unit/src/sqlbuild/executor/local/_helpers/test_conversion_work.py @@ -0,0 +1,131 @@ +"""Local test checks scale with unique statements: each converts or binds once per run.""" + +import uuid + +import pytest + +from sqlbuild.executor.local.models import LocalWorkCounts +from tests.unit.src.sqlbuild.executor.local._helpers._test_types import ( + BindingWorkTestCase, + ConversionWorkTestCase, + PooledConversionWorkTestCase, +) +from tests.unit.src.sqlbuild.executor.local._helpers.helpers import ( + ORDERS_SCHEMA_RELATIONS, + check_each, + counting_convert, + work_counts, + work_delta, +) + + +@pytest.mark.parametrize( + "test_case", + [ + ConversionWorkTestCase( + description="two tests read three times convert twice, serialising the schema once", + statements=( + "SELECT id FROM shop.raw.orders WHERE amount > 1", + "SELECT id, amount FROM shop.raw.orders", + ), + repeats=3, + expected_conversions=2, + expected_schema_keys=1, + expected_relations=frozenset({"SHOP.RAW.ORDERS"}), + ), + ConversionWorkTestCase( + description="a repeated statement converts once", + statements=("SELECT id FROM shop.raw.customers",) * 4, + repeats=2, + expected_conversions=1, + expected_schema_keys=1, + expected_relations=frozenset({"SHOP.RAW.CUSTOMERS"}), + ), + ], + ids=lambda case: case.description, +) +def test_given_tests_when_checking_locally_then_each_statement_converts_once_with_its_relations( + monkeypatch: pytest.MonkeyPatch, test_case: ConversionWorkTestCase +) -> None: + calls: list[frozenset[str]] = counting_convert(monkeypatch) + schema: dict[str, object] = {"relations": dict(ORDERS_SCHEMA_RELATIONS)} + tag: str = uuid.uuid4().hex + statements: tuple[str, ...] = tuple(f"{sql} /* {tag} */" for sql in test_case.statements) + before: LocalWorkCounts = work_counts() + + _pooled, checks = check_each( + statements=statements, schema=schema, repeats=test_case.repeats, convert=True + ) + + delta: LocalWorkCounts = work_delta(before) + assert len(checks) == len(statements) * test_case.repeats + assert len(calls) == test_case.expected_conversions + assert delta.conversions == test_case.expected_conversions + assert delta.schema_keys == test_case.expected_schema_keys + assert delta.bindings == 0 + assert set(calls) == {test_case.expected_relations} + + +@pytest.mark.parametrize( + "test_case", + [ + PooledConversionWorkTestCase( + description="ten tests convert ten times in workers, none again when the tests run", + statement_count=10, + expected_conversions=10, + expected_schema_keys=1, + ), + ], + ids=lambda case: case.description, +) +def test_given_many_tests_when_checking_in_workers_then_running_them_converts_nothing_more( + test_case: PooledConversionWorkTestCase, +) -> None: + schema: dict[str, object] = {"relations": dict(ORDERS_SCHEMA_RELATIONS)} + tag: str = uuid.uuid4().hex + statements: tuple[str, ...] = tuple( + f"SELECT id + {index} AS id FROM shop.raw.orders /* {tag} */" + for index in range(test_case.statement_count) + ) + before: LocalWorkCounts = work_counts() + + pooled, _checks = check_each(statements=statements, schema=schema, repeats=2, convert=True) + + delta: LocalWorkCounts = work_delta(before) + assert pooled == test_case.expected_conversions + assert delta.conversions == test_case.expected_conversions + assert delta.schema_keys == test_case.expected_schema_keys + + +@pytest.mark.parametrize( + "test_case", + [ + BindingWorkTestCase( + description="DuckDB statements bind once each and name a relation only DuckDB lacks", + statements=("SELECT 1 AS one", "SELECT * FROM nowhere_table"), + repeats=3, + expected_bindings=2, + expected_missing=(None, "nowhere_table"), + ), + ], + ids=lambda case: case.description, +) +def test_given_duckdb_tests_when_checking_locally_then_each_binds_once_in_an_empty_database( + test_case: BindingWorkTestCase, +) -> None: + tag: str = uuid.uuid4().hex + statements: tuple[str, ...] = tuple(f"{sql} /* {tag} */" for sql in test_case.statements) + before: LocalWorkCounts = work_counts() + + _pooled, checks = check_each( + statements=statements, schema=None, repeats=test_case.repeats, convert=False + ) + + delta: LocalWorkCounts = work_delta(before) + assert delta.bindings == test_case.expected_bindings + assert delta.conversions == 0 + assert tuple(check.missing for check in checks[: len(statements)]) == test_case.expected_missing + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"]) diff --git a/tests/unit/src/sqlbuild/executor/local/_helpers/test_runtime.py b/tests/unit/src/sqlbuild/executor/local/_helpers/test_runtime.py new file mode 100644 index 0000000000..01d0288055 --- /dev/null +++ b/tests/unit/src/sqlbuild/executor/local/_helpers/test_runtime.py @@ -0,0 +1,131 @@ +"""Which DuckDB failures of converted SQL mean the test belongs on the warehouse.""" + +import pytest + +from sqlbuild.errors.contracts.exceptions import LocalRunRefusedError +from sqlbuild.executor.local._helpers.runtime import local_failure_refusal, local_run_refusal +from tests.unit.src.sqlbuild.executor.local._helpers._test_types import ( + FailureTextRefusalTestCase, + LocalRunRefusalTestCase, + OwnFailureTestCase, + OwnFailureTextTestCase, +) + + +@pytest.mark.parametrize( + "test_case", + [ + LocalRunRefusalTestCase( + description="a guard's raise names the guard", + error_type="ConversionException", + message=( + "Conversion Error: Could not convert string 'array_agg_order#0123456789ab: " + "ARRAY_AGG of several values in no defined order' to INT32" + ), + fatal=False, + expected_title="SQLQuack guard: array_agg_order", + ), + LocalRunRefusalTestCase( + description="a DuckDB internal error names its first line", + error_type="InternalException", + message="INTERNAL Error: an expression should not be used here yet!\n\nStack Trace:", + fatal=True, + expected_title="DuckDB internal error: an expression should not be used here yet!", + ), + ], + ids=lambda case: case.description, +) +def test_given_a_guard_or_engine_bug_when_classifying_then_it_refuses_naming_it( + test_case: LocalRunRefusalTestCase, +) -> None: + error: Exception = type(test_case.error_type, (Exception,), {})(test_case.message) + + refused: LocalRunRefusedError | None = local_run_refusal(error=error, fatal=test_case.fatal) + + assert refused is not None + assert f"{refused.category}: {refused.construct}" == test_case.expected_title + + +@pytest.mark.parametrize( + "test_case", + [ + OwnFailureTestCase( + description="an emulated Snowflake error is the test's own result", + error_type="ConversionException", + message=( + "Conversion Error: Could not convert string 'sqlquack:100038#0123456789ab: " + "Numeric value is not recognized' to INT32" + ), + fatal=False, + expected_refused=False, + ), + OwnFailureTestCase( + description="any other DuckDB error is the test's own result", + error_type="BinderException", + message="Binder Error: Referenced column a not found", + fatal=False, + expected_refused=False, + ), + ], + ids=lambda case: case.description, +) +def test_given_an_error_snowflake_would_raise_too_when_classifying_then_it_is_the_tests_own( + test_case: OwnFailureTestCase, +) -> None: + error: Exception = type(test_case.error_type, (Exception,), {})(test_case.message) + + refused: LocalRunRefusedError | None = local_run_refusal(error=error, fatal=test_case.fatal) + + assert (refused is not None) is test_case.expected_refused + + +@pytest.mark.parametrize( + "test_case", + [ + FailureTextRefusalTestCase( + description="a model step whose guard raised", + message=( + "local model 'order_id_lists' failed: Conversion Error: Could not convert string" + " 'array_agg_order#0123456789ab: ARRAY_AGG of several values in no defined order'" + " to INT32" + ), + expected_title="SQLQuack guard: array_agg_order", + ), + FailureTextRefusalTestCase( + description="a model step DuckDB failed internally", + message="local model 'orders' failed: INTERNAL Error: unexpected plan\nStack Trace:", + expected_title="DuckDB internal error: unexpected plan", + ), + ], + ids=lambda case: case.description, +) +def test_given_a_scenario_step_failure_when_classifying_its_text_then_guards_and_bugs_refuse( + test_case: FailureTextRefusalTestCase, +) -> None: + refused: LocalRunRefusedError | None = local_failure_refusal(test_case.message) + + assert refused is not None + assert f"{refused.category}: {refused.construct}" == test_case.expected_title + + +@pytest.mark.parametrize( + "test_case", + [ + OwnFailureTextTestCase( + description="a model step that failed as Snowflake would", + message="local model 'orders' failed: Binder Error: Referenced column a not found", + expected_refused=False, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_scenario_step_that_failed_as_snowflake_would_when_classifying_then_it_is_its_own( + test_case: OwnFailureTextTestCase, +) -> None: + refused: LocalRunRefusedError | None = local_failure_refusal(test_case.message) + + assert (refused is not None) is test_case.expected_refused + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"]) diff --git a/tests/unit/src/sqlbuild/executor/local/_helpers/test_warehouse_relations.py b/tests/unit/src/sqlbuild/executor/local/_helpers/test_warehouse_relations.py new file mode 100644 index 0000000000..bb58a2401c --- /dev/null +++ b/tests/unit/src/sqlbuild/executor/local/_helpers/test_warehouse_relations.py @@ -0,0 +1,55 @@ +"""Declared relations a converted test reads itself, rather than through its fixtures.""" + +import pytest + +from sqlbuild.executor.local._helpers.conversion import converted, warehouse_relations +from sqlbuild.executor.local.models import ConvertedSql +from tests.unit.src.sqlbuild.executor.local._helpers._test_types import WarehouseRelationsTestCase +from tests.unit.src.sqlbuild.executor.local._helpers.helpers import ORDERS_SCHEMA_RELATIONS + + +@pytest.mark.parametrize( + "test_case", + [ + WarehouseRelationsTestCase( + description="a fixture CTE named like a declared relation reads no warehouse relation", + sql="WITH orders AS (SELECT 1 AS id) SELECT id FROM orders", + expected_relations=(), + ), + WarehouseRelationsTestCase( + description="a declared relation read by name beside a fixture is the warehouse's", + sql=( + "WITH orders AS (SELECT 1 AS id) " + "SELECT orders.id FROM orders JOIN shop.raw.customers AS c ON c.id = orders.id" + ), + expected_relations=("SHOP.RAW.CUSTOMERS",), + ), + WarehouseRelationsTestCase( + description="each declared relation read is named once", + sql=( + "SELECT o.id FROM shop.raw.orders AS o " + "JOIN shop.raw.customers AS c ON c.id = o.id JOIN shop.raw.orders AS p ON p.id = o.id" + ), + expected_relations=("SHOP.RAW.CUSTOMERS", "SHOP.RAW.ORDERS"), + ), + ], + ids=lambda case: case.description, +) +def test_given_converted_test_sql_when_finding_warehouse_relations_then_fixtures_do_not_count( + test_case: WarehouseRelationsTestCase, +) -> None: + schema: dict[str, object] = {"relations": dict(ORDERS_SCHEMA_RELATIONS)} + conversion: ConvertedSql = converted( + sql=test_case.sql, schema=schema, time_zone=None, path="test.sql" + ) + + relations: tuple[str, ...] = warehouse_relations( + sql=test_case.sql, schema=schema, conversion=conversion + ) + + assert conversion.converted + assert relations == test_case.expected_relations + + +if __name__ == "__main__": + pytest.main([__file__, "-vv"]) diff --git a/tests/unit/src/sqlbuild/executor/pipeline/_helpers/_test_types.py b/tests/unit/src/sqlbuild/executor/pipeline/_helpers/_test_types.py index 8be28169f2..b1caedc70b 100644 --- a/tests/unit/src/sqlbuild/executor/pipeline/_helpers/_test_types.py +++ b/tests/unit/src/sqlbuild/executor/pipeline/_helpers/_test_types.py @@ -124,7 +124,6 @@ class ScenarioLocalPipelineTestCase: description: str snapshot_state: str - strict: bool load_error_message: str | None expected_local_status: str expected_status: str diff --git a/tests/unit/src/sqlbuild/executor/pipeline/_helpers/test_scenario.py b/tests/unit/src/sqlbuild/executor/pipeline/_helpers/test_scenario.py index d6fdebf610..2438e3d82f 100644 --- a/tests/unit/src/sqlbuild/executor/pipeline/_helpers/test_scenario.py +++ b/tests/unit/src/sqlbuild/executor/pipeline/_helpers/test_scenario.py @@ -275,7 +275,6 @@ def test_given_local_scenario_planning_failure_when_running_then_canonical_attem scenarios=pipeline_result.project.sql_scenarios, adapter=ScenarioLocalPipelineTestAdapter(), project_name="waffle_shop", - strict=False, replay_source=ScenarioLocalReplaySource(lexical_syntax=SqlLexicalSyntax()), ) @@ -295,20 +294,8 @@ def test_given_local_scenario_planning_failure_when_running_then_canonical_attem "test_case", ( ScenarioLocalPipelineTestCase( - description="missing snapshot skips by default", + description="missing snapshot is an error", snapshot_state="missing", - strict=False, - load_error_message=None, - expected_local_status="SKIP", - expected_status="skipped", - expected_retained=False, - expected_duckdb_exists=False, - expected_error_code=SCENARIO_LOCAL_SNAPSHOT_MISSING, - ), - ScenarioLocalPipelineTestCase( - description="missing snapshot errors in strict mode", - snapshot_state="missing", - strict=True, load_error_message=None, expected_local_status="ERROR", expected_status="failed", @@ -317,12 +304,11 @@ def test_given_local_scenario_planning_failure_when_running_then_canonical_attem expected_error_code=SCENARIO_LOCAL_SNAPSHOT_MISSING, ), ScenarioLocalPipelineTestCase( - description="stale snapshot skips by default", + description="stale snapshot is an error", snapshot_state="stale", - strict=False, load_error_message=None, - expected_local_status="SKIP", - expected_status="skipped", + expected_local_status="ERROR", + expected_status="failed", expected_retained=False, expected_duckdb_exists=False, expected_error_code=SCENARIO_LOCAL_SNAPSHOT_STALE, @@ -330,7 +316,6 @@ def test_given_local_scenario_planning_failure_when_running_then_canonical_attem ScenarioLocalPipelineTestCase( description="fresh snapshot pass keeps DuckDB by default", snapshot_state="fresh", - strict=False, load_error_message=None, expected_local_status="PASS", expected_status="success", @@ -341,7 +326,6 @@ def test_given_local_scenario_planning_failure_when_running_then_canonical_attem ScenarioLocalPipelineTestCase( description="load error retains DuckDB", snapshot_state="fresh", - strict=False, load_error_message="bad jsonl", expected_local_status="ERROR", expected_status="failed", @@ -352,7 +336,7 @@ def test_given_local_scenario_planning_failure_when_running_then_canonical_attem ), ids=lambda case: case.description, ) -def test_given_selected_scenarios_when_running_local_scenario_pipeline_then_loads_or_skips( +def test_given_selected_scenarios_when_running_local_scenario_pipeline_then_loads_or_errors( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, test_case: ScenarioLocalPipelineTestCase, @@ -400,7 +384,6 @@ def classify_snapshot( scenarios=pipeline_result.project.sql_scenarios, adapter=adapter, project_name="waffle_shop", - strict=test_case.strict, replay_source=ScenarioLocalReplaySource(lexical_syntax=SqlLexicalSyntax()), ) diff --git a/tests/unit/src/sqlbuild/executor/pipeline/main/_test_types.py b/tests/unit/src/sqlbuild/executor/pipeline/main/_test_types.py index bd55e58eef..0c5fe8e071 100644 --- a/tests/unit/src/sqlbuild/executor/pipeline/main/_test_types.py +++ b/tests/unit/src/sqlbuild/executor/pipeline/main/_test_types.py @@ -27,3 +27,12 @@ class RunTerminalTestCase: expected_event_type: str expected_error_type: str | None expected_failed_count: int | None + + +@dataclass(frozen=True) +class EmptySqlPhaseTestCase: + description: str + execution_announced: bool + expected_event_types: tuple[str, ...] + expected_phase: dict[str, object] | None + expected_connects: int diff --git a/tests/unit/src/sqlbuild/executor/pipeline/main/test_sql_phase.py b/tests/unit/src/sqlbuild/executor/pipeline/main/test_sql_phase.py new file mode 100644 index 0000000000..4dc5a1463d --- /dev/null +++ b/tests/unit/src/sqlbuild/executor/pipeline/main/test_sql_phase.py @@ -0,0 +1,75 @@ +"""A build whose SQL phase has nothing to run announces its start and opens no warehouse connections.""" + +from __future__ import annotations + +from pathlib import Path +from unittest.mock import Mock + +import pytest + +import sqlbuild.executor.pipeline.main.run as run_module +from sqlbuild._native import PlanOutput, SettingsConfig +from sqlbuild.adapter.contract.classes.base_adapter import BaseAdapter +from sqlbuild.executor.build.models import BuildExecutionResult, BuildRuntimeParams +from sqlbuild.executor.build.types import BuildStatus +from sqlbuild.observability import ( + EventDispatcher, + LifecycleEvent, + dispatcher_scope, + invocation_scope, +) +from tests.unit.src.sqlbuild.executor.pipeline.main._test_types import EmptySqlPhaseTestCase + + +@pytest.mark.parametrize( + "test_case", + [ + EmptySqlPhaseTestCase( + description="a Python-only plan starts execution without connection details", + execution_announced=False, + expected_event_types=("run_started", "invocation_phase", "run_completed"), + expected_phase={"phase": "started_execution", "count": 1}, + expected_connects=0, + ), + EmptySqlPhaseTestCase( + description="a caller that announced the start first is not announced twice", + execution_announced=True, + expected_event_types=("run_started", "run_completed"), + expected_phase=None, + expected_connects=0, + ), + ], + ids=lambda case: case.description, +) +def test_given_a_plan_without_sql_work_when_building_then_no_connection_opens( + test_case: EmptySqlPhaseTestCase, +) -> None: + adapter: Mock = Mock(spec=BaseAdapter) + events: list[LifecycleEvent] = [] + dispatcher: EventDispatcher = EventDispatcher() + _ = dispatcher.subscribe_lifecycle(subscriber=events.append, accepts_opaque=False) + + with dispatcher_scope(dispatcher): + with invocation_scope("inv-python-only"): + result: BuildExecutionResult = run_module.run_build_pipeline( + plan=PlanOutput(), + connection_config={}, + adapter=adapter, + settings=Mock(spec=SettingsConfig), + runtime=BuildRuntimeParams( + run_id="run-python-only", runtime_dir=Path("target"), target="dev" + ), + execution_announced=test_case.execution_announced, + ) + + assert ( + result.status, + tuple(event.event_type for event in events), + {event.event_type: dict(event.payload) for event in events}.get("invocation_phase"), + adapter.connect.call_count, + ) == ( + BuildStatus.SUCCESS, + test_case.expected_event_types, + test_case.expected_phase, + test_case.expected_connects, + ), test_case.description diff --git a/tests/unit/src/sqlbuild/executor/scenario/_helpers/_test_types.py b/tests/unit/src/sqlbuild/executor/scenario/_helpers/_test_types.py index fb5658e8cb..a1c1a8162a 100644 --- a/tests/unit/src/sqlbuild/executor/scenario/_helpers/_test_types.py +++ b/tests/unit/src/sqlbuild/executor/scenario/_helpers/_test_types.py @@ -202,6 +202,13 @@ class LocalScenarioSqlTestCase: expected_sql: str +@dataclass(frozen=True) +class LocalScenarioRefusalTestCase: + description: str + source_dialect: str + expected_reasons: tuple[tuple[str, str], ...] + + @dataclass(frozen=True) class ScenarioLocalVariantLoadTestCase: """A Snowflake-captured VARIANT JSONL value and the variant type it must load as.""" diff --git a/tests/unit/src/sqlbuild/executor/scenario/_helpers/test_local_snapshots.py b/tests/unit/src/sqlbuild/executor/scenario/_helpers/test_local_snapshots.py index 5f9f20be74..62575acc6e 100644 --- a/tests/unit/src/sqlbuild/executor/scenario/_helpers/test_local_snapshots.py +++ b/tests/unit/src/sqlbuild/executor/scenario/_helpers/test_local_snapshots.py @@ -187,7 +187,7 @@ def test_given_invalid_local_snapshot_when_loading_then_raises_coded_error( ScenarioLocalVariantLoadTestCase( description="driver JSON text of an object loads as that object", value='{\n "qty": 2\n}', - expected_variant_type="OBJECT(qty)", + expected_variant_type="OBJECT", expected_matches_parsed_json=True, ), ScenarioLocalVariantLoadTestCase( @@ -205,7 +205,7 @@ def test_given_invalid_local_snapshot_when_loading_then_raises_coded_error( ], ids=lambda case: case.description, ) -def test_given_snowflake_variant_text_when_loading_into_duckdb_then_it_loads_as_parsed_json( +def test_given_snowflake_variant_text_when_loading_into_duckdb_then_it_loads_as_json_text( tmp_path: Path, test_case: ScenarioLocalVariantLoadTestCase, ) -> None: @@ -225,8 +225,8 @@ def test_given_snowflake_variant_text_when_loading_into_duckdb_then_it_loads_as_ connection=connection, ) loaded: tuple[object, ...] | None = connection.execute( - "SELECT variant_typeof(payload), " - "payload IN (SELECT CAST(CAST('{\"qty\": 2}' AS JSON) AS VARIANT)) " + "SELECT json_type(payload), " + "COALESCE(CAST(json_extract(payload, '$.qty') AS INTEGER) = 2, false) " f'FROM "{result.relations[0].table_name}"' ).fetchone() diff --git a/tests/unit/src/sqlbuild/executor/scenario/_helpers/test_local_sql.py b/tests/unit/src/sqlbuild/executor/scenario/_helpers/test_local_sql.py index 4f10779043..01cc3387b3 100644 --- a/tests/unit/src/sqlbuild/executor/scenario/_helpers/test_local_sql.py +++ b/tests/unit/src/sqlbuild/executor/scenario/_helpers/test_local_sql.py @@ -2,11 +2,15 @@ import pytest -from sqlbuild.executor.scenario._helpers.local.sql import transpile_sql_for_local_duckdb +from sqlbuild.executor.scenario._helpers.local.sql import convert_sql_for_local_duckdb +from sqlbuild.executor.scenario.exceptions import LocalSqlRefusedError from tests.unit.src.sqlbuild.executor.scenario._helpers._test_types import ( + LocalScenarioRefusalTestCase, LocalScenarioSqlTestCase, ) +_SCHEMA: dict[str, object] = {"relations": {"ORDERS": [["TOTAL", "NUMBER(38,0)"]]}} + @pytest.mark.parametrize( "test_case", @@ -18,27 +22,59 @@ expected_sql="select ifnull(total, 0) as total, list_value(1, 2) as ids from orders", ), LocalScenarioSqlTestCase( - description="other captured dialects are translated for local DuckDB", + description="Snowflake captures are converted by SQLQuack", source_dialect="snowflake", sql="select IFNULL(total, 0) as total from orders", - expected_sql="SELECT COALESCE(total, 0) AS total FROM orders", + expected_sql=( + 'SELECT COALESCE(CAST("ORDERS"."TOTAL" AS DECIMAL(38,0)), ' + 'CAST(0 AS DECIMAL(38,0))) AS "TOTAL" FROM "ORDERS"' + ), ), ], ids=lambda case: case.description, ) -def test_given_captured_dialect_when_preparing_local_scenario_sql_then_only_translates_foreign_sql( +def test_given_captured_dialect_when_preparing_local_scenario_sql_then_only_converts_snowflake( test_case: LocalScenarioSqlTestCase, ) -> None: - result: str = transpile_sql_for_local_duckdb( + result: str = convert_sql_for_local_duckdb( sql=test_case.sql, source_dialect=test_case.source_dialect, - scenario_name="order_totals", - resource_kind="model", - resource_name="order_totals", - ) + schema=_SCHEMA, + time_zone=None, + resource=("order_totals", "model", "order_totals"), + ).sql assert result == test_case.expected_sql +@pytest.mark.parametrize( + "test_case", + [ + LocalScenarioRefusalTestCase( + description="another adapter's SQL is refused with a dialect reason", + source_dialect="postgres", + expected_reasons=(("dialect", "postgres"),), + ), + ], + ids=lambda case: case.description, +) +def test_given_other_captured_dialect_when_preparing_local_scenario_sql_then_refuses_with_reason( + test_case: LocalScenarioRefusalTestCase, +) -> None: + with pytest.raises(LocalSqlRefusedError) as raised: + convert_sql_for_local_duckdb( + sql="select 1", + source_dialect=test_case.source_dialect, + schema=None, + time_zone=None, + resource=("order_totals", "model", "order_totals"), + ) + + assert ( + tuple((refusal["category"], refusal["construct"]) for refusal in raised.value.refusals) + == test_case.expected_reasons + ) + + if __name__ == "__main__": pytest.main([__file__, "-vv"]) diff --git a/ui/e2e/attention-ack.spec.ts b/ui/e2e/attention-ack.spec.ts index e8978c232e..3f638e53fa 100644 --- a/ui/e2e/attention-ack.spec.ts +++ b/ui/e2e/attention-ack.spec.ts @@ -30,11 +30,11 @@ test('acknowledging a condition moves it under Acknowledged until it changes, an test('a run is acknowledged for good', async ({ page }) => { await page.goto('/?mock'); - const row = page.locator('section.health .issues .issue', { hasText: 'core_build partial' }); + const row = page.locator('section.health .issues .issue', { hasText: 'core_build failed' }); await expect(row).toBeVisible({ timeout: 20_000 }); await expect(row.getByRole('button', { name: 'Acknowledge' })).toHaveAttribute('title', /^Hide this from the attention list for everyone viewing this target\./); await row.getByRole('button', { name: 'Acknowledge' }).click(); const handled = page.locator('section.health .handled'); await handled.getByRole('button', { name: /^Acknowledged/ }).click(); - await expect(handled.locator('.issue', { hasText: 'core_build partial' })).toContainText('for good'); + await expect(handled.locator('.issue', { hasText: 'core_build failed' })).toContainText('for good'); }); diff --git a/ui/e2e/run-page-filters.spec.ts b/ui/e2e/run-page-filters.spec.ts new file mode 100644 index 0000000000..14c09f775f --- /dev/null +++ b/ui/e2e/run-page-filters.spec.ts @@ -0,0 +1,178 @@ +import { expect, test, type Page } from '@playwright/test'; + +// Every control on the run page that filters toggles: the first click turns its filter on and says so, +// the second puts the page back exactly as it was. Each text field clears with its ✕ or Esc, keeping focus. +test.use({ viewport: { width: 1500, height: 1000 } }); + +const RUN = '/runs/run-pa93?mock'; +const summary = (page: Page) => page.getByTestId('run-summary'); +const logCount = (page: Page) => page.getByRole('tab', { name: /^Log/ }).textContent(); +const logFilter = (page: Page) => page.getByLabel('Filter the log'); +const selector = (page: Page) => page.getByLabel('Selection', { exact: true }); + +async function open(page: Page, url = RUN) { + await page.goto(url); + await expect(summary(page)).toContainText('built', { timeout: 20_000 }); +} + +/** What the log shows and how the page reads: rows, the Showing line, what is pressed, and the layout around it. */ +async function snapshot(page: Page) { + await page.waitForTimeout(300); + return { + box: (await logFilter(page).inputValue()).trim(), + line: (await page.getByTestId('log-filter-active').count()) ? (await page.getByTestId('log-filter-active').textContent())?.trim() : null, + rows: await page.locator('.log tbody tr').evaluateAll((rows) => rows.slice(0, 40).map((r) => (r.textContent ?? '').replace(/\s+/g, ' ').trim())), + pressed: await page.locator('[aria-pressed="true"], [aria-current="true"]').evaluateAll((els) => els.map((e) => (e.textContent ?? '').trim()).filter(Boolean).sort()), + layout: [await logCount(page), await page.getByRole('radio', { name: 'Events' }).count(), await page.getByRole('button', { name: 'Levels' }).count(), await page.getByRole('button', { name: 'Kinds' }).count() + (await page.locator('.filters .menu-trigger').count())] + }; +} + +// Every quick filter only writes words into the log's filter box: clicking it shows exactly what typing +// those words does, the layout never moves, and a second click takes out only its own words. +const QUICK_FILTERS: { run: string; name: string; control: (page: Page) => ReturnType; text: string }[] = [ + { run: RUN, name: 'the failed-audits figure', control: (p) => summary(p).getByRole('link', { name: '1 audit failed' }), text: 'kind:audit outcome:failed' }, + { run: RUN, name: 'the built figure', control: (p) => summary(p).getByRole('link', { name: '1 built' }), text: 'outcome:built' }, + { run: '/runs/run-4f2a?mock', name: 'the skipped figure', control: (p) => summary(p).getByRole('link', { name: /^\d+ skipped$/ }), text: 'outcome:skipped' }, + { run: RUN, name: 'the Errors chip', control: (p) => p.getByRole('button', { name: /^Errors \d/ }), text: 'level:error' } +]; + +for (const q of QUICK_FILTERS) { + test(`${q.name} does exactly what typing ${q.text} does`, async ({ page }) => { + await open(page, q.run); + const before = await snapshot(page); + await q.control(page).click(); + const clicked = await snapshot(page); + expect(clicked.box).toBe(q.text); + expect(clicked.line).toMatch(/^Showing .+ · [\d,]+ of [\d,]+ events?$/); + expect(clicked.layout).toEqual(before.layout); + await q.control(page).click(); + expect(await snapshot(page)).toEqual(before); + await logFilter(page).fill(`${q.text} `); + await logFilter(page).evaluate((el) => (el as HTMLInputElement).blur()); + expect(await snapshot(page)).toEqual(clicked); + }); + + test(`${q.name} moves nothing in the log toolbar`, async ({ page }) => { + await open(page, q.run); + // The header's figures, the log toolbar, the filter box, each control in it, and the table's header under the Showing line. + const boxes = () => + page.evaluate(() => + ['[data-testid="run-summary"]', '[data-testid="run-summary"] .fig', '.log-head .filters', '.log-filter .field', '.filters .menu-trigger', '.filters .count', '.log thead'].flatMap((sel) => + [...document.querySelectorAll(sel)].map((el) => { + const r = el.getBoundingClientRect(); + return `${sel} ${r.x},${r.y},${r.width},${r.height}`; + }) + ) + ); + const before = await boxes(); + expect(before.length).toBeGreaterThan(3); + await q.control(page).click(); + await expect(page.getByTestId('log-filter-active')).toBeVisible(); + expect(await boxes()).toEqual(before); + await q.control(page).click(); + await expect(page.getByTestId('log-filter-active')).toHaveCount(0); + expect(await boxes()).toEqual(before); + }); + + test(`${q.name}'s second click keeps what was typed`, async ({ page }) => { + await open(page, q.run); + await logFilter(page).fill('orders'); + await q.control(page).click(); + await expect(logFilter(page)).toHaveValue(`orders ${q.text} `); + await expect(page.getByTestId('log-filter-active')).toContainText(`Showing orders ${q.text}`); + await q.control(page).click(); + await expect(logFilter(page)).toHaveValue(/^orders\s*$/); + }); +} + +for (const how of ['✕', 'Esc'] as const) { + test(`the node selector clears with ${how} and keeps focus`, async ({ page }) => { + await open(page); + await selector(page).fill('currency'); + const clear = page.getByRole('button', { name: 'Clear selection' }); + await expect(clear).toBeVisible(); + if (how === '✕') await clear.click(); + else await selector(page).press('Escape'); + await expect(selector(page)).toHaveValue(''); + await expect(clear).toHaveCount(0); + await expect(selector(page)).toBeFocused(); + }); + + test(`the log filter clears with ${how} and keeps focus`, async ({ page }) => { + await open(page); + await logFilter(page).fill('level:error'); + const clear = page.getByRole('button', { name: 'Clear the log filter' }); + await expect(clear).toBeVisible(); + if (how === '✕') await clear.click(); + else await logFilter(page).press('Escape'); + await expect(logFilter(page)).toHaveValue(''); + await expect(clear).toHaveCount(0); + await expect(logFilter(page)).toBeFocused(); + }); +} + +// The rerun plan holds no state of its own: it opens on failed:+, the box's own suggestions offer the +// presets as text, "from run" is read from the selection, and Run submits the command shown beside it. +test('the rerun plan opens on failed:+ and the box suggests the run selectors', async ({ page }) => { + await page.goto('/plan/rerun?run=run-pa93&mode=from_failure&mock'); + const box = page.locator('.sel-field').first(); + await expect(box).toContainText('failed:run-pa93+', { timeout: 20_000 }); + await expect(page.getByTestId('rerun-of')).toHaveCount(0); + await expect(page.getByRole('listbox')).toHaveCount(0); + await expect(page.getByTestId('rerun-from')).toContainText('from run'); + await expect(page.getByRole('cell', { name: 'orders_match_payments' })).toBeVisible(); + await expect(page.getByTestId('rerun-command')).toHaveText('sqb build -s failed:run-pa93+'); + await page.getByRole('button', { name: 'Clear selection' }).click(); + await selector(page).fill('run:'); + const whole = page.getByRole('option', { name: /Rerun the whole run/ }); + await expect(whole).toBeVisible(); + await whole.click(); + await expect(box).toContainText('run:run-pa93'); + await expect(page.getByTestId('rerun-from')).toContainText('from run'); + await expect(page.getByTestId('rerun-command')).toHaveText('sqb build -s run:run-pa93'); + await page.getByRole('button', { name: 'Clear selection' }).click(); + await selector(page).fill('country_codes '); + await expect(page.getByTestId('rerun-from')).toHaveCount(0); + await expect(page.getByTestId('rerun-command')).toHaveText('sqb build -s country_codes'); + await page.getByRole('button', { name: 'Run', exact: true }).click(); + await expect(page).toHaveURL(/\/runs\/(?!run-pa93)[^/?]+/); +}); + +// A rerun is an ad-hoc run of its selection, so the run it starts says which run it came from. +test('a rerun started from the rerun plan says which run it came from', async ({ page }) => { + await page.goto('/plan/rerun?run=run-pa93&mode=from_failure&mock'); + await expect(page.getByTestId('rerun-command')).toHaveText('sqb build -s failed:run-pa93+', { timeout: 20_000 }); + await page.getByRole('button', { name: 'Run', exact: true }).click(); + await expect(page).toHaveURL(/\/runs\/(?!run-pa93)[^/?]+/); + await expect(page.getByText('from run pa93')).toBeVisible({ timeout: 20_000 }); +}); + +// An audit whose reads the target doesn't have is not run: the run succeeds, the summary counts it on its +// own, and its figure filters the log to it, with why. +test('an audit that was not run is counted and filtered on its own', async ({ page }) => { + await open(page, '/runs/run-nr41?mock'); + const figure = page.getByRole('link', { name: '1 audit not run' }); + await expect(figure).toBeVisible({ timeout: 20_000 }); + await figure.click(); + await expect(logFilter(page)).toHaveValue(/kind:audit outcome:not-run/); + await expect(page.getByText("reads fct_order_payments, fct_payment_totals, which don't exist in the target").first()).toBeVisible(); + await logFilter(page).fill('outcome:not-run '); + await expect(page.getByText("reads fct_order_payments, fct_payment_totals, which don't exist in the target").first()).toBeVisible(); +}); + +// A failed audit's warehouse error is read from its result (behind view.evidence), not from the run's +// listings: the summary line gives the cause, and opened, the SQLSTATE and the warehouse's sentence. +test('the failure summary shows a failed audit’s warehouse error', async ({ page }) => { + await open(page); + const failures = page.getByTestId('failure-summary'); + await expect(failures).toContainText('Failed: audit orders_match_payments after the build · input not built in prod'); + await failures.getByRole('button', { name: /Failed: audit/ }).click(); + await expect(failures).toContainText('42S02'); + await expect(failures).toContainText("Object 'WAFFLE_SHOP.RECONCILIATION.FCT_ORDER_PAYMENTS' does not exist or not authorized."); +}); + +// A run_failed event links each failed node as `/runs/?node=`: the page opens with that node in the drawer. +test('a link to one node of a run opens it in the drawer', async ({ page }) => { + await page.goto('/runs/run-4f2a?mock&node=dim_customers'); + await expect(page.getByRole('complementary').filter({ hasText: 'dim_customers' }).first()).toBeVisible({ timeout: 20_000 }); +}); diff --git a/ui/e2e/server-health.spec.ts b/ui/e2e/server-health.spec.ts new file mode 100644 index 0000000000..bd5ecee552 --- /dev/null +++ b/ui/e2e/server-health.spec.ts @@ -0,0 +1,81 @@ +import { expect, test } from '@playwright/test'; +import { FakeControl, LOCATIONS } from './support/fake-control'; + +// The shell against a faked server whose control database fails: health answers, every other read is a 503 +// naming the cause. The page keeps its URL, says why, and loads by itself once the database is back. +test.use({ viewport: { width: 1440, height: 900 } }); + +const DNS = "Can't reach the control database: control-db.internal doesn't resolve (DNS)"; +const since = () => new Date(Date.now() - 12 * 60_000).toISOString(); + +test('a control database outage keeps the page, says why and loads it by itself on recovery', async ({ page }) => { + const control = new FakeControl(); + control.outage = { case: 'name_lookup', message: DNS, since: since() }; + await control.install(page); + await page.goto('/runs'); + const outage = page.getByTestId('outage'); + await expect(outage.locator('h1')).toHaveText("Runs isn't available", { timeout: 30_000 }); + await expect(page.getByTestId('outage-reason')).toHaveText(DNS); + await expect(outage).toContainText('Checking again every 1 s'); + await expect(outage.locator('tr[data-component="control_database"]')).toContainText('Unavailable'); + await expect(page.getByTestId('server-indicator')).toContainText('Unavailable'); + await expect(page.locator('aside a', { hasText: 'Runs' })).toHaveAttribute('aria-disabled', 'true'); + await expect(page.getByTestId('nav-status')).not.toHaveAttribute('aria-disabled', 'true'); + await page.evaluate(() => Object.assign(window, { stayedLoaded: true })); + control.outage = null; + await expect(outage).toHaveCount(0, { timeout: 15_000 }); + await expect(page).toHaveURL(/\/runs$/); + await expect(page.locator('.app-topbar h1')).toHaveText('Runs'); + await expect(page.getByTestId('server-indicator')).not.toContainText('Unavailable'); + expect(await page.evaluate(() => (window as unknown as { stayedLoaded?: boolean }).stayedLoaded)).toBe(true); +}); + +test('each control database failure reaches the page by its own message', async ({ page }) => { + const cases = [ + ['name_lookup', DNS], + ['unreachable', "Can't reach the control database at control-db.internal:5432"], + ['login_rejected', 'The control database rejected the login for sqb'], + ['no_free_connections', 'The control database has no free connections'], + ['restarting', 'The control database is restarting'], + ['pool_exhausted', 'All 10 control database connections were busy for 30 s'], + ['locked', 'The control database is locked by another process'], + ['other', 'Control database error: could not read block 7 in file "base/16384/2619"'] + ]; + const control = new FakeControl(); + control.outage = { case: cases[0][0], message: cases[0][1], since: since() }; + await control.install(page); + await page.goto('/'); + const shown: string[] = []; + for (const [kind, message] of cases) { + control.outage = { case: kind, message, since: since() }; + await expect(page.getByTestId('outage-reason')).toHaveText(message, { timeout: 15_000 }); + shown.push((await page.getByTestId('outage-reason').textContent()) ?? ''); + } + expect(shown).toEqual(cases.map(([, message]) => message)); +}); + +test('a degraded part is named in a banner that links to Status, and pages still work', async ({ page }) => { + const control = new FakeControl(); + const silent = "Hasn't reported since 2026-11-25 17:40 UTC"; + control.degraded = [{ component: 'location', name: 'returns', status: 'degraded', reason: silent, location_id: LOCATIONS.returns }]; + await control.install(page); + await page.goto('/runs'); + const banner = page.getByTestId('health-banner'); + await expect(banner).toContainText(`returns: ${silent}`, { timeout: 30_000 }); + await expect(page.getByTestId('server-indicator')).toContainText('Degraded'); + await expect(page.getByTestId('outage')).toHaveCount(0); + await banner.getByRole('link', { name: 'View status →' }).click(); + await expect(page).toHaveURL(/\/status$/); + await expect(page.getByTestId('health-table').locator('tr', { hasText: 'returns' })).toContainText(silent); +}); + +test('Status shows every part without a session', async ({ page }) => { + const control = new FakeControl(); + control.signedOut = true; + await control.install(page); + await page.goto('/status'); + const table = page.getByTestId('health-table'); + await expect(table.locator('tr[data-component="control_database"]')).toContainText('Healthy', { timeout: 30_000 }); + await expect(table.locator('tr[data-component="location"]')).toHaveCount(2); + await expect(page).toHaveURL(/\/status$/); +}); diff --git a/ui/e2e/support/fake-control.ts b/ui/e2e/support/fake-control.ts index 7b774739ab..d5f9536d40 100644 --- a/ui/e2e/support/fake-control.ts +++ b/ui/e2e/support/fake-control.ts @@ -7,7 +7,7 @@ import type { Page, Route } from '@playwright/test'; export const LOCATIONS = { shop: '0190d1a0-0000-7000-8000-000000000001', returns: '0190d1a0-0000-7000-8000-000000000002' } as const; export type TargetName = keyof typeof LOCATIONS; const SNAPSHOT = '0190d1a0-0000-7000-8000-0000000000aa'; -const ACTIONS = ['view', 'view.sql', 'view.evidence', 'job.run', 'run.cancel', 'run.rerun', 'run.adhoc', 'audit.view']; +const ACTIONS = ['view', 'view.sql', 'view.evidence', 'job.run', 'run.cancel', 'run.rerun', 'run.adhoc', 'audit.view', 'connection.test']; type Ack = { event_id: string; key: string; shape: unknown; acknowledged_at: string }; /** One request the page wrote: an acknowledgement, a withdrawal or a run's acknowledgement. */ @@ -34,12 +34,22 @@ export type TargetState = { healthDelayMs: number; /** Published jobs and groups, with the concurrency limit their runs get. */ jobs: FakeJob[]; + /** A failing run-history sync: whether it reaches the warehouse and whether failed reads stopped it. */ + failingSync: { unreachable: boolean; halted: boolean } | null; }; /** A published job or group: its key, kind, own `concurrency` setting and the limit its runs get; a group's members are the target's jobs. */ export type FakeJob = { key: string; kind: 'job' | 'group'; concurrency: number | null; limit: number }; const MODELS = ['orders', 'order_items', 'customers', 'payments', 'refunds']; +/** A failing sync's first failure, and its reason as the location reports it. */ +export const SYNC_FAILING_SINCE = new Date(Date.now() - 50 * 60_000).toISOString(); +export const SYNC_REASON = '250001 Could not connect to Snowflake backend after 2 attempt(s)'; + +/** A part of the server's health report, as the server sends it. */ +export type FakeHealthPart = { component: 'server' | 'control_database' | 'scheduler' | 'location'; name: string; status: 'healthy' | 'degraded' | 'unavailable'; reason?: string; case?: string; since?: string; location_id?: string }; +/** A control database outage: every API read but health answers 503 with this cause. */ +export type FakeOutage = { case: string; message: string; since: string }; const json = (route: Route, body: unknown, status = 200) => route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(body) }); const later = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); @@ -52,9 +62,17 @@ export class FakeControl { #notices: string[] = []; #states: Record = { shop: { seen: '', version: 0 }, returns: { seen: '', version: 0 } }; #lease = new Date(Date.now() - 60_000).toISOString(); + /** The control database's outage, while there is one. */ + outage: FakeOutage | null = null; + /** Parts that aren't healthy while pages still work. */ + degraded: FakeHealthPart[] = []; + /** No session: the bootstrap is refused, as for a person who hasn't signed in. */ + signedOut = false; + /** Health reads answered so far. */ + healthReads = 0; constructor(overrides: Partial>> = {}) { - const base = (): TargetState => ({ changed: [], sync: 'settled', schedulerLeader: true, acks: [], failedRun: false, readDelayMs: 0, failReads: false, failWithdrawals: false, healthDelayMs: 0, jobs: [] }); + const base = (): TargetState => ({ changed: [], sync: 'settled', schedulerLeader: true, acks: [], failedRun: false, readDelayMs: 0, failReads: false, failWithdrawals: false, healthDelayMs: 0, jobs: [], failingSync: null }); this.targets = { shop: { ...base(), ...overrides.shop }, returns: { ...base(), ...overrides.returns } }; } @@ -90,6 +108,11 @@ export class FakeControl { const request = route.request(); const url = new URL(request.url()); const path = url.pathname; + if (path === '/api/health') return this.#serverHealth(route); + if (this.outage) { + return json(route, { error: this.outage.message, request_id: '0190d1a0-0000-7000-8000-0000000000ff', cause: { case: this.outage.case, since: this.outage.since } }, 503); + } + if (this.signedOut && path === '/api/control/bootstrap') return json(route, { error: 'sign in required' }, 401); if (path === '/api/control/bootstrap') { return json(route, { login_mode: 'disabled', @@ -103,7 +126,18 @@ export class FakeControl { } if (path === '/api/control/platform/problems') { // Answered as things stood when the request arrived, however long the reply takes. - const answer = { scheduler_leader: Object.values(this.targets).every((t) => t.schedulerLeader), scheduler_lease_expires_at: this.#lease, broken_locations: [], overdue_ticks: [], low_calendars: [] }; + const answer = { + scheduler_leader: Object.values(this.targets).every((t) => t.schedulerLeader), + scheduler_lease_expires_at: this.#lease, + broken_locations: [], + overdue_ticks: [], + low_calendars: [], + failing_syncs: (Object.keys(LOCATIONS) as TargetName[]).flatMap((name) => { + const failing = this.targets[name].failingSync; + if (!failing) return []; + return [{ location_id: LOCATIONS[name], location_name: name, target: 'dev', since: SYNC_FAILING_SINCE, reason: SYNC_REASON, unreachable: failing.unreachable, halted: failing.halted, retry_at: failing.halted ? null : new Date(Date.now() + 40_000).toISOString(), retry_seconds: failing.halted ? null : 60, last_success_at: '2026-11-01T00:00:00Z' }]; + }) + }; const delay = Math.max(...Object.values(this.targets).map((t) => t.readDelayMs)); if (delay) await later(delay); return json(route, answer); @@ -178,6 +212,28 @@ export class FakeControl { return json(route, { applied: applies }); } + /** `/api/health` as the server answers it: 503 with the same report unless every part is healthy. */ + #serverHealth(route: Route) { + this.healthReads += 1; + const now = new Date().toISOString(); + const started = new Date(Date.now() - 3_600_000).toISOString(); + const row = (part: FakeHealthPart) => ({ location_id: part.location_id, reason: part.reason ?? null, case: part.case, since: part.since ?? started, last_success: part.status === 'healthy' ? now : started, last_failure: part.status === 'healthy' ? null : now, ...part }); + const database: FakeHealthPart = this.outage + ? { component: 'control_database', name: 'Control database', status: 'unavailable', reason: this.outage.message, case: this.outage.case, since: this.outage.since } + : { component: 'control_database', name: 'Control database', status: 'healthy' }; + const parts: FakeHealthPart[] = [ + { component: 'server', name: 'Server', status: 'healthy' }, + database, + { component: 'scheduler', name: 'Scheduler', status: 'healthy' }, + ...(Object.keys(LOCATIONS) as TargetName[]).map((name): FakeHealthPart => this.degraded.find((d) => d.name === name) ?? { component: 'location', name, status: 'healthy', location_id: LOCATIONS[name] }), + ...this.degraded.filter((d) => d.component !== 'location') + ]; + const status = this.outage ? 'unavailable' : this.degraded.length ? 'degraded' : 'healthy'; + // Retried every second here, so a recovery shows quickly; the server says 10. + const report = { status, checked_at: now, retry_seconds: 1, server: { version: '0.262.0', started_at: started, uptime_seconds: 3600 }, components: parts.map(row) }; + return json(route, report, status === 'healthy' ? 200 : 503); + } + #node(target: TargetState, model: string) { const builtAt = '2026-11-01T00:00:00Z'; return { @@ -190,6 +246,25 @@ export class FakeControl { #health(target: TargetState) { const at = new Date().toISOString(); + if (target.failingSync) { + const failing = target.failingSync; + const report = { + kind: 'warehouse_sync', + generation: 1, + location: { database: null, schema: 'dev' }, + table: 'catalog', + failure: 'read', + records_sent: 0, + elapsed_millis: 10, + error: SYNC_REASON, + read_failure: { kind: failing.unreachable ? 'unreachable' : 'read_error' }, + progress: { position: 1, kinds: 2, rows: 0, elapsed_millis: 20, completed: false, halted: failing.halted }, + failing_since: SYNC_FAILING_SINCE, + retry_at: failing.halted ? null : new Date(Date.now() + 40_000).toISOString(), + retry_seconds: failing.halted ? null : 60 + }; + return { state: 'healthy', observations: [{ received_at: at, report: { event_id: '0190d1a0-0000-7000-8000-0000000000de', session_id: '0190d1a0-0000-7000-8000-0000000000ee', target: 'dev', health: report } }] }; + } const health = { kind: 'warehouse_sync', generation: 1, diff --git a/ui/e2e/sync-health.spec.ts b/ui/e2e/sync-health.spec.ts new file mode 100644 index 0000000000..a6c85b0f43 --- /dev/null +++ b/ui/e2e/sync-health.spec.ts @@ -0,0 +1,33 @@ +import { expect, test } from '@playwright/test'; +import { FakeControl, SYNC_REASON } from './support/fake-control'; + +// A failing run-history sync is named in the top bar and on the attention list, and leaves both once it +// works again; a sync failed reads stopped can be resumed from the list. +test.use({ viewport: { width: 1920, height: 1000 } }); + +test('a sync that can’t reach the warehouse is named in the top bar and needs attention until it recovers', async ({ page }) => { + const control = new FakeControl({ shop: { failingSync: { unreachable: true, halted: false } } }); + await control.install(page); + await page.goto('/'); + const status = page.getByTestId('sync-status'); + await expect(status).toHaveText(new RegExp(`^Run history can't reach the warehouse since (\\d{4}-\\d{2}-\\d{2} )?\\d{2}:\\d{2} · retrying every 60 s · ${SYNC_REASON.replace(/[()]/g, '\\$&')}$`), { timeout: 30_000 }); + await expect(status).toHaveAttribute('href', /\/locations\//); + const issues = page.locator('.issues'); + await expect(issues).toContainText("run history can't reach the warehouse since", { timeout: 30_000 }); + await expect(page.getByTestId('attention-quiet')).toHaveCount(0); + control.targets.shop.failingSync = null; + control.notify('all'); + await expect(issues).toHaveCount(0, { timeout: 30_000 }); + await expect(status).not.toContainText('Run history'); +}); + +test('a sync that failed reads stopped can be resumed from the attention list', async ({ page }) => { + const control = new FakeControl({ shop: { failingSync: { unreachable: false, halted: true } } }); + await control.install(page); + await page.goto('/'); + await expect(page.getByTestId('sync-status')).toContainText('Run history sync stopped since', { timeout: 30_000 }); + const resume = page.getByTestId('attention-resume'); + await expect(resume).toBeVisible({ timeout: 30_000 }); + await resume.click(); + await expect.poll(() => control.writes.filter((w) => w.path === '/warehouse-syncs').length).toBe(1); +}); diff --git a/ui/src/lib/api/http-checks.test.ts b/ui/src/lib/api/http-checks.test.ts index 050ffba003..63cf6f21e9 100644 --- a/ui/src/lib/api/http-checks.test.ts +++ b/ui/src/lib/api/http-checks.test.ts @@ -52,7 +52,9 @@ describe('check mapping', () => { it('keeps evidence cells aligned to their columns', () => { const evidence = toCheckEvidence({ binding_key: 'b', event_id: 'e1', columns: ['id', 'note'], rows: [[7, null]] as never, truncated: 'true' }); - expect([evidence.rows, evidence.truncated]).toEqual([[[7, null]], true]); + expect([evidence.rows, evidence.truncated, evidence.executionError]).toEqual([[[7, null]], true, null]); + const errored = toCheckEvidence({ binding_key: 'b', event_id: 'e2', columns: [], rows: [], truncated: 'false', execution_error: "002003 (42S02): Object 'X' does not exist" }); + expect(errored.executionError).toBe("002003 (42S02): Object 'X' does not exist"); }); it('shortens an sqb run id to its random suffix, not its date', () => { diff --git a/ui/src/lib/api/http-checks.ts b/ui/src/lib/api/http-checks.ts index ed3d34253f..69dd27f279 100644 --- a/ui/src/lib/api/http-checks.ts +++ b/ui/src/lib/api/http-checks.ts @@ -79,6 +79,7 @@ export function toCheckEvidence(wire: Wire['CheckEvidence']): CheckEvidence { evaluationId: wire.event_id, columns: wire.columns, rows: wire.rows as unknown as CheckEvidence['rows'], - truncated: wire.truncated === 'true' + truncated: wire.truncated === 'true', + executionError: wire.execution_error ?? null }; } diff --git a/ui/src/lib/api/http-client.ts b/ui/src/lib/api/http-client.ts index c4661647ed..139c148bca 100644 --- a/ui/src/lib/api/http-client.ts +++ b/ui/src/lib/api/http-client.ts @@ -16,6 +16,7 @@ import { toMaintenanceHistory } from './http-maintenance'; import { toProviders } from './http-providers'; import { overviewOf } from './http-overview'; import { toPlatformEventRecords, toPlatformEvents, toPlatformHealth } from './http-problems'; +import { toHealthDetails, toServerHealth } from './http-health'; import { roleDetailOf, toRoleDefinition } from './http-roles'; import { jobDetailOf, runWindowOf, toJob, toTick, toTrigger, toTriggerStateEvent, triggerDetailOf } from './http-jobs'; import { timelineOf } from './http-timeline'; @@ -24,7 +25,7 @@ import { toSelectionEvaluation, toSelectionVocabulary } from './http-selection'; import { costSeriesGroups, toCostSelection } from './http-cost'; import type { ChangeSubscription, ChangedChannel, ChangedSignal, ConnectionState } from './signals'; import type { AuthMode, Bootstrap, BuiltInRole, Capability, DiscoveredSet, Location, NavCounts, PlatformEvent, RepublishResult, Scope, Snapshot, WarehouseSync } from './types'; -import type { Account, AuditEntry, AuditQuery, ConnectionTest, IssuedToken, KeyRotation, LocationDetail, NewPasswordAccount, NewServiceAccount, ServiceAccount, ServerSettings, WarehouseConnection, LocationSummary, PlatformEventQuery, PlatformEventRecord, PlatformHealth, MaintenanceHistory, ProviderConnection, RoleAssignment, RoleAssignmentRequest, RoleDefinition, RoleDetail } from './types/platform'; +import type { Account, AuditEntry, AuditQuery, ConnectionTest, IssuedToken, KeyRotation, LocationDetail, NewPasswordAccount, NewServiceAccount, ServiceAccount, ServerSettings, WarehouseConnection, LocationSummary, PlatformEventQuery, PlatformEventRecord, PlatformHealth, ServerHealth, HealthComponentDetails, MaintenanceHistory, ProviderConnection, RoleAssignment, RoleAssignmentRequest, RoleDefinition, RoleDetail } from './types/platform'; import type { Acknowledgement, CatalogNode, CatalogNodeDetail, Check, CheckDetail, CheckEvidence, CheckSql, NodeStates, NodeStatusDelta, Overview, SnapshotChange, ColumnLineage, AttentionAcknowledgement, ConditionShape, AutomaticWithdrawal } from './types/build'; import type { NodeOutputIndex, NodeOutputPage, NodeOutputSearch, RunNode, RunOutputFollow, AdhocRunCheck, AdhocRunRequest, BulkRunResult, SelectionEvaluation, SelectionRequest, SelectionVocabulary, PlanDiff, PlanPage, PlanPageSection, PlanResult, QueueEntry, Timeline, Job, JobDetail, JobLaunchOptions, RerunMode, SnapshotNode, Run, RunDetail, RunListQuery, RunRowPage, RunRowQuery, RunTabCounts, Trigger, TriggerDetail, TriggerState, RunEventPage, RunNodeError, RunOutputLine, RunStatement, IgnoredAuditFailure, RunCostRow, CostSummary, CostSelection, CostSelectionQuery, CostSeriesGroup, NodeBuildCost, StatementSql } from './types/operate'; import { newRequestId } from '$lib/browser/request-id'; @@ -100,6 +101,8 @@ const SUPPORTED: ReadonlySet = new Set([ 'listPlatformEvents', 'listPlatformEventHistory', 'platformHealth', + 'readHealth', + 'readHealthDetails', 'listRoles', 'getRole', 'getLatestSnapshot', @@ -889,6 +892,19 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, ); }, platformHealth: async (): Promise => toPlatformHealth(await problems()), + /** A 503 carries the same report: the server answers, and says which part isn't working. */ + async readHealth(): Promise { + const { data, error, response } = await http.GET('/api/health'); + const report = data ?? (response.status === 503 ? (error as Wire['HealthReport'] | undefined) : undefined); + if (!report?.components) throw new ApiError(errorText(error, response), response.status); + return toServerHealth(report); + }, + async readHealthDetails(): Promise { + const { data, error, response } = await http.GET('/api/health/details'); + if (response.status === 401) onUnauthorized(); + if (!data) throw new ApiError(errorText(error, response), response.status); + return toHealthDetails(data); + }, /** Each location the person sees, with health only where they may list the whole target. */ async listLocations(): Promise { const [locations, events] = await Promise.all([bootstrapLocations(), problems().then((p) => toPlatformEvents(p, Date.now()))]); diff --git a/ui/src/lib/api/http-health.test.ts b/ui/src/lib/api/http-health.test.ts new file mode 100644 index 0000000000..278de2e5dd --- /dev/null +++ b/ui/src/lib/api/http-health.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest'; +import { toHealthDetails, toServerHealth } from './http-health'; + +describe('health mapping', () => { + it('keeps each component with its state, since when, reason and case', () => { + expect( + toServerHealth({ + status: 'unavailable', + checked_at: '2026-11-25T18:00:10Z', + retry_seconds: 10, + server: { version: '0.262.0', started_at: '2026-11-25T17:00:00Z', uptime_seconds: 3610 }, + components: [ + { component: 'server', name: 'Server', status: 'healthy', since: '2026-11-25T17:00:00Z', reason: null, last_success: '2026-11-25T18:00:10Z', last_failure: null }, + { + component: 'control_database', + name: 'Control database', + status: 'unavailable', + since: '2026-11-25T17:42:00Z', + reason: "Can't reach the control database: db.internal doesn't resolve (DNS)", + case: 'name_lookup', + last_success: '2026-11-25T17:41:55Z', + last_failure: '2026-11-25T18:00:05Z' + }, + { component: 'location', name: 'orders', location_id: 'loc-1', status: 'degraded', since: '2026-11-25T17:40:00Z', reason: "Hasn't reported since 2026-11-25 17:40 UTC", last_success: '2026-11-25T17:40:00Z', last_failure: null } + ] + }) + ).toEqual({ + status: 'unavailable', + checkedAt: '2026-11-25T18:00:10Z', + retrySeconds: 10, + server: { version: '0.262.0', startedAt: '2026-11-25T17:00:00Z', uptimeSeconds: 3610 }, + components: [ + { component: 'server', name: 'Server', locationId: null, status: 'healthy', since: '2026-11-25T17:00:00Z', reason: null, case: null, lastSuccess: '2026-11-25T18:00:10Z', lastFailure: null }, + { + component: 'control_database', + name: 'Control database', + locationId: null, + status: 'unavailable', + since: '2026-11-25T17:42:00Z', + reason: "Can't reach the control database: db.internal doesn't resolve (DNS)", + case: 'name_lookup', + lastSuccess: '2026-11-25T17:41:55Z', + lastFailure: '2026-11-25T18:00:05Z' + }, + { component: 'location', name: 'orders', locationId: 'loc-1', status: 'degraded', since: '2026-11-25T17:40:00Z', reason: "Hasn't reported since 2026-11-25 17:40 UTC", case: null, lastSuccess: '2026-11-25T17:40:00Z', lastFailure: null } + ] + }); + }); + + it('keeps where the database is, each cause and the failed requests for administrators', () => { + expect( + toHealthDetails({ components: [{ component: 'control_database', host: 'db.internal:5432', error_chain: ['failed to lookup address information'], request_ids: ['req-1'] }] }) + ).toEqual([{ component: 'control_database', locationId: null, host: 'db.internal:5432', errorChain: ['failed to lookup address information'], requestIds: ['req-1'] }]); + }); +}); diff --git a/ui/src/lib/api/http-health.ts b/ui/src/lib/api/http-health.ts new file mode 100644 index 0000000000..7f6ad9880e --- /dev/null +++ b/ui/src/lib/api/http-health.ts @@ -0,0 +1,30 @@ +import type { components } from '$control/schema.d.ts'; +import type { HealthComponentDetails, ServerHealth } from './types/platform'; + +type Wire = components['schemas']; + +/** The server's health report in the UI's shape. */ +export function toServerHealth(wire: Wire['HealthReport']): ServerHealth { + return { + status: wire.status, + checkedAt: wire.checked_at, + retrySeconds: wire.retry_seconds, + server: { version: wire.server.version, startedAt: wire.server.started_at, uptimeSeconds: wire.server.uptime_seconds }, + components: wire.components.map((c) => ({ + component: c.component, + name: c.name, + locationId: c.location_id ?? null, + status: c.status, + since: c.since ?? null, + reason: c.reason ?? null, + case: c.case ?? null, + lastSuccess: c.last_success ?? null, + lastFailure: c.last_failure ?? null + })) + }; +} + +/** Administrators' health details in the UI's shape. */ +export function toHealthDetails(wire: Wire['HealthDetails']): HealthComponentDetails[] { + return wire.components.map((c) => ({ component: c.component, locationId: c.location_id ?? null, host: c.host ?? null, errorChain: c.error_chain, requestIds: c.request_ids })); +} diff --git a/ui/src/lib/api/http-locations.test.ts b/ui/src/lib/api/http-locations.test.ts index eabb5219ad..50fe119e26 100644 --- a/ui/src/lib/api/http-locations.test.ts +++ b/ui/src/lib/api/http-locations.test.ts @@ -122,7 +122,31 @@ describe('warehouseSyncOf', () => { sync('2026-11-08T12:01:00Z', 'catalog', null), sync('2026-11-08T12:00:00Z', 'statistics', 'delivery') ]); - expect(result).toEqual({ lastSyncedAt: '2026-11-08T12:02:00Z', lastError: 'catalog: failed while reading the warehouse', lastReportedAt: '2026-11-08T12:03:00Z', syncing: null, completed: null }); + expect(result).toEqual({ + lastSyncedAt: '2026-11-08T12:02:00Z', + lastError: 'catalog: failed while reading the warehouse', + lastReportedAt: '2026-11-08T12:03:00Z', + syncing: null, + completed: null, + failing: { since: '2026-11-08T12:03:00Z', reason: 'failed while reading the warehouse', halted: false, unreachable: false, retrySeconds: null, retryAt: null } + }); + }); + + it('says since when a failing sync has failed, why, whether the warehouse was reached and when it tries again', () => { + const failed = (at: string) => { + const report = sync(at, 'catalog', 'read', '250001 Could not connect to Snowflake backend'); + const health = { ...report.report.health, read_failure: { kind: 'unreachable' as const }, failing_since: '2026-11-08T11:42:00Z', retry_at: '2026-11-08T12:04:00Z', retry_seconds: 60 }; + return { ...report, report: { ...report.report, health } }; + }; + expect(warehouseSyncOf([failed('2026-11-08T12:03:00Z'), failed('2026-11-08T12:02:00Z'), sync('2026-11-08T11:40:00Z', 'catalog', null)])?.failing).toEqual({ + since: '2026-11-08T11:42:00Z', + reason: '250001 Could not connect to Snowflake backend', + halted: false, + unreachable: true, + retrySeconds: 60, + retryAt: '2026-11-08T12:04:00Z' + }); + expect(warehouseSyncOf([sync('2026-11-08T12:05:00Z', 'catalog', null), failed('2026-11-08T12:03:00Z')])?.failing).toBeNull(); }); it("gives each table its newest sync, the time it last synced cleanly, and where the state tables are read from", () => { @@ -206,7 +230,7 @@ describe('warehouseSyncOf', () => { const location = { id: 'loc:development', name: 'Orders', health: null, lastSeenAt: null, target: { name: 'development', adapter: null, connectionSummary: null }, warehouseSync: { lastSyncedAt: null, lastError: null } }; const observations = [sync('2026-11-08T12:03:00Z', 'catalog', 'busy'), sync('2026-11-08T12:01:00Z', 'catalog', null)]; expect(toWarehouseConnection(location, observations).tables.map((t) => [t.failure, t.waiting, t.lastSyncedAt])).toEqual([['Waiting for a build that holds the warehouse file', true, '2026-11-08T12:01:00Z']]); - expect(warehouseSyncOf(observations)).toEqual({ lastSyncedAt: '2026-11-08T12:01:00Z', lastError: null, lastReportedAt: '2026-11-08T12:03:00Z', syncing: null, completed: null }); + expect(warehouseSyncOf(observations)).toEqual({ lastSyncedAt: '2026-11-08T12:01:00Z', lastError: null, lastReportedAt: '2026-11-08T12:03:00Z', syncing: null, completed: null, failing: null }); }); it('says why a read failed and on what page size, without the warehouse message', () => { diff --git a/ui/src/lib/api/http-locations.ts b/ui/src/lib/api/http-locations.ts index 9b28166798..7e9e55fc4e 100644 --- a/ui/src/lib/api/http-locations.ts +++ b/ui/src/lib/api/http-locations.ts @@ -206,7 +206,9 @@ function readCauseOf(health: SyncHealth): string { const reason = cause.kind === 'timed_out' ? `no reply within ${cause.seconds} s` - : health.error + : cause.kind === 'unreachable' + ? "couldn't reach the warehouse, so no compute ran" + : health.error ? 'the read failed' : 'the read failed; the location’s log has why'; const page = health.page_limit ? `, on a page of ${health.page_limit.toLocaleString('en-US')} ${health.table === 'statistics' ? 'relations' : 'rows'}` : ''; @@ -287,7 +289,25 @@ export function warehouseSyncOf(observations: Wire['LocationHealthObservation'][ lastError: failing.length ? failing.sort().join('\n') : null, lastReportedAt: syncs[0].received_at, syncing: running.progress && !running.progress.completed && !running.progress.halted ? { position: running.progress.position, kinds: running.progress.kinds, table: running.table, rows: running.progress.rows } : null, - completed: done?.report.health.progress ? { at: done.received_at, kinds: done.report.health.progress.kinds, rows: done.report.health.progress.rows, elapsedMs: done.report.health.progress.elapsed_millis } : null + completed: done?.report.health.progress ? { at: done.received_at, kinds: done.report.health.progress.kinds, rows: done.report.health.progress.rows, elapsedMs: done.report.health.progress.elapsed_millis } : null, + failing: failingSyncOf(syncs) + }; +} + +/** The newest sync report's failure: since its first failure in a row, its reason, and how it retries. */ +function failingSyncOf(syncs: Sync[]): WarehouseSync['failing'] { + const newest = syncs[0]?.report.health; + if (!newest?.failure || newest.failure === 'busy') return null; + const end = syncs.findIndex((s) => !s.report.health.failure || s.report.health.failure === 'busy'); + const streak = end === -1 ? syncs : syncs.slice(0, end); + const halted = newest.progress?.halted ?? false; + return { + since: newest.failing_since ?? streak[streak.length - 1].received_at, + reason: newest.error ?? `failed while ${SYNC_STAGE[newest.failure]}`, + halted, + unreachable: newest.read_failure?.kind === 'unreachable', + retrySeconds: halted ? null : (newest.retry_seconds ?? null), + retryAt: halted ? null : (newest.retry_at ?? null) }; } diff --git a/ui/src/lib/api/http-overview.test.ts b/ui/src/lib/api/http-overview.test.ts index 18b4bf750f..13f8e7f454 100644 --- a/ui/src/lib/api/http-overview.test.ts +++ b/ui/src/lib/api/http-overview.test.ts @@ -26,7 +26,7 @@ describe('overview from live reads', () => { run('adhoc-new', 'failed', 2.2, 2.1, null), run('orders-new', 'failed', 3, 2.5), run('fulfilment-failed', 'failed', 4, 3.5, 'fulfilment'), - run('catalogue-partial', 'partial', 5, 4.5, 'catalogue'), + run('catalogue-failed', 'failed', 5, 4.5, 'catalogue'), run('orders-old', 'failed', 6, 5.5), // Neither a cancelled run nor a run of part of a job shows the job has recovered. run('catalogue-cancelled', 'cancelled', 4.2, 1, 'catalogue'), @@ -68,7 +68,7 @@ describe('overview from live reads', () => { }); it('counts top-level runs queued in the last 24 hours', () => { - expect(overview.metrics.runs24h).toEqual({ total: 13, success: 2, warn: 1, partial: 1, failed: 6, active: 2 }); + expect(overview.metrics.runs24h).toEqual({ total: 13, success: 2, warn: 1, failed: 7, active: 2 }); }); it('lists each job’s latest failure once, and each ad-hoc failure, newest first, then unresponsive runs and active platform events', () => { @@ -77,7 +77,7 @@ describe('overview from live reads', () => { 'run_problem:presumed:-', 'run_problem:adhoc-new:-', 'run_problem:orders-new:ada', - 'run_problem:catalogue-partial:-', + 'run_problem:catalogue-failed:-', 'run_problem:adhoc-old:-', 'run_unresponsive:stuck:-', 'event:scheduler', diff --git a/ui/src/lib/api/http-overview.ts b/ui/src/lib/api/http-overview.ts index 0a36b21fe4..0ce5ca06aa 100644 --- a/ui/src/lib/api/http-overview.ts +++ b/ui/src/lib/api/http-overview.ts @@ -9,7 +9,7 @@ import type { Acknowledgement, AttentionAcknowledgement, AttentionItem, Attentio const DAY = 24 * 60 * 60 * 1000; const MODEL_KINDS = new Set(['view', 'table', 'incremental']); -const PROBLEM_STATUSES = new Set(['failed', 'partial', 'presumed_failed']); +const PROBLEM_STATUSES = new Set(['failed', 'presumed_failed']); const ACTIVE_STATUSES = new Set(['queued', 'launched', 'running', 'unresponsive']); export type OverviewInputs = { @@ -106,7 +106,6 @@ export function overviewOf({ runs, checks, nodes, changes, events, triggers, ack total: recent.length, success: count(['success']), warn: count(['warn']), - partial: count(['partial']), failed: count(['failed', 'presumed_failed']), active: recent.filter((r) => ACTIVE_STATUSES.has(r.status)).length }, diff --git a/ui/src/lib/api/http-problems.test.ts b/ui/src/lib/api/http-problems.test.ts index bd1a36b1f5..da89fe771d 100644 --- a/ui/src/lib/api/http-problems.test.ts +++ b/ui/src/lib/api/http-problems.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest'; import { toPlatformEventRecords, toPlatformEvents, toPlatformHealth } from './http-problems'; +import { formatClock } from '$lib/format/time'; const NOW = Date.parse('2026-11-08T12:00:00Z'); const tick = (name: string, location: string, scheduledFor: string) => ({ @@ -21,6 +22,38 @@ describe('toPlatformEvents', () => { expect([degraded.severity, degraded.message.split('. ')[0]]).toEqual(['warning', 'orders · production: the warehouse connection check failed']); }); + it('makes a failing run-history sync a problem since its first failure, with its reason and how it retries', () => { + const sync = (unreachable: boolean, halted: boolean) => ({ + location_id: 'l1', + location_name: 'orders', + target: 'production', + since: '2026-11-08T11:42:00Z', + reason: '250001 Could not connect to Snowflake backend after 2 attempt(s)', + unreachable, + halted, + retry_at: halted ? null : '2026-11-08T12:00:40Z', + retry_seconds: halted ? null : 60, + last_success_at: '2026-11-08T11:40:00Z' + }); + const events = toPlatformEvents({ scheduler_leader: true, broken_locations: [], overdue_ticks: [], failing_syncs: [sync(true, false), sync(false, true)] }, NOW); + const since = formatClock('2026-11-08T11:42:00Z', NOW); + expect(events.map((e) => [e.kind, e.severity, e.occurredAt, e.locationId, e.message, e.sync?.halted])).toEqual([ + ['warehouse_sync_failed', 'warning', '2026-11-08T11:42:00Z', 'l1:production', `orders · production: run history can't reach the warehouse since ${since} · retrying every 60 s: 250001 Could not connect to Snowflake backend after 2 attempt(s)`, false], + ['warehouse_sync_failed', 'warning', '2026-11-08T11:42:00Z', 'l1:production', `orders · production: run history sync stopped after failed reads in a row since ${since}: 250001 Could not connect to Snowflake backend after 2 attempt(s). Resume it once the cause is fixed.`, true] + ]); + }); + + it('makes a sink that loses events, and a webhook the server can’t deliver to, problems since they began', () => { + const sink = { location_id: 'l1', location_name: 'orders', target: 'production', sink: 'kafka', since: '2026-11-08T11:42:00Z', reason: '8 of 8 events not delivered (8 failed)', run_id: 'r-9', last_success_at: null }; + const forwarding = { name: 'Platform event forwarding', since: '2026-11-08T11:50:00Z', reason: 'Can’t deliver platform events: the webhook answered HTTP 503; they are kept and retried every 5 s', last_success_at: null }; + const events = toPlatformEvents({ scheduler_leader: true, broken_locations: [], overdue_ticks: [], failing_sinks: [sink], failing_forwarding: [forwarding] }, NOW); + const at = (iso: string) => formatClock(iso, NOW); + expect(events.map((e) => [e.kind, e.severity, e.locationId, e.subject, e.message])).toEqual([ + ['event_sink_failed', 'warning', 'l1:production', 'kafka', `orders · production: event sink kafka losing events since ${at(sink.since)}: 8 of 8 events not delivered (8 failed).`], + ['event_forwarding_failed', 'warning', null, 'Platform event forwarding', `Platform event forwarding failing since ${at(forwarding.since)}: ${forwarding.reason}.`] + ]); + }); + it('reports nothing while the scheduler leads and nothing is late', () => { expect(toPlatformEvents({ scheduler_leader: true, scheduler_lease_expires_at: '2026-11-08T12:00:10Z', broken_locations: [], overdue_ticks: [] }, NOW)).toEqual([]); }); @@ -157,7 +190,7 @@ describe('toPlatformEventRecords', () => { open, [ { storage_id: 9, event_id: 'e9', occurred_at: '2026-11-08T11:00:00Z', location_id: 'l1', target: 'development', event: { kind: 'launch_failed', run_id: 'r1', claim_id: 'c1', code: 'image_missing' } }, - { storage_id: 7, event_id: 'e7', occurred_at: '2026-11-08T10:30:00Z', event: { kind: 'run_failed', run_id: 'r2', run_kind: 'job', job_key: 'orders_daily', location_id: 'l1', target: 'development', outcome: 'failed', failed_nodes: [{ node_key: 'model:orders' }], failed_node_count: 1 } }, + { storage_id: 7, event_id: 'e7', occurred_at: '2026-11-08T10:30:00Z', event: { kind: 'run_failed', run_id: 'r2', run_kind: 'job', job_key: 'orders_daily', location_id: 'l1', target: 'development', outcome: 'failed', trigger: { kind: 'schedule' }, failed_nodes: [{ node_key: 'model:orders' }], failed_node_count: 1, failed_audits: [], failed_audit_count: 0, succeeded_node_count: 3, skipped_nodes: [], skipped_node_count: 0 } }, { storage_id: 4, event_id: 'e4', occurred_at: '2026-11-08T10:00:00Z', event: { kind: 'scheduler_no_leader' } } ], new Map([['l1:development', 'orders']]) diff --git a/ui/src/lib/api/http-problems.ts b/ui/src/lib/api/http-problems.ts index d160b56a1e..46d2a0a67f 100644 --- a/ui/src/lib/api/http-problems.ts +++ b/ui/src/lib/api/http-problems.ts @@ -1,5 +1,5 @@ import type { components } from '$control/schema.d.ts'; -import { formatStamp } from '$lib/format/time'; +import { formatClock, formatStamp } from '$lib/format/time'; import { locationKey as keyOf } from './http-client'; import type { PlatformEvent } from './types'; import type { PlatformEventRecord, PlatformHealth } from './types/platform'; @@ -73,6 +73,50 @@ export function toPlatformEvents(problems: Wire['PlatformProblems'], now: number message: failingMessage(place, location) }); } + for (const sync of problems.failing_syncs ?? []) { + const place = placeOf(sync.location_name, sync.target); + events.push({ + id: `sync:${keyOf(sync.location_id, sync.target)}`, + kind: 'warehouse_sync_failed', + severity: 'warning', + occurredAt: sync.since, + // The first failure in a row tells one failing streak from the next. + occurrence: sync.since, + active: true, + locationId: keyOf(sync.location_id, sync.target), + subject: place, + message: syncMessage(place, sync, now), + sync: { halted: sync.halted, unreachable: sync.unreachable, retrySeconds: sync.retry_seconds ?? null, retryAt: sync.retry_at ?? null, lastSuccessAt: sync.last_success_at ?? null } + }); + } + for (const sink of problems.failing_sinks ?? []) { + const place = placeOf(sink.location_name, sink.target); + events.push({ + id: `sink:${keyOf(sink.location_id, sink.target)}:${sink.sink}`, + kind: 'event_sink_failed', + severity: 'warning', + occurredAt: sink.since, + // The first lossy run in a row tells one failing streak from the next. + occurrence: sink.since, + active: true, + locationId: keyOf(sink.location_id, sink.target), + subject: sink.sink, + message: `${place}: event sink ${sink.sink} losing events since ${formatClock(sink.since, now)}: ${sink.reason}.` + }); + } + for (const forwarding of problems.failing_forwarding ?? []) { + events.push({ + id: `forwarding:${forwarding.name}`, + kind: 'event_forwarding_failed', + severity: 'warning', + occurredAt: forwarding.since, + occurrence: forwarding.since, + active: true, + locationId: null, + subject: forwarding.name, + message: `${forwarding.name} failing since ${formatClock(forwarding.since, now)}: ${forwarding.reason}.` + }); + } const late = new Map(); for (const tick of problems.overdue_ticks) { const key = keyOf(tick.location_id, tick.target); @@ -255,3 +299,12 @@ function storedRecord(wire: Wire['PersonPlatformEvent'], names: Map { wire('r2', { status: 'cancelled', cancel_requested_at: '2026-11-06T09:05:00Z' }), wire('r3', { status: 'queued' }), wire('r4', { status: 'failed', node_counts_json: { success: 1, failed: 2, skipped: 3 } }), - wire('r5', { status: 'partial' }), + wire('r5', { status: 'failed' }), wire('r5-child', { status: 'queued', parent_run_id: 'r5', root_run_id: 'r5' }), wire('r6', { status: 'success' }), wire('r7', { status: 'cancelled', node_counts_json: { success: 1, failed: 1, cancelled: 2, skipped: 1 } }) diff --git a/ui/src/lib/api/http-runs.ts b/ui/src/lib/api/http-runs.ts index 708651f233..e59e8fbfd4 100644 --- a/ui/src/lib/api/http-runs.ts +++ b/ui/src/lib/api/http-runs.ts @@ -165,6 +165,7 @@ export function toRun(wire: Wire['RunRecord'], locationId: string, childRunCount rerunOfRunId: wire.rerun_of_run_id ?? null, memberAttempt: wire.member_attempt ?? null, narrowing: wire.narrowing ?? null, + command: wire.command ?? null, window: wire.window ? { start: String(wire.window.start), end: String(wire.window.end) } : null, requestedBy: requesterOf(wire), priority: wire.priority, @@ -255,7 +256,7 @@ function rowOf(run: Run, wire: Wire['RunRecord']): RunRow { function inTab(run: Run, tab: RunRowQuery['tab']): boolean { if (tab === 'active') return isActiveRun(run.status); if (tab === 'queued') return run.status === 'queued'; - if (tab === 'failed') return run.status === 'failed' || run.status === 'partial' || run.status === 'presumed_failed'; + if (tab === 'failed') return run.status === 'failed' || run.status === 'presumed_failed'; if (tab === 'cancelled') return run.status === 'cancelled'; return true; } @@ -475,7 +476,7 @@ export function toRunEvent(wire: Wire['RunEventRecord'], runId: string): RunEven }; } -const CHECK_OUTCOMES: Record = { pass: 'passed', warn: 'warned', error: 'failed' }; +const CHECK_OUTCOMES: Record = { pass: 'passed', warn: 'warned', error: 'failed', not_run: 'not-run' }; /** A check result's name, outcome and rows from its event; a result with no name recorded is named by its outcome. */ export function checkOf(wire: Wire['RunEventRecord']): RunEventCheck { diff --git a/ui/src/lib/api/http-selection.test.ts b/ui/src/lib/api/http-selection.test.ts index b85b25d608..247e3af9e7 100644 --- a/ui/src/lib/api/http-selection.test.ts +++ b/ui/src/lib/api/http-selection.test.ts @@ -3,9 +3,10 @@ import { toSelectionEvaluation, toSelectionVocabulary } from './http-selection'; describe('selection mapping', () => { it('keeps a page of keys and the total, with no error', () => { - expect(toSelectionEvaluation({ snapshot_id: 'snap-1', count: 3, keys: ['model:customers', 'model:orders'], next_offset: 2, error: null })).toEqual({ + expect(toSelectionEvaluation({ snapshot_id: 'snap-1', count: 3, audits: 2, keys: ['model:customers', 'model:orders'], next_offset: 2, error: null })).toEqual({ snapshotId: 'snap-1', count: 3, + audits: 2, keys: ['model:customers', 'model:orders'], nextOffset: 2, error: null @@ -63,7 +64,8 @@ describe('selection mapping', () => { jobs: [entry('nightly_orders', 12)], sources: [entry('shop.orders', 1)], seeds: [entry('currencies', 1)], - kinds: [entry('model', 4)] + kinds: [entry('model', 4)], + audits: [entry('not_null_orders_id', 1)] }) ).toEqual({ snapshotId: null, @@ -72,7 +74,8 @@ describe('selection mapping', () => { jobs: [entry('nightly_orders', 12)], sources: [entry('shop.orders', 1)], seeds: [entry('currencies', 1)], - kinds: [entry('model', 4)] + kinds: [entry('model', 4)], + audits: [entry('not_null_orders_id', 1)] }); }); }); diff --git a/ui/src/lib/api/http-selection.ts b/ui/src/lib/api/http-selection.ts index 848b33bed3..2725469ae2 100644 --- a/ui/src/lib/api/http-selection.ts +++ b/ui/src/lib/api/http-selection.ts @@ -9,6 +9,7 @@ export function toSelectionEvaluation(wire: Wire['SelectionEvaluation']): Select return { snapshotId: wire.snapshot_id ?? null, count: wire.count, + audits: wire.audits ?? 0, keys: wire.keys, nextOffset: wire.next_offset ?? null, error: toSelectionProblem(wire.error) @@ -44,6 +45,7 @@ export function toSelectionVocabulary(wire: Wire['SelectionVocabulary']): Select jobs: entries(wire.jobs), sources: entries(wire.sources), seeds: entries(wire.seeds), - kinds: entries(wire.kinds) + kinds: entries(wire.kinds), + audits: entries(wire.audits ?? []) }; } diff --git a/ui/src/lib/api/mock/build-fixtures.ts b/ui/src/lib/api/mock/build-fixtures.ts index 3b2089ac69..8f738a8441 100644 --- a/ui/src/lib/api/mock/build-fixtures.ts +++ b/ui/src/lib/api/mock/build-fixtures.ts @@ -3,6 +3,7 @@ // state itself (last builds, outcomes, staleness) is derived in mock/build.ts // from the OPERATE run history plus a few builds made outside the scheduler. +import { ORDERS_MATCH_PAYMENTS_SQL, SEED_AUDIT_CHECK } from './seed-audit-run'; import type { CheckAttachment, CheckKind, @@ -450,7 +451,9 @@ export const CHECK_SPECS: CheckSpec[] = [ { id: 'chk-cc-unique', name: 'unique(code)', definition: 'unique', kind: 'audit', attachment: 'seed', node: 'country_codes', column: 'code', severity: 'error', runScopePhase: 'final', evaluationMode: 'violations', thresholds: [], description: null, latest: { outcome: 'pass', violations: 0 }, history: {}, sql: 'SELECT code, count(*) AS n FROM {relation} GROUP BY 1 HAVING count(*) > 1' }, { id: 'chk-end-reconcile', name: 'revenue_reconciles', definition: null, kind: 'sql_test', attachment: 'end', node: null, column: null, severity: 'error', runScopePhase: 'final', evaluationMode: 'measurement', thresholds: [{ level: 'warn', operator: 'above', value: 0.05 }, { level: 'error', operator: 'above', value: 0.1 }], description: 'Mart revenue matches successful payments within 0.1%.', latest: { outcome: 'pass', measured: 0.02 }, history: { measuredBase: 0.03, warnEvery: 8 }, sql: `SELECT 100 * abs(m.total - p.total) / nullif(p.total, 0) AS measured_value FROM (SELECT sum(total_revenue_cents) AS total FROM "WAFFLE_SHOP"."MARTS"."DAILY_REVENUE") m, - (SELECT sum(amount_cents) AS total FROM "WAFFLE_SHOP"."STAGING"."STG_PAYMENTS" WHERE status = 'success') p` } + (SELECT sum(amount_cents) AS total FROM "WAFFLE_SHOP"."STAGING"."STG_PAYMENTS" WHERE status = 'success') p` }, + // The run-page failure mock-up's singular audit: it reads two models never built in prod. + { id: 'chk-end-orders-payments', name: SEED_AUDIT_CHECK, definition: null, kind: 'audit', attachment: 'end', node: null, column: null, severity: 'error', runScopePhase: 'final', evaluationMode: 'violations', thresholds: [], description: 'Every order has a payment of the same amount.', latest: { outcome: 'error', violations: 0 }, history: {}, sql: ORDERS_MATCH_PAYMENTS_SQL } ]; // ---- snapshot change feed (one entry per deploy) ---- diff --git a/ui/src/lib/api/mock/build.ts b/ui/src/lib/api/mock/build.ts index 00764ad966..69048ff9c2 100644 --- a/ui/src/lib/api/mock/build.ts +++ b/ui/src/lib/api/mock/build.ts @@ -3,6 +3,7 @@ // server derives it: scheduler run nodes plus builds outside the scheduler // (synced fingerprints), compared against the snapshot change feed. +import { MISSING_OBJECT_ERROR, SEED_AUDIT_BINDING, SEED_AUDIT_CHECK } from './seed-audit-run'; import { ApiError } from '../client'; import { groupStatusOf, problemRunsOf } from '../http-overview'; import { clearedAcknowledgements, withConditions } from '$lib/build-area/attention-conditions'; @@ -225,6 +226,11 @@ export class MockBuild { getCheckEvidence(scope: Scope, checkId: string, evaluationId: string): Promise { if (!this.#ctx.can('view.evidence')) throw new ApiError('Missing permission: view.evidence', 403); + // The end-of-build audit of the failed mock run: its query could not run, so it has an error, not rows. + if (checkId === SEED_AUDIT_BINDING) { + this.#ctx.platform.recordEvidenceRead(scope, checkId, `Read the error of ${SEED_AUDIT_CHECK} (${evaluationId})`); + return this.#ctx.reply({ evaluationId, columns: [], rows: [], truncated: false, executionError: MISSING_OBJECT_ERROR }); + } const spec = CHECK_SPECS.find((s) => s.id === checkId); const evaluation = spec && this.#evaluations(spec, this.#states(scope), 40).find((e) => e.id === evaluationId); if (!spec || !evaluation) throw new ApiError(`Unknown evaluation ${evaluationId}`, 404); @@ -232,7 +238,7 @@ export class MockBuild { const count = Math.min(evaluation.evidenceCount ?? 0, 10); const rows = Array.from({ length: count }, (_, i) => columns.map((col) => evidenceValue(col, hash(`${evaluationId}/${i}`)))); this.#ctx.platform.recordEvidenceRead(scope, checkId, `Read ${count} evidence rows of ${spec.name} (${evaluationId})`); - return this.#ctx.reply({ evaluationId, columns, rows, truncated: evaluation.evidenceTruncated || (evaluation.evidenceCount ?? 0) > count }); + return this.#ctx.reply({ evaluationId, columns, rows, truncated: evaluation.evidenceTruncated || (evaluation.evidenceCount ?? 0) > count, executionError: null }); } // ---- change feed ---- @@ -292,7 +298,6 @@ export class MockBuild { total: recent.length, success: recent.filter((r) => r.status === 'success').length, warn: recent.filter((r) => r.status === 'warn').length, - partial: recent.filter((r) => r.status === 'partial').length, failed: recent.filter((r) => r.status === 'failed' || r.status === 'presumed_failed').length, active: recent.filter((r) => ['queued', 'launched', 'running', 'unresponsive'].includes(r.status)).length }, diff --git a/ui/src/lib/api/mock/cost-project.ts b/ui/src/lib/api/mock/cost-project.ts index faa294c7de..1d313058fe 100644 --- a/ui/src/lib/api/mock/cost-project.ts +++ b/ui/src/lib/api/mock/cost-project.ts @@ -144,7 +144,7 @@ function build(now: number) { for (let at = start + rand() * every; at < now; at += every) { const noisy = credits * (0.7 + rand() * 0.6) * (rand() < 0.01 ? 5 + rand() * 4 : 1) * (at > now - 9 * 86_400_000 && job === 'events_hourly' ? 1.45 : 1); const roll = rand(); - const status: RunStatus = now - at < every && now - at < 1_200_000 ? 'running' : roll < 0.03 ? 'failed' : roll < 0.06 ? 'partial' : 'success'; + const status: RunStatus = now - at < every && now - at < 1_200_000 ? 'running' : roll < 0.06 ? 'failed' : 'success'; const spent = status === 'failed' ? noisy * 0.3 : noisy; runs.push({ id: id(at, 2654435761), job, at, status, credits: spent, seconds: (spent / RATE[size]) * 3600 }); } @@ -255,7 +255,7 @@ function evaluateCostSelection(select: string, exclude: string): SelectionEvalua } return chosen; }; - const reply = (keys: string[], error: SelectionProblem | null): SelectionEvaluation => ({ snapshotId: 'mock-snapshot', count: keys.length, keys, nextOffset: null, error }); + const reply = (keys: string[], error: SelectionProblem | null): SelectionEvaluation => ({ snapshotId: 'mock-snapshot', count: keys.length, audits: 0, keys, nextOffset: null, error }); const selected = select.trim() ? resolve('select', select) : new Set(catalog().metas.map((m) => m.key)); if (!(selected instanceof Set)) return reply([], selected); const excluded = exclude.trim() ? resolve('exclude', exclude) : new Set(); @@ -281,7 +281,8 @@ function costVocabulary(): SelectionVocabulary { jobs: [...jobs].filter(([j]) => j !== MANUAL).map(([value, keys]) => ({ value, count: keys.length })).sort((a, b) => a.value.localeCompare(b.value)), sources: [], seeds: [], - kinds: [{ value: 'model', count: metas.length }] + kinds: [{ value: 'model', count: metas.length }], + audits: [] }; } @@ -335,7 +336,7 @@ function costSelection(query: CostSelectionQuery): CostSelection { j.seconds += r.seconds; j.runs += 1; j.daily[day] += r.credits; - if (r.status === 'running' || r.status === 'partial') j.pending += 1; + if (r.status === 'running') j.pending += 1; } } const facts: CostFact[] = []; diff --git a/ui/src/lib/api/mock/mock-client.ts b/ui/src/lib/api/mock/mock-client.ts index 1952b42ecd..fd5d39fde5 100644 --- a/ui/src/lib/api/mock/mock-client.ts +++ b/ui/src/lib/api/mock/mock-client.ts @@ -537,6 +537,12 @@ export class MockApiClient implements ApiClient { platformHealth(...args: Parameters) { return this.#platform.platformHealth(...args); } + readHealth() { + return this.#platform.readHealth(); + } + readHealthDetails() { + return this.#platform.readHealthDetails(); + } listPlatformEventHistory(...args: Parameters) { return this.#platform.listPlatformEventHistory(...args); } diff --git a/ui/src/lib/api/mock/operate-graph-selection.test.ts b/ui/src/lib/api/mock/operate-graph-selection.test.ts index c41a74c09f..b2f4655bea 100644 --- a/ui/src/lib/api/mock/operate-graph-selection.test.ts +++ b/ui/src/lib/api/mock/operate-graph-selection.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { evaluateMockSelection, mockVocabulary } from './operate-graph'; +import { evaluateMockSelection, mockVocabulary, resolveSelection } from './operate-graph'; +import './operate'; describe('mock selection evaluation', () => { it('expands + on its own comma part before intersecting', () => { @@ -26,9 +27,15 @@ describe('mock selection evaluation', () => { expect(mockVocabulary().kinds).toEqual([ { value: 'asset', count: 46 }, { value: 'loader', count: 2 }, - { value: 'model', count: 31 }, + // 2 from the run-page failure mock-up (seed-audit-run.ts); its 92 seeds load only where it is shown. + { value: 'model', count: 33 }, { value: 'seed', count: 1 }, { value: 'source', count: 6 } ]); }); + + it("a job run narrowed on the plan page resolves as the server does: job:core_build,fact_orders is fact_orders", () => { + expect(resolveSelection(['job:core_build,fact_orders'])).toEqual({ nodes: ['fact_orders'], unknown: [] }); + expect(resolveSelection(['job:core_build,no_such_node']).unknown).toEqual(['job:core_build,no_such_node']); + }); }); diff --git a/ui/src/lib/api/mock/operate-graph.ts b/ui/src/lib/api/mock/operate-graph.ts index 82d348bb55..880b035194 100644 --- a/ui/src/lib/api/mock/operate-graph.ts +++ b/ui/src/lib/api/mock/operate-graph.ts @@ -2,6 +2,10 @@ // resolves selectors against the real snapshot; this stands in for it. import type { NodeKind, SnapshotNode } from '../types'; +import { SEED_AUDIT_CHECK } from './seed-audit-run'; + +/** End-of-build checks a selection can name with `check:`, as a rerun target. */ +const END_CHECKS = new Set([SEED_AUDIT_CHECK, 'revenue_reconciles']); import { DISCOVERED_NODES } from './discovered'; import type { SelectionProblem, SelectionVocabulary, VocabularyEntry } from '../types/operate'; import { MODELS_ROOT, PATH_SELECTOR_ROOTS, PYTHON_NODES_ROOT, SQL_ROOT } from '$lib/project-layout'; @@ -76,7 +80,11 @@ export const SNAPSHOT_NODES: SnapshotNode[] = [ // A notebook runner that prints about 2 million lines (CHI-1597). node('notebook_runner', 'asset', 'ml', ['fact_orders'], { path: 'python/nodes/ml/notebook_runner.py' }), // Discovered steps of two forecast plans (discovered.ts). - ...DISCOVERED_NODES + ...DISCOVERED_NODES, + // The run-page failure mock-up (seed-audit-run.ts): 92 reference seeds, and two models no run builds. + // Never built, and read only by the audit: no edges, so the rest of the mock project lays out as before. + node('fct_order_payments', 'table', 'finance', [], { path: `${MODELS_ROOT}/finance/reconciliation/fct_order_payments.sql` }), + node('fct_payment_totals', 'table', 'finance', [], { path: `${MODELS_ROOT}/finance/reconciliation/fct_payment_totals.sql` }) ]; const BY_KEY = new Map(SNAPSHOT_NODES.map((n) => [n.key, n])); @@ -127,6 +135,19 @@ export function sortTopologically(keys: Iterable): string[] { } function matchTerm(term: string): Set | null { + // An intersection (`job:core_build,fact_orders`, as the plan page narrows a job run) and the job and run + // selectors read as the server reads them: each part on its own, then what they share. + if (term.includes(',')) { + let hits: Set | null = null; + for (const part of term.split(',')) { + const found: Set | null = matchTerm(part); + if (!found) return null; + const prev: Set | null = hits; + hits = prev ? new Set([...prev].filter((k: string) => found.has(k))) : found; + } + return hits; + } + if (/^\+?(job|run|failed|skipped):/.test(term)) return matchPart(term); const up = term.startsWith('+'); const down = term.endsWith('+') && term.length > 1; const body = term.replace(/^\+/, '').replace(/\+$/, ''); @@ -193,6 +214,42 @@ function inDir(n: SnapshotNode, dir: string): boolean { return rooted && (dirOf(n) === at || dirOf(n).startsWith(`${at}/`)); } +/** What `run:`, `failed:` and `skipped:` read: a run's own nodes by result (set by the run store). */ +export type RunResults = { selected: string[]; failed: string[]; skipped: string[]; failedAudits: string[] }; +let runIdsKnown: () => string[] = () => []; +let runResultsOf: (id: string) => RunResults | null = () => null; +export function setRunResolver(ids: () => string[], results: (id: string) => RunResults | null) { + runIdsKnown = ids; + runResultsOf = results; +} + +/** A run ID, or a unique prefix of at least 8 characters, as the run it names; a refusal reads why. */ +export function resolveRunId(text: string): { id: string } | { error: string } { + const ids = runIdsKnown(); + if (ids.includes(text)) return { id: text }; + if (text.length < 8) return { error: `run ID prefix '${text}' is shorter than 8 characters` }; + const hits = ids.filter((id) => id.startsWith(text)); + if (hits.length === 1) return { id: hits[0] }; + return { error: hits.length ? `run ID prefix '${text}' matches ${hits.length} runs: ${hits.join(', ')}` : `no run '${text}'` }; +} + +/** The audits a selection names: `audit:`, and the failed audits of each `failed:` or `run:` run. */ +export function auditsSelected(select: string): string[] { + const out = new Set(); + for (const token of select.split(/\s+/)) { + const body = token.replace(/^\+/, '').replace(/\+$/, ''); + const colon = body.indexOf(':'); + if (colon < 0) continue; + const [type, value] = [body.slice(0, colon), body.slice(colon + 1)]; + if (type === 'audit' && END_CHECKS.has(value)) out.add(value); + if (type === 'failed' || type === 'run') { + const run = resolveRunId(value); + if ('id' in run) for (const a of runResultsOf(run.id)?.failedAudits ?? []) out.add(a); + } + } + return [...out]; +} + /** `job:`: the job's nodes, as `operate.ts` resolves them (set there, which imports this module). */ let jobNodesOf: (key: string) => string[] = () => []; export function setJobResolver(resolve: (key: string) => string[]) { @@ -205,7 +262,9 @@ function matchPart(part: string): Set | null { const down = part.endsWith('+') && part.length > 1; const body = part.replace(/^\+/, '').replace(/\+$/, ''); const [type, value] = body.includes(':') ? [body.slice(0, body.indexOf(':')), body.slice(body.indexOf(':') + 1)] : ['name', body]; - const jobKeys = type === 'job' ? new Set(jobNodesOf(value)) : null; + const run = type === 'run' || type === 'failed' || type === 'skipped' ? resolveRunId(value) : null; + const results = run && 'id' in run ? runResultsOf(run.id) : null; + const jobKeys = type === 'job' ? new Set(jobNodesOf(value)) : results ? new Set(type === 'run' ? results.selected : type === 'failed' ? results.failed : results.skipped) : null; const base = SNAPSHOT_NODES.filter((n) => jobKeys ? jobKeys.has(n.key) : type === 'tag' ? n.tags.includes(value) : type === 'kind' ? selectorKind(n) === value : type === 'path' ? inDir(n, value) : n.key === value @@ -225,6 +284,16 @@ export function evaluateMockSelection(select: string, exclude: string): { keys: const chosen = new Set(); for (const match of text.matchAll(/\S+/g)) { const token = match[0]; + // An audit selects itself, not nodes; so does a run whose failures are audits only (the server needs this too). + if (token.startsWith('audit:') && END_CHECKS.has(token.slice(6))) continue; + const runPart = /^(failed|skipped|run):([^,+]+)\+?$/.exec(token); + if (runPart) { + const run = resolveRunId(runPart[2]); + if ('error' in run) return { code: 'S007', message: run.error, help: null, location: { field, token, start: match.index, end: match.index + token.length }, suggestions: [], refused: { part: 0, type: runPart[1], value: runPart[2] } }; + const found = matchPart(token); + for (const key of found ?? []) chosen.add(key); + continue; + } let hits = null as Set | null; for (const [index, part] of token.split(',').entries()) { const found = matchPart(part); @@ -245,7 +314,10 @@ export function evaluateMockSelection(select: string, exclude: string): { keys: if (!(selected instanceof Set)) return { keys: [], error: selected }; const excluded = resolve('exclude', exclude); if (!(excluded instanceof Set)) return { keys: [], error: excluded }; - const keys = [...selected].filter((key) => !excluded.has(key)).sort(); + // Audits are selected as `audit:` keys beside the nodes, as the server returns them. + const leftOut = new Set(auditsSelected(exclude)); + const audits = auditsSelected(select).filter((name) => !leftOut.has(name)).map((name) => `audit:${name}`); + const keys = [...[...selected].filter((key) => !excluded.has(key)), ...audits].sort(); if (!keys.length) return { keys, error: { code: null, message: 'the selectors match no nodes in the current publication', help: null, location: null, suggestions: [], refused: null } }; return { keys, error: null }; } @@ -269,6 +341,7 @@ export function mockVocabulary(): Omit n.kind === 'source').map((n) => n.key)), seeds: counted(SNAPSHOT_NODES.filter((n) => n.kind === 'seed').map((n) => n.key)), - kinds: counted(SNAPSHOT_NODES.map(selectorKind)) + kinds: counted(SNAPSHOT_NODES.map(selectorKind)), + audits: counted([...END_CHECKS]) }; } diff --git a/ui/src/lib/api/mock/operate-store.ts b/ui/src/lib/api/mock/operate-store.ts index 483fbe7e34..b3c532b628 100644 --- a/ui/src/lib/api/mock/operate-store.ts +++ b/ui/src/lib/api/mock/operate-store.ts @@ -2,6 +2,7 @@ // its claims, jobs, triggers and sensors. A small loop advances live runs so // cancels, launches and claims behave like they do on the server. +import { SEED_AUDIT_CHECK, SEED_AUDIT_RUN_ID, seedAuditSql } from './seed-audit-run'; import { bigAvailable, bigDownloadUrl, bigIndex, bigPage, bigSearch } from './big-output'; import { parseCommand } from '$lib/run/command'; import { isUnfinishedNode } from '$lib/status'; @@ -96,6 +97,7 @@ import { } from './operate'; import { SCHEDULER } from './principals'; import { costFolder, costPeriod, costSelectionOf, costSeriesOf, type CostRowIn } from './cost-rows'; +import { setRunResolver } from './operate-graph'; import { ancestors, evaluateMockSelection, isWritable, mockVocabulary, resolveSelection, SNAPSHOT_NODES, snapshotNode, sortTopologically, edgesWithin, writeSetOf } from './operate-graph'; import { commandOf, @@ -189,6 +191,17 @@ export class MockOperate { this.#fx = createOperateFixtures(now); this.#records = this.#fx.records; for (const rec of this.#records) this.#settle(rec, now); + // `run:`, `failed:` and `skipped:` read a run's results from this store, as the server reads its own. + setRunResolver( + () => this.#records.map((r) => r.run.id), + (id) => { + const rec = this.#byId(id); + if (!rec) return null; + const nodes = this.#nodesOf(rec, Date.now()); + const of = (s: string[]) => nodes.filter((n) => s.includes(n.status)).map((n) => n.nodeKey); + return { selected: nodes.map((n) => n.nodeKey), failed: of(['failed', 'cancelled', 'not_run']), skipped: of(['skipped']), failedAudits: id === SEED_AUDIT_RUN_ID ? [SEED_AUDIT_CHECK] : [] }; + } + ); if (typeof window !== 'undefined' && !ctx.still) setInterval(() => this.#advance(), 1500); } @@ -298,7 +311,7 @@ export class MockOperate { if (f.statuses?.length && !f.statuses.includes(view.status)) continue; if (tab === 'active' && !isActive(view.status)) continue; if (tab === 'queued' && view.status !== 'queued') continue; - if (tab === 'failed' && !['failed', 'partial', 'presumed_failed'].includes(view.status)) continue; + if (tab === 'failed' && !['failed', 'presumed_failed'].includes(view.status)) continue; if (tab === 'cancelled' && view.status !== 'cancelled') continue; out.push({ rec, view }); } @@ -541,7 +554,7 @@ export class MockOperate { const statement = execution(rec, this.#nodesOf(rec, now), now).statements.find((st) => st.id === statementId); if (!statement) throw new ApiError(`Unknown statement ${statementId}`, 404); const target = this.#ctx.target(scope); - const sql = statement.kind === 'audit' ? auditSql(statement.nodeKey, statementId, target) : sqlFor(statement.nodeKey, statement.kind, target); + const sql = seedAuditSql(statement) ?? (statement.kind === 'audit' ? auditSql(statement.nodeKey, statementId, target) : sqlFor(statement.nodeKey, statement.kind, target)); return this.#ctx.reply({ statementId, sql: statement.sqlRecorded ? sql : null }); } @@ -652,7 +665,7 @@ export class MockOperate { const offset = request.offset ?? 0; const limit = Math.min(Math.max(request.limit ?? 1000, 1), 10_000); const page = keys.slice(offset, offset + limit); - return this.#ctx.reply({ snapshotId: 'mock-snapshot', count: keys.length, keys: page, nextOffset: offset + limit < keys.length ? offset + limit : null, error }); + return this.#ctx.reply({ snapshotId: 'mock-snapshot', count: keys.length, audits: keys.filter((key) => key.startsWith('audit:')).length, keys: page, nextOffset: offset + limit < keys.length ? offset + limit : null, error }); } selectionVocabulary(scope: Scope): Promise { @@ -792,7 +805,8 @@ export class MockOperate { flags: parts.flags, nodes: check.writeSet.length ? check.writeSet : check.selection.filter((n) => snapshotNode(n)?.kind !== 'source'), priority: request.priority, - verb: parts.verb + verb: parts.verb, + command: request.command }); this.#ctx.changes.emit('runs'); return this.#ctx.reply(this.#view(rec, scope)); @@ -1196,6 +1210,7 @@ export class MockOperate { origin: Run['origin']; jobKey: string | null; narrowing?: Run['narrowing']; + command?: string[]; by: Principal; select: string[]; exclude: string[]; @@ -1227,6 +1242,7 @@ export class MockOperate { rerunOfRunId: spec.rerunOf ?? null, memberAttempt: null, narrowing: spec.narrowing ?? null, + command: spec.command ?? null, window: null, requestedBy: spec.by, priority: spec.priority, @@ -1279,9 +1295,17 @@ export class MockOperate { const parts = parseCommand(request.command.join(' ')); const unknownFlag = Object.keys(parts.flags).find((f) => !flagSpec(parts.verb, f)); if (unknownFlag) return refused(`${unknownFlag} is not available for ad-hoc runs`); - const resolution = resolveSelection(parts.select, parts.exclude); + // Run and audit selectors resolve as the selection bar's evaluation does; the rest as before. + const pastToken = (t: string) => /^\+?(failed|skipped|run|audit):/.test(t); + const past = parts.select.filter(pastToken); + const plain = parts.select.filter((t) => !pastToken(t)); + const resolution = plain.length || !past.length ? resolveSelection(plain, parts.exclude.filter((t) => !pastToken(t))) : { nodes: [], unknown: [] }; + const fromRuns = past.length ? evaluateMockSelection(past.join(' '), parts.exclude.filter(pastToken).join(' ')) : { keys: [], error: null }; + if (fromRuns.error) return refused(fromRuns.error.message); if (resolution.unknown.length) return refused(`no nodes match selector '${resolution.unknown[0]}'`); - if (!resolution.nodes.length) return refused('the selection resolves to no nodes'); + const audits = fromRuns.keys.filter((k) => k.startsWith('audit:')); + resolution.nodes = [...new Set([...resolution.nodes, ...fromRuns.keys.filter((k) => !k.startsWith('audit:'))])]; + if (!resolution.nodes.length && !audits.length) return refused('the selection resolves to no nodes'); const isSource = (n: string) => snapshotNode(n)?.kind === 'source'; const isManaged = (n: string) => snapshotNode(n)?.kind === 'loader'; const selection = @@ -1293,7 +1317,7 @@ export class MockOperate { ? resolution.nodes.filter(isManaged) : resolution.nodes; const empty = { seed: 'the selectors match no seeds in the current publication', load: 'the selectors match no managed sources in the current publication' } as Partial>; - if (!selection.length) return refused(empty[parts.verb] ?? 'no sources are selected or upstream of the selection'); + if (!selection.length && !(audits.length && parts.verb === 'build')) return refused(empty[parts.verb] ?? 'no sources are selected or upstream of the selection'); const writable = selection.filter((n) => !isSource(n)); const writeSet = parts.verb === 'build' @@ -1325,7 +1349,7 @@ export class MockOperate { ]; return { verb: parts.verb, - selection, + selection: [...selection, ...audits], writeSet, settings, permissions, diff --git a/ui/src/lib/api/mock/operate.ts b/ui/src/lib/api/mock/operate.ts index 0fb76c53fe..a5c56ad915 100644 --- a/ui/src/lib/api/mock/operate.ts +++ b/ui/src/lib/api/mock/operate.ts @@ -27,6 +27,7 @@ import { DISCOVERED_PLANS } from './discovered'; import { BIG_GROUP, bigGroupFile, bigGroupSelect, bigGroupShape } from './big-group'; import { resolveSelection, setJobResolver, writeSetOf } from './operate-graph'; import type { RunEnd, RunRecord, RunScript } from './run-detail'; +import { NOT_RUN_AUDIT_RUN_ID, SEED_AUDIT_JOB, SEED_AUDIT_RUN_ID } from './seed-audit-run'; const MIN = 60_000; export const IMAGE_ID = 'sha256:4be1c0d97e2a51f3c6a8b0e9d4f7a2c1e5b8d3f6a9c2e7b4d1f8a5c3e6b9d2f4'; @@ -149,6 +150,33 @@ export const JOB_DEFS: JobDef[] = [ description="Every model of the shop, daily", select="path:models", owner="data-platform", +)` + ) + }, + { + key: 'load_reference', + kind: 'job', + description: 'Reference seeds', + select: 'kind:seed', + exclude: [], + members: [], + overlap: 'queue', + onFailure: null, + pools: {}, + priority: 0, + sourceFile: 'orchestration/jobs.py', + settings: { '--concurrency': '8' }, + targets: null, + owner: 'data-platform', + criticalNodes: [], + declaration: decl( + 'orchestration/jobs.py', + 31, + `load_reference = job( + "load_reference", + description="Reference seeds", + select="kind:seed", + owner="data-platform", )` ) }, @@ -929,6 +957,7 @@ export function createOperateFixtures(now: number): OperateFixtures { rerunOfRunId: seed.rerunOf ?? null, memberAttempt: null, narrowing: null, + command: null, window: null, requestedBy: seed.by, priority: seed.priority ?? job?.priority ?? 0, @@ -990,6 +1019,10 @@ export function createOperateFixtures(now: number): OperateFixtures { return (now - t) / MIN - delaySec / 60; }; + // Every seed built, then an end-of-build audit failed (seed-audit-run.ts). + record({ id: SEED_AUDIT_RUN_ID, origin: 'manual', job: SEED_AUDIT_JOB, by: DEMO_USER, queuedAgo: 7.3, startedAgo: 7.2, durationMin: 34 / 60, end: 'check_failed', reason: 'worker executor completed and closed its connections' }); + // The same job once audits with missing reads are not run: it succeeds, its audit not run. + record({ id: NOT_RUN_AUDIT_RUN_ID, origin: 'manual', job: SEED_AUDIT_JOB, by: DEMO_USER, queuedAgo: 5.1, startedAgo: 5, durationMin: 34 / 60 }); record({ id: 'run-9d21', origin: 'manual', job: 'core_build', by: OPS_USER, queuedAgo: 3.2, startedAgo: 3, durationMin: 9, running: true, warn: ['stg_payments'] }); record({ id: 'run-6b02', origin: 'sensor', job: 'load_sources', trigger: 'partner_feed_poll', runKey: 'orders_part_0412.csv', by: SENSOR_DAEMON, queuedAgo: 7.5, startedAgo: 7.2, durationMin: 12, running: true, cancel: { requestedAgoSec: 20, by: OPS_USER, sigtermAgoSec: 19, done: false } }); record({ id: 'run-6a90', origin: 'schedule', job: 'activity_microbatch', trigger: 'activity_microbatch', tick: 2, by: SCHEDULER, queuedAgo: at('activity_microbatch', 2, 0), startedAgo: at('activity_microbatch', 2, 6), durationMin: 60, running: true, lastHeartbeatAgoSec: 95 }); @@ -1243,7 +1276,7 @@ export function createOperateFixtures(now: number): OperateFixtures { cursorBefore: `run_event:${4000 + i * 37}`, cursorAfter: `run_event:${4037 + i * 37}`, runRequests: ok ? 1 : 0, - skipReason: ok ? null : `${b.run.id} was partial; on-success conditions don't fire on partial runs` + skipReason: ok ? null : `${b.run.id} failed; on-success conditions don't fire on failed runs` }) ); if (ok && runId) reqs.push({ runKey: b.run.id, runId, evaluationId, requestedAt: new Date(t).toISOString(), runStatus: 'success' }); diff --git a/ui/src/lib/api/mock/platform.ts b/ui/src/lib/api/mock/platform.ts index c9caa7b496..34c8ba43d2 100644 --- a/ui/src/lib/api/mock/platform.ts +++ b/ui/src/lib/api/mock/platform.ts @@ -6,6 +6,9 @@ import { CAPABILITIES } from '../types'; import type { PlatformApi } from '../platform-client'; import type { LocalChangeBus } from '../signals'; import type { + HealthComponent, + HealthComponentDetails, + ServerHealth, AccessDecision, AccessExplanation, AccessOverview, @@ -640,6 +643,32 @@ export class MockPlatformApi implements PlatformApi { // ---- health ---- + /** Every part working; a browser test fakes an outage through the server client instead. */ + async readHealth(): Promise { + const { now } = this.#ctx; + const at = new Date(now).toISOString(); + const started = new Date(now - 2 * 1440 * MIN).toISOString(); + const healthy = (component: HealthComponent['component'], name: string, locationId: string | null = null): HealthComponent => ({ + component, name, locationId, status: 'healthy', since: started, reason: null, case: null, lastSuccess: at, lastFailure: null + }); + return this.#ctx.reply({ + status: 'healthy', + checkedAt: at, + retrySeconds: 10, + server: { version: this.#ctx.serverVersion, startedAt: started, uptimeSeconds: 2 * 86_400 }, + components: [ + healthy('server', 'Server'), + healthy('control_database', 'Control database'), + healthy('scheduler', 'Scheduler'), + ...this.#ctx.locations.map((l) => healthy('location', l.name, l.id)) + ] + }); + } + + async readHealthDetails(): Promise { + return this.#ctx.reply([{ component: 'control_database', locationId: null, host: 'control-db.internal:5432', errorChain: [], requestIds: [] }]); + } + async platformHealth(): Promise { const { now, events } = this.#ctx; const ago = (minutes: number) => new Date(now - minutes * MIN).toISOString(); diff --git a/ui/src/lib/api/mock/run-detail.ts b/ui/src/lib/api/mock/run-detail.ts index 26ab80c4c8..7f9ff363fb 100644 --- a/ui/src/lib/api/mock/run-detail.ts +++ b/ui/src/lib/api/mock/run-detail.ts @@ -2,6 +2,7 @@ // output) from its record and the clock, the way the server projects it from // facts. Pure: the same record and clock always give the same detail. +import { NOT_RUN_AUDIT_RUN_ID, SEED_AUDIT_RUN_ID, seedAuditExecution } from './seed-audit-run'; import type { RunEventCheck, CancelProgress, @@ -41,7 +42,8 @@ const finishedRows = (key: string, ms: number): number | null => { }; /** `crashed`: the worker stopped before building anything, as when its plan is refused; `crashError` says why. */ -export type RunEnd = 'complete' | 'cancelled' | 'presumed_failed' | 'never_started' | 'crashed'; +/** `check_failed`: every node built, then an end-of-build check failed the run. */ +export type RunEnd = 'complete' | 'cancelled' | 'presumed_failed' | 'never_started' | 'crashed' | 'check_failed'; export type RunScript = { verb: LaunchVerb; @@ -187,7 +189,7 @@ export function computeNodes(record: RunRecord, siblings: RunRecord[], now: numb ...(fails ? (CHECK_FAILS.has(key) ? checkFailureDetail(key) : python ? pythonFailureDetail() : failureDetail(key, run, message ?? '')) : {}) }; }; - if (terminal && script.end === 'complete') return finish(); + if (terminal && (script.end === 'complete' || script.end === 'check_failed')) return finish(); if (e <= clock) return finish(); if (s <= clock) { // A prototype run reports rows so far while a node builds, for the timeline bar and the drawer. @@ -310,20 +312,20 @@ export function countNodes(nodes: RunNode[]): NodeCounts { return c; } -/** Terminal status from node outcomes: partial when something failed and everything else completed. */ +/** Terminal status from node outcomes: failed whenever anything failed; the counts say how much built. */ export function deriveTerminalStatus(end: RunEnd, nodes: RunNode[]): RunStatus { - if (end === 'never_started' || end === 'crashed') return 'failed'; + if (end === 'never_started' || end === 'crashed' || end === 'check_failed') return 'failed'; if (end === 'cancelled') return 'cancelled'; if (end === 'presumed_failed') return 'presumed_failed'; const c = countNodes(nodes); const blocked = c.failed + nodes.filter((n) => n.skippedBecauseOf).length; - if (blocked) return c.success + c.warn > 0 ? 'partial' : 'failed'; + if (blocked) return 'failed'; return c.warn ? 'warn' : 'success'; } export function statusReason(status: RunStatus, nodes: RunNode[]): string | null { const c = countNodes(nodes); - if (status === 'partial') + if (status === 'failed' && c.success + c.warn > 0 && (c.failed || nodes.some((n) => n.skippedBecauseOf))) return c.failed ? `${c.failed} node${c.failed === 1 ? '' : 's'} failed and ${c.skipped} that depend on ${c.failed === 1 ? 'it' : 'them'} were skipped; the other ${c.success + c.warn} finished` : `${c.skipped} node${c.skipped === 1 ? '' : 's'} skipped because something they depend on failed; the other ${c.success + c.warn} finished`; @@ -435,7 +437,7 @@ export function sqlRecorded(statementId: string): boolean { export function execution(record: RunRecord, nodes: RunNode[], now?: number): RunExecution { const { run, script } = record; - type Draft = Omit & { producer?: RunEvent['producer'] }; + type Draft = Omit & { producer?: RunEvent['producer']; level?: RunEventLevel; check?: RunEventCheck }; const drafts: Draft[] = []; const statements: RunStatement[] = []; const output: RunOutputLine[] = []; @@ -457,7 +459,9 @@ export function execution(record: RunRecord, nodes: RunNode[], now?: number): Ru } if (script.cancel) fact('cancel_requested', script.cancel.requestedAt, `Cancel requested by ${script.cancel.requestedBy.displayName}`); - if (inv && run.startedAt && PROTO.test(run.id)) { + if (inv && run.startedAt && run.endedAt && (run.id === SEED_AUDIT_RUN_ID || run.id === NOT_RUN_AUDIT_RUN_ID)) { + seedAuditExecution(Date.parse(run.startedAt), Date.parse(run.endedAt), nodes, { push: (d) => drafts.push(d), statements, output, inv, runId: run.id, command: commandOf(record), notRun: run.id === NOT_RUN_AUDIT_RUN_ID }); + } else if (inv && run.startedAt && PROTO.test(run.id)) { protoExecution(record, nodes, now ?? Date.now(), { ev, out, statements, inv }); } else if (inv && run.startedAt) { const start = Date.parse(run.startedAt); @@ -549,18 +553,19 @@ export function execution(record: RunRecord, nodes: RunNode[], now?: number): Ru producer: d.producer ?? 'sqb', type: d.type, occurredAt: d.occurredAt, - level: - d.type === 'audit_completed' && /\(severity error\)$/.test(d.message) + level: d.level ?? + (d.type === 'audit_completed' && /\(severity error\)$/.test(d.message) ? 'error' : (d.type === 'audit_completed' && /\(severity warn\)$/.test(d.message)) || (d.type === 'node_log' && d.message.startsWith('[warning] ')) ? 'warn' - : LEVEL[d.type], + : LEVEL[d.type]), invocationId: d.invocationId, nodeKey: d.nodeKey, statementId: d.statementId, attempt: d.attempt, message: d.message, - ...(d.type === 'audit_completed' ? { check: mockCheck(d.message) } : {}) + ...(d.type === 'audit_completed' ? { check: d.check ?? mockCheck(d.message) } : {}), + ...(d.phase ? { phase: d.phase } : {}) })); return { events, statements, output: output.sort((a, b) => a.at.localeCompare(b.at)) }; } diff --git a/ui/src/lib/api/mock/seed-audit-run.ts b/ui/src/lib/api/mock/seed-audit-run.ts new file mode 100644 index 0000000000..3085fa7fe6 --- /dev/null +++ b/ui/src/lib/api/mock/seed-audit-run.ts @@ -0,0 +1,99 @@ +// A mock run that failed on an end-of-build singular audit after every node built: the audit reads two +// models never built in the target, so its query fails with 42S02. + +import type { RunEvent, RunEventCheck, RunEventLevel, RunEventPhase, RunNode, RunOutputLine, RunStatement } from '../types'; + +export const SEED_AUDIT_RUN_ID = 'run-pa93'; +/** The same job run since audits whose reads the target lacks are not run: it succeeds, with the audit not run. */ +export const NOT_RUN_AUDIT_RUN_ID = 'run-nr41'; +export const SEED_AUDIT_JOB = 'load_reference'; +export const SEED_AUDIT_CHECK = 'orders_match_payments'; +/** The audit's ID on the Checks page. */ +export const SEED_AUDIT_BINDING = 'chk-end-orders-payments'; +export const SEED_AUDIT_CHECK_FILE = 'sql/audits/singular/orders_match_payments.sql'; +/** The two models the audit reads; no run builds them in the mock project. */ +export const UNBUILT_INPUTS = ['fct_order_payments', 'fct_payment_totals'] as const; +const DATABASE = 'WAFFLE_SHOP'; + +export const ORDERS_MATCH_PAYMENTS_SQL = `SELECT o.order_id, o.amount_cents, p.amount_cents AS paid_cents +FROM "${DATABASE}"."RECONCILIATION"."FCT_ORDER_PAYMENTS" o +LEFT JOIN "${DATABASE}"."RECONCILIATION"."FCT_PAYMENT_TOTALS" p ON p.order_id = o.order_id +WHERE p.order_id IS NULL OR p.amount_cents <> o.amount_cents`; + +/** How the server lists the audit's failed query: its error's type and code, never its text. */ +const WIRE_ERROR = 'ProgrammingError: 002003'; +export const MISSING_OBJECT_ERROR = `002003 (42S02): SQL compilation error:\nObject '${DATABASE}.RECONCILIATION.FCT_ORDER_PAYMENTS' does not exist or not authorized.`; + +type Draft = Omit & { producer?: RunEvent['producer']; level?: RunEventLevel; check?: RunEventCheck }; +type Emit = { push: (d: Draft) => void; statements: RunStatement[]; output: RunOutputLine[]; inv: string; runId: string; command: string; notRun?: boolean }; + +const iso = (ms: number) => new Date(ms).toISOString(); + +/** What the run's worker did and printed: preparation, its seed loads, then the failed end-of-build audit. */ +export function seedAuditExecution(start: number, end: number, nodes: readonly RunNode[], { push, statements, output, inv, runId, command, notRun = false }: Emit): void { + const ev = (type: Draft['type'], at: number, message: string, extra: Partial = {}) => + push({ type, occurredAt: iso(at), invocationId: inv, nodeKey: null, statementId: null, attempt: null, message, ...extra }); + const out = (stream: RunOutputLine['stream'], at: number, text: string, error = false) => output.push({ invocationId: inv, stream, at: iso(at), text, error }); + const phase = (at: number, p: RunEventPhase) => ev('invocation_phase', at, p.phase, { phase: p }); + const statement = (s: Omit) => + statements.push({ ...s, runId, invocationId: inv, sequence: statements.length + 1, rowsSoFar: null, sqlRecorded: true }); + + ev('invocation_started', start, command); + out('stdout', start + 100, `sqb ${command.replace(/^sqb /, '')}`); + phase(start + 900, { phase: 'discovered', durationMs: 780, count: null, name: null, detail: null }); + phase(start + 2_300, { phase: 'compiled', durationMs: 1_400, count: nodes.length, name: null, detail: null }); + phase(start + 2_500, { phase: 'matched', durationMs: 120, count: null, name: 'generation 42', detail: null }); + phase(start + 3_100, { phase: 'connected', durationMs: 560, count: 1, name: 'snowflake', detail: null }); + phase(start + 3_900, { phase: 'inspected', durationMs: 780, count: null, name: null, detail: null }); + phase(start + 4_100, { phase: 'planned', durationMs: 190, count: nodes.length, name: null, detail: null }); + phase(start + 4_200, { phase: 'started_execution', durationMs: null, count: 8, name: null, detail: null }); + out('stdout', start + 4_200, `✓ Project compiled ${nodes.length} seeds 1.4s`); + out('stdout', start + 4_250, `Building ${nodes.length} nodes, 8 at a time`); + + for (const n of nodes) { + if (!n.startedAt || !n.endedAt) continue; + const s = Date.parse(n.startedAt); + const e = Date.parse(n.endedAt); + const id = `stmt-pa93-${n.nodeKey}`; + ev('resource_attempt_started', s, `Started seed ${n.nodeKey}`, { nodeKey: n.nodeKey, attempt: 1 }); + statement({ id, nodeKey: n.nodeKey, kind: 'load_seed', status: 'completed', startedAt: iso(s + 40), endedAt: iso(e - 60), rowsAffected: n.rowsAffected, error: null, queryId: `01b8e2a1-0000-4c1f-0000-${n.nodeKey.length.toString(16).padStart(4, '0')}` }); + ev('statement_completed', e - 60, `${(n.rowsAffected ?? 0).toLocaleString('en-GB')} rows`, { nodeKey: n.nodeKey, statementId: id, attempt: 1 }); + ev('resource_attempt_completed', e, `Completed in ${((e - s) / 1000).toFixed(1)}s`, { nodeKey: n.nodeKey, attempt: 1 }); + out('stdout', e, ` ✓ ${n.nodeKey} seed ${((e - s) / 1000).toFixed(1)}s`); + } + + const auditAt = end - 2_400; + if (notRun) { + // Its reads don't exist in the target, so the audit is not run and the run succeeds. + const reason = `reads ${UNBUILT_INPUTS.join(', ')}, which don't exist in the target`; + ev('audit_completed', auditAt, reason, { level: 'info', check: { name: SEED_AUDIT_CHECK, outcome: 'not-run', rows: null, bindingKey: SEED_AUDIT_BINDING, resultId: null } }); + out('stdout', auditAt, ` audit ${SEED_AUDIT_CHECK} NOT RUN 0.00s`); + ev('invocation_completed', end - 400, `${nodes.length} built · 1 audit not run`); + out('stdout', end - 400, `✓ Completed successfully PASS=${nodes.length} NOT_RUN=1`); + return; + } + // The end-of-build singular audit: its query can't run, as the models it reads were never built here. + const auditId = 'stmt-pa93-audit-orders_match_payments'; + statement({ id: auditId, nodeKey: '', kind: 'audit', status: 'failed', startedAt: iso(auditAt - 350), endedAt: iso(auditAt), rowsAffected: null, queryId: '01b8e2a3-0000-4c1f-0000-00000000a93e', error: WIRE_ERROR }); + ev('statement_failed', auditAt, WIRE_ERROR, { statementId: auditId }); + // As the server lists them: no error text in events or statements, only its type and code; the + // audit's error is read from its result (build.ts getCheckEvidence), behind view.evidence. + ev('audit_completed', auditAt + 20, 'error', { + statementId: auditId, + level: 'error', + check: { name: SEED_AUDIT_CHECK, outcome: 'failed', rows: null, bindingKey: SEED_AUDIT_BINDING, resultId: null } + }); + out('stderr', auditAt + 20, ` ✗ audit ${SEED_AUDIT_CHECK} ${MISSING_OBJECT_ERROR.replace('\n', ' ')}`, true); + ev('invocation_failed', end - 400, `${nodes.length} built · 0 failed · 0 skipped · 1 audit failed`); + out('stderr', end - 400, `✗ Completed with errors ${nodes.length} built · 1 audit failed`, true); + // The worker's own housekeeping line, which today's page shows as the run's reason. + out('stdout', end - 200, 'worker executor completed and closed its connections'); +} + +/** The SQL of the mock run's own statements: the audit's query and the seed loads. */ +export function seedAuditSql(st: RunStatement): string | null { + if (st.runId !== SEED_AUDIT_RUN_ID) return null; + if (st.kind === 'audit') return ORDERS_MATCH_PAYMENTS_SQL; + if (st.kind === 'load_seed') return `COPY INTO ${DATABASE}.REFERENCE.${st.nodeKey.toUpperCase()} FROM @sqlbuild_seeds/${st.nodeKey}.csv`; + return null; +} diff --git a/ui/src/lib/api/platform-client.ts b/ui/src/lib/api/platform-client.ts index 29d8eb207e..2095bb8419 100644 --- a/ui/src/lib/api/platform-client.ts +++ b/ui/src/lib/api/platform-client.ts @@ -20,6 +20,8 @@ import type { PlatformEventQuery, PlatformEventRecord, PlatformHealth, + ServerHealth, + HealthComponentDetails, ProviderConnection, RoleAssignment, RoleAssignmentRequest, @@ -44,6 +46,10 @@ export interface PlatformApi { // ---- server status and problems (shown on Locations) ---- /** Scheduler, server replicas, heartbeat and event forwarding. */ platformHealth(): Promise; + /** The server's own health, read without signing in; it answers while the control database is unreachable. */ + readHealth(): Promise; + /** Where the control database is, each cause and the failed requests, for people who may manage people. */ + readHealthDetails(): Promise; /** Problems recorded as platform events, newest first; by location, or server-wide with `locationId: null`. */ listPlatformEventHistory(query?: PlatformEventQuery): Promise; diff --git a/ui/src/lib/api/types.ts b/ui/src/lib/api/types.ts index 04d3b4166e..24b0822885 100644 --- a/ui/src/lib/api/types.ts +++ b/ui/src/lib/api/types.ts @@ -78,6 +78,8 @@ export type WarehouseSync = { syncing?: { position: number; kinds: number; table: string; rows: number } | null; /** The newest completed sync among recent reports; null when none completed in them. */ completed?: { at: Iso; kinds: number; rows: number; elapsedMs: number } | null; + /** While the newest report is a failure: since when, why, and how it retries; null while the sync works. */ + failing?: { since: Iso; reason: string; halted: boolean; unreachable: boolean; retrySeconds: number | null; retryAt: Iso | null } | null; }; /** The one target a location is deployed against, e.g. `prod` on Snowflake. */ @@ -135,6 +137,8 @@ export type PlatformEventKind = | 'launch_failed' | 'connection_test_failed' | 'warehouse_sync_failed' + | 'event_sink_failed' + | 'event_forwarding_failed' | 'heartbeat'; export type PlatformEventSeverity = 'info' | 'warning' | 'critical'; export type PlatformEvent = { @@ -154,6 +158,8 @@ export type PlatformEvent = { * stopped scheduler's expired lease or a broken location's last check-in. */ occurrence?: string; + /** A failing run-history sync: whether failed reads stopped it, so Resume restarts it, and when it tries again. */ + sync?: { halted: boolean; unreachable: boolean; retrySeconds: number | null; retryAt: Iso | null; lastSuccessAt: Iso | null }; }; // ---- navigation ---- diff --git a/ui/src/lib/api/types/build.ts b/ui/src/lib/api/types/build.ts index c8167c6282..aed5b1137b 100644 --- a/ui/src/lib/api/types/build.ts +++ b/ui/src/lib/api/types/build.ts @@ -338,6 +338,8 @@ export type CheckEvidence = { /** JSON cells: scalars, or objects and arrays from structured warehouse columns. */ rows: unknown[][]; truncated: boolean; + /** The warehouse's error when the audit's query could not run, SQLSTATE included; null when it ran. */ + executionError: string | null; }; // ---- change feed (snapshot diffs per deploy) ---- @@ -444,7 +446,7 @@ export type AttentionItem = export type OverviewMetrics = { models: { total: number; addedThisWeek: number; removedThisWeek: number }; - runs24h: { total: number; success: number; warn: number; partial: number; failed: number; active: number }; + runs24h: { total: number; success: number; warn: number; failed: number; active: number }; checks: CheckCounts; /** Distinct stale nodes, and how many are changed or behind (a node can be both); null when the server reports no project-wide build state, and `sources` null when source freshness is not checked. */ stale: { nodes: number; changed: number; behind: number; sources: number | null } | null; diff --git a/ui/src/lib/api/types/operate.ts b/ui/src/lib/api/types/operate.ts index d4712122ad..2cce4e1a35 100644 --- a/ui/src/lib/api/types/operate.ts +++ b/ui/src/lib/api/types/operate.ts @@ -15,7 +15,6 @@ export const RUN_STATUSES = [ 'unresponsive', 'success', 'warn', - 'partial', 'failed', 'cancelled', 'skipped', @@ -74,6 +73,8 @@ export type Run = { memberAttempt: number | null; /** How a person narrowed this run of a job, as typed; null when it runs the whole job. */ narrowing: { select: string[]; exclude: string[] } | null; + /** An ad-hoc run's command as typed, as the argument tokens after `sqb`; null for every other run. */ + command: string[] | null; /** The cursor window a backfill processes, inclusive; null for every other run. */ window: { start: string; end: string } | null; requestedBy: Principal; @@ -112,7 +113,7 @@ export type RunListQuery = { // ---- runs list (cursor-paged rows with a plain status line) ---- -/** Status tabs of the runs list. `active` is queued, launched, running or unresponsive; `failed` includes partial and lost runs. */ +/** Status tabs of the runs list. `active` is queued, launched, running or unresponsive; `failed` includes lost runs. */ export const RUN_TABS = ['all', 'active', 'queued', 'failed', 'cancelled'] as const; export type RunTab = (typeof RUN_TABS)[number]; @@ -316,7 +317,8 @@ export type RunEventPhase = { /** A check's result in a run: its name as declared, its outcome, the rows it found, and its identity for its evidence. */ export type RunEventCheck = { name: string; - outcome: 'passed' | 'warned' | 'failed' | 'skipped'; + /** `not-run`: an end-of-build audit whose reads the target doesn't have; its event's message says which. */ + outcome: 'passed' | 'warned' | 'failed' | 'skipped' | 'not-run'; rows: number | null; /** The check's ID on the Checks page and this result's, to read the rows it found once they are synced. */ bindingKey: string | null; @@ -742,7 +744,10 @@ export type SelectionProblem = { /** What `sqb build --select … --exclude …` selects in the current publication: one page of keys and the total. */ export type SelectionEvaluation = { snapshotId: string | null; + /** Every selected node and audit. */ count: number; + /** How many of them are audits (`audit:[:…]` keys). */ + audits: number; keys: string[]; nextOffset: number | null; error: SelectionProblem | null; @@ -761,6 +766,8 @@ export type SelectionVocabulary = { sources: VocabularyEntry[]; seeds: VocabularyEntry[]; kinds: VocabularyEntry[]; + /** Audit names an `audit:` selector takes, counting the targets each is attached to. */ + audits: VocabularyEntry[]; }; // ---- ad-hoc runs (the plan page) ---- @@ -1054,7 +1061,7 @@ export type RerunMode = 'all' | 'from_failure' | 'selected'; /** What a schedule tick or sensor request does while a run of the job is active; people's runs always queue. */ export type OverlapPolicy = 'queue' | 'skip'; -/** A job's `[retry]`: a failed or partial run reruns from failure up to `retries` times (`attempts` is one more, counting the first run), `retryDelaySeconds` (`delay_seconds`) after the last ended. */ +/** A job's `[retry]`: a failed run reruns from failure up to `retries` times (`attempts` is one more, counting the first run), `retryDelaySeconds` (`delay_seconds`) after the last ended. */ export type OnFailure = { retries: number; retryDelaySeconds: number }; export type JobKind = 'job' | 'group'; diff --git a/ui/src/lib/api/types/platform.ts b/ui/src/lib/api/types/platform.ts index c591f3980c..453f839e03 100644 --- a/ui/src/lib/api/types/platform.ts +++ b/ui/src/lib/api/types/platform.ts @@ -670,3 +670,38 @@ export type ServerSettings = { schedulerEnabled: boolean; retention: RetentionSetting[]; }; + +/** How a part of the server, or the server as a whole, stands. */ +export type HealthStatus = 'healthy' | 'degraded' | 'unavailable'; +/** Which kind of control database failure a reason describes. */ +export type ControlCauseCase = 'name_lookup' | 'unreachable' | 'login_rejected' | 'no_free_connections' | 'restarting' | 'pool_exhausted' | 'locked' | 'other'; +export type HealthComponentKind = 'server' | 'control_database' | 'scheduler' | 'location' | 'event_forwarding'; + +/** One part of the server as anyone may see it, read from the server's memory. */ +export type HealthComponent = { + component: HealthComponentKind; + /** "Control database", "Scheduler", or a location's name. */ + name: string; + locationId: string | null; + status: HealthStatus; + /** When it stopped being healthy, or since when it has been. */ + since: string | null; + reason: string | null; + case: ControlCauseCase | null; + /** When it last worked; for a location, its last report. */ + lastSuccess: string | null; + lastFailure: string | null; +}; + +/** `GET /api/health`, which answers without signing in and while the control database is unreachable. */ +export type ServerHealth = { + status: HealthStatus; + checkedAt: string; + /** How often to ask again while the server isn't healthy. */ + retrySeconds: number; + server: { version: string; startedAt: string; uptimeSeconds: number }; + components: HealthComponent[]; +}; + +/** What administrators see beside the health report. */ +export type HealthComponentDetails = { component: HealthComponentKind; locationId: string | null; host: string | null; errorChain: string[]; requestIds: string[] }; diff --git a/ui/src/lib/components/app-sidebar.svelte b/ui/src/lib/components/app-sidebar.svelte index ee483a46d7..972f591976 100644 --- a/ui/src/lib/components/app-sidebar.svelte +++ b/ui/src/lib/components/app-sidebar.svelte @@ -5,6 +5,10 @@ import logoForLight from '$website/src/assets/logo-light.png'; import { page } from '$app/state'; import SettingsIcon from '@lucide/svelte/icons/settings'; + import ActivityIcon from '@lucide/svelte/icons/activity'; + + /** While the server can't serve pages, every entry but Status is greyed: it would only show the same outage. */ + let { blocked = false }: { blocked?: boolean } = $props(); import { visibleNav, type NavBadge } from '$lib/nav'; import { app } from '$lib/state/app.svelte'; import { signOutFor } from '$lib/platform/sign-out'; @@ -61,7 +65,7 @@ {#each group.items as item (item.href)} {@const Glyph = item.icon} {@const count = item.badge && app.navCounts ? item.badge.value(app.navCounts) : 0} - + {item.label} {#if item.badge && count > 0} @@ -79,8 +83,14 @@
+ {#if app.client.supports('readHealth')} + + + Status + + {/if} {#if app.client.supports('serverSettings')} - + Settings @@ -111,4 +121,8 @@ .sb-nav { scrollbar-width: thin; } + .blocked { + pointer-events: none; + opacity: 0.45; + } diff --git a/ui/src/lib/components/app-topbar.svelte b/ui/src/lib/components/app-topbar.svelte index 22116c914f..0bdd2f629d 100644 --- a/ui/src/lib/components/app-topbar.svelte +++ b/ui/src/lib/components/app-topbar.svelte @@ -9,6 +9,9 @@ import { pageTitle } from '$lib/format/page-title'; import { app } from '$lib/state/app.svelte'; import PlatformEventBanner from './shell/platform-event-banner.svelte'; + import HealthBanner from './shell/health-banner.svelte'; + import { health } from '$lib/state/health.svelte'; + import { to } from '$lib/paths'; import WarehouseSyncStatus from './shell/warehouse-sync-status.svelte'; /** @@ -37,6 +40,20 @@ offline: 'Offline' }; + /** The server's own health decides the label once read: Live, Degraded or Unavailable; Live still says whether updates stream. */ + const healthTone: Record<'degraded' | 'unavailable', string> = { degraded: 'var(--sb-warning)', unavailable: 'var(--sb-error)' }; + const healthLabel: Record<'degraded' | 'unavailable', string> = { degraded: 'Degraded', unavailable: 'Unavailable' }; + const serverState = $derived(health.status === 'degraded' || health.status === 'unavailable' ? health.status : null); + const indicatorTone = $derived(serverState ? healthTone[serverState] : connectionTone[app.connection]); + const indicatorLabel = $derived(serverState ? healthLabel[serverState] : connectionLabel[app.connection]); + const indicatorTitle = $derived( + serverState === 'unavailable' + ? (health.outage?.reason ?? 'The server is unavailable.') + : serverState === 'degraded' + ? health.degraded.map((part) => `${part.name}: ${part.reason ?? 'degraded'}`).join('\n') + : connectionTitle[app.connection] + ); + const snapshot = $derived(app.snapshot); const where = $derived(app.location ? `${app.location.name} · ${app.location.target.name}` : '—'); @@ -49,14 +66,15 @@
- {connectionLabel[app.connection]} + {indicatorLabel} {#if snapshot !== undefined} · {snapshot ? `v${snapshot.generation} · ${formatAgo(snapshot.publishedAt, app.now)}` : 'Not deployed'} @@ -72,10 +90,12 @@
+ diff --git a/ui/src/lib/components/graph/graph-canvas.svelte b/ui/src/lib/components/graph/graph-canvas.svelte index 9b1dfbfde8..1eeaed1ffd 100644 --- a/ui/src/lib/components/graph/graph-canvas.svelte +++ b/ui/src/lib/components/graph/graph-canvas.svelte @@ -27,6 +27,8 @@ setViewport = $bindable(), readable = true, fitFloor = READABLE_ZOOM, + minFitZoom, + fitLabel, controls = 'fit', showLock = false, framed = false, @@ -48,6 +50,10 @@ readable?: boolean; /** The lowest zoom an automatic fit goes to: the readable zoom, unless a page draws a very large graph whole. */ fitFloor?: number; + /** The lowest zoom the readable fit (first view and Reset view) opens at, whatever the graph's size. */ + minFitZoom?: number; + /** The fit button's name: "Reset view" where it returns to the view the graph opened at. */ + fitLabel?: string; /** `fit`: zoom buttons with a readable fit; `full`: the library's own controls, for a very large graph drawn whole. */ controls?: 'fit' | 'full' | 'none'; showLock?: boolean; @@ -144,12 +150,12 @@
0} data-compact={level || undefined} data-stage={stage} style:--sb-inv={1 / settledZoom} style:--sb-title-unzoom={titleUnzoom} style:--sb-unzoom={controlScale} bind:this={element} onpointerdowncapture={onpointerdown} onpointermovecapture={onpointermove} onclickcapture={onclick}> - +
- {#if controls === 'fit'} fit?.()} {showLock} />{:else if controls === 'full'}{/if} + {#if controls === 'fit'} fit?.()} {showLock} label={fitLabel} />{:else if controls === 'full'}{/if} {@render children?.()}
@@ -176,8 +182,11 @@ .graph-canvas :global(.svelte-flow__controls-button svg) { fill: var(--muted-foreground); } - /* Compact cards: the card's lines keep their room, hidden, under its compact face. */ - .compact :global(:is(.svelte-flow__node-asset, .svelte-flow__node-folder, .svelte-flow__node-member) > * > :not(.cface)) { + /* Compact cards: the card's lines keep their room, hidden, under its compact face. At the name-only + stage a node card shows its own enlarged name instead, so only folders and member jobs go compact; + hiding a node card's lines there left it blank (the run graph opened on blank cards). */ + .compact:not([data-stage='name']) :global(:is(.svelte-flow__node-asset, .svelte-flow__node-folder, .svelte-flow__node-member) > * > :not(.cface)), + .compact[data-stage='name'] :global(:is(.svelte-flow__node-folder, .svelte-flow__node-member) > * > :not(.cface)) { visibility: hidden; } /* Edges, plain, highlighted or selected, are drawn beneath every card, so they never take a card's diff --git a/ui/src/lib/components/selection/selection-bar.svelte b/ui/src/lib/components/selection/selection-bar.svelte index 01ca14d29b..24b0eb4c13 100644 --- a/ui/src/lib/components/selection/selection-bar.svelte +++ b/ui/src/lib/components/selection/selection-bar.svelte @@ -16,7 +16,7 @@ import { noun } from '$lib/format/plural'; import { buildHref, copyCommand, problemParts, problemText, problemToken } from '$lib/selection/command'; import { parseSelection } from '$lib/selection/syntax'; - import type { NameEntry } from '$lib/selection/suggest'; + import type { NameEntry, SuggestionItem } from '$lib/selection/suggest'; import type { SelectionState } from '$lib/state/selection.svelte'; import SelectionField from './selection-field.svelte'; @@ -26,6 +26,7 @@ let { selection, names, + runs = [], total, build = true, copy: offerCopy = true, @@ -36,6 +37,8 @@ selection: SelectionState; /** Node names to suggest and pick. */ names: NameEntry[]; + /** Run selectors the field offers first, such as the rerun plan's `failed:+`. */ + runs?: SuggestionItem[]; /** Every node, for the count when nothing narrows. */ total: number; /** Offer Build these. */ @@ -101,6 +104,7 @@ placeholder="Select nodes: type, paste sqb syntax, or pick below" vocabulary={selection.vocabulary} {names} + {runs} recent={selection.recent} problem={selectProblem} onrecent={(r) => { @@ -113,7 +117,7 @@ {#if !selection.active}All {total.toLocaleString('en')} nodes {:else if problem}0 nodes - {:else if selection.evaluation}{selection.evaluation.count.toLocaleString('en')} {noun(selection.evaluation.count, 'node')} + {:else if selection.evaluation}{@const { count, audits } = selection.evaluation}{#if count - audits || !audits}{(count - audits).toLocaleString('en')} {noun(count - audits, 'node')}{/if}{#if count - audits && audits} · {/if}{#if audits}{audits.toLocaleString('en')} {noun(audits, 'audit')}{/if} {:else}—{/if} {#if offerCopy}{/if} diff --git a/ui/src/lib/components/selection/selection-field.svelte b/ui/src/lib/components/selection/selection-field.svelte index 627c4f3813..c480103f19 100644 --- a/ui/src/lib/components/selection/selection-field.svelte +++ b/ui/src/lib/components/selection/selection-field.svelte @@ -1,6 +1,7 @@ diff --git a/ui/src/lib/components/shell/health-banner.svelte b/ui/src/lib/components/shell/health-banner.svelte new file mode 100644 index 0000000000..0160cbdfb8 --- /dev/null +++ b/ui/src/lib/components/shell/health-banner.svelte @@ -0,0 +1,39 @@ + + +{#if line} + +{/if} + + diff --git a/ui/src/lib/components/shell/health-table.svelte b/ui/src/lib/components/shell/health-table.svelte new file mode 100644 index 0000000000..995680a94a --- /dev/null +++ b/ui/src/lib/components/shell/health-table.svelte @@ -0,0 +1,80 @@ + + +
+ `${part.component}:${part.locationId ?? ''}`} empty="No parts reported."> + {#snippet row(part)} + {@const detail = detailOf(part.component, part.locationId)} + + + {part.name} + {#if part.component === 'server'}v{report.server.version}{/if} + + {label[part.status]} + {part.since ? `${formatClock(part.since, app.now)} · ${formatAgo(part.since, app.now)}` : '—'} + + {part.reason ?? '—'} + {#if detail && (detail.host || detail.errorChain.length || detail.requestIds.length)} +
+ {#if detail.host}
Host {detail.host}
{/if} + {#each detail.errorChain as cause, i (i)}
{cause}
{/each} + {#if detail.requestIds.length}
Requests {#each detail.requestIds as id (id)}{id} {/each}
{/if} +
+ {/if} + + {part.component === 'server' ? `up ${formatAgo(report.server.startedAt, app.now).replace(/ ago$/, '')}` : part.lastSuccess ? formatAgo(part.lastSuccess, app.now) : 'Not yet'} + + {/snippet} +
+
+ + diff --git a/ui/src/lib/components/shell/outage-panel.svelte b/ui/src/lib/components/shell/outage-panel.svelte new file mode 100644 index 0000000000..a37eda8dd5 --- /dev/null +++ b/ui/src/lib/components/shell/outage-panel.svelte @@ -0,0 +1,46 @@ + + +
+

{page} isn't available

+ {#if outage} +

{outage.reason}

+

+ {#if outage.since}Since {formatClock(outage.since, app.now)} ({formatAgo(outage.since, app.now)}) · {/if}Checking again every {health.retrySeconds} s; this page loads by itself when the server is back. +

+ {/if} + {#if health.report} +
+ {/if} +
+ + diff --git a/ui/src/lib/components/shell/sync-line.test.ts b/ui/src/lib/components/shell/sync-line.test.ts new file mode 100644 index 0000000000..0fae0f5bed --- /dev/null +++ b/ui/src/lib/components/shell/sync-line.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest'; +import { syncLine } from './sync-line'; + +const failing = { since: '2026-11-25T17:42:00Z', reason: '250001 Could not connect to Snowflake backend', halted: false, unreachable: false, retrySeconds: 60, retryAt: '2026-11-25T18:30:00Z' }; + +describe('syncLine', () => { + it('says what stands, since when, how it retries and why', () => { + expect([ + syncLine(failing, '17:42'), + syncLine({ ...failing, unreachable: true }, '17:42'), + syncLine({ ...failing, halted: true, retrySeconds: null, retryAt: null }, '17:42') + ]).toEqual([ + 'Run history not syncing since 17:42 · retrying every 60 s · 250001 Could not connect to Snowflake backend', + "Run history can't reach the warehouse since 17:42 · retrying every 60 s · 250001 Could not connect to Snowflake backend", + 'Run history sync stopped since 17:42 · 250001 Could not connect to Snowflake backend' + ]); + }); +}); diff --git a/ui/src/lib/components/shell/sync-line.ts b/ui/src/lib/components/shell/sync-line.ts new file mode 100644 index 0000000000..fdf4c2e189 --- /dev/null +++ b/ui/src/lib/components/shell/sync-line.ts @@ -0,0 +1,9 @@ +import type { WarehouseSync } from '$lib/api'; + +/** The top bar's words for a failing run-history sync: what stands, since when (`since`, already formatted), how it retries, and why. */ +export function syncLine(failing: NonNullable, since: string): string { + if (failing.halted) return `Run history sync stopped since ${since} · ${failing.reason}`; + const what = failing.unreachable ? `Run history can't reach the warehouse since ${since}` : `Run history not syncing since ${since}`; + const retry = failing.retrySeconds ? ` · retrying every ${failing.retrySeconds} s` : ''; + return `${what}${retry} · ${failing.reason}`; +} diff --git a/ui/src/lib/components/shell/warehouse-sync-status.svelte b/ui/src/lib/components/shell/warehouse-sync-status.svelte index 21447e7cc4..cb7724eebc 100644 --- a/ui/src/lib/components/shell/warehouse-sync-status.svelte +++ b/ui/src/lib/components/shell/warehouse-sync-status.svelte @@ -1,13 +1,17 @@ -{sync ? text : 'Synced just now'} +{#if failing && app.location} + {text} +{:else} + {sync ? text : 'Synced just now'} +{/if} diff --git a/ui/src/routes/runs/[id]/check-list.svelte b/ui/src/routes/runs/[id]/check-list.svelte index 8fcd0e1930..fc32e25e72 100644 --- a/ui/src/routes/runs/[id]/check-list.svelte +++ b/ui/src/routes/runs/[id]/check-list.svelte @@ -54,8 +54,8 @@ } } const statementOf = (c: CheckResult) => statements.find((s) => s.id === c.statementId) ?? null; - const GLYPH = { failed: '✗', warned: '⚠', passed: '✓', skipped: '–' } as const; - const SEVERITY = { failed: 'error', warned: 'warn', passed: '', skipped: '' } as const; + const GLYPH = { failed: '✗', warned: '⚠', passed: '✓', skipped: '–', 'not-run': '○' } as const; + const SEVERITY = { failed: 'error', warned: 'warn', passed: '', skipped: '', 'not-run': '' } as const;
@@ -64,7 +64,7 @@
{GLYPH[c.outcome]} {c.name} - {c.outcome}{#if c.count != null}{` · ${c.count.toLocaleString('en-GB')} ${c.noun} (${SEVERITY[c.outcome]})`}{/if} + {c.outcome === 'not-run' ? `not run${c.reason ? ` · ${c.reason}` : ''}` : c.outcome}{#if c.count != null}{` · ${c.count.toLocaleString('en-GB')} ${c.noun} (${SEVERITY[c.outcome]})`}{/if} {#if c.statementId}{/if} {#if (c.outcome === 'failed' || c.outcome === 'warned') && c.statementId && app.client.getCheckSample}{/if} diff --git a/ui/src/routes/runs/[id]/details-drawer.svelte b/ui/src/routes/runs/[id]/details-drawer.svelte new file mode 100644 index 0000000000..e8670174ca --- /dev/null +++ b/ui/src/routes/runs/[id]/details-drawer.svelte @@ -0,0 +1,208 @@ + + +{#snippet copyable(value: string, label: string, shown: string = value)} + {shown} +{/snippet} + +{#if d && view.showDetails} + view.toggleDetails()}> + {#snippet header()} + Details +
Run {shortRunId(d.run.id)}{d.run.jobKey ? ` · ${d.run.jobKey}` : ''}
+ {/snippet} + + +
+ {#if p?.command}
Command
{@render copyable(p.command, 'Copy command')}
{/if} + {#if selection.length} +
Selection
+
+ {#if selection.length > 12}
{selection.length} nodes{selection.join(' ')}
{:else}{@render copyable(selection.join(' '), 'Copy selection')}{/if} + {#if p?.exclude.length} excluding {p.exclude.join(' ')}{/if} +
+ {/if} + {#if p} +
Project
+
Version {p.snapshotGeneration}{#if p.gitDirty} · uncommitted changes{/if}
+ {#if p.gitRevision}
Commit
{@render copyable(p.gitRevision, 'Copy commit')}
{/if} +
Snapshot
{@render copyable(p.snapshotId, 'Copy snapshot ID')}
+ {/if} +
Run ID
{@render copyable(d.run.id, 'Copy run ID')}
+
+
+ + +
+ {#if d.liveness} +
Worker
+
+ {@render copyable(d.liveness.workerInstance ?? '—', 'Copy worker')} + {#if d.liveness.lastHeartbeatAt}
Last heartbeat {formatAgo(d.liveness.lastHeartbeatAt, app.now)}
{/if} +
+ {#if d.liveness.containerId}
Container
{@render copyable(d.liveness.containerId, 'Copy container ID')}
{/if} + {/if} + {#if p}
{p.imageId ? 'Image' : 'sqb'}
{#if p.imageId}{@render copyable(p.imageId, 'Copy image', shortImage(p.imageId))}
sqb {p.sqbVersion}
{:else}{p.sqbVersion}{/if}
{/if} + {#if d.invocations.length === 1} + {@const inv = d.invocations[0]} +
Invocation
+
{@render copyable(inv.invocationId, 'Copy invocation ID')}
{formatDuration(inv.startedAt, inv.endedAt, app.now)}{inv.exitCode != null ? ` · exit ${inv.exitCode}` : ''}
+ {/if} +
+ {#if d.invocations.length > 1} + + inv.invocationId} empty="No invocations."> + {#snippet row(inv)} + + {inv.invocationId} + {inv.attempt} + {formatStamp(inv.startedAt)} + {inv.exitCode ?? '—'} + + {/snippet} + + {/if} +
+ + +
+ {#if view.cost && view.cost.status !== 'none'}
Cost
{/if} +
Priority
{d.run.priority}
+
Rebuilds history
{d.run.rewriteHistory ? 'Yes' : 'No'}
+
Queued
{formatStamp(d.run.queuedAt)}
+ {#if d.run.tickScheduledFor}
Scheduled for
{formatStamp(d.run.tickScheduledFor)}
{/if} + {#if d.run.runKey}
Sensor run key
{@render copyable(d.run.runKey, 'Copy run key')}
{/if} + {#if related.length} +
Related runs
+
+ +
+ {/if} +
+
+
+{/if} + + diff --git a/ui/src/routes/runs/[id]/failure-summary.svelte b/ui/src/routes/runs/[id]/failure-summary.svelte new file mode 100644 index 0000000000..8925cee727 --- /dev/null +++ b/ui/src/routes/runs/[id]/failure-summary.svelte @@ -0,0 +1,199 @@ + + +{#snippet full(f: RunFailure)} + {@const inputs = unbuilt(f)} + {@const st = f.statementId ? view.statements.find((s) => s.id === f.statementId) : undefined} +
+
+ {#if f.code}
Code
{f.code}
{/if} + {#if f.message}
Message
{errorLine(f.message)}
{:else if !app.can('view.evidence')}
Message
Needs the view.evidence permission
{/if} + {#if inputs.length}
Not built in {target}
{#each inputs as key, i (key)}{#if i}{', '}{/if}{key}{/each}
{/if} +
+
+ {#if st}{/if} + + {#if f.checkId}Open the audit{:else if f.kind === 'node' && f.nodeKey}{/if} + {#if f.message}{/if} +
+ {#if st && queryOpen.has(f.id)}
view.showStatement(st.id, st.nodeKey)} />
{/if} +
+{/snippet} + +{#if first} +
+ + + {#if open} + {@render full(first)} + {#if failures.length > 1} +
    + {#each failures.slice(1) as f (f.id)} +
  • + + + {#if restOpen === f.id}{@render full(f)}{/if} +
  • + {/each} +
+ {/if} + {/if} +
+{/if} + + diff --git a/ui/src/routes/runs/[id]/log-filter.svelte b/ui/src/routes/runs/[id]/log-filter.svelte index aa63de2687..29451883f4 100644 --- a/ui/src/routes/runs/[id]/log-filter.svelte +++ b/ui/src/routes/runs/[id]/log-filter.svelte @@ -1,5 +1,6 @@ @@ -69,6 +82,7 @@ onblur={() => setTimeout(() => (open = false), 120)} {onkeydown} /> + {#if value}{/if} {#if open && suggestions.length}
- +
diff --git a/ui/src/routes/runs/[id]/run-header.svelte b/ui/src/routes/runs/[id]/run-header.svelte index a1e7faac17..111ff3c63c 100644 --- a/ui/src/routes/runs/[id]/run-header.svelte +++ b/ui/src/routes/runs/[id]/run-header.svelte @@ -6,13 +6,17 @@ import { formatAgo, formatDuration, formatStamp } from '$lib/format/time'; import { narrowingText, shortRunId } from '$lib/operate/labels'; import { app } from '$lib/state/app.svelte'; + import { runsNamed } from '$lib/selection/command'; import { runKindLabel, runOriginLabel } from '$lib/status'; import RunSummary from './run-summary.svelte'; + import RerunMenu from './rerun-menu.svelte'; + import PanelRightIcon from '@lucide/svelte/icons/panel-right'; import { retriedMembers } from './utils'; import type { RunDetailState } from './state.svelte'; let { view, runId }: { view: RunDetailState; runId: string } = $props(); + const run = $derived(view.run); const what = $derived(run?.jobKey ?? (view.detail?.selection.join(' ') || 'whole project')); const cancelRequested = $derived(!!view.detail?.cancel && !view.detail.cancel.terminatedAt); @@ -20,6 +24,10 @@ /** A group's member that never started: "not started", never "skipped". */ const notStarted = $derived(!!run?.parentRunId && run.status === 'skipped' && !run.startedAt); type Fact = { text: string; href?: string; title?: string; live?: boolean }; + /** A full run ID links to its run; a typed prefix is shown as written. */ + const FULL_RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + /** The past runs an ad-hoc run's command reran from, read from its command alone. */ + const fromRuns = $derived(run?.command ? runsNamed(run.command.join(' ')) : []); /** The first line's facts, in order; a missing one leaves no separator behind. */ const facts = $derived.by((): Fact[] => { if (!run) return []; @@ -31,6 +39,7 @@ ? { text: `rerun of ${shortRunId(run.rerunOfRunId)}`, href: `/runs/${run.rerunOfRunId}` } : { text: runOriginLabel[run.origin].toLowerCase() }, run.narrowing ? { text: `part: ${narrowingText(run.narrowing)}`, title: `Ran part of ${run.jobKey}` } : null, + ...fromRuns.map((written): Fact => ({ text: `from run ${shortRunId(written)}`, href: FULL_RUN_ID.test(written) ? `/runs/${written}` : undefined, title: `sqb ${run.command?.join(' ')}` })), run.window ? { text: `window ${run.window.start} → ${run.window.end}` } : null, retried ? { text: `${retried} retried`, title: 'Member jobs the group retried inside this run' } : null, { text: `by ${run.requestedBy.displayName}`, title: run.requestedBy.name }, @@ -51,22 +60,43 @@ {#if run} - +
-

- {#if run.jobKey}{run.jobKey}{:else}ad hoc: {what}{/if} -

- - - {#each facts as f, i (i)} - {#if i}{' · '}{/if} - {#if f.href}{f.text}{:else}{f.text}{/if} - {/each} - -
-
- - +
+

+ {#if run.jobKey}{run.jobKey}{:else}ad hoc: {what}{/if} +

+ + + {#each facts as f, i (i)} + {#if i}{' · '}{/if} + {#if f.href}{f.text}{:else}{f.text}{/if} + {/each} + {' · '} + +
+
+ {#if !view.active}{/if} + {#if view.active} + + + + {/if} + + +
{:else if view.detailRes.error}

Couldn't load this run: {view.detailRes.error}

@@ -74,23 +104,6 @@

There's no run {runId} in this location. It may belong to another location.

{/if}
- {#if run} -
- {#if view.active} - - - - {/if} -
- {/if} {#if view.actionError}{/if} @@ -126,10 +139,17 @@ } .title-row { display: flex; + align-items: flex-start; + gap: 16px; + margin-top: 4px; + } + .title { + display: flex; + min-width: 0; + flex: 1; flex-wrap: wrap; align-items: center; - gap: 10px; - margin-top: 4px; + gap: 4px 10px; } h2 { font-family: var(--font-display); @@ -142,7 +162,10 @@ .adhoc { font-size: 15px; } + /* Stays beside the title while it has room, wrapping inside itself; below that it wraps under the title. */ .meta { + min-width: 0; + flex: 1 1 360px; display: inline-flex; flex-wrap: wrap; align-items: center; @@ -157,15 +180,9 @@ .sep { color: var(--sb-text-faint); } - .summary-row { - display: flex; - align-items: baseline; - gap: 14px; - margin-top: 8px; - } - .summary-row :global(.details-toggle) { - margin-left: auto; - font-size: 12.5px; + /* Clear of the first figure's reserved pill room, as between the figures. */ + .before-figures { + margin-right: 6px; } .live { color: var(--sb-running); @@ -173,9 +190,9 @@ } .actions { display: flex; + flex: none; align-items: center; - gap: 8px; - padding-top: 18px; + gap: 6px; } .err, .action-error { diff --git a/ui/src/routes/runs/[id]/run-lineage.svelte b/ui/src/routes/runs/[id]/run-lineage.svelte index e96ecf00a3..edbfa3c747 100644 --- a/ui/src/routes/runs/[id]/run-lineage.svelte +++ b/ui/src/routes/runs/[id]/run-lineage.svelte @@ -12,6 +12,7 @@ import { folderTree, layoutFolderGraph, withFolderClosed } from '$lib/lineage/folder-graph'; import { lineageGraph } from '$lib/lineage/folder-selection'; import { folderOf } from '$lib/lineage/catalog-graph'; + import { LABEL_MIN_ZOOM, NAME_ZOOM } from '$lib/lineage/fit'; import type { CatalogNode, RunNode } from '$lib/api'; import { useCatalogNodes } from '$lib/state/catalog.svelte'; import { createResource } from '$lib/state/resource.svelte'; @@ -55,7 +56,10 @@ const graph = lineageGraph(data, { grouped: true, open: opened, selected: [], tree: folderTree(data), onclose: (f) => setOpen(withFolderClosed(opened, f)), onadd: () => {} }); const selected = new Set(view.selected); const excluded = new Set(view.excluded); - return { nodes: graph.nodes.map((n) => ({ ...n, selected: selected.has(n.id), class: excluded.has(n.id) ? 'excluded' : undefined })), edges: graph.edges }; + // A folder box holding open folder boxes is marked, so zoomed out only the innermost ones show counts. + const outer = new Set(graph.nodes.filter((n) => n.type === 'folderBox' && n.parentId).map((n) => n.parentId)); + const classOf = (n: Node) => [excluded.has(n.id) ? 'excluded' : '', outer.has(n.id) ? 'has-boxes' : ''].filter(Boolean).join(' ') || undefined; + return { nodes: graph.nodes.map((n) => ({ ...n, selected: selected.has(n.id), class: classOf(n) })), edges: graph.edges }; } function setOpen(next: ReadonlySet) { open = next; @@ -108,7 +112,7 @@ (view.detail?.children ?? []).flatMap((c) => (c.jobKey ? [[c.jobKey, { nodeCount: view.nodes.filter((n) => n.runId === c.id).length || null, lastRun: { id: c.id, status: c.status, startedAt: c.startedAt, endedAt: c.endedAt }, nodes: memberNodes.data?.get(c.jobKey) ?? null }]] : [])) ) ); - const failedMembers = $derived((view.detail?.children ?? []).filter((c) => c.status === 'failed' || c.status === 'partial').filter((c) => view.nodes.some((n) => n.runId === c.id && n.status === 'failed')).flatMap((c) => (c.jobKey ? [c.jobKey] : []))); + const failedMembers = $derived((view.detail?.children ?? []).filter((c) => c.status === 'failed').filter((c) => view.nodes.some((n) => n.runId === c.id && n.status === 'failed')).flatMap((c) => (c.jobKey ? [c.jobKey] : []))); let memberSelection = $state(null); $effect(() => { const node = memberSelection?.node; @@ -127,9 +131,11 @@ {/if} {:else} -
- - +
+ +
{/if} @@ -139,6 +145,15 @@ opacity: 0.5; text-decoration: line-through; } + /* Zoomed out to dots: a folder's cards give way to its count, in a size that stays readable. */ + /* The library sets each node's own visibility inline, so the cards' contents are hidden, not the nodes. */ + .run-graph :global(.graph-canvas[data-stage='dot'] .svelte-flow__node-asset > *) { + visibility: hidden; + } + /* Only the innermost open folders show a count; an outer box keeps its header, so counts never overlap. */ + .run-graph :global(.graph-canvas[data-stage='dot'] .svelte-flow__node-folderBox:not(.has-boxes) .zoomed-out) { + display: flex; + } .wait { padding: 32px; color: var(--sb-text-faint); diff --git a/ui/src/routes/runs/[id]/run-summary.svelte b/ui/src/routes/runs/[id]/run-summary.svelte index a28cdac6c6..dba50801fb 100644 --- a/ui/src/routes/runs/[id]/run-summary.svelte +++ b/ui/src/routes/runs/[id]/run-summary.svelte @@ -1,32 +1,41 @@
+ {#if jobsLine && figs.length}{jobsLine}{' · '}{/if} {#each figs as f, i (f.key)} {#if i}{' · '}{/if} @@ -34,13 +43,14 @@ { ev.preventDefault(); - view.focusGroup(f.key, f.text.replace(/^\d+ /, '')); + view.toggleLog(f.filter.text); }} - title="Show only these on the timeline and in the log">{f.text}{f.text}{#if f.note}{` ${f.note}`}{/if} {:else} @@ -50,33 +60,59 @@ diff --git a/uv.lock b/uv.lock index c91b7626a4..d7602a1282 100644 --- a/uv.lock +++ b/uv.lock @@ -2540,19 +2540,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, ] -[[package]] -name = "polyglot-sql-chio" -version = "0.13.10" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/18/8c/b48d0fcca36c2e6df0a2ab8aa24e029373264b6dfa9db683eb533f6b6249/polyglot_sql_chio-0.13.10.tar.gz", hash = "sha256:4365617889c3779fd1a3ebdd15ab03c92c517cb1be36dedf82e5853b31d39781", size = 2279296, upload-time = "2026-10-28T23:07:03.083Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/bb/7a/c66b36a40c0931d9647215f315f90e2e0d83328165dce7275d624f694381/polyglot_sql_chio-0.13.10-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:a1abe78cde4b54d145f42356ca4c3a7585775aa4efee954209084ea993633f90", size = 13701198, upload-time = "2026-10-28T23:06:50.006Z" }, - { url = "https://files.pythonhosted.org/packages/5f/e2/b2ba58e445163b9e29a715d9e3eab5fd9e276e8bbe58f5710bd77aae70d7/polyglot_sql_chio-0.13.10-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:a7d01559916bff555fd0c258f4a52a98e3f2fa25b1f4c482ef35cb868704c3b6", size = 12941723, upload-time = "2026-10-28T23:06:52.738Z" }, - { url = "https://files.pythonhosted.org/packages/c6/08/a9e5cb57c9938551edeb0884cc1b57ef54bbb38eb5f371bb146b663881ab/polyglot_sql_chio-0.13.10-cp312-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:25e5ee843dccffe87501113238ba333c17dce55b31867fcdc1b81e245b9c3eb4", size = 12895624, upload-time = "2026-10-28T23:06:55.52Z" }, - { url = "https://files.pythonhosted.org/packages/a0/9e/0879b3a267899906c231270d0167d8c32c14dcc2ae346b86834c4f7bb8b2/polyglot_sql_chio-0.13.10-cp312-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd2ca982a19c7fbeb460914eceae60d9c5f7e6e631473f0141585b778772c1ce", size = 12661001, upload-time = "2026-10-28T23:06:58.287Z" }, - { url = "https://files.pythonhosted.org/packages/e7/13/dbdbce022153042edb59abe07e64c51a0e0a9a8f4c86cf2043f1c42a1da7/polyglot_sql_chio-0.13.10-cp312-abi3-win_amd64.whl", hash = "sha256:f366391d63fbf455f71c07fb03e4ac1cf860609de7fd875759647ffe98659320", size = 12301030, upload-time = "2026-10-28T23:07:00.945Z" }, -] - [[package]] name = "pre-commit" version = "4.6.0" @@ -3710,10 +3697,10 @@ dependencies = [ { name = "duckdb" }, { name = "filelock" }, { name = "orjson" }, - { name = "polyglot-sql-chio" }, { name = "pydantic-settings" }, { name = "pyyaml" }, { name = "sqlbuild-cli" }, + { name = "sqlquack" }, ] [package.optional-dependencies] @@ -3779,7 +3766,6 @@ requires-dist = [ { name = "google-cloud-bigquery", marker = "extra == 'bigquery'", specifier = ">=3.37.0" }, { name = "jinja2", marker = "extra == 'dbt'", specifier = ">=3.1" }, { name = "orjson", specifier = ">=3.11.7" }, - { name = "polyglot-sql-chio", specifier = "==0.13.10" }, { name = "psycopg", extras = ["binary"], marker = "extra == 'postgres'", specifier = ">=3.2.0" }, { name = "pydantic-settings", specifier = ">=2,<3" }, { name = "pymssql", marker = "extra == 'sqlserver'", specifier = ">=2.3.0" }, @@ -3787,6 +3773,7 @@ requires-dist = [ { name = "rivers", marker = "extra == 'rivers'", specifier = ">=0.1.4" }, { name = "snowflake-connector-python", marker = "extra == 'snowflake'", specifier = ">=4.7.1,<5" }, { name = "sqlbuild-cli", directory = "crates/sqlbuild-cli" }, + { name = "sqlquack", specifier = "==0.24.1" }, ] provides-extras = ["dbt", "snowflake", "bigquery", "databricks", "dagster", "postgres", "sqlserver", "clickhouse", "rivers"] @@ -3834,6 +3821,35 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/49/4b/359f28a903c13438ef59ebeee215fb25da53066db67b305c125f1c6d2a25/sqlparse-0.5.5-py3-none-any.whl", hash = "sha256:12a08b3bf3eec877c519589833aed092e2444e68240a3577e8e26148acc7b1ba", size = 46138, upload-time = "2025-12-19T07:17:46.573Z" }, ] +[[package]] +name = "sqlquack" +version = "0.24.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "sqlquack-cli" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f6/86/2d1c1e0b8dbfca0ed68576a469a2179ac33ef1f24c8070c7958fac3eebd0/sqlquack-0.24.1.tar.gz", hash = "sha256:c9cef6e9ed9adc563c8cd88fa48ea9b65166f4f59766348e67444ead4e61a5d1", size = 2863449, upload-time = "2026-11-25T22:20:20.458Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9e/7f/b6bedc6e98797eb3cf20eb0eb5c38247c65ca51cb9d1846755cbcb857fc9/sqlquack-0.24.1-cp312-abi3-macosx_10_15_x86_64.whl", hash = "sha256:dafbd5edbe576266fa7ef1f5e319ce9b33be8815b6c1305843973ff2f34c48bd", size = 29876339, upload-time = "2026-11-25T22:19:54.384Z" }, + { url = "https://files.pythonhosted.org/packages/60/84/e0e75923675cc2f1be6daf16418208de23e1dad80b785a1f52b1a0dcb55e/sqlquack-0.24.1-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:5e0d9d82cb72308964d095a57bc84a4fec621fc045bdbfacf623005755f0c038", size = 27488445, upload-time = "2026-11-25T22:19:56.906Z" }, + { url = "https://files.pythonhosted.org/packages/5e/6c/9ec501cbe267f609d6c6e1353384c80ba69f88c8e0354a2fffedcd7e2103/sqlquack-0.24.1-cp312-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f366a83f9b47449db9f59666d579ed67ea511132b00b6235995fbd8a7a4f6d09", size = 30525363, upload-time = "2026-11-25T22:19:59.643Z" }, + { url = "https://files.pythonhosted.org/packages/4c/1d/da7e566a70fbadafb4365706dc69ce2b211012777e025ef5a27529e04566/sqlquack-0.24.1-cp312-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:314cc611663220954bcdc271ff82a010a3c02f3a491e68bc8d8891e0e7bc14bd", size = 34844049, upload-time = "2026-11-25T22:20:03.005Z" }, + { url = "https://files.pythonhosted.org/packages/71/56/a09e4a2a036e4ec4e324fff8284f24f02b01b067ea21f4e3faf3fc10555a/sqlquack-0.24.1-cp312-abi3-win_amd64.whl", hash = "sha256:7fa84842a955709fab4bf90645424456cf28bb58b109e3dcedaebf54bb4a2629", size = 28451971, upload-time = "2026-11-25T22:20:05.624Z" }, +] + +[[package]] +name = "sqlquack-cli" +version = "0.24.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/35/23/58409317f7f9c23a489cbe9e0469238fee5265a899d172c874e36e304ed7/sqlquack_cli-0.24.1.tar.gz", hash = "sha256:adde8e30804e59dcfc3ce39e6bbc88dd3f55c015dc65be3ae7e4eab9f458058e", size = 2860471, upload-time = "2026-11-25T22:20:22.021Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/be/23/368ee2a21b21679f136a23b02079bfcf76682a7a812e72eaea408e7845e3/sqlquack_cli-0.24.1-py3-none-macosx_10_15_x86_64.whl", hash = "sha256:a077bfb6e5dea7918c0c245020bcca5829b880dcc28f6925ba6a347e25d5269e", size = 32643365, upload-time = "2026-11-25T22:20:08.05Z" }, + { url = "https://files.pythonhosted.org/packages/6a/94/8b4c2621ab37d25264d4d85b619f700cc0fb4734648d716c3c181c7e69be/sqlquack_cli-0.24.1-py3-none-macosx_11_0_arm64.whl", hash = "sha256:04b99c3de459971f61e92f430b11776c996e1893440c693df8f325d6be2d28c2", size = 30031261, upload-time = "2026-11-25T22:20:10.478Z" }, + { url = "https://files.pythonhosted.org/packages/6c/5a/8af0e62f054c25e25d43d8c09890e321ffe5b2cb761ab041f0757c0c0c82/sqlquack_cli-0.24.1-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:453c3f665c0c7b6e8d1a5136a090353c2e0aff0a413bac3307c486ba9da33bc8", size = 32459560, upload-time = "2026-11-25T22:20:12.927Z" }, + { url = "https://files.pythonhosted.org/packages/5b/69/996f2a2ec653874e16013c5bf778207f3118bdc108d66c4dc8b19d91af21/sqlquack_cli-0.24.1-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:98e4d145fbb87a2209ce1a32b72750a49ef3f42940d3ef06bbe09a18bec89edd", size = 36744504, upload-time = "2026-11-25T22:20:15.506Z" }, + { url = "https://files.pythonhosted.org/packages/de/57/8d4ebc27a5f0397001943a51a4593c7fcfc585b7d75ac9b314074e96ea71/sqlquack_cli-0.24.1-py3-none-win_amd64.whl", hash = "sha256:6017a2874197ca574ec74bfc4021e5641b9d223044398c8bb3374b47ffa9d9c6", size = 30671202, upload-time = "2026-11-25T22:20:18.073Z" }, +] + [[package]] name = "starlette" version = "1.0.0" diff --git a/website/src/content/docs/docs/cli/audit.mdx b/website/src/content/docs/docs/cli/audit.mdx index aa795b9cfb..52dc0d5188 100644 --- a/website/src/content/docs/docs/cli/audit.mdx +++ b/website/src/content/docs/docs/cli/audit.mdx @@ -25,6 +25,7 @@ Positional `SELECTOR` arguments work like `--select`, and both forms can be comb | `--select`, `-s` | Select audits attached to specific models | | `--select-file` | Read selectors from a file | | `--exclude` | Exclude audits attached to specific models | +| `--server`, `--location-id`, `--ca-cert` | Read the runs that [`run:`, `failed:` and `skipped:`](/docs/concepts/selectors#selecting-from-a-past-run) name from this server's runs of the location, with your [`sqb login`](/docs/cli/login) session, instead of the local Recall history | | `--concurrency` | Maximum number of audits to run concurrently (default: `1`) | | `--json` | Print structured audit results | | `--json-output` | Write structured audit results to a file | diff --git a/website/src/content/docs/docs/cli/build.mdx b/website/src/content/docs/docs/cli/build.mdx index b36819dd31..d6e3c4ea3f 100644 --- a/website/src/content/docs/docs/cli/build.mdx +++ b/website/src/content/docs/docs/cli/build.mdx @@ -69,6 +69,7 @@ own option. `--version` works only directly after `sqb`, as in `sqb --version`: | `SELECTOR ...` | Positional selectors, the same as `--select` | | `--select`, `-s` | Select specific models, or unit tests by name (`test:`); selecting only unit tests runs them without building models | | `--exclude` | Exclude specific models | +| `--server`, `--location-id`, `--ca-cert` | Read the runs that [`run:`, `failed:` and `skipped:`](/docs/concepts/selectors#selecting-from-a-past-run) name from this server's runs of the location, with your [`sqb login`](/docs/cli/login) session, instead of the local Recall history | | `--warehouse ` | Snowflake warehouse for this invocation; overrides the target's `build` [warehouse group](/docs/concepts/adapters/snowflake#command-group-warehouses) and the connection warehouse | ## Fast iteration @@ -285,6 +286,12 @@ skipped as for any other failure. Its row shows `TIMEOUT`. In the summary line, failures were timeouts. A timeout is a failure for the exit code: the build exits non-zero and its JSON `status` is `failed`. +A singular audit whose references don't all exist in the target is not run. Its row shows +`NOT RUN`, the summary line counts it under `NOT_RUN=` (shown only when there is one) and in no +other count, and a `Not run` section names what each one reads that is missing. In `--json` +output, `summary.not_run_count` counts them. The build still succeeds; see +[Singular audits](/docs/concepts/audits#singular-audits). + ## Limits A target's [`execution_limits`](/docs/concepts/project-configuration#execution-limits) cap a whole diff --git a/website/src/content/docs/docs/cli/check.mdx b/website/src/content/docs/docs/cli/check.mdx index 01141bec8b..574cd1619c 100644 --- a/website/src/content/docs/docs/cli/check.mdx +++ b/website/src/content/docs/docs/cli/check.mdx @@ -22,6 +22,7 @@ Positional `SELECTOR` arguments work like `--select`, and both forms can be comb | `SELECTOR ...` | Positional selectors, the same as `--select` | | `--select`, `-s` | Select checks to run (by name, `check:`, `tag:`, or graph expansion) | | `--exclude` | Exclude checks from the selection | +| `--server`, `--location-id`, `--ca-cert` | Read the runs that [`run:`, `failed:` and `skipped:`](/docs/concepts/selectors#selecting-from-a-past-run) name from this server's runs of the location, with your [`sqb login`](/docs/cli/login) session, instead of the local Recall history | | `--no-sql-analysis` | Disable compile-time SQL analysis (`--no-sql-validation` is an alias) | | `--json` | Print check results as JSON | | `--json-output` | Write check results JSON to a file path | diff --git a/website/src/content/docs/docs/cli/plan.mdx b/website/src/content/docs/docs/cli/plan.mdx index 4a42f74c7b..8145555a38 100644 --- a/website/src/content/docs/docs/cli/plan.mdx +++ b/website/src/content/docs/docs/cli/plan.mdx @@ -42,6 +42,7 @@ Positional `SELECTOR` arguments work like `--select`, and both forms can be comb | `SELECTOR ...` | Positional selectors, the same as `--select` | | `--select`, `-s` | Select specific models | | `--exclude` | Exclude specific models | +| `--server`, `--location-id`, `--ca-cert` | Read the runs that [`run:`, `failed:` and `skipped:`](/docs/concepts/selectors#selecting-from-a-past-run) name from this server's runs of the location, with your [`sqb login`](/docs/cli/login) session, instead of the local Recall history | | `--warehouse ` | Snowflake warehouse for this invocation; overrides the target's `build` [warehouse group](/docs/concepts/adapters/snowflake#command-group-warehouses) and the connection warehouse | ## Output @@ -233,6 +234,27 @@ error[S301]: cannot build selected scope: audit 'relationships' on 'stg_orders' Load or build the resource first (for a seed, `sqb seed`), or add it to the selection. When both kinds are missing, the error lists the missing upstream resources and then the audit reads. +The same applies to a singular audit selected by name, with `audit:` or a past run's failed audits: + +``` +error[S301]: cannot build selected scope: audit 'orders_have_payments' reads 'payments', which is not selected and does not exist in the warehouse; select it or build it first +``` + +A singular audit the plan selects only because the build builds something it references is not +refused. When something it references doesn't exist in the target, the plan lists it as not run, +and the build succeeds without running it; see [Singular audits](/docs/concepts/audits#singular-audits): + +``` +Plan ready 1 selected, 1 audit not run +Models (1) +└── orders table +Audits not run (1) +└── orders_have_payments reads payments, which doesn't exist in the target +``` + +`sqb plan --json` lists these audits under `audits_not_run`, each with its `name` and the +`missing` resources it reads. + ## Missing source tables When a selected model reads an external source whose table does not exist in the warehouse, diff --git a/website/src/content/docs/docs/cli/scenario.mdx b/website/src/content/docs/docs/cli/scenario.mdx index eb0c1e9948..bf95103a1b 100644 --- a/website/src/content/docs/docs/cli/scenario.mdx +++ b/website/src/content/docs/docs/cli/scenario.mdx @@ -1,6 +1,6 @@ --- title: "sqb scenario" -description: "Run end-to-end scenario tests against the warehouse or locally with DuckDB." +description: "Run end-to-end scenario tests locally with DuckDB or against the warehouse." sidebar: label: "scenario" --- @@ -9,7 +9,7 @@ Run end-to-end scenario tests. Scenarios materialize fixture inputs as physical ## sqb scenario test -Run scenario tests against the warehouse. +Run scenario tests locally in DuckDB from captured snapshots, or against the warehouse. ```bash sqb scenario test [flags] @@ -23,12 +23,12 @@ sqb scenario test [flags] | `--exclude` | Exclude scenarios from the selection | | `--retain` | Keep scenario-owned warehouse artifacts for inspection | | `--scenario-namespace NAMESPACE` | Isolate warehouse artifacts for this run; overrides environment and config | -| `--local` | Run locally against DuckDB using captured JSONL snapshots | -| `--strict` | Treat missing/stale local snapshots as errors instead of skips | +| `--run-on auto\|local\|warehouse` | Where scenarios run; overrides the target's and `[settings]` `scenario_run_on` (see [Where scenarios run](#where-scenarios-run)) | +| `--verbose` | Print every reason that keeps a scenario off DuckDB in full, instead of the census | | `--concurrency N` | Run up to `N` scenarios at once (default: the project `concurrency` setting) | -| `--scenario-timeout ` | Time limit for each scenario in this warehouse run, such as `10m`, or `disabled`; overrides `SCENARIO(timeout ...)`, the target and `[settings] scenario_timeout`. Not applied with `--local` | -| `--sync-snapshots` | Capture missing/stale snapshots before local run (requires `--local`) | -| `--refresh` | Recapture all selected snapshots before local run (requires `--local`) | +| `--scenario-timeout ` | Time limit for each scenario run on the warehouse, such as `10m`, or `disabled`; overrides `SCENARIO(timeout ...)`, the target and `[settings] scenario_timeout`. Not applied to local runs | +| `--sync-snapshots` | Capture missing or stale snapshots before the run, so those scenarios can run locally; not with `--run-on warehouse` | +| `--refresh` | Recapture all selected snapshots before the run; not with `--run-on warehouse` | | `--force` | Bypass snapshot capture safety limits | | `--max-snapshot-rows` | Override per-relation row limit for capture | | `--max-snapshot-total-rows` | Override total row limit for capture | @@ -92,45 +92,63 @@ sqb scenario test --select daily_revenue_minimal --retain sqb scenario test --select revenue ``` -### Local examples +### Where scenarios run + +| `--run-on` | Where each scenario runs | +|------|-------------| +| `auto` (default) | Locally when its snapshot is fresh and SQLQuack converts all its SQL; otherwise on the warehouse | +| `local` | Locally. A missing or stale snapshot, or SQL SQLQuack refuses, is an `ERROR`; nothing goes to the warehouse | +| `warehouse` | On the warehouse | + +The setting comes from, in order: `--run-on`, the default target's `scenario_run_on`, +`[settings] scenario_run_on` in `sqlbuild_local.toml`, then in `sqlbuild_project.toml`, then +`auto`. `--retain` keeps warehouse artifacts only, so it is rejected with `--run-on local`. ```bash # Run locally (requires prior capture) -sqb scenario test --local +sqb scenario test --run-on local -# Run locally, capture missing/stale snapshots first -sqb scenario test --local --sync-snapshots +# Capture missing/stale snapshots first, then run locally +sqb scenario test --run-on local --sync-snapshots -# Run locally, recapture everything first -sqb scenario test --local --refresh - -# Fail on missing/stale snapshots instead of skipping -sqb scenario test --local --strict +# Recapture everything first +sqb scenario test --run-on local --refresh ``` ### Output -Remote scenarios report per-scenario PASS/FAIL with nested check rows: +Scenarios report per-scenario PASS/FAIL, where each ran, and nested check rows: ``` -daily_revenue_minimal PASS 0.84s +daily_revenue_minimal PASS warehouse 0.84s expect expected daily_revenue PASS expect assertion no_negative_revenue PASS -PASS=1 FAIL=0 TOTAL=1 (0.91s) -Statements: 9 (CREATE 3, SELECT 3, DROP 2, ALTER 1); compile time not reported by duckdb +PASS=1 FAIL=0 TOTAL=1 (0 local, 1 warehouse, 0.91s) +Statements: 9 on the warehouse (CREATE 3, SELECT 3, DROP 2, ALTER 1); compile time not reported by duckdb ``` Each scenario row shows its wall time and the summary shows the total. `--json` reports the same values as `scenarios[].duration_ms` and `summary.duration_ms`. The `Statements:` line and the JSON `statements` section are described in [Statement summary](/docs/cli/test#statement-summary). -Local scenarios add ERROR and SKIP statuses: +A scenario that cannot run, such as one without a fresh snapshot under `--run-on local`, is +`ERROR`, and the summary adds an `ERROR=` count: ``` -PASS=2 FAIL=0 ERROR=0 SKIP=1 TOTAL=3 (1.20s) +PASS=2 FAIL=0 ERROR=1 TOTAL=3 (3 local, 0 warehouse, 1.20s) ``` +After the summary, `--run-on local` lists why scenarios could not run locally (`Can't run locally`), +and `auto` counts what sent scenarios to the warehouse (`On the warehouse`), as +[`sqb test`](/docs/cli/test#local-and-warehouse-runs) does. A snapshot reason reads +`snapshot stale: scenario:` or `snapshot missing: scenario:`. A scenario whose +converted SQL hits a SQLQuack guard or a DuckDB internal error while it replays runs again on the +warehouse in `auto`, with the reason `SQLQuack guard: ` or `DuckDB internal error: `, +and its local attempt prints nothing; with `--run-on local` it is an `ERROR` (`T007`). With `--json`, each +scenario has `run_on` and `run_on_reason`, `summary` has `local_count` and `warehouse_count`, and +the document has `refusals`, as for `sqb test`. + Failed scenarios suggest rerunning with `--retain` for inspection. Local runs always keep the DuckDB file at `target/run/scenarios//local.duckdb`. ## sqb scenario capture diff --git a/website/src/content/docs/docs/cli/server.mdx b/website/src/content/docs/docs/cli/server.mdx index f5af2d7b19..1b507e23f0 100644 --- a/website/src/content/docs/docs/cli/server.mdx +++ b/website/src/content/docs/docs/cli/server.mdx @@ -78,6 +78,55 @@ process group, so Ctrl+C in the server's terminal reaches only the server. A sec SIGTERM while the workers stop kills their process groups at once; the server still records the runs and releases their claims before it exits. +## Check the server's health + +Each server keeps its own health in memory, so it can answer while its control database can't be +reached: + +| Path | Sign-in | Answers | +| --- | --- | --- | +| `/livez` | None | `200 ok` while the process runs; it checks nothing else | +| `/api/health` | None | Each part's state, since when and a short reason; `200` when every part is healthy, `503` otherwise | +| `/api/health/details` | People who may manage people | Where the control database is, each cause's own message and the IDs of requests that failed | + +The parts are the server (version and uptime), the control database (checked every 10 seconds), +the scheduler on servers that run one, each location, which is degraded once it hasn't +reported for 90 seconds, and each event webhook the server forwards to (see +[Receive platform events](#receive-platform-events)). The report's `status` is `unavailable` while the control database is, +`degraded` while any other part isn't healthy, and `healthy` otherwise. Point a load balancer's +liveness check at `/livez`, and monitoring at `/api/health`. + +When a request fails because of the control database, the error says why instead of a generic +"busy": + +| `cause.case` | Message | +| --- | --- | +| `name_lookup` | Can't reach the control database: `` doesn't resolve (DNS) | +| `unreachable` | Can't reach the control database at `:` | +| `login_rejected` | The control database rejected the login for `` | +| `no_free_connections` | The control database has no free connections | +| `restarting` | The control database is restarting | +| `pool_exhausted` | All 10 control database connections were busy for 30 s | +| `locked` | The control database is locked by another process | +| `other` | Control database error: `` | + +The response body carries `error` (the message), `cause` with `case` and `since`, and +`request_id`, which every response also sends as `x-request-id`. The server log has each failure +with its request ID and every cause's own message, never the password. Any other unknown path +under `/api/` is a JSON `404`, never the UI's page. + +`sqb server` listens before it opens its control database. While the database can't be reached, +for example because its host doesn't resolve, the server answers `/livez`, `/api/health` and the +UI, refuses other API requests with `503` and the cause, and tries again with a wait that doubles +up to 30 seconds. It then starts the full API on the same address without a restart. A failure that +retrying can't fix, such as a rejected login or a schema it can't migrate, stops the server. + +The UI reads the same health. The top bar says **Live**, **Degraded** or **Unavailable**, and +links to **Status**, which shows every part without signing in. While the control database is +unavailable, every page keeps its address and says it isn't available, with the reason, since +when and the parts, and loads by itself when the database is back. While a part is degraded, pages +work and a banner names it. + ## Serve over HTTPS Code locations and workers send their bearer token with every request to the `--server` URL. @@ -312,16 +361,30 @@ receive the URL. "job_key": "daily_orders", "location_id": "01a1d38b-e214-7151-8c8e-8606917c3ee6", "target": "production", - "outcome": "partial", + "outcome": "failed", + "url": "https://sqlbuild.example.com/runs/01a1d3b9-2c4e-7f10-8a3b-1d2e3f4a5b6c", + "trigger": { "kind": "schedule", "name": "daily_orders", "person": null }, + "started_at": "2026-11-13T06:52:51.204Z", + "ended_at": "2026-11-13T07:12:04.112Z", + "duration_ms": 1152908, + "error": null, "failed_nodes": [ { "node_key": "model:fct_orders", "error_code": "E100", "message": "Conversion Error: Could not convert string 'n/a' to INT32", - "path": "sql/models/marts/fct_orders.sql" + "path": "sql/models/marts/fct_orders.sql", + "phase": "post_hook", + "url": "https://sqlbuild.example.com/runs/01a1d3b9-2c4e-7f10-8a3b-1d2e3f4a5b6c?node=model%3Afct_orders", + "logs_url": "https://sqlbuild.example.com/runs/01a1d3b9-2c4e-7f10-8a3b-1d2e3f4a5b6c/output/model%3Afct_orders" } ], - "failed_node_count": 1 + "failed_node_count": 1, + "failed_audits": [], + "failed_audit_count": 0, + "succeeded_node_count": 194, + "skipped_nodes": ["model:fct_order_margin", "model:order_summary"], + "skipped_node_count": 2 } } } @@ -331,6 +394,13 @@ Delivery is at least once and in order. A response other than `2xx`, or no respo seconds, stops delivery and retries the same event. Deduplicate by `event_id`, which the `Idempotency-Key` header repeats. +While the webhook fails, **Platform event forwarding** is degraded in the server's health, with +since when and why, such as `the webhook answered HTTP 503` or `can't connect to the webhook`, and +it is an item on every Overview's attention list. Events are kept and retried every 5 seconds, and +the item clears with the first delivery. The security audit webhook +(`SQLBUILD_SECURITY_AUDIT_WEBHOOK_URL`) is reported the same way, as **Security audit event +forwarding**. + | `kind` | Sent when | Fields | | --- | --- | --- | | `heartbeat` | Each server replica is alive, periodically | `replica_id`, `store_bytes` (the control database size on disk) | @@ -340,7 +410,7 @@ seconds, stops delivery and retries the same event. Deduplicate by `event_id`, w | `location_broken` | Every instance of a location and target has stopped reporting for over 90 seconds | `location_id`, `target`, `last_seen_at` | | `location_failing` | A location and target that checks in failed its latest load (`falling_back`), its plan of what changed (`change_plan_failed`), a discover function (`discovery_failed`) or the connection check after its last load (`degraded`) | `location_id`, `target`, `state`, `failed_at`, `error`, `serving_generation` (the generation runs use instead) | | `launch_failed` | Starting a worker failed; it may still start | `run_id`, `claim_id`, `code` | -| `run_failed` | A job, group or ad-hoc run ends `failed` or `partial` | `run_id`, `run_kind`, `job_key`, `location_id`, `target`, `outcome`, `failed_nodes`, `failed_node_count` | +| `run_failed` | A job, group or ad-hoc run ends `failed` | See [Fields of `run_failed`](#fields-of-run_failed) | | `trigger_skipped` | The scheduler skips a trigger whose stored job or snapshot can't be read, or a sensor whose check failed; the sensor is checked again a minute later | `trigger_id`, `snapshot_id`, `reason` | | `sensor_rechecked` | A sensor's last check can't be read, so it is checked again from scratch | `trigger_id`, `snapshot_id`, `evaluation_id` | | `calendar_times_dropped` | A publish drops a calendar schedule's due times | `trigger_id`, `snapshot_id`, `times` | @@ -354,12 +424,51 @@ completed check in that snapshot: a later attempt that fails differently sends n doesn't replace it. Everyone who can view the target sees the reason, and it can quote stored values. -`run_failed` lists at most 20 failed nodes, ordered by node key; `failed_node_count` is the full -number. A `partial` run is included because some of its nodes failed. `job_key` is `null` for -ad-hoc runs. Each `message` is the node's error text with credentials redacted, cut to 2,000 -characters, and `null` when the worker reported none. It can quote warehouse data, so treat the -webhook like other run evidence. `run_failed` events appear only in the webhook, not in the -server's platform history. +### Fields of `run_failed` + +`run_failed` carries what an alert needs to say what failed, where, and to link to it: + +| Field | Meaning | +| --- | --- | +| `run_id`, `run_kind`, `job_key`, `location_id`, `target` | The run, its kind (`job`, `group`, `adhoc`), its job (`null` for ad-hoc runs), and where it ran | +| `outcome` | `failed` | +| `url` | The run's page in the UI | +| `trigger` | What started the run: `kind` is `schedule`, `sensor`, `manual` (a person) or `api` (a service account); `name` is the schedule's or sensor's name; `person` is who asked for a manual or API run | +| `started_at`, `ended_at`, `duration_ms` | When the run's worker started and the run ended; `null` for a run that never started | +| `error` | Why the run failed when no node or audit says, such as a project that can't load: `phase` (`launch`, `worker_start`, `load`, `planning` or `build`), `code` (the error's type) and `message`; `null` when `failed_nodes` or `failed_audits` say why | +| `failed_nodes` | The first 20 failed nodes, ordered by key, each with `node_key`, `error_code`, `message`, `path` (the node's file), `phase` (where a model failed: `pre_hook`, `staging`, `contract`, `audit`, `post_hook` and so on; `null` for other nodes), `url` (the node on the run's page) and `logs_url` (its output) | +| `failed_node_count` | Every failed node | +| `failed_audits` | The first 20 error-severity audit failures the run didn't let through, ordered by name, each with `name`, `node_key` (`null` for an end-of-build singular audit), `sqlstate` and `message` (the warehouse's error when the audit's query couldn't run) and `failing_rows` (when it ran) | +| `failed_audit_count` | Every such audit failure | +| `succeeded_node_count`, `skipped_node_count` | How many nodes built and how many were skipped | +| `skipped_nodes` | The first 20 skipped nodes, ordered by key | + +The links (`url`, and each failed node's `url` and `logs_url`) are `null` when the server has no +sign-in origin, such as `[server] password_origin`. `job_key` is `null` for ad-hoc runs. Each +`message` is the error text with credentials redacted, cut to 2,000 characters, and `null` when the +worker reported none. It can quote warehouse data, so treat the webhook like other run evidence. +`run_failed` events appear in the webhook and to +[`platform_event` sensors](/docs/concepts/orchestration#react-with-a-sensor), not in the server's +platform history. + +## See lost lifecycle events + +A worker counts what each of the project's lifecycle event sinks delivered when its run's command +closes, and reports it with the run. A location's own interpreters, which compile, read run history +and evaluate sensors, run the same sinks: once a minute, each idle one says what its sinks +delivered, and the location reports what changed since the last report. + +A sink that dropped or failed events in the newest run or location report of a location and target +is an item on that target's attention list, such as `event sink kafka losing events since 17:42: +116 of 116 events not delivered (116 failed)`, from its first lossy run or report in a row. A sink +provider whose teardown raised at the end of a run is listed as `sink providers`, because events it +still held may not have been delivered. The item clears once a run, or a minute in which the sink +took events, delivers every event. Reports from the last 7 days count. + +SQLBuild counts what a sink function does: an event it raised on is failed, and one it never got +is dropped. A sink that hands events to a client which sends them later, such as a Kafka producer, +reports a send that fails afterwards only if it raises, from a later call or when its provider +closes. ## Acknowledge attention items @@ -790,11 +899,17 @@ Details: - On Snowflake, a sync skips state tables that haven't changed since the last sync, the pause table included, so a sync with nothing new doesn't resume the warehouse. - When a read fails, the Connections page shows the warehouse error. A read that ran out of memory - or time retries a smaller page. Any other error, such as a missing permission or table, retries - after 30 seconds, then waits twice as long after each failure in a row. After 5 failures in a row - the sync stops until a run ends, you request one, the location publishes again, or the next safety - sync is due (`sync_at_least_every`). It then starts again from the first kind of history, and - failed reads back off again before they stop it. + or time retries a smaller page. A read that never reached the warehouse, such as a host that + doesn't resolve, a refused connection or Snowflake's `250001 Could not connect`, spent no + compute: it retries after 30 seconds, then every 60 seconds, and never stops the sync. Any other + error, such as a missing permission or table, retries after 30 seconds, then every 60 seconds. + After 5 such failures in a row the sync stops until a run ends, you request one (**Resume** on + the Overview's attention item), the location publishes again, or the next safety sync is due + (`sync_at_least_every`). It then starts again from the first kind of history. +- A request to the server that fails, for example while its control database is unreachable, + keeps the page and retries it every 30 seconds; it never stops the sync. After a failing streak, + the location logs `Run history sync recovered after N min; M pages caught up.` once the sync + completes. - `[control]` holds no secrets. The session stays in the login `sqb login` saved for that server. - When a state table holds two rows with the same ID, such as one check result written twice, the server keeps the row with the earlier time. Estimated query costs are the exception: when two @@ -836,13 +951,15 @@ Warehouse history synchronization completed: 14 kinds, 31,204 rows in 12.8 s. A page holds up to 2,000 rows and ends early at 8 MiB, so wide rows make smaller pages. A failed read prints which kind failed, the page size and why, then what the location does next. A read that -ran out of time or memory retries a smaller page; any other failure retries the same page after a -wait that doubles each time, and the fifth in a row stops the sync: +ran out of time or memory retries a smaller page; any other failure retries the same page after 30 +seconds, then every 60 seconds. One that never reached the warehouse never stops the sync; the +fifth other failure in a row does: ```text Warehouse history read failed for statistics (100-relation page): no reply within 130 s. Sync incomplete; retaining mirror and retrying a smaller page in 30 s. Warehouse history read failed for catalog (2000-row page): permission denied for table _sqlbuild_catalog. Sync incomplete; retaining mirror and retrying in 60 s. Warehouse history read failed for catalog (2000-row page): permission denied for table _sqlbuild_catalog. Synchronization stopped after 5 failed reads in a row; it resumes after the next run, on request or after a publish. +Warehouse history read failed for catalog (2000-row page): 250001 Could not connect to Snowflake backend after 2 attempt(s). Run history can't reach the warehouse; no compute ran. Retrying in 60 s; this never stops the sync. ``` | Cause | Printed as | @@ -863,6 +980,12 @@ The location's page shows a failing sync as **failing** with when it last synced each failing kind with the cause, the page size and the warehouse's message, shortened and with secrets removed. The Connections page shows a stopped sync as **stopped after failed reads**. +While the sync fails, the top bar says what stands, since when, how it retries and why, for example +`Run history can't reach the warehouse since 17:42 · retrying every 60 s · 250001 Could not +connect…`, and links to the location's page; its tooltip has the last success and the next +attempt. The Overview lists it as needing attention with the same reason, and drops it once a sync +report succeeds. A sync that failed reads stopped has a **Resume** action there. + ## Skip overlapping runs and retry failures Declare who owns a job, whether scheduled requests wait for a running copy, and how often a failed @@ -886,7 +1009,7 @@ delay_seconds = 600 | --- | --- | --- | --- | | `owner` | Any non-blank text | None | Shown on the job's page and in the job list | | `overlap` | `queue` or `skip` | `queue` | With `skip`, a schedule tick or sensor request that arrives while a run of the job is queued or running starts no run | -| `retry` | `attempts` from 2 to 11, `delay_seconds` from 0 to 86400 | None | A failed or partial run nobody cancelled reruns its failed, cancelled and skipped nodes, and those it never reached, after the delay, until it succeeds or has run `attempts` times in all | +| `retry` | `attempts` from 2 to 11, `delay_seconds` from 0 to 86400 | None | A failed run nobody cancelled reruns its failed, cancelled and skipped nodes, and those it never reached, after the delay, until it succeeds or has run `attempts` times in all | A skipped tick shows as **skipped** in the trigger's tick log, with the run it yielded to, and creates no run. A sensor tick lists the requests it skipped the same way. @@ -907,7 +1030,7 @@ Details: - A member job's `[retry]` also applies inside a group run. When the member fails, the group runs it again after `delay_seconds`, inside the same group run, and the jobs that depend on it wait instead of skipping. The group keeps its pool slots meanwhile. -- A group's own `[retry]` is a final sweep: after the group run ends `failed` or `partial`, it +- A group's own `[retry]` is a final sweep: after the group run ends `failed`, it queues one new linked rerun of the group's failed, cancelled and skipped nodes, and those it never reached. - So a retry of a whole run, a job's or a group's, is a new linked run, and a retry of a member stays inside its group run. @@ -1043,8 +1166,19 @@ runs. A `build` loads the managed sources its models read, as `sqb build` does, alone; `--no-load` turns that off. A `test` or `audit` run reports each selected node with the worst result of its tests or audits. -Selectors use the CLI grammar: names, `seed:`, `source:`, `tag:`, `path:`, `test:` and `job:`, -with `+` for upstream or downstream nodes. Positional selectors work as on the command line. +Selectors use the CLI grammar: names, `seed:`, `source:`, `tag:`, `path:`, `test:`, `job:` and +`audit:`, with `+` for upstream or downstream nodes. Positional selectors work as on the command line. +[`run:`, `failed:` and `skipped:`](/docs/concepts/selectors#selecting-from-a-past-run) select from +a run of the same location and target, by full ID or a unique prefix of at least 8 characters. The +server resolves them when the run is requested and freezes the nodes and audits they select with +it, so later runs don't change what it runs. + +In the web UI, Rerun on a run opens the rerun plan on `failed:+`; rerunning the whole run opens +on `run:`, and one node or audit on its own name or `audit:`. The box holds the whole +selection: its suggestions only rewrite the text, and Run starts the ad-hoc run +`sqb build -s ` shown beside it, against the current publication. The run it starts shows +`from run ` for each past run its selection names. Reruns of several runs at once, and retries, +still repeat each run's own frozen version and settings. A `build` whose selection names a job takes the job's settings, exactly as `sqb build` and the job's own runs do; see diff --git a/website/src/content/docs/docs/cli/test.mdx b/website/src/content/docs/docs/cli/test.mdx index b7ee428306..9cfcf2a644 100644 --- a/website/src/content/docs/docs/cli/test.mdx +++ b/website/src/content/docs/docs/cli/test.mdx @@ -25,8 +25,11 @@ Positional `SELECTOR` arguments work like `--select`, and both forms can be comb | `SELECTOR ...` | Positional selectors, the same as `--select` | | `--select`, `-s` | Select tests by name (`order_status_rules` or `test:order_status_rules`), or the tests targeting specific models | | `--exclude` | Exclude tests by name, or the tests targeting specific models | +| `--server`, `--location-id`, `--ca-cert` | Read the runs that [`run:`, `failed:` and `skipped:`](/docs/concepts/selectors#selecting-from-a-past-run) name from this server's runs of the location, with your [`sqb login`](/docs/cli/login) session, instead of the local Recall history | | `--warehouse ` | Snowflake warehouse for this invocation; overrides the target's `query` [warehouse group](/docs/concepts/adapters/snowflake#command-group-warehouses) and the connection warehouse | | `--test-timeout ` | Time limit for each test in this run, such as `30s` or `2m`, or `disabled`; overrides `TEST(timeout ...)`, the target and `[settings] test_timeout` | +| `--run-on auto\|local\|warehouse` | Where unit tests run; overrides the target's and `[settings]` `test_run_on`. See [Local and warehouse runs](#local-and-warehouse-runs) | +| `--verbose` | Print every refusal that keeps a test off DuckDB in full, instead of the census | | `--since ` | Run only the tests affected by changes since the merge base of `` and `HEAD` (see [Run only affected tests](#run-only-affected-tests)); `@base` reads `[git] base_ref` | | `--explain` | With `--since`, print why each selected test was selected | | `--sql` | Run only SQL tests | @@ -55,13 +58,59 @@ counted under `TIMEOUT=` and excluded from `FAIL=` in the summary line output, `summary.fail_count` still includes timed-out tests, and `summary.timeout_count` reports how many of them timed out. A timeout still fails the run: `sqb test` exits non-zero. +## Local and warehouse runs + +Each SQL test runs locally in DuckDB or on the warehouse, decided per test at compile time; see +[Running tests locally](/docs/concepts/testing-reference#running-tests-locally). Each row names +where its test ran, and the summary splits the total: + +``` +fact_orders + test test_fact_orders PASS warehouse 1 real model 0.84s +PASS=4 FAIL=0 TOTAL=4 (3 local, 1 warehouse) +Statements: 5 on the warehouse (CREATE 2, DROP 2, WITH 1); compile 0.4s, execution 0.1s +``` + +A test that does not run is an `ERROR` row with a short reason: `can't run locally` (`T007`, with +`--run-on local`) or `needs the warehouse (no connection)` (`T008`, in `auto`). A local test whose +converted SQL hits a SQLQuack guard or a DuckDB internal error while it runs is also `T007` with +`--run-on local`; in `auto` it runs again on the warehouse. + +After the summary: + +- With `--run-on local`, `Can't run locally (N tests)` lists SQLQuack's diagnostics: code, + message, the model or test file position, the source line with a caret and label, notes and + help, and `= tests:` with every test the refusal blocks. A refusal in a model's SQL points at + the model file; one in a fixture or expected rows at the test file; one inside a macro expansion + at the call site, with the generated SQL as the source line; one in SQL SQLBuild generates at the + compiled test under `target/run/tests/`. +- In `auto`, `On the warehouse (N tests)` counts the tests each refusal sends to the warehouse, + most tests first: + +``` +On the warehouse (4 tests) + a known difference that isn't allowed: fn:HASH 3 tests + missing rule: node:method_call 1 test +``` + +`--verbose` and `--inspect` print the full diagnostics instead, as notes (`note[SQ0003]`), since these +tests still run; under `--run-on local` they are errors. + +With `--json`, each check has `run_on` (`local` or `warehouse`) and `run_on_reason` (the first +refusal's `: `, or `null`), `summary` has `local_count` and +`warehouse_count`, and the document has `refusals`: each refusal once per construct and place, +with SQLQuack's `code`, `category`, `construct`, `reason`, `message`, `label`, `notes` and +`help`, its `path`, `line` and `column`, its `title` (`: `), and `tests`, +the tests it blocks. + ## Statement summary After the pass/fail summary, `sqb test` and `sqb scenario test` print how many warehouse statements -the SQL tests or scenarios sent, by leading keyword, and how long the warehouse spent compiling and executing them: +the SQL tests or scenarios sent, by leading keyword, and how long the warehouse spent compiling and executing them. +Statements of tests and scenarios that ran locally are not counted: ``` -Statements: 12 (SELECT 7, CREATE 2, DROP 2, ALTER 1); compile 1.5s, execution 0.3s +Statements: 12 on the warehouse (SELECT 7, CREATE 2, DROP 2, ALTER 1); compile 1.5s, execution 0.3s ``` With `--json`, the document gains a `statements` section with `total`, `by_kind` and diff --git a/website/src/content/docs/docs/concepts/adapters/sqlite.mdx b/website/src/content/docs/docs/concepts/adapters/sqlite.mdx index bbde5ffe3b..1e13478ea5 100644 --- a/website/src/content/docs/docs/concepts/adapters/sqlite.mdx +++ b/website/src/content/docs/docs/concepts/adapters/sqlite.mdx @@ -94,7 +94,7 @@ SQLite stores values by type affinity, so SQLBuild keeps column types explicitly | Snapshots (timestamp, check, historical) | Supported | | Schema changes | Add, drop and rename columns in place; type changes rebuild the table and its indexes in one transaction | | `sqb diff`, `sqb clone` | Supported; clones are physical copies | -| Scenarios, `sqb scenario capture`, `--local` replay | Supported; see below | +| Scenarios, `sqb scenario capture` | Supported on SQLite; see below | | Statement time limits | Connection interrupt | | `sqb load`: Python loaders | Supported | @@ -104,9 +104,9 @@ Scenario fixtures and models are tables in the same file, named `____sqb_____`, and are dropped when the scenario finishes unless you pass `--retain`. Concurrent scenarios queue for the file's single writer. -`sqb scenario test --local` transpiles SQLite SQL to DuckDB. Date functions with modifiers, such -as `datetime(ordered_at, 'start of day')`, have no DuckDB translation and fail locally; use -`date(...)` or `strftime(...)` in models you want to replay locally. +Scenarios run on the SQLite file. Local replay converts Snowflake SQL only, so with +`--run-on auto` SQLite scenarios run on SQLite (reason `dialect: sqlite`), and `--run-on local` +refuses them. ## Limits diff --git a/website/src/content/docs/docs/concepts/audits.mdx b/website/src/content/docs/docs/concepts/audits.mdx index 0834554395..8f89ab1353 100644 --- a/website/src/content/docs/docs/concepts/audits.mdx +++ b/website/src/content/docs/docs/concepts/audits.mdx @@ -348,9 +348,27 @@ singular audit must live under the nearest folder containing everything it refer directly under `sql/audits/` or in any other `sql/audits/` child are compile errors. SQLBuild infers where a singular audit runs from its references. When one referenced model is -downstream of every other referenced model, the audit attaches to that model. Otherwise it runs at -the end of the build, after the resources it references are published. Only singular audits run at -the end of the build; attached audits always gate their target. +downstream of every other referenced model and the build builds it, the audit attaches to that +model. Otherwise it runs at the end of the build, after the resources it references are published. +Only singular audits run at the end of the build; attached audits always gate their target. + +A build selects a singular audit when it builds anything the audit references. The audit runs when +everything it references exists: built in this run, or already in the target. When something it +references doesn't exist in the target, the audit is not run. That is neither a pass nor a failure, +and the build still succeeds. The plan lists the audit under `Audits not run` with what is +missing, the build shows it as `NOT RUN` and counts it under `NOT_RUN=`, and the run page shows it +as not run with the same reason: + +``` +✓ Completed successfully PASS=1 WARN=0 FAIL=0 INSUFFICIENT=0 SKIP=0 NOT_RUN=1 TOTAL=2 (0.35s) + +Not run (1): + orders_have_payments (audit) reads payments, which doesn't exist in the target +``` + +Selecting the audit itself, with `audit:orders_have_payments` or a past run's failed audits, fails +planning with `S301` instead, naming what it reads that doesn't exist; see +[Missing upstream dependencies](/docs/cli/plan#missing-upstream-dependencies). ## Source audits diff --git a/website/src/content/docs/docs/concepts/orchestration.mdx b/website/src/content/docs/docs/concepts/orchestration.mdx index eb164ead75..c4342b3ae4 100644 --- a/website/src/content/docs/docs/concepts/orchestration.mdx +++ b/website/src/content/docs/docs/concepts/orchestration.mdx @@ -282,7 +282,7 @@ Pass `name="..."` to choose another name, which must also end in `_sensor`. | Not set | Every `minimum_interval_seconds`: a polling sensor | `kinds` take the enums `RunEventKind`, `NodeEventKind`, `CheckEventKind` and `PlatformEventKind` -from `sqlbuild.orchestration`. `RunEventKind` has `SUCCESS`, `WARN`, `PARTIAL`, `FAILED`, +from `sqlbuild.orchestration`. `RunEventKind` has `SUCCESS`, `WARN`, `FAILED` (a node failed, was skipped or never ran), `CANCELLED`, `SKIPPED` (a member its group did not run) and `COMPLETED` for any of them. `CheckEventKind` has `FAILED` and `WARN`. `check_event` covers checks inside job runs and manual builds, such as one started from the Plan page, where the event's `job` is `None`. It doesn't @@ -302,6 +302,42 @@ cover standalone `sqb test` or `sqb audit` runs, or `sqb scenario test`. | `platform_event` | `PlatformEvent` | `id`, `occurred_at`, `event`, `details` | | Not set | `None` | None; keep your place between polls in `ctx.cursor` | +A `platform_event` sensor for `PlatformEventKind.RUN_FAILED` gets every field of the server's +[`run_failed` event](/docs/cli/server#fields-of-run_failed) in `ctx.event.details`, enough to build +an alert for any failed run. SQLBuild ships no chat integration; this sensor builds a message for a +`team_chat` provider the project defines: + +```python +# orchestration/sensors/platform/failed_run_alert_sensor.py +from sqlbuild.orchestration import PlatformEvent, PlatformEventKind, SensorContext, platform_event, sensor + + +@sensor( + description="Post every failed run to the team channel", + when=platform_event(kinds=[PlatformEventKind.RUN_FAILED]), +) +def failed_run_alert_sensor(ctx: SensorContext[PlatformEvent], team_chat): + run = ctx.event.details + minutes, seconds = divmod((run["duration_ms"] or 0) // 1000, 60) + lines = [ + f"{run['job_key'] or 'Ad-hoc run'} failed in {run['target']}", + f"{run['succeeded_node_count']} built, {run['failed_node_count']} failed, " + f"{run['skipped_node_count']} skipped · {minutes}m {seconds}s", + ] + for node in run["failed_nodes"][:3]: + where = f" in {node['phase']}" if node["phase"] else "" + lines.append(f"• {node['node_key']} failed{where}: {node['message'] or node['error_code']}") + for audit in run["failed_audits"][:3]: + lines.append(f"• audit {audit['name']} failed: {audit['message'] or audit['failing_rows']}") + if run["error"]: + lines.append(f"• failed in {run['error']['phase']}: {run['error']['message']}") + if run["skipped_nodes"]: + lines.append("Skipped: " + ", ".join(run["skipped_nodes"][:5])) + if run["url"]: + lines.append(run["url"]) + team_chat.post("\n".join(lines)) +``` + `ctx.cursor` is for polling sensors only. A sensor with a `when` condition always sees `None`, and a value it assigns is ignored: the server keeps its place in the events. diff --git a/website/src/content/docs/docs/concepts/project-configuration.mdx b/website/src/content/docs/docs/concepts/project-configuration.mdx index de9de76ff0..a187efe892 100644 --- a/website/src/content/docs/docs/concepts/project-configuration.mdx +++ b/website/src/content/docs/docs/concepts/project-configuration.mdx @@ -106,8 +106,8 @@ schema = "dev" # uses connections.local, the only named connection A command that needs the warehouse, such as `build`, `plan`, `query`, `diff`, or `debug`, fails with `D001` before connecting when no connection is configured. Commands and modes that don't -connect, such as `compile`, `format`, `lineage`, `scope`, `rename`, `mv`, `test --inspect`, and -`scenario test --local`, keep working without one. +connect, such as `compile`, `format`, `lineage`, `scope`, `rename`, `mv`, `test --inspect`, +`test --run-on local` and `scenario test --run-on local`, keep working without one. SQLBuild never falls back to an implicit in-memory DuckDB database; to use one, set it explicitly: @@ -162,6 +162,8 @@ A target is a named build context - the database and schema you build into, plus | `missing_migration_origin` | What a build does when a declared `migrate_from` origin does not exist in this target: `allow` (default), `require_confirmation`, or `deny`. See [Missing migration origins](/docs/concepts/models/migrations#missing-migration-origins) | | `warehouses` | Snowflake warehouse per command group: `build`, `query` and `sync` (a location's warehouse syncs). See [Command-group warehouses](/docs/concepts/adapters/snowflake#command-group-warehouses) | | `concurrency` | Worker limit for commands run against this target, replacing `[settings] concurrency` (see below) | +| `test_run_on` | Where `sqb test` runs unit tests on this target: `auto`, `local` or `warehouse`; replaces `[settings] test_run_on` | +| `scenario_run_on` | Where `sqb scenario test` runs scenarios on this target: `auto`, `local` or `warehouse`; replaces `[settings] scenario_run_on` | | `ignore_audit_failures` | Whether builds on this target let audit failures through, replacing `[settings] ignore_audit_failures`; see [Ignoring audit failures](/docs/concepts/audits#ignoring-audit-failures) | | `plan_from` | Where `sqb plan` and `sqb build` read warehouse state: `live` (default) or `synced_state`; see [Planning from synced state](#planning-from-synced-state) | | `pause_dynamic` | `true` keeps this target's [dynamic models](/docs/concepts/models/dynamic) suspended between builds; each build refreshes the ones it selects. Default `false` | @@ -591,6 +593,8 @@ default_audit_run_scope = "delta_and_final" unit_test_max_real_models = 10 test_timeout = "30s" scenario_timeout = "15m" +test_run_on = "auto" +scenario_run_on = "auto" delta_compile = true ``` @@ -609,6 +613,8 @@ delta_compile = true | `unit_test_max_real_models` | `10` | Most real (unmocked) models one SQL unit test may execute; a larger test fails compilation. See [Unit test and scenario limits](#unit-test-and-scenario-limits). | | `test_timeout` | `30s` | Time limit for each SQL unit test, or `"disabled"` | | `scenario_timeout` | none | Time limit for each scenario, or `"disabled"` | +| `test_run_on` | `auto` | Where `sqb test` runs unit tests: `auto` (locally in DuckDB when SQLQuack converts a test, otherwise on the warehouse), `local` or `warehouse`. See [Running tests locally](/docs/concepts/testing-reference#running-tests-locally) | +| `scenario_run_on` | `auto` | Where `sqb scenario test` runs scenarios: `auto` (locally with a fresh snapshot whose SQL converts, otherwise on the warehouse), `local` or `warehouse`. See [Local scenario testing](/docs/concepts/scenarios#local-scenario-testing) | | `delta_compile` | `true` | After an edit to model SQL or SQL test files only, compile just the changed files against the previous compile. See [Compiling after an edit](/docs/cli/compile#compiling-after-an-edit). | | `allow_missing_secrets` | `false` | Let `compile`, `rules run`, `format`, `dag`, `lineage` and `scope` run without any provider's secrets on this machine. `sqlbuild_local.toml` only; a target lists the providers it expects to miss in [`[targets.] allow_missing_secrets`](#allowed-missing-secrets). See [Secrets](/docs/concepts/python-nodes/providers#allowing-missing-secrets). | | `allow_warehouse_round_trips` | `false` | Allow a loader to depend on an asset that reads SQL, so data can leave the warehouse and come back through a source. Project file only. See [The SQL boundary](/docs/concepts/python-nodes/overview#warehouse-round-trips). | diff --git a/website/src/content/docs/docs/concepts/scenarios.mdx b/website/src/content/docs/docs/concepts/scenarios.mdx index 6a96616d7d..1dd153490e 100644 --- a/website/src/content/docs/docs/concepts/scenarios.mdx +++ b/website/src/content/docs/docs/concepts/scenarios.mdx @@ -203,7 +203,7 @@ fixtures still isolate every scenario. On Ctrl-C, SQLBuild prints one notice, cancels scenarios that have not started, cancels the statements running scenarios have in flight, drops their relations (unless `--retain`), and only then exits. A second Ctrl-C skips that cleanup and exits immediately; the next run of the same -scenarios drops whatever they left behind. `--local` replay and `sqb scenario capture` run one +scenarios drops whatever they left behind. Local replay and `sqb scenario capture` run one scenario at a time. ### Parallel CI runs @@ -314,15 +314,20 @@ When a limit is exceeded, capture fails with a clear error and suggests narrowin Run scenarios locally against DuckDB: ```bash -sqb scenario test --local +sqb scenario test --run-on local ``` -This: +By default (`auto`), a scenario replays locally when its snapshot is fresh and SQLQuack converts +all of its SQL, and runs on the warehouse otherwise. With `--run-on local`, every scenario replays +locally, and one that cannot is an `ERROR`. Set the default with `[settings] scenario_run_on` or +a target's `scenario_run_on`; see [`sqb scenario test`](/docs/cli/scenario#where-scenarios-run). + +Local replay: -1. Checks snapshot freshness via the input fingerprint (missing/stale snapshots are skipped by default) +1. Checks snapshot freshness via the input fingerprint; a missing or stale snapshot keeps the scenario off DuckDB 2. Creates a temporary DuckDB database at `target/run/scenarios//local.duckdb` 3. Loads JSONL snapshots into typed DuckDB tables using column metadata from `scenario.json` -4. Transpiles model and check SQL from the project adapter dialect to DuckDB; SQL captured from a DuckDB project runs as authored +4. Converts function, model and check SQL from Snowflake to DuckDB with [SQLQuack](https://github.com/sqlstack-io/sqlquack), in a UTC session, reading the snapshot columns' captured types and models' declared column types; SQL captured from a DuckDB project runs as authored, and other adapters' scenarios run on the warehouse 5. Builds functions, models, and runs expected/assertion checks in DuckDB 6. Keeps the local DuckDB file for inspection (it lives under `target/`, so it's always retained) @@ -332,22 +337,14 @@ Instead of running capture and test separately, sync snapshots in one command: ```bash # Capture missing/stale snapshots, then run locally -sqb scenario test --local --sync-snapshots +sqb scenario test --sync-snapshots # Recapture all snapshots, then run locally -sqb scenario test --local --refresh +sqb scenario test --refresh ``` With `--sync-snapshots`, fresh snapshots are reused. With `--refresh`, all selected snapshots are recaptured even if fresh. -### Strict mode - -By default, missing or stale snapshots are skipped with a warning. Use `--strict` to treat them as errors: - -```bash -sqb scenario test --local --strict -``` - ### Local type overrides When the automatic warehouse-to-DuckDB type conversion produces an incompatible type, you can override it in `sqlbuild_project.toml`: @@ -385,5 +382,5 @@ See the [CLI reference](/docs/cli/scenario) for full command documentation. order, whitespace and number spelling do not matter, so a Snowflake capture's pretty-printed JSON equals an expected `PARSE_JSON(...)`. Values of non-JSON types with the same JSON text also compare equal, for example `DATE '2024-01-01'::VARIANT` and `'2024-01-01'::VARIANT`. -- Local replay transpiles SQL from the project adapter dialect to DuckDB. Adapter-specific SQL that cannot be translated will produce a clear error with the failing resource name and reason. -- Outside local replay, scenario fixture, expected and assertion SQL runs as authored: SQLBuild replaces `__ref`, `__source`, `__seed` and `__dbt_ref` calls with relation names and may wrap a partial fixture to add its missing columns, but never regenerates the query. Calls inside comments and quoted text are left unchanged. Quoted text and comments follow the project adapter's rules, including with `--local`: backslash escapes on Snowflake, BigQuery and Databricks, `E'...'` strings on DuckDB and Postgres, nested block comments on DuckDB, Postgres, Databricks and SQL Server, `#` line comments on BigQuery, and `//` line comments on Snowflake. A call naming a relation the scenario does not provide, or SQL with an unclosed string or comment, fails planning with `S511` naming the scenario file. +- Local replay runs only SQL SQLQuack converts. A model read by another model needs fully typed declared columns, or SQLQuack refuses the reading SQL (`unresolved name`) and the scenario runs on the warehouse. +- Outside local replay, scenario fixture, expected and assertion SQL runs as authored: SQLBuild replaces `__ref`, `__source`, `__seed` and `__dbt_ref` calls with relation names and may wrap a partial fixture to add its missing columns, but never regenerates the query. Calls inside comments and quoted text are left unchanged. Quoted text and comments follow the project adapter's rules, including in local replay: backslash escapes on Snowflake, BigQuery and Databricks, `E'...'` strings on DuckDB and Postgres, nested block comments on DuckDB, Postgres, Databricks and SQL Server, `#` line comments on BigQuery, and `//` line comments on Snowflake. A call naming a relation the scenario does not provide, or SQL with an unclosed string or comment, fails planning with `S511` naming the scenario file. diff --git a/website/src/content/docs/docs/concepts/selectors.mdx b/website/src/content/docs/docs/concepts/selectors.mdx index eca9a1cdfb..a22f6deeea 100644 --- a/website/src/content/docs/docs/concepts/selectors.mdx +++ b/website/src/content/docs/docs/concepts/selectors.mdx @@ -117,6 +117,25 @@ sqb test "test:orders_*" stg_customers Test selectors are unioned with other selectors and cannot use `+` or `,`. Other commands reject them with `S013`. +### Audit + +`audit:` selects an audit by name, the end-of-build singular audits included, and accepts glob +patterns: + +```bash +sqb build audit:orders_match_payments +sqb audit "audit:not_null_*" +sqb build daily_revenue audit:revenue_reconciles +``` + +An audit has no upstream or downstream nodes, so `+` adds nothing to it, and it composes with `,` +and `--exclude` like any other selector. An audit selected by name runs whether or not its target +is in the selection: when the build doesn't build the target, the audit runs after everything else, +against the target as it is. `sqb plan` lists audits selected by name under `Audits`, and its +`--json` output under `audits`. + +`plan`, `build`, `test`, `audit` and `check` accept `audit:`; other commands reject it with `S010`. + ## Graph expansion ### Upstream @@ -194,6 +213,49 @@ sqb build --select path:sql/models/marts --exclude daily_revenue sqb build --select +fact_orders --exclude tag:staging ``` +## Selecting from a past run + +Three selectors select from a run that already happened: + +| Selector | Selects | +| --- | --- | +| `run:` | Every node the run selected | +| `failed:` | The nodes that failed, were cancelled or never ran, and the audits that failed, not counting ignored audit failures | +| `skipped:` | The nodes the run skipped | + +They compose like any other selector, so `failed:+` reruns what didn't succeed and everything +downstream of it, and `run: --exclude skipped:` repeats what the run didn't skip: + +```bash +sqb plan failed:20261125T142600Z_1732548e8aea+ +sqb build failed:20261125T1426+ +sqb build model_a model_b failed:20261125T1426+ +``` + +The last command builds `model_a` and `model_b` too, for example when a failed audit read them +and they don't exist in the target yet. + +`` is the run's full ID or a prefix of at least 8 characters that only one run starts with; +wildcards are not accepted. A prefix that more runs start with is an error that lists them. + +Without `--server`, the run comes from the project's local [Recall](/docs/cli/recall) history, +which needs the default SQLite store. To list the latest local runs: + +```bash +sqb recall query "SELECT run_id, MIN(occurred_at) AS started FROM events + WHERE run_id IS NOT NULL GROUP BY run_id ORDER BY started DESC LIMIT 5" +``` + +With `--server`, `--location-id` and an [`sqb login`](/docs/cli/login) session, the run comes from +the server's runs of that location on the command's target, as the web UI shows them: + +```bash +sqb plan failed:0192c1a4+ --server https://control.example.com --location-id +``` + +`plan`, `build`, `test`, `audit` and `check` read past runs; other commands reject run selectors with +`S010`. + ## Error handling Unknown resource names, name patterns with no matches, empty paths, and malformed selectors produce @@ -207,6 +269,17 @@ error[S000]: no SQL resources or Python nodes found with tag 'nonexistent_tag' error[S007]: unknown node kind 'modle' error[S003]: path selector 'fact_orders~' requires names on both sides of '~' error[S013]: selector 'order_status_rules' selects a unit test; only `sqb test` and `sqb build` accept unit-test selectors +error[S007]: unknown audit name 'orders_match_payment' +error[S010]: selector 'failed:20261125T1426' selects from a past run; only plan, build, test, audit and check read past runs +``` + +A run ID that is too short, names no run, or starts more than one is refused before anything is +planned: + +``` +error[S000]: run ID '2026112' is too short: give the full ID or at least 8 characters of it +error[S000]: no run '20261124' in the local Recall history +error[S000]: run ID '20261125' is ambiguous: it starts 20261125T142600Z_1732548e8aea, 20261125T153329Z_746e30e62302; give more of the ID ``` Unknown names suggest the closest selectable names, including unit tests: diff --git a/website/src/content/docs/docs/concepts/testing-reference.mdx b/website/src/content/docs/docs/concepts/testing-reference.mdx index 04679a3ba8..bbecd50e89 100644 --- a/website/src/content/docs/docs/concepts/testing-reference.mdx +++ b/website/src/content/docs/docs/concepts/testing-reference.mdx @@ -416,6 +416,71 @@ to change it, without the scenario advice. Scenarios have their own limit, `scenario_timeout`; see [Scenario timeouts](/docs/concepts/project-configuration#unit-test-and-scenario-limits). +## Running tests locally + +`sqb test` runs each SQL unit test either locally, in a run-scoped in-memory DuckDB database, or on +the warehouse. Unit test fixtures are inline, so a local test needs no captured data and no +credentials. + +| Setting | Where each test runs | +| --- | --- | +| `auto` (default) | Locally when [SQLQuack](https://github.com/sqlstack-io/sqlquack) converts its comparison SQL to DuckDB, otherwise on the warehouse | +| `local` | Locally. A test SQLQuack refuses is an `ERROR` (`T007`, `can't run locally`); it is never skipped or sent to the warehouse | +| `warehouse` | On the warehouse, as every test ran before | + +The setting comes from, in order: `--run-on`, the selected target's `test_run_on` (a target in +`sqlbuild_local.toml` replaces the project file's), `[settings] test_run_on` in +`sqlbuild_local.toml`, then in `sqlbuild_project.toml`, then `auto`. + +```toml +[settings] +test_run_on = "auto" + +[targets.ci] +test_run_on = "local" +``` + +How SQLBuild decides, at compile time, before anything runs: + +- **Snowflake projects.** SQLQuack converts the test's comparison SQL: every real model in its + chain, its fixtures, expected rows and assertions. SQLQuack converts only constructs whose rules + were verified against recorded Snowflake results, and refuses anything else. SQLBuild gives + SQLQuack the declared columns of the project's sources, seeds and models. +- **DuckDB projects.** The SQL is already DuckDB SQL, so tests run locally as written. +- **Project functions.** A local run makes temporary copies of the functions a test calls. A + function whose body reads a table or view, or any function in a project that isn't DuckDB, needs + the warehouse (reason `project function: `). +- **Unmocked relations.** A test whose SQL still reads a relation the local database doesn't have, + rather than one of its fixtures, needs the warehouse (reason `warehouse relation: `). In a + Snowflake project SQLQuack refuses names the project doesn't declare, and a declared relation the + converted SQL reads by name, such as a table a model names directly, is one only the warehouse has. +- **Work per run.** Each distinct test statement is converted once, in worker processes, and the + test run reuses those conversions. Conversions are kept in `target/sqlquack-cache/`, keyed by the + SQL, the declared relations it reads, the session and the SQLQuack version, so a later run + converts only the statements that changed. At the end of a run, SQLBuild deletes the conversions + no run has used for 7 days. Deleting the folder is always safe. +- **Other adapters.** SQLQuack converts Snowflake SQL only, so tests run on the warehouse (reason + `dialect: `). +- **Time zone.** Local runs use a UTC session. When the target's connection sets another + `TIMEZONE` in `session_parameters`, SQLQuack refuses SQL whose result depends on the time zone, + and those tests go to the warehouse. + +`sqb test --inspect` adds one line per test: `runs on: local`, or +`runs on: warehouse ()`, where the reason is SQLQuack's refusal label +`: `, such as `missing rule: node:method_call` or +`a known difference that isn't allowed: fn:HASH`. The full diagnostics follow the plan. + +In `auto`, when the warehouse connection cannot be made, the local tests still run and each +warehouse test is an `ERROR` (`T008`, `needs the warehouse (no connection)`). + +Some problems only show when a test runs. SQLQuack's converted SQL raises, instead of returning a +different value, for inputs DuckDB would read differently from Snowflake, and DuckDB can fail with +an internal error on SQL it accepted. In `auto` such a test runs again on the warehouse, with the +reason `SQLQuack guard: `, such as `SQLQuack guard: array_agg_order`, or +`DuckDB internal error: `. The local attempt prints nothing; the test's row shows +`warehouse ()`. With `--run-on local` it is an `ERROR` (`T007`) that names the guard. An error Snowflake would raise too, such as a value that isn't a number, is the test's +own result wherever it runs. + ## Skipping SQL analysis Compile checks test fixtures and assertions like model SQL. For SQL the parser can't read, add